mirror of
https://github.com/mileswolfallen2/OmniEmu2.0.git
synced 2026-12-04 07:47:45 +00:00
feat: enhance emulator configuration and controller support
- Refactored built-in presets in configurator.ts to improve organization and added new configurations for various emulators. - Implemented caching for scraped cover URLs in scraper.ts and added functionality to apply cached covers to game entries. - Updated IPC handlers in ipc.ts to support caching of cover URLs. - Enhanced gamepad navigation in useGamepadNav.ts for better user experience with controller inputs. - Improved controller detection and button labeling in ControllerPage.tsx to support PlayStation, Xbox, and Switch controllers. - Added accessibility features to game cards in Dashboard.tsx and LibraryPage.tsx for keyboard navigation. - Introduced a new presets.json file with recommended configurations for various emulators. - Updated styles.css to enhance focus visibility for keyboard and controller navigation.
This commit is contained in:
1 parent
9a3002010d
commit
bd8b83a02f
11 files changed
+477
-158
No files matched your search
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"dolphin": [
|
||||
{
|
||||
"name": "OmniEmu Recommended",
|
||||
"description": "Best balance of performance and quality for most systems",
|
||||
"files": {
|
||||
"Config/Dolphin.ini": "[General]\nLastFilename =\nShowLag = False\nShowRenderTimes = False\n[Display]\nFullscreenDisplayRes = Auto\nFullscreen = True\nRenderToMain = True\n[Interface]\nConfirmStop = False\nPauseOnFocusLost = False\n[Core]\nCPUCore = 3\nFastmem = True\nMMU = False\n[Enhancements]\nInternalResolution = 3\nMaxAnisotropy = 4\n[Android]\nSIDevice0 = 6\nAdapterRumble0 = True\n",
|
||||
"Config/GFX.ini": "[Settings]\nBackend = Vulkan\nShaderCompilationMode = 2\nWaitForShadersBeforeStarting = True\nHiresTextures = False\nCacheHiresTextures = True\n[Enhancements]\nForceFiltering = False\nWidescreenHack = True\n"
|
||||
}
|
||||
}
|
||||
],
|
||||
"rpcs3": [
|
||||
{
|
||||
"name": "OmniEmu Recommended",
|
||||
"description": "Optimized settings for RPCS3 with Vulkan backend",
|
||||
"files": {
|
||||
"config.yml": "Video:\n Format: Vulkan\n FrameLimit: Auto\n Resolution: 1920x1080\n AntiAliasing: Disabled\n RenderScale: 100\nAudio:\n Format: XAudio2\n Device: Default\nInput:\n PadHandler: DualShock4\n MouseHandler: Basic\nCPU:\n PPUDecoder: LLVM\n SPUDecoder: ASMJIT\n ThreadScheduler: OS\n"
|
||||
}
|
||||
}
|
||||
],
|
||||
"eden": [
|
||||
{
|
||||
"name": "OmniEmu Recommended",
|
||||
"description": "Best settings for Eden Switch emulation",
|
||||
"files": {
|
||||
"Config.json": "{\n \"graphics_backend\": \"Vulkan\",\n \"resolution_scale\": 2,\n \"docked_mode\": true,\n \"anisotropy_filtering\": 4,\n \"aspect_ratio\": \"16:9\",\n \"enable_vsync\": true,\n \"shader_cache\": true,\n \"audio_backend\": \"OpenAL\",\n \"controller\": \"SDL\"\n}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"pcsx2": [
|
||||
{
|
||||
"name": "OmniEmu Recommended",
|
||||
"description": "Optimal PCSX2 configuration for modern hardware",
|
||||
"files": {
|
||||
"inis/PCSX2.ini": "[Filenames]\n[Settings]\nUserMode = 0\nEnableVSync = 1\n[EmuCore]\nGSRenderer = 13\nEnableCheats = 0\nEnableWideScreenPatches = 1\n[GS]\nRenderer = Vulkan\nUpscaleMultiplier = 3\nBilinearFilter = 1\nTrilinearFilter = 1\n[Pad]\nMultitapPort0_Enabled = false\nMultitapPort1_Enabled = false\nPad1 = SDL\n"
|
||||
}
|
||||
}
|
||||
],
|
||||
"retroarch": [
|
||||
{
|
||||
"name": "OmniEmu Recommended",
|
||||
"description": "Universal RetroArch config with optimal defaults",
|
||||
"files": {
|
||||
"retroarch.cfg": "video_driver = \"vulkan\"\naudio_driver = \"pulseaudio\"\nvideo_fullscreen = true\nvideo_vsync = true\nvideo_scale_integer = false\nvideo_smooth = true\naudio_sync = true\nsavestate_thumbnail_enable = true\nnotification_show_autoconfig = false\ninput_autodetect_enable = \"true\"\ninput_player1_joypad_index = \"0\"\n"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "OmniEmu Performance",
|
||||
"description": "Performance-focused RetroArch config",
|
||||
"files": {
|
||||
"retroarch.cfg": "video_driver = \"vulkan\"\naudio_driver = \"pulseaudio\"\nvideo_fullscreen = true\nvideo_threaded = true\nvideo_vsync = false\nvideo_max_swapchain_images = 2\nvideo_scale_integer = false\nvideo_smooth = false\naudio_sync = false\naudio_rate_control = false\nrewind_enable = false\nsavestate_auto_load = false\nsavestate_auto_save = false\ninput_autodetect_enable = \"true\"\ninput_player1_joypad_index = \"0\"\n"
|
||||
}
|
||||
}
|
||||
],
|
||||
"mame": [
|
||||
{
|
||||
"name": "OmniEmu Recommended",
|
||||
"description": "MAME optimized settings",
|
||||
"files": {
|
||||
"mame.ini": "#\n# OmniEmu Recommended MAME Config\n#\nvideo auto\nscreen auto\naspect 4:3\neffect none\nwaitvsync 1\nsyncrefresh 0\nsleep 0\nautosave 0\njoystick 1\nkeyboard 0\n"
|
||||
}
|
||||
}
|
||||
],
|
||||
"duckstation": [
|
||||
{
|
||||
"name": "OmniEmu Recommended",
|
||||
"description": "Optimal DuckStation settings for PS1 emulation",
|
||||
"files": {
|
||||
"settings.ini": "[General]\nUserMode = 0\nStartFullscreen = True\n[Display]\nRenderToMain = True\nFullscreen = True\nVSync = True\n[GPU]\nRenderer = Vulkan\nResolutionScale = 3\nMultisamples = 1\nPGXPEnable = True\nPGXPCulling = True\nWidescreenHack = True\n[Input]\nControllerBackend = SDL\n[ControllerPort0]\nMultitapPort1 = false\n"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+133
-25
@@ -1,4 +1,4 @@
|
||||
import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync } from 'fs';
|
||||
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
|
||||
import { join, dirname } from 'path';
|
||||
import { app } from 'electron';
|
||||
import { ConfigPreset, InstallProgress, Platform } from '../shared/types';
|
||||
@@ -6,11 +6,8 @@ import { getPlatform, isWindows, isMacOS } from './platform';
|
||||
|
||||
const platform = getPlatform();
|
||||
|
||||
/**
|
||||
* Built-in recommended presets for each emulator.
|
||||
* These are known-good configs curated by the EmuDeck community and
|
||||
* adapted for OmniEmu. They set optimal performance/quality balances.
|
||||
*/
|
||||
// ---- Built-in presets ----
|
||||
|
||||
const builtInPresets: Record<string, ConfigPreset[]> = {
|
||||
dolphin: [
|
||||
{
|
||||
@@ -35,6 +32,9 @@ MMU = False
|
||||
[Enhancements]
|
||||
InternalResolution = 3
|
||||
MaxAnisotropy = 4
|
||||
[Android]
|
||||
SIDevice0 = 6
|
||||
AdapterRumble0 = True
|
||||
`,
|
||||
'Config/GFX.ini': `[Settings]
|
||||
Backend = Vulkan
|
||||
@@ -87,7 +87,8 @@ CPU:
|
||||
"aspect_ratio": "16:9",
|
||||
"enable_vsync": true,
|
||||
"shader_cache": true,
|
||||
"audio_backend": "OpenAL"
|
||||
"audio_backend": "OpenAL",
|
||||
"controller": "SDL"
|
||||
}`,
|
||||
},
|
||||
},
|
||||
@@ -110,6 +111,10 @@ Renderer = Vulkan
|
||||
UpscaleMultiplier = 3
|
||||
BilinearFilter = 1
|
||||
TrilinearFilter = 1
|
||||
[Pad]
|
||||
MultitapPort0_Enabled = false
|
||||
MultitapPort1_Enabled = false
|
||||
Pad1 = SDL
|
||||
`,
|
||||
},
|
||||
},
|
||||
@@ -121,7 +126,6 @@ TrilinearFilter = 1
|
||||
files: {
|
||||
'retroarch.cfg': `video_driver = "vulkan"
|
||||
audio_driver = "pulseaudio"
|
||||
input_driver = "udev"
|
||||
video_fullscreen = true
|
||||
video_vsync = true
|
||||
video_scale_integer = false
|
||||
@@ -129,6 +133,30 @@ video_smooth = true
|
||||
audio_sync = true
|
||||
savestate_thumbnail_enable = true
|
||||
notification_show_autoconfig = false
|
||||
input_autodetect_enable = "true"
|
||||
input_player1_joypad_index = "0"
|
||||
`,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'OmniEmu Performance',
|
||||
description: 'Performance-focused RetroArch config',
|
||||
files: {
|
||||
'retroarch.cfg': `video_driver = "vulkan"
|
||||
audio_driver = "pulseaudio"
|
||||
video_fullscreen = true
|
||||
video_threaded = true
|
||||
video_vsync = false
|
||||
video_max_swapchain_images = 2
|
||||
video_scale_integer = false
|
||||
video_smooth = false
|
||||
audio_sync = false
|
||||
audio_rate_control = false
|
||||
rewind_enable = false
|
||||
savestate_auto_load = false
|
||||
savestate_auto_save = false
|
||||
input_autodetect_enable = "true"
|
||||
input_player1_joypad_index = "0"
|
||||
`,
|
||||
},
|
||||
},
|
||||
@@ -149,6 +177,8 @@ waitvsync 1
|
||||
syncrefresh 0
|
||||
sleep 0
|
||||
autosave 0
|
||||
joystick 1
|
||||
keyboard 0
|
||||
`,
|
||||
},
|
||||
},
|
||||
@@ -172,20 +202,28 @@ Multisamples = 1
|
||||
PGXPEnable = True
|
||||
PGXPCulling = True
|
||||
WidescreenHack = True
|
||||
[Input]
|
||||
ControllerBackend = SDL
|
||||
[ControllerPort0]
|
||||
MultitapPort1 = false
|
||||
`,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// ---- Remote presets URL ----
|
||||
|
||||
const presetSourceUrl = 'https://raw.githubusercontent.com/mileswolfallen2/omniemu-presets/main/presets.json';
|
||||
|
||||
/** Fetch remote presets, falling back to built-in */
|
||||
async function fetchRemotePresets(): Promise<Record<string, ConfigPreset[]> | null> {
|
||||
try {
|
||||
const { get } = await import('https');
|
||||
const data = await new Promise<string>((resolve, reject) => {
|
||||
get(presetSourceUrl, (res) => {
|
||||
get(presetSourceUrl, {
|
||||
headers: { 'User-Agent': 'OmniEmu/0.1.0' },
|
||||
timeout: 10000,
|
||||
}, (res) => {
|
||||
if (res.statusCode !== 200) { reject(new Error(`HTTP ${res.statusCode}`)); return; }
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (c: Buffer) => chunks.push(c));
|
||||
@@ -198,18 +236,44 @@ async function fetchRemotePresets(): Promise<Record<string, ConfigPreset[]> | nu
|
||||
}
|
||||
}
|
||||
|
||||
/** Load presets from a local file in userData (user can drop their own presets.json there) */
|
||||
function loadLocalPresets(): Record<string, ConfigPreset[]> | null {
|
||||
const localPath = join(app.getPath('userData'), 'presets.json');
|
||||
try {
|
||||
return JSON.parse(readFileSync(localPath, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isPSController(name?: string): boolean {
|
||||
if (!name) return false;
|
||||
const l = name.toLowerCase();
|
||||
return l.includes('dualsense') || l.includes('dualshock') || l.includes('sony')
|
||||
|| l.includes('ps4') || l.includes('ps5') || l.includes('playstation');
|
||||
}
|
||||
|
||||
function isXboxController(name?: string): boolean {
|
||||
if (!name) return false;
|
||||
const l = name.toLowerCase();
|
||||
return l.includes('xbox') || l.includes('x-input') || l.includes('microsoft');
|
||||
}
|
||||
|
||||
// ---- Exported API ----
|
||||
|
||||
export function getBuiltInPresets(): Record<string, ConfigPreset[]> {
|
||||
return builtInPresets;
|
||||
}
|
||||
|
||||
export async function getPresets(emulatorId: string): Promise<ConfigPreset[]> {
|
||||
// Try remote first, fall back to built-in
|
||||
// Priority: remote > local file > built-in
|
||||
const remote = await fetchRemotePresets();
|
||||
if (remote && remote[emulatorId]) return remote[emulatorId];
|
||||
const local = loadLocalPresets();
|
||||
if (local && local[emulatorId]) return local[emulatorId];
|
||||
return builtInPresets[emulatorId] || [];
|
||||
}
|
||||
|
||||
/** Get the config directory for an emulator given its install path */
|
||||
function getConfigDir(emulatorId: string, installPath: string): string {
|
||||
const platformDirs: Record<string, Record<string, string>> = {
|
||||
dolphin: {
|
||||
@@ -251,14 +315,12 @@ function getConfigDir(emulatorId: string, installPath: string): string {
|
||||
return platformDirs[emulatorId]?.[platform] || dirname(installPath);
|
||||
}
|
||||
|
||||
/** Check if an emulator has been configured with OmniEmu presets */
|
||||
export function checkConfigured(emulatorId: string, installPath?: string): boolean {
|
||||
if (!installPath) return false;
|
||||
const marker = join(app.getPath('userData'), 'configs', `${emulatorId}.configured`);
|
||||
return existsSync(marker);
|
||||
}
|
||||
|
||||
/** Apply a config preset to the emulator's config directory */
|
||||
export async function applyPreset(
|
||||
emulatorId: string,
|
||||
preset: ConfigPreset,
|
||||
@@ -289,7 +351,6 @@ export async function applyPreset(
|
||||
report(Math.round((done / totalFiles) * 100), `Wrote ${relativePath}`);
|
||||
}
|
||||
|
||||
// Write marker so we know this emulator was configured
|
||||
const markerDir = join(app.getPath('userData'), 'configs');
|
||||
if (!existsSync(markerDir)) mkdirSync(markerDir, { recursive: true });
|
||||
writeFileSync(join(markerDir, `${emulatorId}.configured`), new Date().toISOString(), 'utf-8');
|
||||
@@ -297,7 +358,6 @@ export async function applyPreset(
|
||||
report(100, `${emulatorId} configured with "${preset.name}"`);
|
||||
}
|
||||
|
||||
/** Apply the recommended preset (first preset available) */
|
||||
export async function applyRecommendedConfig(
|
||||
emulatorId: string,
|
||||
installPath: string,
|
||||
@@ -309,18 +369,20 @@ export async function applyRecommendedConfig(
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Write controller config for a given emulator */
|
||||
/** Write controller config for a given emulator — PS-aware */
|
||||
export function applyControllerConfig(emulatorId: string, installPath: string, controllerName?: string): boolean {
|
||||
const configDir = getConfigDir(emulatorId, installPath);
|
||||
if (!existsSync(configDir)) {
|
||||
mkdirSync(configDir, { recursive: true });
|
||||
}
|
||||
|
||||
const isPS = isPSController(controllerName);
|
||||
const isXbox = isXboxController(controllerName);
|
||||
|
||||
switch (emulatorId) {
|
||||
case 'retroarch': {
|
||||
const cfgPath = join(configDir, 'retroarch.cfg');
|
||||
const existing = existsSync(cfgPath) ? readFileSync(cfgPath, 'utf-8') : '';
|
||||
// Append (or overwrite) controller-specific lines
|
||||
const lines = existing.split('\n').filter(l =>
|
||||
!l.startsWith('input_player1_joypad_index') &&
|
||||
!l.startsWith('input_driver') &&
|
||||
@@ -328,13 +390,40 @@ export function applyControllerConfig(emulatorId: string, installPath: string, c
|
||||
);
|
||||
lines.push('input_player1_joypad_index = "0"');
|
||||
lines.push('input_autodetect_enable = "true"');
|
||||
// Set input driver per platform
|
||||
|
||||
if (isMacOS()) lines.push('input_driver = "hid"');
|
||||
else if (isWindows()) lines.push('input_driver = "dinput"');
|
||||
else lines.push('input_driver = "udev"');
|
||||
|
||||
// PS controller-specific RetroArch bindings
|
||||
if (isPS) {
|
||||
lines.push('input_player1_a_btn = "1"');
|
||||
lines.push('input_player1_b_btn = "2"');
|
||||
lines.push('input_player1_x_btn = "0"');
|
||||
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 = "8"`);
|
||||
lines.push(`input_player1_start_btn = "9"`);
|
||||
} else if (isXbox) {
|
||||
lines.push('input_player1_a_btn = "0"');
|
||||
lines.push('input_player1_b_btn = "1"');
|
||||
lines.push('input_player1_x_btn = "2"');
|
||||
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"`);
|
||||
}
|
||||
|
||||
writeFileSync(cfgPath, lines.join('\n'), 'utf-8');
|
||||
return true;
|
||||
}
|
||||
|
||||
case 'duckstation': {
|
||||
const iniPath = join(configDir, 'settings.ini');
|
||||
const existing = existsSync(iniPath) ? readFileSync(iniPath, 'utf-8') : '';
|
||||
@@ -349,6 +438,7 @@ export function applyControllerConfig(emulatorId: string, installPath: string, c
|
||||
writeFileSync(iniPath, lines.join('\n'), 'utf-8');
|
||||
return true;
|
||||
}
|
||||
|
||||
case 'pcsx2': {
|
||||
const iniPath = join(configDir, 'inis', 'PCSX2.ini');
|
||||
const dir = dirname(iniPath);
|
||||
@@ -360,10 +450,11 @@ export function applyControllerConfig(emulatorId: string, installPath: string, c
|
||||
lines.push('[Pad]');
|
||||
lines.push('MultitapPort0_Enabled = false');
|
||||
lines.push('MultitapPort1_Enabled = false');
|
||||
lines.push('Pad1 = "SDL"');
|
||||
lines.push(isPS ? 'Pad1 = SDL (DualShock4)' : 'Pad1 = SDL');
|
||||
writeFileSync(iniPath, lines.join('\n'), 'utf-8');
|
||||
return true;
|
||||
}
|
||||
|
||||
case 'dolphin': {
|
||||
const iniPath = join(configDir, 'Config', 'Dolphin.ini');
|
||||
const dir = dirname(iniPath);
|
||||
@@ -373,16 +464,33 @@ export function applyControllerConfig(emulatorId: string, installPath: string, c
|
||||
!l.startsWith('SIDevice') && !l.startsWith('AdapterRumble')
|
||||
);
|
||||
lines.push('[Android]');
|
||||
lines.push('SIDevice0 = 6');
|
||||
// 6 = Standard controller, 12 = DualShock 4
|
||||
lines.push(isPS ? 'SIDevice0 = 12' : 'SIDevice0 = 6');
|
||||
lines.push('AdapterRumble0 = True');
|
||||
writeFileSync(iniPath, lines.join('\n'), 'utf-8');
|
||||
return true;
|
||||
}
|
||||
case 'eden':
|
||||
case 'rpcs3': {
|
||||
// RPCS3/Eden don't have simple config overrides for controller
|
||||
break;
|
||||
|
||||
case 'eden': {
|
||||
const cfgPath = join(configDir, 'Config.json');
|
||||
let cfg: any = {};
|
||||
if (existsSync(cfgPath)) {
|
||||
try { cfg = JSON.parse(readFileSync(cfgPath, 'utf-8')); } catch {}
|
||||
}
|
||||
cfg.controller = isPS ? 'DualShock4' : 'SDL';
|
||||
writeFileSync(cfgPath, JSON.stringify(cfg, null, 2), 'utf-8');
|
||||
return true;
|
||||
}
|
||||
|
||||
case 'rpcs3': {
|
||||
const cfgPath = join(configDir, 'config.yml');
|
||||
const existing = existsSync(cfgPath) ? readFileSync(cfgPath, 'utf-8') : '';
|
||||
const lines = existing.split('\n').filter(l => !l.startsWith(' PadHandler:'));
|
||||
lines.push(isPS ? ' PadHandler: DualShock4' : ' PadHandler: SDL');
|
||||
writeFileSync(cfgPath, lines.join('\n'), 'utf-8');
|
||||
return true;
|
||||
}
|
||||
|
||||
case 'mame': {
|
||||
const iniPath = join(configDir, 'mame.ini');
|
||||
const existing = existsSync(iniPath) ? readFileSync(iniPath, 'utf-8') : '';
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from '../shared/types';
|
||||
import { getPlatform, getArch, isWindows, isMacOS, isLinux } from './platform';
|
||||
import { settings } from './settings';
|
||||
import { applyCachedCovers } from './scraper';
|
||||
|
||||
const platform = getPlatform();
|
||||
const arch = getArch();
|
||||
@@ -631,7 +632,7 @@ export function scanRoms(directory: string): GameEntry[] {
|
||||
}
|
||||
|
||||
scanDir(directory);
|
||||
return entries;
|
||||
return applyCachedCovers(entries);
|
||||
}
|
||||
|
||||
function guessPlatform(ext: string): string {
|
||||
|
||||
+7
-1
@@ -18,7 +18,7 @@ import { applyRecommendedConfig, getPresets, checkConfigured, applyControllerCon
|
||||
import { settings } from './settings';
|
||||
import { getSystemInfo, platformName, getPlatform, getArch } from './platform';
|
||||
import { InstallProgress, AppSettings, GameEntry } from '../shared/types';
|
||||
import { addRecentGame, parseGameTitle, buildScrapeTitle, findValidThumbnail } from './scraper';
|
||||
import { addRecentGame, parseGameTitle, buildScrapeTitle, findValidThumbnail, cacheCovers } from './scraper';
|
||||
import { scanBiosDirectory, getKnownBiosList, getDefaultBiosDir, updateRetroarchBiosPath } from './bios';
|
||||
|
||||
export function registerIpcHandlers(): void {
|
||||
@@ -168,6 +168,12 @@ export function registerIpcHandlers(): void {
|
||||
return findValidThumbnail(buildScrapeTitle(title), platform);
|
||||
});
|
||||
|
||||
// Cache scraped cover URLs
|
||||
ipcMain.handle('games:cache-covers', (_event, entries: { romPath: string; coverUrl: string }[]) => {
|
||||
cacheCovers(entries);
|
||||
return true;
|
||||
});
|
||||
|
||||
// Settings
|
||||
ipcMain.handle('settings:get', () => settings.get());
|
||||
ipcMain.handle('settings:save', (_event, s: Partial<AppSettings>) =>
|
||||
|
||||
@@ -75,6 +75,8 @@ const api = {
|
||||
clearRecent: (): Promise<boolean> => ipcRenderer.invoke('games:clear-recent'),
|
||||
scrapeArt: (title: string, platform: string): Promise<string | undefined> =>
|
||||
ipcRenderer.invoke('games:scrape-art', title, platform),
|
||||
cacheCovers: (entries: { romPath: string; coverUrl: string }[]): Promise<boolean> =>
|
||||
ipcRenderer.invoke('games:cache-covers', entries),
|
||||
},
|
||||
|
||||
bios: {
|
||||
|
||||
+75
-20
@@ -1,4 +1,7 @@
|
||||
import { get as httpsGet } from 'https';
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
|
||||
import { join, dirname } from 'path';
|
||||
import { app } from 'electron';
|
||||
import { GameEntry } from '../shared/types';
|
||||
|
||||
/** Clean a filename into a display title */
|
||||
@@ -49,36 +52,32 @@ function safeTitle(title: string): string {
|
||||
return title.replace(/[:]/g, '').replace(/[/\\?*]/g, '_').trim();
|
||||
}
|
||||
|
||||
export function buildThumbnailUrl(title: string, platform: string): string | undefined {
|
||||
const dir = platformThumbDir[platform];
|
||||
if (!dir) return undefined;
|
||||
/** Build a properly URL-encoded thumbnail URL */
|
||||
function buildEncodedUrl(dir: string, subdir: string, title: string): string {
|
||||
const safe = safeTitle(title);
|
||||
return `${thumbBase}/${dir}/Named_Boxarts/${safe}.png`;
|
||||
const raw = `${thumbBase}/${dir}/${subdir}/${safe}.png`;
|
||||
return encodeURI(raw);
|
||||
}
|
||||
|
||||
/** Try multiple URL patterns and return the first that resolves */
|
||||
/** Try multiple URL patterns via GET and return the first valid URL */
|
||||
export async function findValidThumbnail(title: string, platform: string): Promise<string | undefined> {
|
||||
const dir = platformThumbDir[platform];
|
||||
if (!dir) return undefined;
|
||||
|
||||
const urls: string[] = [];
|
||||
const safe = safeTitle(title);
|
||||
// Try with and without region info
|
||||
const regionStripped = title.replace(/\([^)]*\)/g, '').trim();
|
||||
const safeStripped = safeTitle(regionStripped);
|
||||
|
||||
const basePaths = [`${thumbBase}/${dir}`];
|
||||
const subdirs = ['Named_Boxarts', 'Named_Snaps'];
|
||||
const titles = new Set<string>();
|
||||
|
||||
if (safe) titles.add(safe);
|
||||
if (safeStripped && safeStripped !== safe) titles.add(safeStripped);
|
||||
// Try raw title (with region codes)
|
||||
titles.add(safeTitle(title));
|
||||
// Try title without region codes
|
||||
const stripped = title.replace(/\([^)]*\)/g, '').trim();
|
||||
const safeStripped = safeTitle(stripped);
|
||||
if (safeStripped && safeStripped !== safeTitle(title)) titles.add(safeStripped);
|
||||
|
||||
for (const base of basePaths) {
|
||||
for (const sub of subdirs) {
|
||||
for (const t of titles) {
|
||||
urls.push(`${base}/${sub}/${t}.png`);
|
||||
}
|
||||
for (const sub of subdirs) {
|
||||
for (const t of titles) {
|
||||
urls.push(buildEncodedUrl(dir, sub, t));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,14 +92,70 @@ export async function findValidThumbnail(title: string, platform: string): Promi
|
||||
|
||||
function urlExists(url: string): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const req = httpsGet(url, { method: 'HEAD' }, (res) => {
|
||||
const req = httpsGet(url, {
|
||||
method: 'GET',
|
||||
headers: { 'User-Agent': 'OmniEmu/0.1.0' },
|
||||
timeout: 10000,
|
||||
}, (res) => {
|
||||
// GitHub raw returns 200 for existing or redirects to it
|
||||
resolve(res.statusCode === 200);
|
||||
res.resume(); // drain response
|
||||
});
|
||||
req.on('error', () => resolve(false));
|
||||
req.setTimeout(5000, () => { req.destroy(); resolve(false); });
|
||||
req.on('timeout', () => { req.destroy(); resolve(false); });
|
||||
});
|
||||
}
|
||||
|
||||
// --- Scrape Cache ---
|
||||
|
||||
interface ScrapeCache {
|
||||
[key: string]: string; // "romPath" -> "coverUrl"
|
||||
}
|
||||
|
||||
function cachePath(): string {
|
||||
const dir = join(app.getPath('userData'), 'cache');
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
||||
return join(dir, 'scrape-cache.json');
|
||||
}
|
||||
|
||||
function readCache(): ScrapeCache {
|
||||
try {
|
||||
return JSON.parse(readFileSync(cachePath(), 'utf-8'));
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(cache: ScrapeCache): void {
|
||||
try {
|
||||
writeFileSync(cachePath(), JSON.stringify(cache, null, 2), 'utf-8');
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
/** Get cached cover URL for a ROM */
|
||||
export function getCachedCover(romPath: string): string | undefined {
|
||||
return readCache()[romPath];
|
||||
}
|
||||
|
||||
/** Save cover URLs to cache */
|
||||
export function cacheCovers(entries: { romPath: string; coverUrl: string }[]): void {
|
||||
const cache = readCache();
|
||||
for (const e of entries) {
|
||||
if (e.coverUrl) cache[e.romPath] = e.coverUrl;
|
||||
}
|
||||
writeCache(cache);
|
||||
}
|
||||
|
||||
/** Apply cached covers to an array of GameEntry objects (mutates in place) */
|
||||
export function applyCachedCovers(entries: GameEntry[]): GameEntry[] {
|
||||
const cache = readCache();
|
||||
for (const entry of entries) {
|
||||
const cached = cache[entry.romPath];
|
||||
if (cached) entry.coverUrl = cached;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** Track a game launch in the recent games list */
|
||||
export function addRecentGame(games: GameEntry[], game: GameEntry, max: number = 10): GameEntry[] {
|
||||
const updated = [game, ...games.filter(g => g.romPath !== game.romPath)];
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
const DEBOUNCE_MS = 200;
|
||||
const DEBOUNCE_MS = 300;
|
||||
|
||||
type NavDir = 'up' | 'down' | 'left' | 'right';
|
||||
const SIDEBAR_SELECTOR = '.nav-item';
|
||||
|
||||
export function useGamepadNav() {
|
||||
const lastInput = useRef<Record<string, number>>({});
|
||||
const lastTime = useRef<Record<string, number>>({});
|
||||
|
||||
useEffect(() => {
|
||||
let raf = 0;
|
||||
@@ -17,76 +17,69 @@ export function useGamepadNav() {
|
||||
for (const gp of gamepads) {
|
||||
if (!gp || !gp.connected) continue;
|
||||
|
||||
// D-Pad buttons (indices 12-15)
|
||||
const dpadUp = gp.buttons[12]?.pressed;
|
||||
const dpadDown = gp.buttons[13]?.pressed;
|
||||
const dpadLeft = gp.buttons[14]?.pressed;
|
||||
const dpadRight = gp.buttons[15]?.pressed;
|
||||
const debounced = (key: string): boolean => {
|
||||
if (now - (lastTime.current[key] || 0) < DEBOUNCE_MS) return false;
|
||||
lastTime.current[key] = now;
|
||||
return true;
|
||||
};
|
||||
|
||||
// Left stick axes (indices 0, 1)
|
||||
const axisX = gp.axes[0] || 0;
|
||||
const axisY = gp.axes[1] || 0;
|
||||
// D-Pad buttons (12-15) and left stick
|
||||
const dpadUp = gp.buttons[12]?.pressed || gp.axes[1] < -0.6;
|
||||
const dpadDown = gp.buttons[13]?.pressed || gp.axes[1] > 0.6;
|
||||
const dpadLeft = gp.buttons[14]?.pressed || gp.axes[0] < -0.6;
|
||||
const dpadRight = gp.buttons[15]?.pressed || gp.axes[0] > 0.6;
|
||||
|
||||
const threshold = 0.5;
|
||||
|
||||
const dirs: NavDir[] = [];
|
||||
if (dpadUp) dirs.push('up');
|
||||
if (dpadDown) dirs.push('down');
|
||||
if (dpadLeft) dirs.push('left');
|
||||
if (dpadRight) dirs.push('right');
|
||||
|
||||
if (axisY < -threshold) dirs.push('up');
|
||||
if (axisY > threshold) dirs.push('down');
|
||||
if (axisX < -threshold) dirs.push('left');
|
||||
if (axisX > threshold) dirs.push('right');
|
||||
|
||||
for (const dir of dirs) {
|
||||
const key = `dir:${dir}`;
|
||||
if (now - (lastInput.current[key] || 0) < DEBOUNCE_MS) continue;
|
||||
lastInput.current[key] = now;
|
||||
|
||||
const keyMap: Record<NavDir, string> = {
|
||||
up: 'ArrowUp',
|
||||
down: 'ArrowDown',
|
||||
left: 'ArrowLeft',
|
||||
right: 'ArrowRight',
|
||||
};
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
key: keyMap[dir],
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}));
|
||||
// --- Sidebar navigation with Left/Right ---
|
||||
if (dpadLeft && debounced('left')) {
|
||||
cycleSidebar(-1);
|
||||
}
|
||||
if (dpadRight && debounced('right')) {
|
||||
cycleSidebar(1);
|
||||
}
|
||||
|
||||
// A button (0) → Enter
|
||||
if (gp.buttons[0]?.pressed) {
|
||||
if (now - (lastInput.current['a'] || 0) < DEBOUNCE_MS) continue;
|
||||
lastInput.current['a'] = now;
|
||||
// --- Page content navigation with Up/Down (Tab/Shift+Tab) ---
|
||||
if (dpadUp && debounced('up')) {
|
||||
const focused = document.activeElement;
|
||||
if (focused) {
|
||||
focused.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
|
||||
const sidebar = focused?.closest('.sidebar');
|
||||
if (sidebar) {
|
||||
cycleSidebar(-1);
|
||||
} else {
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
key: 'Enter', bubbles: true, cancelable: true,
|
||||
}));
|
||||
// Focus previous focusable element
|
||||
const focusable = getFocusableElements();
|
||||
const idx = focusable.indexOf(focused as HTMLElement);
|
||||
if (idx > 0) focusable[idx - 1]?.focus();
|
||||
}
|
||||
}
|
||||
if (dpadDown && debounced('down')) {
|
||||
const focused = document.activeElement;
|
||||
const sidebar = focused?.closest('.sidebar');
|
||||
if (sidebar) {
|
||||
cycleSidebar(1);
|
||||
} else {
|
||||
const focusable = getFocusableElements();
|
||||
const idx = focusable.indexOf(focused as HTMLElement);
|
||||
if (idx < focusable.length - 1) focusable[idx + 1]?.focus();
|
||||
else focusable[0]?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
// B button (1) → Escape
|
||||
if (gp.buttons[1]?.pressed) {
|
||||
if (now - (lastInput.current['b'] || 0) < DEBOUNCE_MS) continue;
|
||||
lastInput.current['b'] = now;
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
key: 'Escape', bubbles: true, cancelable: true,
|
||||
}));
|
||||
// A button (0) → click
|
||||
if (gp.buttons[0]?.pressed && debounced('a')) {
|
||||
const el = document.activeElement as HTMLElement;
|
||||
if (el) el.click();
|
||||
}
|
||||
|
||||
// Start (9) → Enter on first focusable
|
||||
if (gp.buttons[9]?.pressed) {
|
||||
if (now - (lastInput.current['start'] || 0) < DEBOUNCE_MS) continue;
|
||||
lastInput.current['start'] = now;
|
||||
const firstBtn = document.querySelector<HTMLElement>('button, [tabindex]:not([tabindex="-1"]), a, input');
|
||||
firstBtn?.focus();
|
||||
// B button (1) → focus sidebar (return to nav)
|
||||
if (gp.buttons[1]?.pressed && debounced('b')) {
|
||||
const sideItems = document.querySelectorAll<HTMLElement>(SIDEBAR_SELECTOR);
|
||||
const active = document.querySelector('.nav-item.active') as HTMLElement;
|
||||
(active || sideItems[0])?.focus();
|
||||
}
|
||||
|
||||
// Start (9) → focus first interactive element on page
|
||||
if (gp.buttons[9]?.pressed && debounced('start')) {
|
||||
const all = getFocusableElements();
|
||||
all[0]?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,3 +90,24 @@ export function useGamepadNav() {
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, []);
|
||||
}
|
||||
|
||||
function getFocusableElements(): HTMLElement[] {
|
||||
return Array.from(
|
||||
document.querySelectorAll<HTMLElement>(
|
||||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"]), .game-card, .nav-item'
|
||||
)
|
||||
).filter(el => el.offsetParent !== null); // only visible
|
||||
}
|
||||
|
||||
function cycleSidebar(dir: 1 | -1): void {
|
||||
const items = document.querySelectorAll<HTMLElement>(SIDEBAR_SELECTOR);
|
||||
if (items.length === 0) return;
|
||||
const activeIdx = Array.from(items).findIndex(el =>
|
||||
el.classList.contains('active') || el === document.activeElement
|
||||
);
|
||||
let next = activeIdx + dir;
|
||||
if (next < 0) next = items.length - 1;
|
||||
if (next >= items.length) next = 0;
|
||||
items[next]?.click();
|
||||
items[next]?.focus();
|
||||
}
|
||||
@@ -9,11 +9,42 @@ interface ControllerState {
|
||||
connected: boolean;
|
||||
}
|
||||
|
||||
const buttonLabels = [
|
||||
'A', 'B', 'X', 'Y', 'LB', 'RB', 'LT', 'RT',
|
||||
'Back', 'Start', 'L3', 'R3', 'DPad-Up', 'DPad-Down', 'DPad-Left', 'DPad-Right',
|
||||
'Home',
|
||||
];
|
||||
type ControllerVendor = 'xbox' | 'playstation' | 'switch' | 'generic';
|
||||
|
||||
function detectVendor(id: string): ControllerVendor {
|
||||
const lower = id.toLowerCase();
|
||||
if (lower.includes('ps4') || lower.includes('ps5') || lower.includes('dualsense')
|
||||
|| lower.includes('dualshock') || lower.includes('sony') || lower.includes('wireless controller')
|
||||
|| lower.includes('playstation')) return 'playstation';
|
||||
if (lower.includes('xbox') || lower.includes('xinput') || lower.includes('x-box')
|
||||
|| lower.includes('microsoft')) return 'xbox';
|
||||
if (lower.includes('switch') || lower.includes('pro controller') || lower.includes('nintendo'))
|
||||
return 'switch';
|
||||
return 'generic';
|
||||
}
|
||||
|
||||
const vendorLabels: Record<ControllerVendor, string[]> = {
|
||||
playstation: [
|
||||
'Cross', 'Circle', 'Square', 'Triangle', 'L1', 'R1', 'L2', 'R2',
|
||||
'Share', 'Options', 'L3', 'R3', 'DPad-Up', 'DPad-Down', 'DPad-Left', 'DPad-Right',
|
||||
'PS',
|
||||
],
|
||||
xbox: [
|
||||
'A', 'B', 'X', 'Y', 'LB', 'RB', 'LT', 'RT',
|
||||
'Back', 'Start', 'L3', 'R3', 'DPad-Up', 'DPad-Down', 'DPad-Left', 'DPad-Right',
|
||||
'Home',
|
||||
],
|
||||
switch: [
|
||||
'B', 'A', 'Y', 'X', 'L', 'R', 'ZL', 'ZR',
|
||||
'-', '+', 'L3', 'R3', 'DPad-Up', 'DPad-Down', 'DPad-Left', 'DPad-Right',
|
||||
'Home',
|
||||
],
|
||||
generic: [
|
||||
'A', 'B', 'X', 'Y', 'LB', 'RB', 'LT', 'RT',
|
||||
'Back', 'Start', 'L3', 'R3', 'DPad-Up', 'DPad-Down', 'DPad-Left', 'DPad-Right',
|
||||
'Home',
|
||||
],
|
||||
};
|
||||
|
||||
export function ControllerPage() {
|
||||
const [controllers, setControllers] = useState<ControllerState[]>([]);
|
||||
@@ -95,51 +126,58 @@ export function ControllerPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{controllers.map((ctrl) => (
|
||||
<div key={ctrl.index} className="card mb-4">
|
||||
<div className="card-header">
|
||||
<h3>Controller {ctrl.index + 1}</h3>
|
||||
<span className="badge badge-installed">Connected</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted mb-2">{ctrl.id}</p>
|
||||
{controllers.map((ctrl) => {
|
||||
const vendor = detectVendor(ctrl.id);
|
||||
const labels = vendorLabels[vendor];
|
||||
|
||||
<div className="controller-buttons">
|
||||
{ctrl.buttons.length > 0 && buttonLabels.map((label, i) => {
|
||||
const btn = ctrl.buttons[i];
|
||||
if (!btn) return null;
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className={`controller-btn ${btn.pressed ? 'pressed' : ''}`}
|
||||
>
|
||||
<span className="controller-btn-label">{label}</span>
|
||||
<span className="controller-btn-value">{btn.value.toFixed(2)}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{ctrl.axes.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<p className="text-sm text-muted mb-2">Axes</p>
|
||||
<div className="controller-axes">
|
||||
{ctrl.axes.map((val, i) => (
|
||||
<div key={i} className="axis-bar">
|
||||
<span className="axis-label">Axis {i}</span>
|
||||
<div className="axis-track">
|
||||
<div
|
||||
className="axis-fill"
|
||||
style={{ left: `${((val + 1) / 2) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="axis-value">{val.toFixed(2)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
return (
|
||||
<div key={ctrl.index} className="card mb-4">
|
||||
<div className="card-header">
|
||||
<h3>
|
||||
{vendor === 'playstation' ? '🎮 PlayStation' : vendor === 'xbox' ? '🎮 Xbox' : '🎮 Controller'} {ctrl.index + 1}
|
||||
</h3>
|
||||
<span className="badge badge-installed">Connected</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<p className="text-sm text-muted mb-2">{ctrl.id}</p>
|
||||
|
||||
<div className="controller-buttons">
|
||||
{ctrl.buttons.length > 0 && labels.map((label, i) => {
|
||||
const btn = ctrl.buttons[i];
|
||||
if (!btn) return null;
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className={`controller-btn ${btn.pressed ? 'pressed' : ''}`}
|
||||
>
|
||||
<span className="controller-btn-label">{label}</span>
|
||||
<span className="controller-btn-value">{btn.value.toFixed(2)}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{ctrl.axes.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<p className="text-sm text-muted mb-2">Axes</p>
|
||||
<div className="controller-axes">
|
||||
{ctrl.axes.map((val, i) => (
|
||||
<div key={i} className="axis-bar">
|
||||
<span className="axis-label">Axis {i}</span>
|
||||
<div className="axis-track">
|
||||
<div
|
||||
className="axis-fill"
|
||||
style={{ left: `${((val + 1) / 2) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="axis-value">{val.toFixed(2)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{emulators.length > 0 && (
|
||||
<div>
|
||||
|
||||
@@ -100,6 +100,8 @@ export function Dashboard({ onNavigate }: { onNavigate?: (tab: string) => void }
|
||||
<div
|
||||
key={game.id}
|
||||
className="game-card"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onClick={async () => {
|
||||
await window.omni.game.launch(game.emulatorId, game.romPath);
|
||||
const updated = await window.omni.game.recent();
|
||||
|
||||
@@ -28,13 +28,17 @@ export function LibraryPage() {
|
||||
}, []);
|
||||
|
||||
const scrapeMissingArt = async (list: GameEntry[]): Promise<GameEntry[]> => {
|
||||
return Promise.all(list.map(async (g) => {
|
||||
const updated = await Promise.all(list.map(async (g) => {
|
||||
if (!g.coverUrl) {
|
||||
const url = await window.omni.game.scrapeArt(g.title, g.platform);
|
||||
if (url) g.coverUrl = url;
|
||||
}
|
||||
return g;
|
||||
}));
|
||||
// Persist found covers
|
||||
const toCache = updated.filter(g => g.coverUrl).map(g => ({ romPath: g.romPath, coverUrl: g.coverUrl! }));
|
||||
if (toCache.length > 0) window.omni.game.cacheCovers(toCache);
|
||||
return updated;
|
||||
};
|
||||
|
||||
const scanDirectory = useCallback(async (dir: string) => {
|
||||
@@ -118,6 +122,9 @@ export function LibraryPage() {
|
||||
className="game-card"
|
||||
key={game.id}
|
||||
onClick={() => handleLaunch(game)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') handleLaunch(game); }}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
title={`Launch ${game.title} via ${game.emulatorId}`}
|
||||
>
|
||||
<div className="game-card-cover">
|
||||
|
||||
@@ -6,6 +6,19 @@
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* Focus ring for controller/keyboard navigation */
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--accent) !important;
|
||||
outline-offset: 2px !important;
|
||||
}
|
||||
|
||||
/* Game cards need special treatment since they use div click handlers */
|
||||
.game-card:focus-visible {
|
||||
outline: 2px solid var(--accent) !important;
|
||||
outline-offset: 2px !important;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
:root {
|
||||
--bg-primary: #0f0f1a;
|
||||
--bg-secondary: #1a1a2e;
|
||||
|
||||
Reference in new issue
Block a user