From b317bfec4dfe248a8fd8ea682303eaef884298d9 Mon Sep 17 00:00:00 2001 From: mileswa1q22 Date: Thu, 16 Jul 2026 03:43:37 -0500 Subject: [PATCH] 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. --- LICENSE | 352 +++++++++- README.md | 23 +- src/main/configurator.ts | 151 ++++- src/main/emulators.ts | 178 +++--- src/main/filters.ts | 176 +++++ src/main/index.ts | 112 ++-- src/main/installer.ts | 119 ++-- src/main/ipc.ts | 102 ++- src/main/preload.ts | 25 + src/main/ra.ts | 49 +- src/main/saveManager.ts | 3 +- src/main/scraper.ts | 85 ++- src/main/syncthing.ts | 29 +- src/renderer/App.tsx | 40 +- src/renderer/components/GameDetailModal.tsx | 66 +- src/renderer/pages/CloudSyncPage.tsx | 669 ++++++++++++-------- src/renderer/pages/ControllerPage.tsx | 11 +- src/renderer/pages/InstallerPage.tsx | 398 ++++++++++++ src/renderer/pages/SettingsPage.tsx | 18 + src/renderer/pages/UtilitiesPage.tsx | 186 ++++++ src/renderer/types.ts | 11 + src/shared/types.ts | 4 + 22 files changed, 2271 insertions(+), 536 deletions(-) create mode 100644 src/main/filters.ts create mode 100644 src/renderer/pages/InstallerPage.tsx diff --git a/LICENSE b/LICENSE index 1440b82..d159169 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,339 @@ -MIT License + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 -Copyright (c) 2026 mileswa1q22 + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Preamble -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md index 74f3a63..2313b38 100644 --- a/README.md +++ b/README.md @@ -13,12 +13,19 @@ OmniEmu is a cross-platform emulator manager, game launcher, and ROM library for ## Features -- **One-Click Emulator Setup** — Download, install, and auto-configure 10 emulators from inside the app +- **One-Click Emulator Setup** — Download, install, and auto-configure 20+ emulators from inside the app - **ROM Library** — Scan your ROMs, browse by platform, and launch games directly - **Auto-Update** — Built-in updater keeps OmniEmu current without manual downloads -- **Game Art Scraping** — Automatically fetches covers, screenshots, and titles +- **Game Art Scraping** — Automatically fetches covers, screenshots, and metadata from SteamGridDB and libretro-thumbnails +- **RetroAchievements** — View per-game achievements in the game detail modal (supports RetroArch, PCSX2, DuckStation, Flycast, melonDS, Mednafen) - **Controller Navigation** — Navigate the entire UI with a gamepad (DPad, A, B, Start) +- **Controller Config** — Apply PS/Xbox-aware controller bindings to installed emulators in one click - **BIOS Manager** — Scan your BIOS files and update RetroArch's config in one click +- **Cloud Sync** — Sync save files between devices with built-in Syncthing integration +- **Save Manager** — Browse, back up, and manage save files across all emulators +- **Decomp Projects** — Install and manage PC port projects (Ship of Harkinian, 2 Ship 2 Harkinian, SM64, and more) +- **Video Filters** — Apply CRT shaders and recommended filters to RetroArch +- **Recommended Settings** — One-click optimal config presets for every supported emulator - **Light & Dark Mode** — Choose your theme or follow the system preference - **Cross-Platform** — Identical experience on Windows, macOS, and Linux (x64 & ARM64) @@ -30,12 +37,22 @@ OmniEmu is a cross-platform emulator manager, game launcher, and ROM library for | RPCS3 | PlayStation 3 | ✅ | ✅ | ✅ | | Eden | Nintendo Switch | ✅ | ✅ | ✅ | | PCSX2 | PlayStation 2 | ✅ | ✅ | ✅ | +| DuckStation | PlayStation 1 | ✅ | ✅ | ✅ | +| Mednafen | PS1, PC Engine, Lynx, Neo Geo Pocket, WonderSwan | ✅ | ✅ | ✅ | | MAME | Arcade | ✅ | ✅ | ✅ | | PPSSPP | PSP | ✅ | ✅ | ✅ | -| DuckStation | PlayStation 1 | ✅ | ✅ | ✅ | | melonDS | Nintendo DS | ✅ | ✅ | ✅ | | Flycast | Dreamcast, Naomi, Atomiswave | ✅ | ✅ | ✅ | +| Cemu | Wii U | ✅ | ✅ | ✅ | +| xemu | Original Xbox | ✅ | ✅ | ✅ | +| Vita3K | PS Vita | ✅ | ✅ | ✅ | +| Azahar | Nintendo 3DS | ✅ | ✅ | ✅ | +| Project64 | Nintendo 64 | ✅ | — | — | +| Snes9x | SNES | ✅ | ✅ | ✅ | +| mGBA | Game Boy, GBA | ✅ | ✅ | ✅ | +| Mesen2 | NES, SNES, GB, GBA, PC Engine | ✅ | ✅ | ✅ | | RetroArch | Multi-system (NES, SNES, N64, GB/GBA, PS1, and more) | ✅ | ✅ | ✅ | +| ES-DE | Frontend / launcher | ✅ | ✅ | ✅ | ## Quick Start diff --git a/src/main/configurator.ts b/src/main/configurator.ts index 9bfaddb..8aa4c74 100644 --- a/src/main/configurator.ts +++ b/src/main/configurator.ts @@ -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)); + 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 = { 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 { try { const https = await import('https'); @@ -1096,6 +1225,12 @@ const raEmulatorConfigs: Record> { diff --git a/src/main/emulators.ts b/src/main/emulators.ts index 7962f1b..b0c6477 100644 --- a/src/main/emulators.ts +++ b/src/main/emulators.ts @@ -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 = { '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; diff --git a/src/main/filters.ts b/src/main/filters.ts new file mode 100644 index 0000000..7bb40b1 --- /dev/null +++ b/src/main/filters.ts @@ -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; + /** 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 { + 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 { + 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 { + 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 }; +} diff --git a/src/main/index.ts b/src/main/index.ts index b733c99..9643582 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -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) { diff --git a/src/main/installer.ts b/src/main/installer.ts index 3b6d642..334a7cd 100644 --- a/src/main/installer.ts +++ b/src/main/installer.ts @@ -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 { + 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; diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 4020b35..1df238a 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -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) => 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; + }); } diff --git a/src/main/preload.ts b/src/main/preload.ts index ac7a73d..4ccd14d 100644 --- a/src/main/preload.ts +++ b/src/main/preload.ts @@ -54,6 +54,10 @@ const api = { configured: (id: string, installPath?: string): Promise => 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 => 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 => ipcRenderer.invoke('games:cache-covers', entries), + clearCoverCache: (): Promise => + ipcRenderer.invoke('games:clear-cover-cache'), searchCoverSGDB: (title: string, platform: string): Promise => ipcRenderer.invoke('games:search-cover-sgdb', title, platform), scrapeMetadata: (romPath: string, title: string, platform: string): Promise => ipcRenderer.invoke('games:scrape-metadata', romPath, title, platform), achievements: (romPath: string, title: string, platform: string): Promise => 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 => ipcRenderer.invoke('cloud:remove-folder', folderId), openWebUI: (): Promise => ipcRenderer.invoke('cloud:open-web-ui'), + uninstall: (): Promise => ipcRenderer.invoke('cloud:uninstall'), pendingDevices: (): Promise => ipcRenderer.invoke('cloud:pending-devices'), acceptPendingDevice: (deviceId: string): Promise => ipcRenderer.invoke('cloud:accept-pending-device', deviceId), @@ -207,6 +228,10 @@ const api = { return () => ipcRenderer.removeListener('cloud:install-progress', handler); }, }, + + app: { + nukeData: (): Promise => ipcRenderer.invoke('app:nuke-data'), + }, }; contextBridge.exposeInMainWorld('omni', api); diff --git a/src/main/ra.ts b/src/main/ra.ts index d289256..1512125 100644 --- a/src/main/ra.ts +++ b/src/main/ra.ts @@ -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 = { 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 { 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 { '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 { 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 { +async function lookupGameIdByHash(romPath: string, username: string): Promise { 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) { diff --git a/src/main/saveManager.ts b/src/main/saveManager.ts index dddadaa..f1021d3 100644 --- a/src/main/saveManager.ts +++ b/src/main/saveManager.ts @@ -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', ]); diff --git a/src/main/scraper.ts b/src/main/scraper.ts index 55cfa0c..0e1fc0e 100644 --- a/src/main/scraper.ts +++ b/src/main/scraper.ts @@ -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 { }); } -function urlExists(url: string): Promise { +function urlExists(url: string, maxRedirects = 5): Promise { 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 { + 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; +} diff --git a/src/main/syncthing.ts b/src/main/syncthing.ts index 3318887..3df19a0 100644 --- a/src/main/syncthing.ts +++ b/src/main/syncthing.ts @@ -360,12 +360,12 @@ export async function getSyncthingStatus(): Promise { })); 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 { + try { + if (stProcess && !stProcess.killed) { + try { await apiRequest('POST', '/rest/system/shutdown'); } catch { /* ignore */ } + await new Promise((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; + } +} diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index 086d2a1..4f87cd6 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -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('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 ; + return ; case 'emulators': - return ; + return ; case 'library': - return ; + return ; case 'saves': - return ; + return ; case 'cloud': return ; case 'settings': - return ; + return ; case 'controller': - return ; + return ; case 'utilities': - return ; + return ; } }; @@ -61,6 +67,24 @@ export function App() { + {showInstaller && ( +
+
+ setShowInstaller(false)} /> +
+
+ )} + {connected && showLegend && (
D-Pad: Navigate diff --git a/src/renderer/components/GameDetailModal.tsx b/src/renderer/components/GameDetailModal.tsx index 1690e7e..bc15811 100644 --- a/src/renderer/components/GameDetailModal.tsx +++ b/src/renderer/components/GameDetailModal.tsx @@ -16,6 +16,7 @@ const platformLabels: Record = { 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(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 - {game.coverUrl && ( + {coverUrl && (