feat: enhance controller polling and settings management

- Improved controller state comparison in ControllerPage to include button and axis states.
- Added a "Danger Zone" section in SettingsPage for wiping all app data with confirmation prompts.
- Introduced new utilities in UtilitiesPage for auto applying covers and managing filter presets.
- Implemented filter management in a new filters module, allowing for applying and downloading shaders.
- Created an InstallerPage for streamlined emulator installation with quick and custom options.
- Updated types to support new functionalities related to filters and emulator settings.
This commit is contained in:
miles committed 2026-07-16 03:43:37 -05:00
1 parent 9150318662
commit b317bfec4d
22 files changed
+2271 -536

No files matched your search

+143 -8
View File
@@ -127,7 +127,6 @@ Pad1 = SDL
description: 'Universal RetroArch config with optimal defaults',
files: {
'retroarch.cfg': `video_driver = "vulkan"
audio_driver = "pulseaudio"
video_fullscreen = true
video_vsync = true
video_scale_integer = false
@@ -153,7 +152,6 @@ nds_default_core = "melonds_libretro"
description: 'Performance-focused RetroArch config',
files: {
'retroarch.cfg': `video_driver = "vulkan"
audio_driver = "pulseaudio"
video_fullscreen = true
video_threaded = true
video_vsync = false
@@ -279,6 +277,24 @@ volume = 100
files: {},
},
],
mednafen: [
{
name: 'OmniEmu Recommended',
description: 'Optimal Mednafen config with hardware rendering and smooth scaling',
files: {
'mednafen.cfg': `video.driver "opengl"
video.fullscreen "yes"
video.vsync "yes"
video.smooth "yes"
video.scale_screen "full"
video.blit_style "hardware"
sound.driver "default"
sound.enable "yes"
cheevos.enable "yes"
`,
},
},
],
};
// ---- Remote presets URL ----
@@ -405,8 +421,33 @@ function getConfigDir(emulatorId: string, installPath: string): string {
darwin: join(require('os').homedir(), 'Library', 'Preferences', 'pegasus-frontend'),
linux: join(require('os').homedir(), '.config', 'pegasus-frontend'),
},
mednafen: {
win32: join(process.env.APPDATA || '', 'mednafen'),
darwin: join(require('os').homedir(), '.mednafen'),
linux: join(require('os').homedir(), '.mednafen'),
},
};
return platformDirs[emulatorId]?.[platform] || dirname(installPath);
const defaultDir = platformDirs[emulatorId]?.[platform] || dirname(installPath);
// RetroArch on macOS: libretro nightlies may use ~/.config/retroarch instead of ~/Library/...
if (emulatorId === 'retroarch') return getRetroArchConfigDir();
return defaultDir;
}
/** Shared RetroArch config dir resolver — probes both candidate paths on macOS */
export function getRetroArchConfigDir(): string {
const os = require('os');
if (platform === 'win32') return join(process.env.APPDATA || '', 'RetroArch');
const candidates = platform === 'darwin'
? [join(os.homedir(), 'Library', 'Application Support', 'RetroArch'), join(os.homedir(), '.config', 'retroarch')]
: [join(os.homedir(), '.config', 'retroarch'), join(os.homedir(), 'Library', 'Application Support', 'RetroArch')];
for (const dir of candidates) {
if (existsSync(join(dir, 'retroarch.cfg'))) return dir;
}
return candidates[0];
}
export function checkConfigured(emulatorId: string, installPath?: string): boolean {
@@ -439,7 +480,28 @@ export async function applyPreset(
if (!existsSync(parentDir)) {
mkdirSync(parentDir, { recursive: true });
}
writeFileSync(fullPath, content, 'utf-8');
// For RetroArch: read-modify-write to preserve user customizations
if (emulatorId === 'retroarch' && existsSync(fullPath)) {
const existing = readFileSync(fullPath, 'utf-8');
const existingLines = existing.split('\n');
const newKeys = Object.keys(preset.files[relativePath]
.split('\n')
.filter(l => l.trim() && !l.trim().startsWith('#'))
.reduce((acc, l) => { const k = l.split('=')[0]?.trim(); if (k) acc[k] = true; return acc; }, {} as Record<string, boolean>));
const filtered = existingLines.filter(l => {
const trimmed = l.trim();
if (!trimmed || trimmed.startsWith('#')) return true;
const key = trimmed.split('=')[0]?.trim();
return key ? !newKeys.includes(key) : true;
});
// Append new settings after existing content
const newSettings = content.split('\n').filter(l => l.trim() && !l.trim().startsWith('#'));
filtered.push(...newSettings);
writeFileSync(fullPath, filtered.join('\n'), 'utf-8');
} else {
writeFileSync(fullPath, content, 'utf-8');
}
done++;
report(Math.round((done / totalFiles) * 100), `Wrote ${relativePath}`);
@@ -486,6 +548,7 @@ const esdeEmulatorNames: Record<string, string> = {
melonds: 'MELONDS',
flycast: 'FLYCAST',
eden: 'EDEN',
mednafen: 'MEDNAFEN',
};
function getEsdeEmulatorName(emulatorId: string): string | undefined {
@@ -900,10 +963,10 @@ export function applyControllerConfig(emulatorId: string, installPath: string, c
lines.push('input_player1_y_btn = "3"');
lines.push(`input_player1_l_btn = "4"`);
lines.push(`input_player1_r_btn = "5"`);
lines.push(`input_player1_l2_btn = "6"`);
lines.push(`input_player1_r2_btn = "7"`);
lines.push(`input_player1_select_btn = "6"`);
lines.push(`input_player1_start_btn = "7"`);
lines.push(`input_player1_select_btn = "8"`);
lines.push(`input_player1_start_btn = "9"`);
lines.push(`input_player1_l2_axis = "+4"`);
lines.push(`input_player1_r2_axis = "+5"`);
}
writeFileSync(cfgPath, lines.join('\n'), 'utf-8');
@@ -1016,6 +1079,72 @@ export function applyControllerConfig(emulatorId: string, installPath: string, c
return false;
}
/** Patch fullscreen setting for an emulator's config file */
export function patchEmulatorFullscreen(emulatorId: string, installPath: string, fullscreen: boolean): void {
const configDir = getConfigDir(emulatorId, installPath);
if (!existsSync(configDir)) return;
const val = fullscreen ? 'true' : 'false';
switch (emulatorId) {
case 'retroarch': {
const cfgPath = join(configDir, 'retroarch.cfg');
if (!existsSync(cfgPath)) return;
const lines = readFileSync(cfgPath, 'utf-8').split('\n')
.filter(l => !l.startsWith('video_fullscreen'));
lines.push(`video_fullscreen = ${val}`);
writeFileSync(cfgPath, lines.join('\n'), 'utf-8');
break;
}
case 'duckstation': {
const iniPath = join(configDir, 'settings.ini');
if (!existsSync(iniPath)) return;
const lines = readFileSync(iniPath, 'utf-8').split('\n')
.filter(l => !l.startsWith('StartFullscreen') && !l.startsWith('Fullscreen ='));
lines.push(`StartFullscreen = ${fullscreen ? 'True' : 'False'}`);
lines.push(`Fullscreen = ${fullscreen ? 'True' : 'False'}`);
writeFileSync(iniPath, lines.join('\n'), 'utf-8');
break;
}
case 'flycast': {
const cfgPath = join(configDir, 'emu.cfg');
if (!existsSync(cfgPath)) return;
const lines = readFileSync(cfgPath, 'utf-8').split('\n')
.filter(l => !l.startsWith('fullscreen'));
lines.push(`fullscreen = ${fullscreen ? 'yes' : 'no'}`);
writeFileSync(cfgPath, lines.join('\n'), 'utf-8');
break;
}
case 'melonds': {
const iniPath = join(configDir, 'melonDS.ini');
if (!existsSync(iniPath)) return;
const lines = readFileSync(iniPath, 'utf-8').split('\n')
.filter(l => !l.startsWith('fullscreen'));
lines.push(`fullscreen = ${fullscreen ? '1' : '0'}`);
writeFileSync(iniPath, lines.join('\n'), 'utf-8');
break;
}
case 'pcsx2': {
const iniPath = join(configDir, 'inis', 'PCSX2.ini');
if (!existsSync(iniPath)) return;
const lines = readFileSync(iniPath, 'utf-8').split('\n')
.filter(l => !l.startsWith('StartFullscreen'));
lines.push(`StartFullscreen = ${fullscreen ? '1' : '0'}`);
writeFileSync(iniPath, lines.join('\n'), 'utf-8');
break;
}
case 'dolphin': {
const cfgPath = join(configDir, 'Config', 'Dolphin.ini');
if (!existsSync(cfgPath)) return;
const lines = readFileSync(cfgPath, 'utf-8').split('\n')
.filter(l => !l.startsWith('Fullscreen ='));
lines.push(`Fullscreen = ${fullscreen ? 'True' : 'False'}`);
writeFileSync(cfgPath, lines.join('\n'), 'utf-8');
break;
}
}
}
async function getRetroAchievementsToken(username: string, password: string): Promise<string | null> {
try {
const https = await import('https');
@@ -1096,6 +1225,12 @@ const raEmulatorConfigs: Record<string, {
username: 'Username = %s',
token: 'Password = %s',
},
mednafen: {
file: 'mednafen.cfg',
enabled: 'cheevos.enable "yes"',
username: 'cheevos.username "%s"',
token: 'cheevos.password "%s"',
},
};
export async function applyRetroAchievements(username: string, password: string): Promise<Record<string, boolean>> {
+102 -76
View File
@@ -1,4 +1,4 @@
import { execSync, exec, ChildProcess } from 'child_process';
import { execSync, exec, spawn, ChildProcess } from 'child_process';
import { existsSync, mkdirSync, readdirSync, renameSync, readFileSync, rmSync, statSync } from 'fs';
import { join, dirname, basename, extname } from 'path';
import { app } from 'electron';
@@ -912,6 +912,40 @@ export const knownEmulators: EmulatorConfig[] = [
linux: 'https://www.mesen.ca/',
},
},
{
id: 'mednafen',
name: 'Mednafen',
description: 'Multi-system emulator (PS1, PCE, Lynx, NGP, WonderSwan)',
platforms: ['ps1', 'pce', 'lynx', 'ngp', 'wswan'],
defaultPath: {
win32: 'C:\\Program Files\\Mednafen\\mednafen.exe',
darwin: '/usr/local/bin/mednafen',
linux: '/usr/bin/mednafen',
},
downloads: {
win32: [
{
url: 'https://github.com/mednafen-emu/mednafen/releases/download/1.32.1/mednafen-1.32.1-win64.zip',
format: 'zip',
executablePath: 'mednafen.exe',
},
],
linux: [
{
url: 'https://github.com/mednafen-emu/mednafen/releases/download/1.32.1/mednafen-1.32.1-linux64.zip',
format: 'zip',
executablePath: 'mednafen',
},
],
},
packageNames: { linux: 'mednafen', darwin: 'mednafen' },
supported: true,
websiteUrl: {
win32: 'https://mednafen.github.io/',
darwin: 'https://mednafen.github.io/',
linux: 'https://mednafen.github.io/',
},
},
];
export function findEmulator(id: string): EmulatorConfig | undefined {
@@ -927,13 +961,18 @@ function detectEmulatorPath(config: EmulatorConfig): string | undefined {
if (existsSync(alt)) return alt;
}
try {
const cmd = isWindows() ? 'where' : 'which';
const result = execSync(`${cmd} ${config.id} 2>${isWindows() ? 'nul' : '/dev/null'}`)
.toString().trim();
if (result) return result.split('\n')[0];
} catch {
// not found
const userData = app.getPath('userData');
const emuDir = settings.get().emulatorsDirectory || join(userData, 'emulators');
const omniEmuDir = join(emuDir, config.id);
if (existsSync(omniEmuDir)) {
try {
const cmd = isWindows() ? 'where' : 'which';
const result = execSync(`${cmd} ${config.id} 2>${isWindows() ? 'nul' : '/dev/null'}`)
.toString().trim();
if (result) return result.split('\n')[0];
} catch {
// not found
}
}
return undefined;
@@ -942,7 +981,8 @@ function detectEmulatorPath(config: EmulatorConfig): string | undefined {
function alternativePaths(emulatorId: string): string[] {
const home = homedir();
const userData = app.getPath('userData');
const omniEmuDir = join(userData, 'emulators', emulatorId);
const emuDir = settings.get().emulatorsDirectory || join(userData, 'emulators');
const omniEmuDir = join(emuDir, emulatorId);
// Check marker file first (written after a successful install)
const markerFile = join(omniEmuDir, '.installed');
@@ -956,17 +996,11 @@ function alternativePaths(emulatorId: string): string[] {
join(omniEmuDir, 'Dolphin.exe'),
join(omniEmuDir, 'Dolphin'),
join(omniEmuDir, 'dolphin-emu'),
join(home, 'Applications', 'Dolphin.app', 'Contents', 'MacOS', 'Dolphin'),
'/usr/local/bin/dolphin-emu',
'/snap/bin/dolphin-emu',
],
retroarch: [
join(omniEmuDir, 'RetroArch.exe'),
join(omniEmuDir, 'RetroArch'),
join(omniEmuDir, 'retroarch'),
join(home, 'Applications', 'RetroArch.app', 'Contents', 'MacOS', 'RetroArch'),
'/usr/local/bin/retroarch',
'/snap/bin/retroarch',
],
rpcs3: [
join(omniEmuDir, 'rpcs3.exe'),
@@ -976,15 +1010,11 @@ function alternativePaths(emulatorId: string): string[] {
eden: [
join(omniEmuDir, 'Eden.exe'),
join(omniEmuDir, 'Eden'),
join(home, 'Applications', 'Eden.app', 'Contents', 'MacOS', 'Eden'),
'/usr/local/bin/eden',
],
duckstation: [
join(omniEmuDir, 'duckstation-qt-x64-ReleaseLGL.normal.exe'),
join(omniEmuDir, 'DuckStation'),
join(omniEmuDir, 'DuckStation.app', 'Contents', 'MacOS', 'DuckStation'),
join(home, 'Applications', 'DuckStation.app', 'Contents', 'MacOS', 'DuckStation'),
'/usr/local/bin/duckstation-qt',
],
pcsx2: [
join(omniEmuDir, 'pcsx2.exe'),
@@ -1000,111 +1030,84 @@ function alternativePaths(emulatorId: string): string[] {
join(omniEmuDir, 'flycast-win64.exe'),
join(omniEmuDir, 'flycast'),
join(omniEmuDir, 'Flycast.app', 'Contents', 'MacOS', 'Flycast'),
join(home, 'Applications', 'Flycast.app', 'Contents', 'MacOS', 'Flycast'),
'/usr/local/bin/flycast',
],
esde: [
join(omniEmuDir, 'esde.exe'),
join(omniEmuDir, 'ES-DE', 'esde.exe'),
join(omniEmuDir, 'es-de'),
join(omniEmuDir, 'ES-DE.app', 'Contents', 'MacOS', 'esde'),
join(home, 'Applications', 'ES-DE.app', 'Contents', 'MacOS', 'esde'),
'/usr/local/bin/es-de',
'/usr/bin/es-de',
],
neostation: [
join(omniEmuDir, 'neostation.exe'),
join(omniEmuDir, 'NeoStation', 'neostation.exe'),
join(omniEmuDir, 'neostation'),
join(omniEmuDir, 'NeoStation.app', 'Contents', 'MacOS', 'neostation'),
join(home, 'Applications', 'NeoStation.app', 'Contents', 'MacOS', 'neostation'),
'/usr/local/bin/neostation',
'/usr/bin/neostation',
],
emubuddy: [
join(omniEmuDir, 'EmuBuddyLauncher.exe'),
join(omniEmuDir, 'EmuBuddy', 'EmuBuddyLauncher.exe'),
join(omniEmuDir, 'EmuBuddyLauncher'),
join(omniEmuDir, 'EmuBuddy.app', 'Contents', 'MacOS', 'EmuBuddy'),
join(home, 'Applications', 'EmuBuddy.app', 'Contents', 'MacOS', 'EmuBuddy'),
'/usr/local/bin/emubuddy',
'/usr/bin/emubuddy',
],
pegasus: [
join(omniEmuDir, 'pegasus-fe.exe'),
join(omniEmuDir, 'pegasus-fe'),
join(omniEmuDir, 'Pegasus.app', 'Contents', 'MacOS', 'pegasus-fe'),
join(home, 'Applications', 'Pegasus.app', 'Contents', 'MacOS', 'pegasus-fe'),
'/usr/local/bin/pegasus-fe',
'/usr/bin/pegasus-fe',
],
melonds: [
join(omniEmuDir, 'melonDS.exe'),
join(omniEmuDir, 'melonDS'),
join(omniEmuDir, 'melonDS.app', 'Contents', 'MacOS', 'melonDS'),
join(home, 'Applications', 'melonDS.app', 'Contents', 'MacOS', 'melonDS'),
],
cemu: [
join(omniEmuDir, 'Cemu.exe'),
join(omniEmuDir, 'Cemu'),
join(omniEmuDir, 'Cemu.app', 'Contents', 'MacOS', 'Cemu'),
join(home, 'Applications', 'Cemu.app', 'Contents', 'MacOS', 'Cemu'),
'/usr/local/bin/cemu',
],
xemu: [
join(omniEmuDir, 'xemu.exe'),
join(omniEmuDir, 'xemu'),
join(omniEmuDir, 'xemu.app', 'Contents', 'MacOS', 'xemu'),
join(home, 'Applications', 'xemu.app', 'Contents', 'MacOS', 'xemu'),
'/usr/bin/xemu',
],
vita3k: [
join(omniEmuDir, 'Vita3K.exe'),
join(omniEmuDir, 'Vita3K'),
join(omniEmuDir, 'Vita3K.app', 'Contents', 'MacOS', 'Vita3K'),
join(home, 'Applications', 'Vita3K.app', 'Contents', 'MacOS', 'Vita3K'),
'/usr/bin/vita3k',
],
azahar: [
join(omniEmuDir, 'azahar.exe'),
join(omniEmuDir, 'azahar'),
join(omniEmuDir, 'Azahar.app', 'Contents', 'MacOS', 'azahar'),
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',
],
mednafen: [
join(omniEmuDir, 'mednafen.exe'),
join(omniEmuDir, 'mednafen', 'mednafen.exe'),
join(omniEmuDir, 'mednafen'),
'/usr/local/bin/mednafen',
'/opt/homebrew/bin/mednafen',
],
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',
join(omniEmuDir, 'Snes9x.app', 'Contents', 'MacOS', '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)];
@@ -1182,7 +1185,7 @@ export function launchEmulator(emulatorId: string): boolean {
const state = checkEmulator(emulatorId);
if (!state.installed || !state.path) return false;
const child = exec(`"${state.path}"`, { cwd: dirname(state.path) });
const child = spawn(state.path, [], { cwd: dirname(state.path), detached: true, stdio: 'ignore' });
if (child) child.unref();
return true;
@@ -1196,17 +1199,23 @@ export function launchGame(emulatorId: string, romPath: string): ChildProcess |
if (!emu) return null;
const args = launchArgs(emulatorId, romPath);
const cmd = `"${state.path}" ${args}`;
const proc = exec(cmd, {
const proc = spawn(state.path, args, {
cwd: dirname(state.path),
detached: true,
stdio: 'ignore',
});
if (proc) proc.unref();
return proc;
}
function findRetroArchCore(romPath: string): string | undefined {
const ext = extname(romPath).toLowerCase().replace(/^\./, '');
const dirPath = dirname(romPath);
const dirName = basename(dirPath).toLowerCase().replace(/[^a-z0-9\s-]/g, '');
const inferredPlatform = dirHints[dirName] || '';
const corePreference: Record<string, string[]> = {
'nes': ['nestopia', 'mesen', 'fceumm'],
'smc': ['snes9x', 'bsnes_hd', 'bsnes', 'mednafen_snes'],
@@ -1221,19 +1230,33 @@ function findRetroArchCore(romPath: string): string | undefined {
'nds': ['melonds', 'desmume'],
'bin': ['mednafen_psx_hw', 'pcsx_rearmed', 'swanstation'],
'cue': ['mednafen_psx_hw', 'pcsx_rearmed', 'swanstation'],
'iso': ['mednafen_psx_hw', 'pcsx_rearmed', 'swanstation'],
'pce': ['mednafen_pce_fast', 'mednafen_pce'],
'md': ['genesis_plus_gx', 'picodrive'],
'smd': ['genesis_plus_gx', 'picodrive'],
};
// .iso is ambiguous — use parent directory to disambiguate
if (ext === 'iso') {
if (inferredPlatform === 'ps2') {
corePreference['iso'] = ['play'];
} else if (inferredPlatform === 'gc') {
corePreference['iso'] = ['dolphin'];
} else if (inferredPlatform === 'wii') {
corePreference['iso'] = ['dolphin'];
} else {
corePreference['iso'] = ['mednafen_psx_hw', 'pcsx_rearmed', 'swanstation'];
}
}
const candidates = corePreference[ext];
if (!candidates) return undefined;
const home = homedir();
const userData = app.getPath('userData');
const emuDir = settings.get().emulatorsDirectory || join(userData, 'emulators');
const coreDirs = [
join(userData, 'emulators', 'retroarch', 'RetroArch.app', 'Contents', 'Resources', 'cores'),
join(userData, 'emulators', 'retroarch', 'cores'),
join(emuDir, 'retroarch', 'RetroArch.app', 'Contents', 'Resources', 'cores'),
join(emuDir, 'retroarch', 'cores'),
join(home, 'Library', 'Application Support', 'RetroArch', 'cores'),
'/usr/local/lib/retroarch/cores',
'/usr/lib/x86_64-linux-gnu/libretro',
@@ -1254,37 +1277,39 @@ function findRetroArchCore(romPath: string): string | undefined {
return undefined;
}
function launchArgs(emulatorId: string, romPath: string): string {
function launchArgs(emulatorId: string, romPath: string): string[] {
switch (emulatorId) {
case 'dolphin':
return `--exec="${romPath}"`;
return ['--exec', romPath];
case 'rpcs3':
return `"${romPath}"`;
return [romPath];
case 'eden':
return `"${romPath}"`;
return [romPath];
case 'pcsx2':
return `"${romPath}"`;
return [romPath];
case 'mame':
return `"${romPath}"`;
return [romPath];
case 'retroarch': {
const core = findRetroArchCore(romPath);
if (core) return `-L "${core}" "${romPath}"`;
return `"${romPath}"`;
if (core) return ['-L', core, romPath];
return [romPath];
}
case 'duckstation':
return `"${romPath}"`;
return [romPath];
case 'flycast':
return `"${romPath}"`;
return [romPath];
case 'esde':
return '';
return [];
case 'neostation':
return '';
return [];
case 'emubuddy':
return '';
return [];
case 'pegasus':
return '';
return [];
case 'mednafen':
return [romPath];
default:
return `"${romPath}"`;
return [romPath];
}
}
@@ -1443,7 +1468,8 @@ function guessPlatform(ext: string, dirPath?: string): string {
export function uninstallEmulator(id: string): boolean {
const userData = app.getPath('userData');
const installDir = join(userData, 'emulators', id);
const emuDir = settings.get().emulatorsDirectory || join(userData, 'emulators');
const installDir = join(emuDir, id);
const configMarker = join(userData, 'configs', `${id}.configured`);
let removed = false;
+176
View File
@@ -0,0 +1,176 @@
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';
import { get as httpsGet } from 'https';
import { getRetroArchConfigDir } from './configurator';
export interface FilterPreset {
id: string;
name: string;
description: string;
/** Keys to set in retroarch.cfg */
cfgOverrides: Record<string, string>;
/** Keys to remove from retroarch.cfg */
cfgRemove?: string[];
}
export const FILTER_PRESETS: FilterPreset[] = [
{
id: 'none',
name: 'None (Default)',
description: 'No shader or filter — raw pixels as the game intended.',
cfgOverrides: {
video_smooth: 'false',
video_scale_integer: 'false',
},
cfgRemove: ['video_shader'],
},
{
id: 'pixel-perfect',
name: 'Pixel Perfect',
description: 'Integer-scaled pixels with no smoothing. Sharp and crisp at native multiples.',
cfgOverrides: {
video_smooth: 'false',
video_scale_integer: 'true',
},
cfgRemove: ['video_shader'],
},
{
id: 'smooth',
name: 'Smooth (Bilinear)',
description: 'Bilinear filtering for a softer, modern look. Good for 3D games.',
cfgOverrides: {
video_smooth: 'true',
video_scale_integer: 'false',
},
cfgRemove: ['video_shader'],
},
{
id: 'crt-geom',
name: 'CRT (Geometry)',
description: 'Classic CRT curvature and phosphor glow. Best for 2D retro games.',
cfgOverrides: {
video_smooth: 'false',
video_scale_integer: 'false',
},
},
];
function readRetroarchCfg(cfgPath: string): string[] {
if (!existsSync(cfgPath)) return [];
return readFileSync(cfgPath, 'utf-8').split('\n');
}
function writeRetroarchCfg(cfgPath: string, lines: string[]): void {
writeFileSync(cfgPath, lines.filter(l => l.trim() !== '').join('\n') + '\n', 'utf-8');
}
function httpsGetBuffer(url: string): Promise<Buffer> {
return new Promise((resolve, reject) => {
const req = httpsGet(url, {
headers: { 'User-Agent': 'OmniEmu/0.3.1' },
timeout: 15000,
}, (res) => {
if (res.statusCode === 301 || res.statusCode === 302) {
const loc = res.headers.location;
if (loc) { httpsGetBuffer(loc).then(resolve, reject); return; }
}
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () => resolve(Buffer.concat(chunks)));
res.on('error', reject);
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
});
}
async function downloadCrtShader(configDir: string): Promise<string | null> {
const shadersDir = join(configDir, 'shaders');
if (!existsSync(shadersDir)) mkdirSync(shadersDir, { recursive: true });
const crtDir = join(shadersDir, 'crt');
if (!existsSync(crtDir)) mkdirSync(crtDir, { recursive: true });
const presetPath = join(crtDir, 'crt-geom.slangp');
if (existsSync(presetPath)) return presetPath;
const base = 'https://raw.githubusercontent.com/libretro/slang-shaders/master/crt';
try {
const [presetBuf, shaderBuf] = await Promise.all([
httpsGetBuffer(`${base}/crt-geom.slangp`),
httpsGetBuffer(`${base}/crt-geom.slang`),
]);
writeFileSync(presetPath, presetBuf);
writeFileSync(join(crtDir, 'crt-geom.slang'), shaderBuf);
// Try to download commonly referenced helper shaders (non-fatal if missing)
const helpers = ['linearize.slang', 'corner.slang', 'glass.slang', 'ntsc-pass1.slang', 'ntsc-pass2.slang'];
for (const h of helpers) {
try {
const buf = await httpsGetBuffer(`${base}/${h}`);
writeFileSync(join(crtDir, h), buf);
} catch { /* ok */ }
}
return presetPath;
} catch (err) {
console.error('[filters] failed to download CRT shader:', err);
return null;
}
}
export interface ApplyFilterResult {
success: boolean;
message: string;
appliedPreset: string;
}
export async function applyFilterPreset(presetId: string): Promise<ApplyFilterResult> {
const preset = FILTER_PRESETS.find(p => p.id === presetId);
if (!preset) return { success: false, message: 'Unknown filter preset', appliedPreset: '' };
const configDir = getRetroArchConfigDir();
if (!existsSync(configDir)) {
mkdirSync(configDir, { recursive: true });
}
const cfgPath = join(configDir, 'retroarch.cfg');
let lines = readRetroarchCfg(cfgPath);
// Remove old filter keys
const removeKeys = [
...(preset.cfgRemove || []),
...FILTER_PRESETS.flatMap(p => Object.keys(p.cfgOverrides)),
'video_shader',
];
lines = lines.filter(l => {
const trimmed = l.trim();
if (trimmed.startsWith('#') || trimmed === '') return true;
const key = trimmed.split(/[= ]/)[0]?.trim();
return key ? !removeKeys.includes(key) : true;
});
// Apply new overrides (unquoted values for RetroArch config parser)
for (const [key, value] of Object.entries(preset.cfgOverrides)) {
lines.push(`${key} = ${value}`);
}
// Download CRT shader if needed
if (preset.id === 'crt-geom') {
const shaderPath = await downloadCrtShader(configDir);
if (shaderPath) {
lines.push(`video_shader = ${shaderPath}`);
} else {
writeRetroarchCfg(cfgPath, lines);
return {
success: true,
message: 'Applied CRT settings (shader download failed — using fallback config)',
appliedPreset: preset.name,
};
}
}
writeRetroarchCfg(cfgPath, lines);
return { success: true, message: `Applied "${preset.name}" filter`, appliedPreset: preset.name };
}
+56 -56
View File
@@ -36,19 +36,19 @@ function isSteamDeck(): boolean {
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()) {
// 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.
app.commandLine.appendSwitch('use-gl', 'angle');
app.commandLine.appendSwitch('use-angle', 'swiftshader');
app.commandLine.appendSwitch('enable-features', 'VaapiVideoDecoder');
@@ -177,58 +177,58 @@ if (!gotLock) {
mainWindow.focus();
}
});
}
// 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();
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 */ }
// 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);
}
createTray();
app.whenReady().then(() => {
ensureRomsStructure();
setupAutoUpdater();
registerIpcHandlers();
// Auto-generate Pegasus collection files if Pegasus is configured
try {
const s = settings.get();
if (s.betaFeatures && s.romsDirectory) {
generatePegasusCollectionsForRomDir(s.romsDirectory);
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 */ }
}
} catch { /* ignore */ }
// Auto-start Syncthing if cloud sync was previously enabled
try {
const s = settings.get();
if (s.cloudSyncEnabled) {
startSyncthing().catch(() => { /* ignore */ });
}
} catch { /* ignore */ }
createTray();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
else mainWindow?.show();
// Auto-generate Pegasus collection files if Pegasus is configured
try {
const s = settings.get();
if (s.betaFeatures && s.romsDirectory) {
generatePegasusCollectionsForRomDir(s.romsDirectory);
}
} catch { /* ignore */ }
// Auto-start Syncthing if cloud sync was previously enabled
try {
const s = settings.get();
if (s.cloudSyncEnabled) {
startSyncthing().catch(() => { /* ignore */ });
}
} catch { /* ignore */ }
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
else mainWindow?.show();
});
});
});
}
app.on('window-all-closed', () => {
if (tray) {
+77 -42
View File
@@ -8,6 +8,7 @@ import { randomBytes } from 'crypto';
import { app } from 'electron';
import { EmulatorDownload, InstallProgress, Platform, Arch } from '../shared/types';
import { getPlatform, getArch, isWindows, isMacOS, isLinux } from './platform';
import { settings } from './settings';
type ProgressCallback = (progress: InstallProgress) => void;
@@ -156,47 +157,11 @@ async function extractArchive(
}
case 'dmg': {
if (!isMacOS()) throw new Error('DMG files can only be extracted on macOS');
onProgress('Opening DMG (please accept the license in the dialog)...');
execSync(`open "${archivePath}"`);
let mountPoint = '';
for (let i = 0; i < 60; i++) {
await new Promise(r => setTimeout(r, 1000));
try {
const lines = execSync('ls /Volumes/').toString().split('\n').filter(Boolean);
for (const vol of lines) {
const volPath = join('/Volumes', vol);
if (existsSync(join(volPath, 'ES-DE.app')) || existsSync(join(volPath, '..app'))) {
mountPoint = volPath;
break;
}
}
if (!mountPoint) {
for (const vol of lines) {
const volPath = join('/Volumes', vol);
if (statSync(volPath).isDirectory() && vol.toLowerCase().includes('es-de')) {
mountPoint = volPath;
break;
}
}
}
if (!mountPoint) {
for (const vol of lines) {
if (vol === 'Macintosh HD' || vol.startsWith('Recovery') || vol === 'OpenCode' || vol.startsWith('com.apple')) continue;
const volPath = join('/Volumes', vol);
try {
const entries = readdirSync(volPath);
if (entries.some(e => e.endsWith('.app'))) {
mountPoint = volPath;
break;
}
} catch { /* skip */ }
}
}
if (mountPoint) break;
} catch { /* retry */ }
}
if (!mountPoint) throw new Error('DMG did not mount within 60 seconds. Please accept the license dialog and try again.');
onProgress('Extracting DMG...');
const mountPoint = join(destDir, '.dmg_mount');
if (!existsSync(mountPoint)) mkdirSync(mountPoint, { recursive: true });
try {
execSync(`hdiutil attach "${archivePath}" -nobrowse -quiet -mountpoint "${mountPoint}"`, { timeout: 60000 });
const entries = readdirSync(mountPoint);
for (const item of entries) {
const src = join(mountPoint, item);
@@ -206,6 +171,7 @@ async function extractArchive(
}
} finally {
try { execSync(`hdiutil detach "${mountPoint}" -quiet 2>/dev/null`); } catch { /* ignore */ }
try { execSync(`rmdir "${mountPoint}" 2>/dev/null`); } catch { /* ignore */ }
}
break;
}
@@ -291,7 +257,8 @@ export async function installEmulator(
onProgress({ emulatorId, stage, percent, message });
};
const installDir = join(app.getPath('userData'), 'emulators', emulatorId);
const baseDir = settings.get().emulatorsDirectory || join(app.getPath('userData'), 'emulators');
const installDir = join(baseDir, emulatorId);
if (!existsSync(installDir)) mkdirSync(installDir, { recursive: true });
const archiveFormats = ['zip', 'tar.gz', 'tar.bz2', 'tar.xz', '7z', 'dmg'];
@@ -343,7 +310,8 @@ async function installViaPackageManager(
const report = (stage: InstallProgress['stage'], percent: number, message: string) => {
onProgress({ emulatorId, stage, percent, message });
};
const installDir = join(app.getPath('userData'), 'emulators', emulatorId);
const baseDir = settings.get().emulatorsDirectory || join(app.getPath('userData'), 'emulators');
const installDir = join(baseDir, emulatorId);
if (!existsSync(installDir)) mkdirSync(installDir, { recursive: true });
if (platform === 'darwin') {
@@ -369,6 +337,73 @@ async function installViaPackageManager(
return installDir;
}
const RETROARCH_ESSENTIAL_CORES = [
'nestopia_libretro',
'snes9x_libretro',
'mupen64plus_next_libretro',
'mgba_libretro',
'gambatte_libretro',
'melonds_libretro',
'mednafen_psx_hw_libretro',
'genesis_plus_gx_libretro',
'mednafen_pce_fast_libretro',
'flycast_libretro',
'pcsx_rearmed_libretro',
'beetle_saturn_libretro',
];
export async function installRetroArchCores(
installDir: string,
arch: Arch,
onProgress: ProgressCallback,
): Promise<void> {
if (!isMacOS()) return;
const report = (stage: InstallProgress['stage'], percent: number, message: string) => {
onProgress({ emulatorId: 'retroarch', stage, percent, message });
};
const coresDir = join(installDir, 'RetroArch.app', 'Contents', 'Resources', 'cores');
if (!existsSync(coresDir)) mkdirSync(coresDir, { recursive: true });
const buildbotArch = arch === 'arm64' ? 'arm64' : 'x86_64';
const baseUrl = `https://buildbot.libretro.com/nightly/apple/osx/${buildbotArch}/latest`;
let completed = 0;
const failed: string[] = [];
const total = RETROARCH_ESSENTIAL_CORES.length;
for (const core of RETROARCH_ESSENTIAL_CORES) {
const coreFileName = `${core}.dylib`;
const destPath = join(coresDir, coreFileName);
if (existsSync(destPath)) {
completed++;
continue;
}
const url = `${baseUrl}/${coreFileName}.zip`;
const pct = Math.round((completed / total) * 100);
report('downloading', pct, `Downloading core ${completed + 1}/${total}: ${core}...`);
const zipPath = tempName('.dylib.zip');
try {
await downloadFile(url, zipPath, () => {});
await runAsync('unzip', ['-o', zipPath, '-d', coresDir]);
} catch {
failed.push(core);
} finally {
try { unlinkSync(zipPath); } catch { /* ignore */ }
}
completed++;
}
if (failed.length > 0) {
report('done', 100, `RetroArch cores installed (${failed.length} failed: ${failed.join(', ')})`);
} else {
report('done', 100, 'RetroArch cores installed');
}
}
export function findInstalledBinary(emulatorId: string, installDir: string, executablePath?: string): string | undefined {
if (!existsSync(installDir)) return undefined;
+93 -9
View File
@@ -1,6 +1,7 @@
import { ipcMain, shell, dialog, BrowserWindow } from 'electron';
import { ipcMain, shell, dialog, BrowserWindow, safeStorage } from 'electron';
import { join } from 'path';
import { writeFileSync } from 'fs';
import { writeFileSync, rmSync, existsSync } from 'fs';
import { app } from 'electron';
import {
getAllEmulatorStates,
checkEmulator,
@@ -24,20 +25,22 @@ import {
openDecompWebsite,
setDecompRomPath,
} from './decomps';
import { installEmulator, findInstalledBinary } from './installer';
import { applyRecommendedConfig, getPresets, checkConfigured, applyControllerConfig, applyRetroAchievements } from './configurator';
import { installEmulator, findInstalledBinary, installRetroArchCores } from './installer';
import { applyRecommendedConfig, getPresets, checkConfigured, applyControllerConfig, applyRetroAchievements, patchEmulatorFullscreen } from './configurator';
import { settings } from './settings';
import { getSystemInfo, platformName, getPlatform, getArch } from './platform';
import { checkForUpdates, downloadUpdate, quitAndInstall } from './updater';
import { InstallProgress, AppSettings, GameEntry, AchievementInfo } from '../shared/types';
import { addRecentGame, parseGameTitle, buildScrapeTitle, findValidThumbnail, cacheCovers, scrapeGameMetadata, searchSteamGridDB } from './scraper';
import { getGameAchievements } from './ra';
import { addRecentGame, parseGameTitle, buildScrapeTitle, findValidThumbnail, cacheCovers, clearCoverCache, scrapeGameMetadata, searchSteamGridDB, autoApplyCovers } from './scraper';
import { getGameAchievements, raSupportedPlatforms } from './ra';
import { FILTER_PRESETS, applyFilterPreset } from './filters';
import { scanBiosDirectory, getKnownBiosList, getDefaultBiosDir, updateRetroarchBiosPath } from './bios';
import { listAllSaves, deleteSave, backupSave } from './saveManager';
import {
installSyncthing,
startSyncthing,
stopSyncthing,
uninstallSyncthing,
getSyncthingStatus,
addRemoteDevice,
removeRemoteDevice,
@@ -72,6 +75,23 @@ export function registerIpcHandlers(): void {
ipcMain.handle('emulators:states', () => getAllEmulatorStates());
ipcMain.handle('emulators:check', (_event, id: string) => checkEmulator(id));
// Apply recommended settings to all installed emulators
ipcMain.handle('emulators:apply-recommended-all', async (_event, fullscreen: boolean) => {
const states = getAllEmulatorStates();
const installed = states.filter(s => s.installed);
const results: { id: string; ok: boolean }[] = [];
for (const emu of installed) {
try {
const ok = await applyRecommendedConfig(emu.config.id, emu.path || '', (p) => {});
if (ok) patchEmulatorFullscreen(emu.config.id, emu.path || '', fullscreen);
results.push({ id: emu.config.id, ok });
} catch {
results.push({ id: emu.config.id, ok: false });
}
}
return results;
});
// Install emulator - direct download + install
ipcMain.handle(
'emulators:install',
@@ -127,6 +147,11 @@ export function registerIpcHandlers(): void {
const installDir = await installEmulator(emulatorId, downloads ?? [], platform, arch, sendProgress, config.packageNames?.[platform]);
// On macOS, download RetroArch cores individually (no bulk archive exists)
if (emulatorId === 'retroarch' && platform === 'darwin') {
await installRetroArchCores(installDir, arch, sendProgress);
}
// Try to find the binary and create a symlink or record it
const download = (downloads ?? []).filter((d) => !d.arch || d.arch === arch)[0];
const binary = findInstalledBinary(emulatorId, installDir, download?.executablePath);
@@ -135,6 +160,12 @@ export function registerIpcHandlers(): void {
writeFileSync(marker, binary);
}
// Apply recommended settings after install
try {
sendProgress({ emulatorId, stage: 'configuring', percent: 0, message: 'Applying recommended settings...' });
await applyRecommendedConfig(emulatorId, installDir, sendProgress);
} catch { /* non-fatal */ }
// Re-check state after install
return checkEmulator(emulatorId);
}
@@ -293,6 +324,18 @@ export function registerIpcHandlers(): void {
return true;
});
// Clear all cached covers
ipcMain.handle('games:clear-cover-cache', () => {
clearCoverCache();
return true;
});
// Recommended video filters
ipcMain.handle('filters:list', () => FILTER_PRESETS);
ipcMain.handle('filters:apply', async (_event, presetId: string) => {
return applyFilterPreset(presetId);
});
// Search SteamGridDB for cover art options
ipcMain.handle('games:search-cover-sgdb', async (_event, title: string, platform: string) => {
const s = settings.get();
@@ -307,13 +350,34 @@ export function registerIpcHandlers(): void {
// Fetch RetroAchievements for a game
ipcMain.handle('games:achievements', async (_event, romPath: string, title: string, platform: string) => {
if (!raSupportedPlatforms.has(platform)) return null;
const s = settings.get();
if (!s.retroAchievementsApiKey || !s.retroAchievementsUsername) return null;
return getGameAchievements(romPath, title, platform, s.retroAchievementsApiKey, s.retroAchievementsUsername);
});
// Auto-apply covers from SteamGridDB
ipcMain.handle('games:auto-apply-covers', async (event) => {
const s = settings.get();
if (!s.steamGridDbApiKey) return { total: 0, alreadyHadCover: 0, applied: 0, failed: 0, skippedNoKey: true };
const romsDir = getRomsDirectory();
const games = scanRoms(romsDir);
const win = BrowserWindow.fromWebContents(event.sender);
return autoApplyCovers(games, s.steamGridDbApiKey, (current, total, title) => {
win?.webContents.send('games:auto-apply-covers-progress', { current, total, title });
});
});
// Settings
ipcMain.handle('settings:get', () => settings.get());
ipcMain.handle('settings:get', async () => {
const s = settings.get();
if (s.retroAchievementsPassword && safeStorage.isEncryptionAvailable()) {
try {
s.retroAchievementsPassword = safeStorage.decryptString(Buffer.from(s.retroAchievementsPassword, 'base64'));
} catch { /* unencrypted legacy value, return as-is */ }
}
return s;
});
ipcMain.handle('settings:save', (_event, s: Partial<AppSettings>) =>
settings.save(s)
);
@@ -360,8 +424,10 @@ export function registerIpcHandlers(): void {
ipcMain.handle(
'retroachievements:save',
async (_event, username: string, password: string) => {
const s = settings.get();
settings.save({ retroAchievementsUsername: username, retroAchievementsPassword: password });
const encrypted = safeStorage.isEncryptionAvailable()
? safeStorage.encryptString(password).toString('base64')
: password;
settings.save({ retroAchievementsUsername: username, retroAchievementsPassword: encrypted });
const results = await applyRetroAchievements(username, password);
return results;
}
@@ -485,6 +551,10 @@ export function registerIpcHandlers(): void {
return false;
});
ipcMain.handle('cloud:uninstall', async () => {
return uninstallSyncthing();
});
// Pending devices and folders
ipcMain.handle('cloud:pending-devices', async () => {
try {
@@ -545,4 +615,18 @@ export function registerIpcHandlers(): void {
return false;
}
});
// Nuke all app data
ipcMain.handle('app:nuke-data', async () => {
const dataDir = app.getPath('userData');
const dirs = ['emulators', 'downloads', 'syncthing', 'decomps', 'cache'];
for (const d of dirs) {
const p = join(dataDir, d);
if (existsSync(p)) rmSync(p, { recursive: true, force: true });
}
const s = settings.reset();
s.firstSetupComplete = false;
settings.save(s);
return true;
});
}
+25
View File
@@ -54,6 +54,10 @@ const api = {
configured: (id: string, installPath?: string): Promise<boolean> =>
ipcRenderer.invoke('emulators:configured', id, installPath),
/** Apply recommended settings to all installed emulators */
applyRecommendedAll: (fullscreen: boolean): Promise<{ id: string; ok: boolean }[]> =>
ipcRenderer.invoke('emulators:apply-recommended-all', fullscreen),
/** Open the emulator's website in browser (fallback) */
openWebsite: (id: string): Promise<boolean> =>
ipcRenderer.invoke('emulators:open-website', id),
@@ -105,12 +109,28 @@ const api = {
ipcRenderer.invoke('games:scrape-art', title, platform),
cacheCovers: (entries: { romPath: string; coverUrl: string }[]): Promise<boolean> =>
ipcRenderer.invoke('games:cache-covers', entries),
clearCoverCache: (): Promise<boolean> =>
ipcRenderer.invoke('games:clear-cover-cache'),
searchCoverSGDB: (title: string, platform: string): Promise<any[]> =>
ipcRenderer.invoke('games:search-cover-sgdb', title, platform),
scrapeMetadata: (romPath: string, title: string, platform: string): Promise<GameMetadata> =>
ipcRenderer.invoke('games:scrape-metadata', romPath, title, platform),
achievements: (romPath: string, title: string, platform: string): Promise<AchievementInfo | null> =>
ipcRenderer.invoke('games:achievements', romPath, title, platform),
autoApplyCovers: (): Promise<{ total: number; alreadyHadCover: number; applied: number; failed: number; skippedNoKey?: boolean }> =>
ipcRenderer.invoke('games:auto-apply-covers'),
onAutoApplyCoversProgress: (cb: (progress: { current: number; total: number; title: string }) => void) => {
const handler = (_event: Electron.IpcRendererEvent, p: { current: number; total: number; title: string }) => cb(p);
ipcRenderer.on('games:auto-apply-covers-progress', handler);
return () => ipcRenderer.removeListener('games:auto-apply-covers-progress', handler);
},
},
filters: {
list: (): Promise<{ id: string; name: string; description: string }[]> =>
ipcRenderer.invoke('filters:list'),
apply: (presetId: string): Promise<{ success: boolean; message: string; appliedPreset: string }> =>
ipcRenderer.invoke('filters:apply', presetId),
},
bios: {
@@ -190,6 +210,7 @@ const api = {
removeFolder: (folderId: string): Promise<boolean> =>
ipcRenderer.invoke('cloud:remove-folder', folderId),
openWebUI: (): Promise<boolean> => ipcRenderer.invoke('cloud:open-web-ui'),
uninstall: (): Promise<boolean> => ipcRenderer.invoke('cloud:uninstall'),
pendingDevices: (): Promise<SyncthingPendingDevice[]> => ipcRenderer.invoke('cloud:pending-devices'),
acceptPendingDevice: (deviceId: string): Promise<boolean> =>
ipcRenderer.invoke('cloud:accept-pending-device', deviceId),
@@ -207,6 +228,10 @@ const api = {
return () => ipcRenderer.removeListener('cloud:install-progress', handler);
},
},
app: {
nukeData: (): Promise<boolean> => ipcRenderer.invoke('app:nuke-data'),
},
};
contextBridge.exposeInMainWorld('omni', api);
+35 -14
View File
@@ -3,6 +3,7 @@ import { createHash } from 'crypto';
import { createReadStream, readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';
import { app } from 'electron';
import { createGunzip } from 'zlib';
import type { RetroAchievement, AchievementInfo } from '../shared/types';
// Platform -> RA console ID mapping
@@ -15,17 +16,26 @@ const raConsoleIds: Record<string, number> = {
dreamcast: 27, arcade: 99,
};
/** Platforms where RetroAchievements is actually supported and has a decent game count */
export const raSupportedPlatforms = new Set(Object.keys(raConsoleIds));
const userAgent = 'OmniEmu/0.3.1';
function fetchText(url: string): Promise<string> {
return new Promise((resolve, reject) => {
const req = httpsGet(url, {
headers: { 'User-Agent': userAgent },
headers: { 'User-Agent': userAgent, 'Accept-Encoding': 'gzip, deflate' },
timeout: 15000,
}, (res) => {
let data = '';
res.on('data', (chunk: string) => data += chunk);
res.on('end', () => resolve(data));
const encoding = res.headers['content-encoding'];
let stream: NodeJS.ReadableStream = res;
if (encoding === 'gzip') {
stream = res.pipe(createGunzip());
}
const chunks: Buffer[] = [];
stream.on('data', (chunk: Buffer) => chunks.push(chunk));
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
stream.on('error', reject);
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
@@ -40,12 +50,19 @@ function postForm(url: string, body: string): Promise<string> {
'User-Agent': userAgent,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body),
'Accept-Encoding': 'gzip, deflate',
},
timeout: 15000,
}, (res) => {
let data = '';
res.on('data', (chunk: string) => data += chunk);
res.on('end', () => resolve(data));
const encoding = res.headers['content-encoding'];
let stream: NodeJS.ReadableStream = res;
if (encoding === 'gzip') {
stream = res.pipe(createGunzip());
}
const chunks: Buffer[] = [];
stream.on('data', (chunk: Buffer) => chunks.push(chunk));
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
stream.on('error', reject);
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
@@ -102,17 +119,20 @@ async function fetchGameList(consoleId: number, apiKey: string, username: string
async function getGameList(consoleId: number, apiKey: string, username: string): Promise<RaGameListEntry[]> {
const cache = readGameListCache();
if (cache[consoleId]) return cache[consoleId];
if (cache[consoleId] && cache[consoleId].length > 0) return cache[consoleId];
const list = await fetchGameList(consoleId, apiKey, username);
cache[consoleId] = list;
writeGameListCache(cache);
if (list.length > 0) {
cache[consoleId] = list;
writeGameListCache(cache);
}
return list;
}
function normalizeTitle(title: string): string {
return title.toLowerCase()
.replace(/\b(the|a|an|and|of|in|to|for)\b/g, '')
.replace(/[^a-z0-9]/g, '')
.replace(/the|a|an|and|of|in|to|for/g, '')
.replace(/\s+/g, '')
.trim();
}
@@ -133,12 +153,13 @@ function findGameIdByTitle(gameList: RaGameListEntry[], title: string): number |
// ---- Main API ----
/** Look up RA game ID by ROM hash (Connect API) */
async function lookupGameIdByHash(romPath: string): Promise<number | null> {
async function lookupGameIdByHash(romPath: string, username: string): Promise<number | null> {
try {
const hash = await computeMD5(romPath);
const body = `r=gameid&m=${hash}`;
const body = `r=gameid&m=${hash}&u=${encodeURIComponent(username)}`;
const response = await postForm('https://retroachievements.org/dorequest.php', body);
const parsed = JSON.parse(response);
console.log('[ra] hash lookup response:', JSON.stringify(parsed).slice(0, 200));
if (parsed.Success && (parsed.ID || parsed.GameID)) return parsed.ID || parsed.GameID;
return null;
} catch (err) {
@@ -208,7 +229,7 @@ export async function getGameAchievements(
if (!apiKey || !username) return null;
// Try hash-based lookup first
let gameId = await lookupGameIdByHash(romPath);
let gameId = await lookupGameIdByHash(romPath, username);
// Fall back to title-based lookup
if (!gameId) {
+1 -2
View File
@@ -181,8 +181,7 @@ const SAVE_EXTENSIONS = new Set([
'.mcd', '.mcr', '.mc0', '.mc1', '.mc2', '.mc3',
'.gci', '.raw', '.ags',
'.mem', '.psm',
'.save', '.Save',
'.SVS',
'.save', '.Save', '.svs',
'.pfd',
'.bin',
]);
+80 -5
View File
@@ -1,5 +1,5 @@
import { get as httpsGet, request as httpsRequest } from 'https';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { readFileSync, writeFileSync, existsSync, mkdirSync, rmSync, readdirSync } from 'fs';
import { join, dirname } from 'path';
import { app } from 'electron';
import { GameEntry, GameMetadata } from '../shared/types';
@@ -130,16 +130,20 @@ function fetchText(url: string): Promise<string> {
});
}
function urlExists(url: string): Promise<boolean> {
function urlExists(url: string, maxRedirects = 5): Promise<boolean> {
return new Promise((resolve) => {
const req = httpsGet(url, {
method: 'GET',
headers: { 'User-Agent': 'OmniEmu/0.3.1' },
timeout: 10000,
}, (res) => {
// GitHub raw returns 200 for existing or redirects to it
resolve(res.statusCode === 200);
res.resume(); // drain response
if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location && maxRedirects > 0) {
res.resume();
resolve(urlExists(res.headers.location, maxRedirects - 1));
return;
}
resolve(!!res.statusCode && res.statusCode >= 200 && res.statusCode < 300);
res.resume();
});
req.on('error', () => resolve(false));
req.on('timeout', () => { req.destroy(); resolve(false); });
@@ -190,6 +194,22 @@ export function cacheCovers(entries: { romPath: string; coverUrl: string }[]): v
writeCache(cache);
}
/** Clear all cached covers and downloaded SGDB images */
export function clearCoverCache(): void {
// Clear the scrape cache (romPath -> coverUrl mapping)
writeCache({});
// Clear downloaded SGDB images
const sgdbDir = sgdbCacheDir();
if (existsSync(sgdbDir)) {
try {
const files = readdirSync(sgdbDir);
for (const f of files) {
rmSync(join(sgdbDir, f), { force: true });
}
} catch { /* ignore */ }
}
}
/** Apply cached covers to an array of GameEntry objects (mutates in place) */
export function applyCachedCovers(entries: GameEntry[]): GameEntry[] {
const cache = readCache();
@@ -556,3 +576,58 @@ export async function searchSteamGridDB(
throw new Error(`SteamGridDB search failed: ${msg}`);
}
}
export interface AutoApplyResult {
total: number;
alreadyHadCover: number;
applied: number;
failed: number;
skippedNoKey: boolean;
}
export async function autoApplyCovers(
games: GameEntry[],
apiKey: string,
onProgress?: (current: number, total: number, title: string) => void,
): Promise<AutoApplyResult> {
const result: AutoApplyResult = {
total: games.length,
alreadyHadCover: 0,
applied: 0,
failed: 0,
skippedNoKey: !apiKey,
};
if (!apiKey) return result;
const cache = readCache();
for (let i = 0; i < games.length; i++) {
const game = games[i];
if (game.coverUrl || cache[game.romPath]) {
result.alreadyHadCover++;
continue;
}
onProgress?.(i + 1, games.length, game.title);
try {
const results = await searchSteamGridDB(buildScrapeTitle(game.title), game.platform, apiKey);
const cover = results.find(r => r.thumb);
if (cover) {
cacheCovers([{ romPath: game.romPath, coverUrl: cover.thumb }]);
result.applied++;
} else {
result.failed++;
}
} catch {
result.failed++;
}
// Rate limit: wait 250ms between requests
if (i < games.length - 1) {
await new Promise(r => setTimeout(r, 250));
}
}
return result;
}
+25 -4
View File
@@ -360,12 +360,12 @@ export async function getSyncthingStatus(): Promise<SyncthingStatus> {
}));
const remoteDevices: SyncthingRemoteDevice[] = (config.devices || [])
.filter((d: any) => d.id && d.id !== status.myID)
.filter((d: any) => d.deviceID && d.deviceID !== status.myID)
.map((d: any) => ({
id: d.id,
name: d.name || (d.id ? d.id.slice(0, 8) : 'Unknown'),
id: d.deviceID,
name: d.name || (d.deviceID ? d.deviceID.slice(0, 8) : 'Unknown'),
addresses: d.addresses || [],
connected: !!status?.connections?.[d.id]?.connected,
connected: !!status?.connections?.[d.deviceID]?.connected,
}));
return {
@@ -534,3 +534,24 @@ export async function acceptPendingFolder(
}
export { getBinaryPath, getPort, getApiKey, apiUrl, getSyncthingDir };
export async function uninstallSyncthing(): Promise<boolean> {
try {
if (stProcess && !stProcess.killed) {
try { await apiRequest('POST', '/rest/system/shutdown'); } catch { /* ignore */ }
await new Promise<void>((resolve) => {
const timeout = setTimeout(() => { stProcess?.kill(); resolve(); }, 3000);
stProcess!.on('exit', () => { clearTimeout(timeout); resolve(); });
});
stProcess = null;
}
const dir = getSyncthingDir();
if (existsSync(dir)) {
const { rmSync } = await import('fs');
rmSync(dir, { recursive: true, force: true });
}
return true;
} catch {
return false;
}
}
+32 -8
View File
@@ -9,6 +9,7 @@ import { ControllerPage } from './pages/ControllerPage';
import { UtilitiesPage } from './pages/UtilitiesPage';
import { SaveManagerPage } from './pages/SaveManagerPage';
import { CloudSyncPage } from './pages/CloudSyncPage';
import { InstallerPage } from './pages/InstallerPage';
import { useGamepadNav } from './hooks/useGamepadNav';
type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'cloud' | 'settings' | 'controller' | 'utilities';
@@ -24,31 +25,36 @@ export function applyTheme(theme: string) {
export function App() {
const [currentPage, setCurrentPage] = useState<Page>('dashboard');
const [showInstaller, setShowInstaller] = useState(false);
const { connected, showLegend, dismissLegend } = useGamepadNav(setCurrentPage, currentPage);
useEffect(() => {
window.omni.settings.get().then((s) => applyTheme(s.theme));
(async () => {
const s = await window.omni.settings.get();
applyTheme(s.theme);
if (!s.firstSetupComplete) setShowInstaller(true);
})();
}, []);
const renderPage = () => {
switch (currentPage) {
case 'dashboard':
return <Dashboard onNavigate={setCurrentPage} />;
return <ErrorBoundary><Dashboard onNavigate={setCurrentPage} /></ErrorBoundary>;
case 'emulators':
return <EmulatorsPage />;
return <ErrorBoundary><EmulatorsPage /></ErrorBoundary>;
case 'library':
return <LibraryPage />;
return <ErrorBoundary><LibraryPage /></ErrorBoundary>;
case 'saves':
return <SaveManagerPage />;
return <ErrorBoundary><SaveManagerPage /></ErrorBoundary>;
case 'cloud':
return <ErrorBoundary><CloudSyncPage /></ErrorBoundary>;
case 'settings':
return <SettingsPage />;
return <ErrorBoundary><SettingsPage /></ErrorBoundary>;
case 'controller':
return <ControllerPage />;
return <ErrorBoundary><ControllerPage /></ErrorBoundary>;
case 'utilities':
return <UtilitiesPage />;
return <ErrorBoundary><UtilitiesPage /></ErrorBoundary>;
}
};
@@ -61,6 +67,24 @@ export function App() {
</div>
</div>
{showInstaller && (
<div style={{
position: 'fixed', inset: 0, zIndex: 1000,
display: 'flex', alignItems: 'center', justifyContent: 'center',
background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(6px)',
}}>
<div style={{
width: '90vw', maxWidth: 820, maxHeight: '85vh',
overflowY: 'auto', borderRadius: 16,
background: 'var(--bg-primary, #0f0f1a)',
border: '1px solid var(--border, #333)',
padding: 32,
}}>
<InstallerPage onClose={() => setShowInstaller(false)} />
</div>
</div>
)}
{connected && showLegend && (
<div className="controller-legend" onClick={dismissLegend}>
<span>D-Pad: Navigate</span>
+40 -26
View File
@@ -16,6 +16,7 @@ const platformLabels: Record<string, string> = {
psp: 'PSP', pce: 'PC Engine',
'sega-md': 'Sega Genesis', 'sega-saturn': 'Sega Saturn', 'sega-dc': 'Sega Dreamcast',
dreamcast: 'Dreamcast', arcade: 'Arcade',
lynx: 'Atari Lynx', ngp: 'Neo Geo Pocket', wswan: 'WonderSwan',
};
const badgeBase = 'https://retroachievements.org/Badge/';
@@ -27,6 +28,7 @@ export function GameDetailModal({ game, onClose, onLaunch }: Props) {
const [loadingAchievements, setLoadingAchievements] = useState(false);
const [currentScreenshot, setCurrentScreenshot] = useState(0);
const [showCoverPicker, setShowCoverPicker] = useState(false);
const [coverUrl, setCoverUrl] = useState<string | undefined>(game.coverUrl);
useEffect(() => {
setLoadingMeta(true);
@@ -37,6 +39,12 @@ export function GameDetailModal({ game, onClose, onLaunch }: Props) {
useEffect(() => {
setLoadingAchievements(true);
const supported = ['nes','snes','n64','gb','gbc','gba','nds','gc','wii','ps1','ps2','ps3','psp','pce','sega-md','sega-saturn','sega-dc','dreamcast','arcade'];
if (!supported.includes(game.platform)) {
setAchievements(null);
setLoadingAchievements(false);
return;
}
window.omni.game.achievements(game.romPath, game.title, game.platform)
.then((a) => { setAchievements(a); setLoadingAchievements(false); })
.catch(() => setLoadingAchievements(false));
@@ -44,7 +52,7 @@ export function GameDetailModal({ game, onClose, onLaunch }: Props) {
const screenshots = metadata?.screenshots || [];
const hasScreenshots = screenshots.length > 0;
const displayScreenshot = hasScreenshots ? screenshots[currentScreenshot] : game.coverUrl;
const displayScreenshot = hasScreenshots ? screenshots[currentScreenshot] : coverUrl;
const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
@@ -113,11 +121,11 @@ export function GameDetailModal({ game, onClose, onLaunch }: Props) {
>
Change Cover
</button>
{game.coverUrl && (
{coverUrl && (
<button
className="btn btn-secondary btn-sm"
onClick={async () => {
game.coverUrl = undefined;
setCoverUrl(undefined);
await window.omni.game.cacheCovers([{ romPath: game.romPath, coverUrl: '' }]);
}}
>
@@ -173,30 +181,36 @@ export function GameDetailModal({ game, onClose, onLaunch }: Props) {
</>
)}
<div className="game-detail-achievements">
<h4>
Achievements
{achievements && (
<span className="text-sm text-muted" style={{ fontWeight: 400, marginLeft: 8 }}>
{achievements.userProgress}/{achievements.totalAchievements} · {achievements.totalPoints} pts
</span>
)}
</h4>
{(() => {
const raPlatforms = ['nes','snes','n64','gb','gbc','gba','nds','gc','wii','ps1','ps2','ps3','psp','pce','sega-md','sega-saturn','sega-dc','dreamcast','arcade'];
if (!raPlatforms.includes(game.platform)) return null;
return (
<div className="game-detail-achievements">
<h4>
Achievements
{achievements && (
<span className="text-sm text-muted" style={{ fontWeight: 400, marginLeft: 8 }}>
{achievements.userProgress}/{achievements.totalAchievements} · {achievements.totalPoints} pts
</span>
)}
</h4>
{loadingAchievements ? (
<p className="text-sm text-muted">Loading achievements...</p>
) : achievements ? (
<div className="achievement-list">
{achievements.achievements.map((a) => (
<AchievementRow key={a.id} achievement={a} />
))}
{loadingAchievements ? (
<p className="text-sm text-muted">Loading achievements...</p>
) : achievements ? (
<div className="achievement-list">
{achievements.achievements.map((a) => (
<AchievementRow key={a.id} achievement={a} />
))}
</div>
) : (
<p className="text-sm text-muted">
Add your RetroAchievements Web API Key in Settings &gt; Utilities to see achievements here.
</p>
)}
</div>
) : (
<p className="text-sm text-muted">
Add your RetroAchievements Web API Key in Settings &gt; Utilities to see achievements here.
</p>
)}
</div>
);
})()}
</div>
<button
@@ -215,7 +229,7 @@ export function GameDetailModal({ game, onClose, onLaunch }: Props) {
gameTitle={game.title}
platform={game.platform}
onSelect={async (url) => {
game.coverUrl = url;
setCoverUrl(url);
await window.omni.game.cacheCovers([{ romPath: game.romPath, coverUrl: url }]);
setShowCoverPicker(false);
}}
+405 -264
View File
@@ -31,6 +31,8 @@ export function CloudSyncPage() {
const [togglingSync, setTogglingSync] = useState('');
const [acceptingDevice, setAcceptingDevice] = useState('');
const [acceptingFolder, setAcceptingFolder] = useState('');
const [setupComplete, setSetupComplete] = useState(false);
const [showAddDevice, setShowAddDevice] = useState(false);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const idRef = useRef<HTMLTextAreaElement>(null);
@@ -50,9 +52,9 @@ export function CloudSyncPage() {
window.omni.cloud.emulatorDirs().catch(() => [] as EmuDir[]),
]);
setCloudEnabled(!!s.cloudSyncEnabled);
setSetupComplete(!!s.cloudSyncSetupComplete);
if (cloudStatus) {
setStatus(cloudStatus);
// Determine which emus are synced
const synced: Record<string, boolean> = {};
for (const d of dirs) {
synced[d.id] = cloudStatus.folders.some(f => f.id === `saves-${d.id}`);
@@ -62,7 +64,6 @@ export function CloudSyncPage() {
setPendingDevices(pendingDev);
setPendingFolders(pendingFol);
setEmuDirs(dirs);
// Auto-resolve folder paths
const paths: Record<string, string> = {};
for (const fol of pendingFol) {
const resolved = await window.omni.cloud.guessPath(fol.folderLabel).catch(() => null);
@@ -99,6 +100,11 @@ export function CloudSyncPage() {
try { await window.omni.settings.save({ cloudSyncEnabled: enabled }); } catch { /* ignore */ }
};
const markSetupComplete = async () => {
setSetupComplete(true);
try { await window.omni.settings.save({ cloudSyncSetupComplete: true }); } catch { /* ignore */ }
};
const handleInstall = async () => {
setInstalling(true); setInstallPercent(0); setInstallMsg('Starting download...');
try {
@@ -113,17 +119,36 @@ export function CloudSyncPage() {
const s = await window.omni.cloud.start();
if (s) {
setStatus(s);
if (s.running) { await saveCloudEnabled(true); showSuccess('Syncthing started!'); setLoading(false); }
else {
if (s.running) {
await saveCloudEnabled(true);
if (!setupComplete) await markSetupComplete();
showSuccess('Syncthing started!');
setLoading(false);
} else {
let attempts = 0;
pollRef.current = setInterval(async () => {
attempts++;
try {
const latest = await window.omni.cloud.status();
setStatus(latest);
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); } }
if (latest.running) {
clearInterval(pollRef.current!); pollRef.current = null;
await saveCloudEnabled(true);
if (!setupComplete) await markSetupComplete();
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'); setLoading(false); }
@@ -132,8 +157,12 @@ export function CloudSyncPage() {
const handleStop = async () => {
setLoading(true);
try { const s = await window.omni.cloud.stop(); setStatus(s); await saveCloudEnabled(false); showSuccess('Syncthing stopped.'); }
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);
};
@@ -142,7 +171,7 @@ export function CloudSyncPage() {
setAddingDevice(true);
try {
const ok = await window.omni.cloud.addDevice(remoteDeviceId.trim(), remoteDeviceName.trim());
if (ok) { showSuccess('Device added!'); setRemoteDeviceId(''); setRemoteDeviceName(''); loadData(); }
if (ok) { showSuccess('Device added!'); setRemoteDeviceId(''); setRemoteDeviceName(''); setShowAddDevice(false); loadData(); }
else showError('Failed to add device');
} catch (err) { showError(`Error: ${err}`); }
setAddingDevice(false);
@@ -194,9 +223,11 @@ export function CloudSyncPage() {
let step: SetupStep;
if (!installed) step = 'install';
else if (!running) step = 'start';
else if (!forceReady && (status?.remoteDevices?.length ?? 0) === 0) step = 'setup';
else if (!forceReady && !setupComplete && (status?.remoteDevices?.length ?? 0) === 0) step = 'setup';
else step = 'ready';
const showStepCounter = !setupComplete;
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);
@@ -211,44 +242,49 @@ export function CloudSyncPage() {
{error && <div className="info-bar mb-4" style={{ color: 'var(--danger, #ff4444)' }}>{error}</div>}
{success && <div className="info-bar mb-4" style={{ color: 'var(--success, #44ff44)' }}>{success}</div>}
{/* Step indicator */}
<div style={{
display: 'flex', gap: 8, marginBottom: 24, alignItems: 'center',
padding: '12px 16px', borderRadius: 10,
background: 'var(--bg-secondary, #1a1a2e)', border: '1px solid var(--border, #333)',
}}>
{(['install', 'start', 'setup', 'ready'] as SetupStep[]).map((s, i) => (
<React.Fragment key={s}>
<div style={{
width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center',
justifyContent: 'center', fontSize: 12, fontWeight: 700,
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',
}}>
{currentIdx > i ? '✓' : i + 1}
</div>
<span style={{
fontSize: 12, fontWeight: step === s ? 600 : 400,
color: step === s ? 'var(--text)' : 'var(--text-muted, #888)', marginRight: i < 3 ? 8 : 0,
}}>
{stepLabel(s)}
</span>
{i < 3 && <div style={{ flex: 1, height: 2, background: 'var(--bg-tertiary, #333)', maxWidth: 40 }} />}
</React.Fragment>
))}
</div>
{/* Step indicator — only during initial setup */}
{showStepCounter && (
<div style={{
display: 'flex', gap: 8, marginBottom: 24, alignItems: 'center',
padding: '12px 16px', borderRadius: 10,
background: 'var(--bg-secondary, #1a1a2e)', border: '1px solid var(--border, #333)',
}}>
{(['install', 'start', 'setup', 'ready'] as SetupStep[]).map((s, i) => (
<React.Fragment key={s}>
<div style={{
width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center',
justifyContent: 'center', fontSize: 12, fontWeight: 700,
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',
}}>
{currentIdx > i ? '✓' : i + 1}
</div>
<span style={{
fontSize: 12, fontWeight: step === s ? 600 : 400,
color: step === s ? 'var(--text)' : 'var(--text-muted, #888)', marginRight: i < 3 ? 8 : 0,
}}>
{stepLabel(s)}
</span>
{i < 3 && <div style={{ flex: 1, height: 2, background: 'var(--bg-tertiary, #333)', maxWidth: 40 }} />}
</React.Fragment>
))}
</div>
)}
{/* Status badge */}
{running && (
{(running || setupComplete) && (
<div style={{
display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 14px',
borderRadius: 20, marginBottom: 20, fontSize: 13, fontWeight: 600,
background: cloudEnabled ? 'rgba(68,255,68,0.1)' : 'rgba(255,200,68,0.1)',
border: `1px solid ${cloudEnabled ? 'rgba(68,255,68,0.3)' : 'rgba(255,200,68,0.3)'}`,
color: cloudEnabled ? 'var(--success, #44ff44)' : '#ffc844',
background: running && cloudEnabled ? 'rgba(68,255,68,0.1)' : running ? 'rgba(255,200,68,0.1)' : 'rgba(255,100,100,0.1)',
border: `1px solid ${running && cloudEnabled ? 'rgba(68,255,68,0.3)' : running ? 'rgba(255,200,68,0.3)' : 'rgba(255,100,100,0.3)'}`,
color: running && cloudEnabled ? 'var(--success, #44ff44)' : running ? '#ffc844' : 'var(--danger, #ff4444)',
}}>
<span style={{ width: 8, height: 8, borderRadius: '50%', background: cloudEnabled ? 'var(--success, #44ff44)' : '#ffc844' }} />
{cloudEnabled ? 'Cloud sync active' : 'Running — not yet paired'}
<span style={{
width: 8, height: 8, borderRadius: '50%',
background: running && cloudEnabled ? 'var(--success, #44ff44)' : running ? '#ffc844' : 'var(--danger, #ff4444)',
}} />
{running ? (cloudEnabled ? 'Cloud sync active' : 'Running — not yet paired') : 'Syncthing stopped'}
</div>
)}
@@ -286,8 +322,8 @@ export function CloudSyncPage() {
</div>
)}
{/* Step 1: Install */}
{!installed && !installing && (
{/* ── Initial Setup: Step 1 — Install ──────────────── */}
{!setupComplete && !installed && !installing && (
<div className="card mb-4" style={{
border: '2px solid var(--accent)',
background: 'linear-gradient(135deg, rgba(108,99,255,0.08), rgba(108,99,255,0.02))',
@@ -304,7 +340,7 @@ export function CloudSyncPage() {
</div>
)}
{installing && (
{!setupComplete && installing && (
<div className="card mb-4">
<div className="card-header"><h3>Installing Syncthing...</h3></div>
<div style={{ padding: 16 }}>
@@ -319,8 +355,8 @@ export function CloudSyncPage() {
</div>
)}
{/* Step 2: Start */}
{installed && !running && (
{/* ── Initial Setup: Step 2 — Start ────────────────── */}
{!setupComplete && installed && !running && (
<div className="card mb-4" style={{
border: '2px solid var(--accent)',
background: 'linear-gradient(135deg, rgba(108,99,255,0.08), rgba(108,99,255,0.02))',
@@ -337,240 +373,345 @@ export function CloudSyncPage() {
</div>
)}
{/* Steps 3-4 */}
{running && (
{/* ── Initial Setup: Step 3 — Pair ─────────────────── */}
{!setupComplete && step === 'setup' && (
<>
{/* Step 3: Your Device ID + Pair */}
{step === 'setup' && (
<div className="card mb-4">
<div className="card-header"><h3>Step 3 — Pair a Device</h3></div>
<div style={{ padding: 16 }}>
<p className="text-muted text-sm" style={{ marginBottom: 12 }}>
Copy this ID and paste it into the other device. Then enter their ID below.
</p>
<div style={{ marginBottom: 16 }}>
<label className="text-sm text-muted" style={{ display: 'block', marginBottom: 4 }}>Your Device ID</label>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<textarea
ref={idRef}
readOnly
value={status?.deviceId || ''}
style={{
flex: 1, fontFamily: 'monospace', fontSize: 11, padding: 8,
borderRadius: 6, border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
resize: 'none', height: 40,
}}
/>
<button className="btn btn-primary btn-sm" onClick={handleCopyDeviceId} style={{ whiteSpace: 'nowrap' }}>
{copied ? 'Copied!' : 'Copy ID'}
</button>
</div>
</div>
<label className="text-sm text-muted" style={{ display: 'block', marginBottom: 4 }}>Add Remote Device</label>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<input
type="text" placeholder="Remote Device ID"
value={remoteDeviceId} onChange={e => setRemoteDeviceId(e.target.value)}
<div className="card mb-4">
<div className="card-header"><h3>Step 3 — Pair a Device</h3></div>
<div style={{ padding: 16 }}>
<p className="text-muted text-sm" style={{ marginBottom: 12 }}>
Copy this ID and paste it into the other device. Then enter their ID below.
</p>
<div style={{ marginBottom: 16 }}>
<label className="text-sm text-muted" style={{ display: 'block', marginBottom: 4 }}>Your Device ID</label>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<textarea
ref={idRef}
readOnly
value={status?.deviceId || ''}
style={{
fontFamily: 'monospace', fontSize: 12, padding: '8px 10px',
flex: 1, fontFamily: 'monospace', fontSize: 11, padding: 8,
borderRadius: 6, border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
resize: 'none', height: 40,
}}
/>
<input
type="text" placeholder="Device name (optional)"
value={remoteDeviceName} onChange={e => setRemoteDeviceName(e.target.value)}
style={{
padding: '8px 10px', borderRadius: 6,
border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
}}
/>
<button className="btn btn-primary" onClick={handleAddDevice} disabled={addingDevice || !remoteDeviceId.trim()}>
{addingDevice ? 'Adding...' : '🔗 Pair Device'}
<button className="btn btn-primary btn-sm" onClick={handleCopyDeviceId} style={{ whiteSpace: 'nowrap' }}>
{copied ? 'Copied!' : 'Copy ID'}
</button>
</div>
</div>
<label className="text-sm text-muted" style={{ display: 'block', marginBottom: 4 }}>Add Remote Device</label>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<input
type="text" placeholder="Remote Device ID"
value={remoteDeviceId} onChange={e => setRemoteDeviceId(e.target.value)}
style={{
fontFamily: 'monospace', fontSize: 12, padding: '8px 10px',
borderRadius: 6, border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
}}
/>
<input
type="text" placeholder="Device name (optional)"
value={remoteDeviceName} onChange={e => setRemoteDeviceName(e.target.value)}
style={{
padding: '8px 10px', borderRadius: 6,
border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
}}
/>
<button className="btn btn-primary" onClick={handleAddDevice} disabled={addingDevice || !remoteDeviceId.trim()}>
{addingDevice ? 'Adding...' : '🔗 Pair Device'}
</button>
</div>
</div>
</div>
<button
className="btn btn-primary"
onClick={() => { setForceReady(true); markSetupComplete(); saveCloudEnabled(true); }}
style={{ fontSize: 15, padding: '12px 28px', width: '100%', marginBottom: 16 }}
>
Next →
</button>
</>
)}
{/* ═══════════════════════════════════════════════════════
POST-SETUP MANAGEMENT VIEW
═══════════════════════════════════════════════════════ */}
{setupComplete && (
<>
{/* ── Start Syncthing (if stopped) ─────────────── */}
{installed && !running && (
<div className="card mb-4" style={{
border: '2px solid var(--accent)',
background: 'linear-gradient(135deg, rgba(108,99,255,0.08), rgba(108,99,255,0.02))',
}}>
<div className="card-header"><h3 style={{ margin: 0 }}>Syncthing is stopped</h3></div>
<div style={{ padding: 16 }}>
<p className="text-muted" style={{ marginBottom: 16 }}>
Start the sync service to manage devices and share saves.
</p>
<button className="btn btn-primary" onClick={handleStart} disabled={loading} style={{ fontSize: 15, padding: '12px 28px' }}>
▶ Start Syncthing
</button>
</div>
</div>
)}
{/* Next button — step 3 only */}
{step === 'setup' && (
<button
className="btn btn-primary"
onClick={() => { setForceReady(true); saveCloudEnabled(true); }}
style={{ fontSize: 15, padding: '12px 28px', width: '100%', marginBottom: 16 }}
>
Next →
</button>
)}
{/* Step 4: Sync Dashboard */}
{step === 'ready' && (
<>
{/* Paired Devices */}
<div className="card mb-4">
<div className="card-header"><h3>Paired Devices</h3></div>
<div style={{ padding: '0 12px 12px' }}>
{status?.remoteDevices && status.remoteDevices.filter(d => d.id).length > 0 ? (
status.remoteDevices.filter(d => d.id).map(device => (
<div key={device.id} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '8px 10px', borderRadius: 8,
border: '1px solid var(--border, #555)', marginBottom: 4,
background: 'var(--bg-tertiary, #222)',
}}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 13 }}>{device.name || 'Unknown Device'}</div>
<div className="text-sm text-muted" style={{ fontFamily: 'monospace', fontSize: 10 }}>
{device.id.slice(0, 12)}...{device.id.slice(-6)}
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ fontSize: 11, color: device.connected ? 'var(--success, #44ff44)' : 'var(--text-muted, #888)' }}>
{device.connected ? 'Connected' : 'Offline'}
</span>
<button className="btn btn-danger btn-sm" onClick={() => handleRemoveDevice(device.id)}>
Remove
</button>
</div>
</div>
))
) : (
<p className="text-muted text-sm" style={{ padding: 8 }}>No devices paired yet.</p>
)}
</div>
</div>
{/* Pending Folder Requests */}
{pendingFolders.length > 0 && (
<div className="card mb-4" style={{ border: '2px solid rgba(255,200,68,0.4)' }}>
<div className="card-header" style={{ background: 'rgba(255,200,68,0.06)' }}>
<h3 style={{ margin: 0 }}>Incoming Folders</h3>
</div>
<div style={{ padding: 12 }}>
{pendingFolders.map(fol => (
<div key={fol.folderId} style={{
padding: '10px 12px', borderRadius: 8,
border: '1px solid rgba(255,200,68,0.25)', marginBottom: 8,
background: 'rgba(255,200,68,0.04)',
}}>
<div style={{ fontWeight: 600, fontSize: 13, marginBottom: 6 }}>{fol.folderLabel}</div>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<input
type="text"
value={pendingFolderPaths[fol.folderId] || ''}
onChange={e => setPendingFolderPaths(prev => ({ ...prev, [fol.folderId]: e.target.value }))}
placeholder="Save location (auto-detected)"
style={{
flex: 1, padding: '6px 10px', borderRadius: 6,
border: '1px solid var(--border, #555)',
background: 'var(--bg-secondary, #1a1a1a)', color: 'var(--text, #fff)',
fontFamily: 'monospace', fontSize: 11,
}}
/>
<button
className="btn btn-primary btn-sm"
onClick={() => handleAcceptPendingFolder(fol)}
disabled={acceptingFolder === fol.folderId || !(pendingFolderPaths[fol.folderId] || '').trim()}
style={{ fontSize: 12, whiteSpace: 'nowrap' }}
>
{acceptingFolder === fol.folderId ? '...' : '✓ Accept'}
</button>
</div>
</div>
))}
</div>
</div>
)}
{/* Save Directories — Sync Toggles */}
<div className="card mb-4">
<div className="card-header">
<h3>Save Directories</h3>
</div>
<div style={{ padding: '0 12px 12px' }}>
<p className="text-muted text-sm" style={{ padding: '4px 0 8px' }}>
Toggle sync on for each emulator to start sharing its saves with paired devices.
</p>
{emuDirs.map(emu => {
const synced = !!emuSynced[emu.id];
const busy = togglingSync === emu.id;
return (
<div key={emu.id} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '10px 12px', borderRadius: 8,
border: `1px solid ${synced ? 'rgba(68,255,68,0.3)' : 'var(--border, #555)'}`,
marginBottom: 4,
background: synced ? 'rgba(68,255,68,0.04)' : 'var(--bg-tertiary, #222)',
transition: 'all 0.2s ease',
}}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 13 }}>{emu.name}</div>
<div className="text-sm text-muted" style={{ fontFamily: 'monospace', fontSize: 10 }}>
{emu.saves}
</div>
</div>
<button
className="btn btn-sm"
onClick={() => handleToggleSync(emu.id, !synced)}
disabled={busy}
style={{
padding: '6px 14px', borderRadius: 20, fontSize: 12, fontWeight: 600,
background: synced ? 'var(--success, #44ff44)' : 'var(--bg-secondary, #1a1a2e)',
color: synced ? '#000' : 'var(--text-muted, #888)',
border: `1px solid ${synced ? 'var(--success, #44ff44)' : 'var(--border, #555)'}`,
transition: 'all 0.2s ease',
}}
>
{busy ? '...' : synced ? 'Syncing' : 'Off'}
</button>
</div>
);
})}
</div>
</div>
{/* Control bar */}
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '12px 16px', borderRadius: 10,
background: 'var(--bg-secondary, #1a1a2e)', border: '1px solid var(--border, #333)',
marginBottom: 16,
}}>
<div style={{ display: 'flex', gap: 8 }}>
<button className="btn btn-secondary btn-sm" onClick={loadData} disabled={loading}>
{/* ── Paired Devices ──────────────────────────── */}
{running && (
<div className="card mb-4">
<div className="card-header" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<h3 style={{ margin: 0 }}>Paired Devices</h3>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<button className="btn btn-secondary btn-sm" onClick={loadData} disabled={loading} style={{ fontSize: 12 }}>
Refresh
</button>
<button className="btn btn-primary btn-sm" onClick={() => setShowAddDevice(!showAddDevice)} style={{ fontSize: 12 }}>
{showAddDevice ? 'Cancel' : '+ Add Device'}
</button>
</div>
<button className="btn btn-danger btn-sm" onClick={handleStop} disabled={loading}>
Stop Syncthing
</button>
</div>
{/* Advanced */}
{status?.apiKey && (
<details style={{ marginBottom: 16 }}>
<summary style={{ cursor: 'pointer', fontSize: 13, color: 'var(--text-muted, #888)', padding: '8px 0' }}>
Advanced Settings
</summary>
<div className="card" style={{ marginTop: 8 }}>
<div className="card-header"><h3>Advanced</h3></div>
<div style={{ padding: 12 }}>
<p className="text-muted text-sm" style={{ marginBottom: 8 }}>Syncthing API Key</p>
<code style={{
display: 'block', padding: '6px 10px', borderRadius: 6,
background: 'var(--bg-tertiary, #222)', fontSize: 11, wordBreak: 'break-all',
}}>
{status.apiKey}
</code>
<div style={{ padding: '0 12px 12px' }}>
{/* Add Device form — inline */}
{showAddDevice && (
<div style={{
padding: 12, borderRadius: 8, marginBottom: 8,
border: '1px solid rgba(108,99,255,0.3)', background: 'rgba(108,99,255,0.04)',
}}>
<div style={{ fontWeight: 600, fontSize: 13, marginBottom: 8 }}>Add New Device</div>
<div style={{ marginBottom: 8 }}>
<label className="text-sm text-muted" style={{ display: 'block', marginBottom: 4 }}>Your Device ID</label>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<textarea
ref={idRef}
readOnly
value={status?.deviceId || ''}
style={{
flex: 1, fontFamily: 'monospace', fontSize: 11, padding: 8,
borderRadius: 6, border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
resize: 'none', height: 40,
}}
/>
<button className="btn btn-primary btn-sm" onClick={handleCopyDeviceId} style={{ whiteSpace: 'nowrap' }}>
{copied ? 'Copied!' : 'Copy ID'}
</button>
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<input
type="text" placeholder="Remote Device ID"
value={remoteDeviceId} onChange={e => setRemoteDeviceId(e.target.value)}
style={{
fontFamily: 'monospace', fontSize: 12, padding: '8px 10px',
borderRadius: 6, border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
}}
/>
<input
type="text" placeholder="Device name (optional)"
value={remoteDeviceName} onChange={e => setRemoteDeviceName(e.target.value)}
style={{
padding: '8px 10px', borderRadius: 6,
border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
}}
/>
<button className="btn btn-primary" onClick={handleAddDevice} disabled={addingDevice || !remoteDeviceId.trim()}>
{addingDevice ? 'Adding...' : '🔗 Pair Device'}
</button>
</div>
</div>
</details>
)}
</>
)}
{/* Device list */}
{status?.remoteDevices && status.remoteDevices.filter(d => d.id).length > 0 ? (
status.remoteDevices.filter(d => d.id).map(device => (
<div key={device.id} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '8px 10px', borderRadius: 8,
border: '1px solid var(--border, #555)', marginBottom: 4,
background: 'var(--bg-tertiary, #222)',
}}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 13 }}>{device.name || 'Unknown Device'}</div>
<div className="text-sm text-muted" style={{ fontFamily: 'monospace', fontSize: 10 }}>
{device.id.slice(0, 12)}...{device.id.slice(-6)}
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ fontSize: 11, color: device.connected ? 'var(--success, #44ff44)' : 'var(--text-muted, #888)' }}>
{device.connected ? 'Connected' : 'Offline'}
</span>
<button className="btn btn-danger btn-sm" onClick={() => handleRemoveDevice(device.id)}>
Remove
</button>
</div>
</div>
))
) : (
<p className="text-muted text-sm" style={{ padding: 8 }}>No devices paired yet. Click "Add Device" to get started.</p>
)}
</div>
</div>
)}
{/* ── Pending Folder Requests ──────────────────── */}
{running && pendingFolders.length > 0 && (
<div className="card mb-4" style={{ border: '2px solid rgba(255,200,68,0.4)' }}>
<div className="card-header" style={{ background: 'rgba(255,200,68,0.06)' }}>
<h3 style={{ margin: 0 }}>Incoming Folders</h3>
</div>
<div style={{ padding: 12 }}>
{pendingFolders.map(fol => (
<div key={fol.folderId} style={{
padding: '10px 12px', borderRadius: 8,
border: '1px solid rgba(255,200,68,0.25)', marginBottom: 8,
background: 'rgba(255,200,68,0.04)',
}}>
<div style={{ fontWeight: 600, fontSize: 13, marginBottom: 6 }}>{fol.folderLabel}</div>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<input
type="text"
value={pendingFolderPaths[fol.folderId] || ''}
onChange={e => setPendingFolderPaths(prev => ({ ...prev, [fol.folderId]: e.target.value }))}
placeholder="Save location (auto-detected)"
style={{
flex: 1, padding: '6px 10px', borderRadius: 6,
border: '1px solid var(--border, #555)',
background: 'var(--bg-secondary, #1a1a1a)', color: 'var(--text, #fff)',
fontFamily: 'monospace', fontSize: 11,
}}
/>
<button
className="btn btn-primary btn-sm"
onClick={() => handleAcceptPendingFolder(fol)}
disabled={acceptingFolder === fol.folderId || !(pendingFolderPaths[fol.folderId] || '').trim()}
style={{ fontSize: 12, whiteSpace: 'nowrap' }}
>
{acceptingFolder === fol.folderId ? '...' : '✓ Accept'}
</button>
</div>
</div>
))}
</div>
</div>
)}
{/* ── Save Directories — Sync Toggles ──────────── */}
{running && (
<div className="card mb-4">
<div className="card-header">
<h3>Save Directories</h3>
</div>
<div style={{ padding: '0 12px 12px' }}>
<p className="text-muted text-sm" style={{ padding: '4px 0 8px' }}>
Toggle sync on for each emulator to start sharing its saves with paired devices.
</p>
{emuDirs.map(emu => {
const synced = !!emuSynced[emu.id];
const busy = togglingSync === emu.id;
return (
<div key={emu.id} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '10px 12px', borderRadius: 8,
border: `1px solid ${synced ? 'rgba(68,255,68,0.3)' : 'var(--border, #555)'}`,
marginBottom: 4,
background: synced ? 'rgba(68,255,68,0.04)' : 'var(--bg-tertiary, #222)',
transition: 'all 0.2s ease',
}}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 13 }}>{emu.name}</div>
<div className="text-sm text-muted" style={{ fontFamily: 'monospace', fontSize: 10 }}>
{emu.saves}
</div>
</div>
<button
className="btn btn-sm"
onClick={() => handleToggleSync(emu.id, !synced)}
disabled={busy}
style={{
padding: '6px 14px', borderRadius: 20, fontSize: 12, fontWeight: 600,
background: synced ? 'var(--success, #44ff44)' : 'var(--bg-secondary, #1a1a2e)',
color: synced ? '#000' : 'var(--text-muted, #888)',
border: `1px solid ${synced ? 'var(--success, #44ff44)' : 'var(--border, #555)'}`,
transition: 'all 0.2s ease',
}}
>
{busy ? '...' : synced ? 'Syncing' : 'Off'}
</button>
</div>
);
})}
</div>
</div>
)}
{/* ── Stop Syncthing ──────────────────────────── */}
{running && (
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
marginBottom: 16,
}}>
<button className="btn btn-secondary btn-sm" onClick={() => window.omni.cloud.openWebUI()}>
Open Web UI
</button>
<button className="btn btn-danger btn-sm" onClick={handleStop} disabled={loading}>
Stop Syncthing
</button>
</div>
)}
{/* ── Advanced Settings ────────────────────────── */}
{running && status?.apiKey && (
<details style={{ marginBottom: 16 }}>
<summary style={{ cursor: 'pointer', fontSize: 13, color: 'var(--text-muted, #888)', padding: '8px 0' }}>
Advanced Settings
</summary>
<div className="card" style={{ marginTop: 8 }}>
<div className="card-header"><h3>Advanced</h3></div>
<div style={{ padding: 12 }}>
<p className="text-muted text-sm" style={{ marginBottom: 8 }}>Syncthing API Key</p>
<code style={{
display: 'block', padding: '6px 10px', borderRadius: 6,
background: 'var(--bg-tertiary, #222)', fontSize: 11, wordBreak: 'break-all',
}}>
{status.apiKey}
</code>
<div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border, #333)' }}>
<p className="text-muted text-sm" style={{ marginBottom: 8 }}>
Uninstall Syncthing and remove all its data. You can reinstall it anytime.
</p>
<button
className="btn btn-danger btn-sm"
onClick={async () => {
if (!confirm('Uninstall Syncthing? This removes the binary and all sync data.')) return;
setLoading(true);
try {
const ok = await window.omni.cloud.uninstall();
if (ok) {
await window.omni.settings.save({ cloudSyncEnabled: false, cloudSyncSetupComplete: false });
setCloudEnabled(false);
setSetupComplete(false);
setStatus(null);
showSuccess('Syncthing uninstalled.');
loadData();
} else showError('Failed to uninstall');
} catch (err) { showError(`Error: ${err}`); }
setLoading(false);
}}
>
Uninstall Syncthing
</button>
</div>
</div>
</div>
</details>
)}
</>
)}
+9 -2
View File
@@ -67,8 +67,15 @@ export function ControllerPage() {
}
}
setControllers(prev => {
const same = prev.length === connected.length &&
prev.every((c, i) => c.id === connected[i]?.id && c.index === connected[i]?.index);
if (prev.length !== connected.length) return connected;
const same = prev.every((c, i) => {
const n = connected[i];
return c.id === n?.id && c.index === n?.index &&
c.buttons.length === n.buttons.length &&
c.buttons.every((b, j) => b.pressed === n.buttons[j]?.pressed && b.value === n.buttons[j]?.value) &&
c.axes.length === n.axes.length &&
c.axes.every((a, j) => a === n.axes[j]);
});
return same ? prev : connected;
});
rafRef.current = requestAnimationFrame(poll);
+398
View File
@@ -0,0 +1,398 @@
import React, { useEffect, useState, useCallback } from 'react';
import type { EmulatorState, InstallProgress } from '../../shared/types';
type View = 'pick' | 'installing';
const QUICK_PICK_IDS = [
'retroarch', 'dolphin', 'duckstation', 'pcsx2',
'ppsspp', 'flycast', 'mgba', 'melonds',
];
const QUICK_PICK_INFO: Record<string, { systems: string; icon: string }> = {
retroarch: { systems: 'NES, SNES, N64, GBA, GB, Genesis, PS1 & more', icon: '🕹️' },
dolphin: { systems: 'GameCube, Wii', icon: '🎮' },
duckstation: { systems: 'PlayStation 1', icon: '💿' },
pcsx2: { systems: 'PlayStation 2', icon: '💿' },
ppsspp: { systems: 'PSP', icon: '🎮' },
flycast: { systems: 'Dreamcast, Naomi', icon: '🎮' },
mgba: { systems: 'GBA, GB, GBC', icon: '🎮' },
melonds: { systems: 'Nintendo DS', icon: '🎮' },
};
interface InstallJob {
id: string;
name: string;
status: 'queued' | 'installing' | 'done' | 'error';
progress: number;
message: string;
}
interface Props {
onClose: () => void;
}
export function InstallerPage({ onClose }: Props) {
const [view, setView] = useState<View>('pick');
const [mode, setMode] = useState<'quick' | 'custom'>('quick');
const [allStates, setAllStates] = useState<EmulatorState[]>([]);
const [selected, setSelected] = useState<Set<string>>(new Set(QUICK_PICK_IDS));
const [jobs, setJobs] = useState<InstallJob[]>([]);
const [currentIdx, setCurrentIdx] = useState(0);
const [loading, setLoading] = useState(true);
const handleClose = async () => {
await window.omni.settings.save({ firstSetupComplete: true });
onClose();
};
const load = useCallback(async () => {
setLoading(true);
const states = await window.omni.emulators.states();
setAllStates(states);
setLoading(false);
}, []);
useEffect(() => { load(); }, [load]);
useEffect(() => {
const unsub = window.omni.emulators.onInstallProgress((p: InstallProgress) => {
setJobs(prev => prev.map(j => {
if (j.id === p.emulatorId && j.status === 'installing') {
return { ...j, progress: p.percent, message: p.message };
}
return j;
}));
});
return unsub;
}, []);
const toggleQuickPick = (id: string) => {
setSelected(prev => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const toggleAll = () => {
const installable = allStates
.filter(s => !s.installed && s.config.downloads && Object.keys(s.config.downloads).length > 0)
.map(s => s.config.id);
if (selected.size === installable.length) {
setSelected(new Set());
} else {
setSelected(new Set(installable));
}
};
const startInstall = async () => {
const toInstall = allStates
.filter(s => selected.has(s.config.id) && !s.installed)
.map(s => ({ id: s.config.id, name: s.config.name }));
if (toInstall.length === 0) return;
const initial: InstallJob[] = toInstall.map(t => ({
id: t.id, name: t.name, status: 'queued', progress: 0, message: '',
}));
setJobs(initial);
setView('installing');
setCurrentIdx(0);
for (let i = 0; i < toInstall.length; i++) {
setCurrentIdx(i);
setJobs(prev => prev.map((j, idx) =>
idx === i ? { ...j, status: 'installing' as const, message: 'Starting...' } : j
));
try {
await window.omni.emulators.install(toInstall[i].id);
setJobs(prev => prev.map((j, idx) =>
idx === i ? { ...j, status: 'done' as const, progress: 100, message: 'Installed' } : j
));
} catch {
setJobs(prev => prev.map((j, idx) =>
idx === i ? { ...j, status: 'error' as const, message: 'Failed' } : j
));
}
}
await load();
};
const installable = allStates.filter(s => !s.installed && s.config.downloads && Object.keys(s.config.downloads).length > 0);
const alreadyInstalled = allStates.filter(s => s.installed);
const notAvailable = allStates.filter(s => !s.installed && (!s.config.downloads || Object.keys(s.config.downloads).length === 0));
if (loading) return <div className="loading">Loading emulators...</div>;
const allDone = view === 'installing' && jobs.every(j => j.status === 'done' || j.status === 'error');
return (
<div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
<h2 style={{ margin: 0 }}>Welcome to OmniEmu</h2>
<button className="btn btn-secondary btn-sm" onClick={handleClose}>Skip for now</button>
</div>
<p className="text-muted" style={{ marginBottom: 24 }}>
Get started by installing the emulators you need. You can always add more later from the Emulators page.
</p>
{alreadyInstalled.length > 0 && (
<div className="info-bar" style={{ marginBottom: 16 }}>
{alreadyInstalled.length} emulator{alreadyInstalled.length !== 1 ? 's' : ''} already installed
</div>
)}
{view === 'pick' && (
<>
{/* Mode selector */}
<div style={{ display: 'flex', gap: 12, marginBottom: 24 }}>
<button
className="btn"
onClick={() => { setMode('quick'); setSelected(new Set(QUICK_PICK_IDS)); }}
style={{
flex: 1, padding: '16px 20px', borderRadius: 12, textAlign: 'left',
border: `2px solid ${mode === 'quick' ? 'var(--accent)' : 'var(--border)'}`,
background: mode === 'quick' ? 'var(--accent-dim)' : 'var(--bg-secondary)',
transition: 'all 0.2s ease',
}}
>
<div style={{ fontSize: 18, fontWeight: 700, marginBottom: 4, color: 'var(--text-primary)' }}>
⚡ Quick Install
</div>
<div style={{ fontSize: 13, color: 'var(--text-muted)' }}>
{QUICK_PICK_IDS.length} essential emulators covering the most popular systems
</div>
</button>
<button
className="btn"
onClick={() => {
setMode('custom');
setSelected(new Set(installable.map(s => s.config.id)));
}}
style={{
flex: 1, padding: '16px 20px', borderRadius: 12, textAlign: 'left',
border: `2px solid ${mode === 'custom' ? 'var(--accent)' : 'var(--border)'}`,
background: mode === 'custom' ? 'var(--accent-dim)' : 'var(--bg-secondary)',
transition: 'all 0.2s ease',
}}
>
<div style={{ fontSize: 18, fontWeight: 700, marginBottom: 4, color: 'var(--text-primary)' }}>
🎛️ Custom Install
</div>
<div style={{ fontSize: 13, color: 'var(--text-muted)' }}>
Pick exactly which emulators to install
</div>
</button>
</div>
{/* Quick Install — curated grid */}
{mode === 'quick' && (
<div style={{ marginBottom: 24 }}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 10 }}>
{QUICK_PICK_IDS.map(id => {
const state = allStates.find(s => s.config.id === id);
if (!state) return null;
const info = QUICK_PICK_INFO[id];
const checked = selected.has(id);
const alreadyDone = state.installed;
return (
<div
key={id}
onClick={() => !alreadyDone && toggleQuickPick(id)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '12px 14px', borderRadius: 10, cursor: alreadyDone ? 'default' : 'pointer',
border: `1px solid ${alreadyDone ? 'var(--success)' : checked ? 'var(--accent)' : 'var(--border)'}`,
background: alreadyDone ? 'var(--bg-tertiary)' : checked ? 'var(--accent-dim)' : 'var(--bg-secondary)',
opacity: alreadyDone ? 0.6 : 1,
transition: 'all 0.15s ease',
}}
>
<div style={{
width: 22, height: 22, borderRadius: 6, display: 'flex', alignItems: 'center',
justifyContent: 'center', fontSize: 13, fontWeight: 700, flexShrink: 0,
border: `2px solid ${alreadyDone ? 'var(--success)' : checked ? 'var(--accent)' : 'var(--border)'}`,
background: alreadyDone ? 'var(--success)' : checked ? 'var(--accent)' : 'transparent',
color: alreadyDone || checked ? '#fff' : 'transparent',
transition: 'all 0.15s ease',
}}>
{alreadyDone ? '✓' : checked ? '✓' : ''}
</div>
<span style={{ fontSize: 20 }}>{info?.icon || '🎮'}</span>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 13, color: 'var(--text-primary)' }}>
{state.config.name}
{alreadyDone && <span style={{ color: 'var(--success)', marginLeft: 6, fontSize: 11 }}>Installed</span>}
</div>
<div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
{info?.systems || state.config.platforms.join(', ')}
</div>
</div>
</div>
);
})}
</div>
</div>
)}
{/* Custom Install — full list */}
{mode === 'custom' && (
<div style={{ marginBottom: 24 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
<span style={{ fontSize: 13, color: 'var(--text-muted)' }}>
{selected.size} of {installable.length} selected
</span>
<button className="btn btn-secondary btn-sm" onClick={toggleAll}>
{selected.size === installable.length ? 'Deselect All' : 'Select All'}
</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{installable.map(state => {
const checked = selected.has(state.config.id);
return (
<div
key={state.config.id}
onClick={() => toggleQuickPick(state.config.id)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '10px 14px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${checked ? 'var(--accent)' : 'var(--border)'}`,
background: checked ? 'var(--accent-dim)' : 'var(--bg-secondary)',
transition: 'all 0.15s ease',
}}
>
<div style={{
width: 20, height: 20, borderRadius: 5, display: 'flex', alignItems: 'center',
justifyContent: 'center', fontSize: 12, fontWeight: 700, flexShrink: 0,
border: `2px solid ${checked ? 'var(--accent)' : 'var(--border)'}`,
background: checked ? 'var(--accent)' : 'transparent',
color: checked ? '#fff' : 'transparent',
transition: 'all 0.15s ease',
}}>
✓
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 13, color: 'var(--text-primary)' }}>{state.config.name}</div>
<div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
{state.config.platforms.join(', ')}
</div>
</div>
</div>
);
})}
</div>
{notAvailable.length > 0 && (
<div style={{ marginTop: 16 }}>
<div style={{ fontSize: 13, color: 'var(--text-muted)', marginBottom: 6, fontWeight: 600 }}>
Not available on this platform
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
{notAvailable.map(s => (
<span key={s.config.id} style={{
padding: '4px 10px', borderRadius: 6, fontSize: 11,
background: 'var(--bg-tertiary)', color: 'var(--text-muted)',
}}>
{s.config.name}
</span>
))}
</div>
</div>
)}
</div>
)}
{/* Install button */}
{selected.size > 0 && (
<button
className="btn btn-primary"
onClick={startInstall}
style={{ fontSize: 16, padding: '14px 32px', width: '100%' }}
>
Install {selected.size} Emulator{selected.size !== 1 ? 's' : ''}
</button>
)}
</>
)}
{/* Installing view */}
{view === 'installing' && (
<div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 24 }}>
{jobs.map((job, i) => (
<div key={job.id} style={{
padding: '10px 14px', borderRadius: 8,
border: `1px solid ${
job.status === 'done' ? 'var(--success)'
: job.status === 'error' ? 'var(--error)'
: job.status === 'installing' ? 'var(--accent)'
: 'var(--border)'
}`,
background: job.status === 'done'
? 'var(--bg-tertiary)'
: job.status === 'error'
? 'var(--bg-tertiary)'
: job.status === 'installing'
? 'var(--accent-dim)'
: 'var(--bg-secondary)',
transition: 'all 0.2s ease',
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: job.status === 'installing' ? 8 : 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{
width: 22, height: 22, borderRadius: '50%', display: 'flex', alignItems: 'center',
justifyContent: 'center', fontSize: 11, fontWeight: 700, flexShrink: 0,
background: job.status === 'done' ? 'var(--success)'
: job.status === 'error' ? 'var(--error)'
: job.status === 'installing' ? 'var(--accent)'
: 'var(--bg-tertiary)',
color: job.status === 'queued' ? 'var(--text-muted)' : '#fff',
}}>
{job.status === 'done' ? '✓' : job.status === 'error' ? '✗' : i + 1}
</span>
<span style={{ fontWeight: 600, fontSize: 13, color: 'var(--text-primary)' }}>{job.name}</span>
</div>
<span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
{job.status === 'done' ? 'Done' : job.status === 'error' ? 'Failed' : job.status === 'installing' ? `${job.progress}%` : 'Waiting...'}
</span>
</div>
{job.status === 'installing' && (
<div style={{ height: 4, borderRadius: 2, background: 'var(--bg-tertiary)', overflow: 'hidden' }}>
<div style={{
height: '100%', borderRadius: 2, width: `${job.progress}%`,
background: 'var(--accent-gradient)',
transition: 'width 0.3s ease',
}} />
</div>
)}
{job.status === 'installing' && job.message && (
<div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 4 }}>{job.message}</div>
)}
</div>
))}
</div>
{allDone && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div className="info-bar" style={{ textAlign: 'center' }}>
{jobs.filter(j => j.status === 'done').length} installed
{jobs.filter(j => j.status === 'error').length > 0 && ` · ${jobs.filter(j => j.status === 'error').length} failed`}
</div>
<button
className="btn btn-primary"
onClick={handleClose}
style={{ width: '100%' }}
>
Done
</button>
</div>
)}
</div>
)}
</div>
);
}
+18
View File
@@ -420,6 +420,24 @@ export function SettingsPage() {
Built with Electron + React + TypeScript
</p>
</div>
<div className="settings-section" style={{ borderColor: 'var(--error)' }}>
<h3 style={{ color: 'var(--error)' }}>Danger Zone</h3>
<p className="text-sm text-muted" style={{ marginBottom: 12 }}>
Delete all installed emulators, downloaded data, Syncthing config, and reset settings to defaults. Your ROMs will not be affected.
</p>
<button
className="btn btn-danger"
onClick={async () => {
if (!confirm('This will delete all emulators, settings, and app data. Your ROMs are safe. Continue?')) return;
if (!confirm('Are you really sure? This cannot be undone.')) return;
await window.omni.app.nukeData();
window.location.reload();
}}
>
Wipe All Data
</button>
</div>
</div>
);
}
+186
View File
@@ -1,5 +1,11 @@
import React, { useState, useEffect } from 'react';
interface FilterPreset {
id: string;
name: string;
description: string;
}
export function UtilitiesPage() {
const [regenerating, setRegenerating] = useState(false);
const [raUsername, setRaUsername] = useState('');
@@ -9,6 +15,15 @@ export function UtilitiesPage() {
const [saving, setSaving] = useState(false);
const [sgdbKey, setSgdbKey] = useState('');
const [sgdbSaved, setSgdbSaved] = useState(false);
const [autoApplying, setAutoApplying] = useState(false);
const [autoApplyProgress, setAutoApplyProgress] = useState<{ current: number; total: number; title: string } | null>(null);
const [autoApplyResult, setAutoApplyResult] = useState<{ total: number; alreadyHadCover: number; applied: number; failed: number; skippedNoKey?: boolean } | null>(null);
const [clearingCovers, setClearingCovers] = useState(false);
const [filterPresets, setFilterPresets] = useState<FilterPreset[]>([]);
const [applyingFilter, setApplyingFilter] = useState<string | null>(null);
const [filterResult, setFilterResult] = useState<{ message: string; ok: boolean } | null>(null);
const [applyingAll, setApplyingAll] = useState(false);
const [applyAllResult, setApplyAllResult] = useState<string | null>(null);
useEffect(() => {
window.omni.settings.get().then((s) => {
@@ -17,6 +32,7 @@ export function UtilitiesPage() {
setRaApiKey(s.retroAchievementsApiKey || '');
setSgdbKey(s.steamGridDbApiKey || '');
});
window.omni.filters.list().then(setFilterPresets);
}, []);
const handleRecreate = async () => {
@@ -25,6 +41,50 @@ export function UtilitiesPage() {
setTimeout(() => setRegenerating(false), 1500);
};
const handleAutoApply = async () => {
setAutoApplying(true);
setAutoApplyResult(null);
setAutoApplyProgress(null);
const unsub = window.omni.game.onAutoApplyCoversProgress((p) => {
setAutoApplyProgress(p);
});
try {
const result = await window.omni.game.autoApplyCovers();
setAutoApplyResult(result);
} catch {
setAutoApplyResult(null);
}
unsub();
setAutoApplying(false);
setAutoApplyProgress(null);
};
const handleApplyFilter = async (presetId: string) => {
setApplyingFilter(presetId);
setFilterResult(null);
try {
const result = await window.omni.filters.apply(presetId);
setFilterResult({ message: result.message, ok: result.success });
} catch {
setFilterResult({ message: 'Failed to apply filter', ok: false });
}
setTimeout(() => { setApplyingFilter(null); setFilterResult(null); }, 2500);
};
const handleApplyAll = async () => {
setApplyingAll(true);
setApplyAllResult(null);
try {
const results = await window.omni.emulators.applyRecommendedAll(true);
const ok = results.filter(r => r.ok).length;
const fail = results.length - ok;
setApplyAllResult(fail === 0 ? `Applied to ${ok} emulator${ok !== 1 ? 's' : ''} (fullscreen enabled)` : `Applied to ${ok}, failed on ${fail}`);
} catch {
setApplyAllResult('Failed to apply settings');
}
setTimeout(() => { setApplyingAll(false); setApplyAllResult(null); }, 3000);
};
const handleRaSave = async () => {
setSaving(true);
setRaResults(null);
@@ -197,6 +257,132 @@ export function UtilitiesPage() {
</button>
</div>
</div>
<div className="settings-section">
<h3>Auto Apply Covers</h3>
<p className="text-sm text-muted" style={{ marginBottom: 12 }}>
Automatically search SteamGridDB for every ROM in your library that
doesn't have cover art and download the first match. Requires a
SteamGridDB API key above.
</p>
<div className="setting-row">
<div>
{autoApplyProgress && (
<div className="setting-desc">
{autoApplyProgress.title} ({autoApplyProgress.current}/{autoApplyProgress.total})
</div>
)}
</div>
<button
className="btn btn-secondary btn-sm"
disabled={autoApplying || !sgdbKey}
onClick={handleAutoApply}
>
{autoApplying ? 'Running...' : 'Auto Apply Covers'}
</button>
</div>
{autoApplyResult && (
<div style={{ fontSize: 13, marginTop: 8 }}>
{autoApplyResult.skippedNoKey ? (
<span style={{ color: 'var(--error)' }}>No SteamGridDB API key set</span>
) : (
<>
<span style={{ color: 'var(--muted)', marginRight: 10 }}>{autoApplyResult.total} ROMs scanned</span>
<span style={{ color: 'var(--muted)', marginRight: 10 }}>{autoApplyResult.alreadyHadCover} already had covers</span>
<span style={{ color: 'var(--success)', marginRight: 10 }}>{autoApplyResult.applied} applied</span>
{autoApplyResult.failed > 0 && (
<span style={{ color: 'var(--error)' }}>{autoApplyResult.failed} failed</span>
)}
</>
)}
</div>
)}
</div>
<div className="settings-section">
<h3>Recommended Filters</h3>
<p className="text-sm text-muted" style={{ marginBottom: 12 }}>
Apply video filters and shaders to RetroArch. CRT shaders are
downloaded from the libretro shader repository on first use.
</p>
{filterPresets.map((preset) => (
<div className="setting-row" key={preset.id}>
<div>
<div className="setting-label">{preset.name}</div>
<div className="setting-desc">{preset.description}</div>
</div>
<button
className="btn btn-secondary btn-sm"
disabled={applyingFilter !== null}
onClick={() => handleApplyFilter(preset.id)}
>
{applyingFilter === preset.id ? 'Applied!' : 'Apply'}
</button>
</div>
))}
{filterResult && (
<div style={{ fontSize: 13, marginTop: 8, color: filterResult.ok ? 'var(--success)' : 'var(--error)' }}>
{filterResult.message}
</div>
)}
</div>
<div className="settings-section">
<h3>Apply Recommended Settings</h3>
<p className="text-sm text-muted" style={{ marginBottom: 12 }}>
Apply the recommended configuration preset to every installed emulator
at once with fullscreen enabled. This writes optimal defaults for
video, audio, and input.
</p>
<div className="setting-row">
<div />
<button
className="btn btn-primary btn-sm"
disabled={applyingAll}
onClick={handleApplyAll}
>
{applyingAll ? 'Applying...' : 'Apply to All Emulators'}
</button>
</div>
{applyAllResult && (
<div style={{ fontSize: 13, marginTop: 8, color: 'var(--success)' }}>
{applyAllResult}
</div>
)}
</div>
<div className="settings-section">
<h3 style={{ color: 'var(--error)' }}>Danger Zone</h3>
<div className="setting-row">
<div>
<div className="setting-label">Clear game covers</div>
<div className="setting-desc">
Remove all downloaded cover art. Covers will be re-fetched from
SteamGridDB or libretro-thumbnails when you re-scrape.
</div>
</div>
<button
className="btn btn-sm"
style={{ background: 'var(--error)', color: '#fff' }}
disabled={clearingCovers}
onClick={async () => {
if (!window.confirm('Are you sure you want to clear all game covers? This cannot be undone.')) return;
setClearingCovers(true);
await window.omni.game.clearCoverCache();
setTimeout(() => setClearingCovers(false), 1500);
}}
>
{clearingCovers ? 'Cleared!' : 'Clear Covers'}
</button>
</div>
</div>
</div>
);
}
+11
View File
@@ -36,6 +36,7 @@ declare global {
configured: (id: string, installPath?: string) => Promise<boolean>;
openWebsite: (id: string) => Promise<boolean>;
updateControllerConfig: (id: string, installPath: string, controllerName?: string) => Promise<boolean>;
applyRecommendedAll: (fullscreen: boolean) => Promise<{ id: string; ok: boolean }[]>;
onInstallProgress: (cb: (p: InstallProgress) => void) => () => void;
};
decomps: {
@@ -59,9 +60,12 @@ declare global {
clearRecent: () => Promise<boolean>;
scrapeArt: (title: string, platform: string) => Promise<string | undefined>;
cacheCovers: (entries: { romPath: string; coverUrl: string }[]) => Promise<boolean>;
clearCoverCache: () => Promise<boolean>;
searchCoverSGDB: (title: string, platform: string) => Promise<any[]>;
scrapeMetadata: (romPath: string, title: string, platform: string) => Promise<GameMetadata>;
achievements: (romPath: string, title: string, platform: string) => Promise<AchievementInfo | null>;
autoApplyCovers: () => Promise<{ total: number; alreadyHadCover: number; applied: number; failed: number; skippedNoKey?: boolean }>;
onAutoApplyCoversProgress: (cb: (progress: { current: number; total: number; title: string }) => void) => () => void;
};
bios: {
listKnown: () => Promise<any[]>;
@@ -92,6 +96,10 @@ declare global {
retroachievements: {
save: (username: string, password: string) => Promise<Record<string, boolean>>;
};
filters: {
list: () => Promise<{ id: string; name: string; description: string }[]>;
apply: (presetId: string) => Promise<{ success: boolean; message: string; appliedPreset: string }>;
};
updates: {
check: () => Promise<boolean>;
download: () => Promise<boolean>;
@@ -118,6 +126,9 @@ declare global {
toggleFolderSync: (emuId: string, sync: boolean) => Promise<boolean>;
onInstallProgress: (cb: (progress: { stage: string; percent: number; message: string }) => void) => () => void;
};
app: {
nukeData: () => Promise<boolean>;
};
};
}
}
+4
View File
@@ -127,6 +127,10 @@ export interface AppSettings {
syncthingPort?: number;
/** Cloud sync enabled (Syncthing installed and configured) */
cloudSyncEnabled?: boolean;
/** Cloud sync initial setup completed (hides step counter on revisit) */
cloudSyncSetupComplete?: boolean;
/** First-time setup completed (hides the initial installer overlay) */
firstSetupComplete?: boolean;
}
export interface RetroAchievement {