feat: Offer the desktop shell's emulator from the save/state play page (#4541)

This commit is contained in:
Sam Dornan
2026-09-22 23:46:40 -04:00
committed by GitHub
parent 95599dadbe
commit 08852917f9
64 changed files with 3769 additions and 33 deletions

View File

@@ -120,6 +120,27 @@
"multiplayer": "Мултиплейър режим",
"multiplayer-hint": "Показва бутон „Присъединяване“ на страницата на играта и запазва чата и уеб камерата видими.",
"mute": "Заглушаване",
"native-applies": "Тези настройки важат и за емулатора на това устройство: {controls}.",
"native-browser-only": "Тези важат само за плейъра в браузъра: {controls}.",
"native-cancel": "Отказ от стартирането",
"native-cancel-failed": "Стартирането не можа да бъде отменено",
"native-canceled": "Стартирането е отказано",
"native-downloading": "Изтегляне {percent}%",
"native-error-download": "{name} не можа да бъде изтеглена",
"native-error-no-emulator": "За тази платформа не е настроен емулатор",
"native-error-running": "{name} вече е стартирана",
"native-fetching-firmware": "Изтегляне на {firmware}",
"native-installing-core": "Инсталиране на {core}",
"native-launch-failed": "{name} не можа да бъде стартирана",
"native-preparing": "Подготвяне на {emulator}",
"native-running": "{name} е стартирана",
"native-save-archived": "Записът за {name} е запазен отделно, RomM има по-нов напредък",
"native-save-downloaded": "Записът за {name} е зареден от RomM",
"native-save-failed": "Записът за {name} не можа да бъде синхронизиран",
"native-save-uploaded": "Записът за {name} е изпратен към RomM",
"native-starting": "Стартиране…",
"native-syncing-save": "Синхронизиране на запис…",
"native-syncing-states": "Синхронизиране на състоянията…",
"netplay": "Мрежова игра",
"new-memory-card": "Нова карта",
"new-slot": "+ Нов слот",
@@ -140,6 +161,9 @@
"pico8-screen": "Игрален екран на PICO-8",
"pico8-up": "Нагоре",
"play": "Играй",
"play-in-browser": "Играй в браузъра",
"play-native": "Играй на това устройство",
"play-native-in": "Играй в {emulator}",
"play-on": "Стрийминг на {label}",
"powered-by": "Захранено от",
"quick-state-loaded": "Бързият запис от слота е зареден",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Твоят токен е създаден. Избери как да го доставиш:",
"delivery-intro-regenerate": "Предишният ти токен е отменен и е генериран нов. Избери как да го доставиш:",
"description": "Description",
"desktop-shell": "Настолна обвивка",
"desktop-shell-desc": "Пътищата до емулаторите, кешът за ROM файлове и местоположението на библиотеката се задават в собствената конфигурация на обвивката, на тази машина. Версия {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Няма платформи.",
"no-tasks-in-history": "Няма задачи в историята",
"no-tokens-help": "Няма токени — създай един, за да започнеш сдвояване на устройства.",
"open-shell-settings": "Отвори настройките на обвивката",
"open-shell-settings-failed": "Настройките на десктоп приложението не можаха да бъдат отворени",
"order-platforms-by": "Подреди платформите по",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Režim pro více hráčů",
"multiplayer-hint": "Na stránce hry se zobrazí tlačítko Připojit se a chat i webkamera zůstanou viditelné.",
"mute": "Ztlumit",
"native-applies": "Pro emulátor v tomto zařízení platí také: {controls}.",
"native-browser-only": "Platí pouze pro přehrávač v prohlížeči: {controls}.",
"native-cancel": "Zrušit spuštění",
"native-cancel-failed": "Spuštění nelze zrušit",
"native-canceled": "Spuštění zrušeno",
"native-downloading": "Stahování {percent}%",
"native-error-download": "Hru {name} nelze stáhnout",
"native-error-no-emulator": "Pro tuto platformu není nastaven žádný emulátor",
"native-error-running": "{name} už běží",
"native-fetching-firmware": "Načítání {firmware}",
"native-installing-core": "Instalace {core}",
"native-launch-failed": "Hru {name} nelze spustit",
"native-preparing": "Připravuje se {emulator}",
"native-running": "{name} běží",
"native-save-archived": "Uložená pozice pro {name} byla uložena zvlášť, RomM má novější postup",
"native-save-downloaded": "Uložená pozice pro {name} byla načtena z RomM",
"native-save-failed": "Uloženou pozici pro {name} nelze synchronizovat",
"native-save-uploaded": "Uložená pozice pro {name} byla odeslána do RomM",
"native-starting": "Spouštění…",
"native-syncing-save": "Synchronizace uložené pozice…",
"native-syncing-states": "Synchronizace uložených stavů…",
"netplay": "Hra po síti",
"new-memory-card": "Nová karta",
"new-slot": "+ Nový slot",
@@ -140,6 +161,9 @@
"pico8-screen": "Obrazovka hry PICO-8",
"pico8-up": "Nahoru",
"play": "Hrát",
"play-in-browser": "Hrát v prohlížeči",
"play-native": "Hrát na tomto zařízení",
"play-native-in": "Hrát v {emulator}",
"play-on": "Streamovat na {label}",
"powered-by": "Poháněno",
"quick-state-loaded": "Rychlý stav načten",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Váš token byl vytvořen. Vyberte způsob doručení:",
"delivery-intro-regenerate": "Váš předchozí token byl zrušen a byl vygenerován nový. Vyberte způsob doručení:",
"description": "Description",
"desktop-shell": "Desktopová aplikace",
"desktop-shell-desc": "Cesty k emulátorům, mezipaměť ROM a umístění knihovny se nastavují ve vlastní konfiguraci aplikace na tomto počítači. Verze {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Žádné platformy.",
"no-tasks-in-history": "V historii nejsou žádné úlohy",
"no-tokens-help": "Žádné tokeny — vytvořte jeden pro spárování zařízení.",
"open-shell-settings": "Otevřít nastavení aplikace",
"open-shell-settings-failed": "Nastavení desktopové aplikace se nepodařilo otevřít",
"order-platforms-by": "Řadit platformy podle",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Mehrspielermodus",
"multiplayer-hint": "Zeigt auf der Seite dieses Spiels eine Schaltfläche zum Beitreten und hält Chat und Webcam sichtbar.",
"mute": "Stummschalten",
"native-applies": "Gilt auch für den Emulator auf diesem Gerät: {controls}.",
"native-browser-only": "Diese gelten nur für den Player im Browser: {controls}.",
"native-cancel": "Start abbrechen",
"native-cancel-failed": "Start konnte nicht abgebrochen werden",
"native-canceled": "Start abgebrochen",
"native-downloading": "Wird heruntergeladen {percent}%",
"native-error-download": "{name} konnte nicht heruntergeladen werden",
"native-error-no-emulator": "Für diese Plattform ist kein Emulator eingerichtet",
"native-error-running": "{name} läuft bereits",
"native-fetching-firmware": "{firmware} wird geholt",
"native-installing-core": "{core} wird installiert",
"native-launch-failed": "{name} konnte nicht gestartet werden",
"native-preparing": "{emulator} wird eingerichtet",
"native-running": "{name} läuft",
"native-save-archived": "Der Spielstand für {name} wurde separat gespeichert, RomM hat neueren Fortschritt",
"native-save-downloaded": "Spielstand für {name} von RomM geladen",
"native-save-failed": "Spielstand für {name} konnte nicht synchronisiert werden",
"native-save-uploaded": "Spielstand für {name} an RomM gesendet",
"native-starting": "Wird gestartet…",
"native-syncing-save": "Spielstand wird synchronisiert…",
"native-syncing-states": "Savestates werden synchronisiert…",
"netplay": "Netplay",
"new-memory-card": "Neue Karte",
"new-slot": "+ Neuer Slot",
@@ -140,6 +161,9 @@
"pico8-screen": "PICO-8-Spielbildschirm",
"pico8-up": "Oben",
"play": "Spielen",
"play-in-browser": "Im Browser spielen",
"play-native": "Auf diesem Gerät spielen",
"play-native-in": "In {emulator} spielen",
"play-on": "Auf {label} streamen",
"powered-by": "Bereitgestellt von",
"quick-state-loaded": "Schnellzustand geladen",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Dein Token wurde erstellt. Wähle, wie es übermittelt werden soll:",
"delivery-intro-regenerate": "Dein vorheriges Token wurde widerrufen und ein neues generiert. Wähle, wie es übermittelt werden soll:",
"description": "Description",
"desktop-shell": "Desktop-Anwendung",
"desktop-shell-desc": "Emulator-Pfade, der ROM-Cache und der Speicherort der Bibliothek werden in der eigenen Konfiguration der Anwendung auf diesem Rechner festgelegt. Version {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Keine Plattformen.",
"no-tasks-in-history": "Keine Aufgaben in der Historie",
"no-tokens-help": "Keine Tokens — erstelle eines, um Geräte zu koppeln.",
"open-shell-settings": "Einstellungen der Anwendung öffnen",
"open-shell-settings-failed": "Die Einstellungen der Desktop-App konnten nicht geöffnet werden",
"order-platforms-by": "Plattformen sortieren nach",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Multiplayer mode",
"multiplayer-hint": "Shows a Join button on this game's page and keeps chat and webcam visible.",
"mute": "Mute",
"native-applies": "Also applies to the emulator on this device: {controls}.",
"native-browser-only": "Only applies to the browser player: {controls}.",
"native-cancel": "Cancel launch",
"native-cancel-failed": "Could not cancel the launch",
"native-canceled": "Launch cancelled",
"native-downloading": "Downloading {percent}%",
"native-error-download": "Could not download {name}",
"native-error-no-emulator": "No emulator is set up for this platform",
"native-error-running": "{name} is already running",
"native-fetching-firmware": "Fetching {firmware}",
"native-installing-core": "Installing {core}",
"native-launch-failed": "Could not start {name}",
"native-preparing": "Setting up {emulator}",
"native-running": "{name} is running",
"native-save-archived": "Kept {name}'s save aside, RomM has newer progress",
"native-save-downloaded": "Loaded {name}'s save from RomM",
"native-save-failed": "Could not sync {name}'s save",
"native-save-uploaded": "Sent {name}'s save to RomM",
"native-starting": "Starting…",
"native-syncing-save": "Syncing save…",
"native-syncing-states": "Syncing states…",
"netplay": "Netplay",
"new-memory-card": "New card",
"new-slot": "+ New slot",
@@ -140,6 +161,9 @@
"pico8-screen": "PICO-8 game screen",
"pico8-up": "Up",
"play": "Play",
"play-in-browser": "Play in browser",
"play-native": "Play on this device",
"play-native-in": "Play in {emulator}",
"play-on": "Stream on {label}",
"powered-by": "Powered by",
"quick-state-loaded": "Quick state loaded",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Your token has been created. Choose how to deliver it:",
"delivery-intro-regenerate": "Your previous token has been revoked and a new one generated. Choose how to deliver it:",
"description": "Description",
"desktop-shell": "Desktop shell",
"desktop-shell-desc": "Emulator paths, the ROM cache and the library location are set in the shell's own configuration, on this machine. Version {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "No platforms.",
"no-tasks-in-history": "No tasks in history",
"no-tokens-help": "No client API tokens found. Create one to start pairing devices.",
"open-shell-settings": "Open shell settings",
"open-shell-settings-failed": "The desktop app's settings could not be opened",
"order-platforms-by": "Order platforms by",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Multiplayer mode",
"multiplayer-hint": "Shows a Join button on this game's page and keeps chat and webcam visible.",
"mute": "Mute",
"native-applies": "Also applies to the emulator on this device: {controls}.",
"native-browser-only": "Only applies to the browser player: {controls}.",
"native-cancel": "Cancel launch",
"native-cancel-failed": "Could not cancel the launch",
"native-canceled": "Launch canceled",
"native-downloading": "Downloading {percent}%",
"native-error-download": "Could not download {name}",
"native-error-no-emulator": "No emulator is set up for this platform",
"native-error-running": "{name} is already running",
"native-fetching-firmware": "Fetching {firmware}",
"native-installing-core": "Installing {core}",
"native-launch-failed": "Could not start {name}",
"native-preparing": "Setting up {emulator}",
"native-running": "{name} is running",
"native-save-archived": "Kept {name}'s save aside, RomM has newer progress",
"native-save-downloaded": "Loaded {name}'s save from RomM",
"native-save-failed": "Could not sync {name}'s save",
"native-save-uploaded": "Sent {name}'s save to RomM",
"native-starting": "Starting…",
"native-syncing-save": "Syncing save…",
"native-syncing-states": "Syncing states…",
"netplay": "Netplay",
"new-memory-card": "New card",
"new-slot": "+ New slot",
@@ -140,6 +161,9 @@
"pico8-screen": "PICO-8 game screen",
"pico8-up": "Up",
"play": "Play",
"play-in-browser": "Play in browser",
"play-native": "Play on this device",
"play-native-in": "Play in {emulator}",
"play-on": "Stream on {label}",
"powered-by": "Powered by",
"quick-state-loaded": "Quick state loaded",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Your token has been created. Choose how to deliver it:",
"delivery-intro-regenerate": "Your previous token has been revoked and a new one generated. Choose how to deliver it:",
"description": "Description",
"desktop-shell": "Desktop shell",
"desktop-shell-desc": "Emulator paths, the ROM cache and the library location are set in the shell's own configuration, on this machine. Version {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "No platforms.",
"no-tasks-in-history": "No tasks in history",
"no-tokens-help": "No client API tokens found. Create one to start pairing devices.",
"open-shell-settings": "Open shell settings",
"open-shell-settings-failed": "The desktop app's settings could not be opened",
"order-platforms-by": "Order platforms by",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Modo multijugador",
"multiplayer-hint": "Muestra un botón Unirse en la página de este juego y mantiene visibles el chat y la cámara web.",
"mute": "Silenciar",
"native-applies": "Esto también se aplica al emulador de este dispositivo: {controls}.",
"native-browser-only": "Estos solo se aplican al reproductor del navegador: {controls}.",
"native-cancel": "Cancelar inicio",
"native-cancel-failed": "No se pudo cancelar el inicio",
"native-canceled": "Inicio cancelado",
"native-downloading": "Descargando {percent}%",
"native-error-download": "No se pudo descargar {name}",
"native-error-no-emulator": "No hay ningún emulador configurado para esta plataforma",
"native-error-running": "{name} ya se está ejecutando",
"native-fetching-firmware": "Obteniendo {firmware}",
"native-installing-core": "Instalando {core}",
"native-launch-failed": "No se pudo iniciar {name}",
"native-preparing": "Preparando {emulator}",
"native-running": "{name} se está ejecutando",
"native-save-archived": "La partida guardada de {name} se ha guardado aparte, RomM tiene una más reciente",
"native-save-downloaded": "Partida guardada de {name} cargada desde RomM",
"native-save-failed": "No se pudo sincronizar la partida guardada de {name}",
"native-save-uploaded": "Partida guardada de {name} enviada a RomM",
"native-starting": "Iniciando…",
"native-syncing-save": "Sincronizando partida guardada…",
"native-syncing-states": "Sincronizando estados…",
"netplay": "Juego en red",
"new-memory-card": "Nueva tarjeta",
"new-slot": "+ Nueva ranura",
@@ -140,6 +161,9 @@
"pico8-screen": "Pantalla de juego de PICO-8",
"pico8-up": "Arriba",
"play": "Jugar",
"play-in-browser": "Jugar en el navegador",
"play-native": "Jugar en este dispositivo",
"play-native-in": "Jugar en {emulator}",
"play-on": "Transmitir en {label}",
"powered-by": "Con la tecnología de",
"quick-state-loaded": "Estado rápido cargado",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Tu nuevo token API ha sido creado. Cópialo ahora — no se mostrará de nuevo.",
"delivery-intro-regenerate": "Tu token API ha sido regenerado. Copia el nuevo valor — el anterior ya no es válido.",
"description": "Description",
"desktop-shell": "Aplicación de escritorio",
"desktop-shell-desc": "Las rutas de los emuladores, la caché de ROM y la ubicación de la biblioteca se configuran en la propia configuración de la aplicación, en este equipo. Versión {version}.",
"developer": "Desarrollador",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Sin plataformas",
"no-tasks-in-history": "No hay tareas en el historial",
"no-tokens-help": "Crea tu primer token API para emparejar dispositivos.",
"open-shell-settings": "Abrir la configuración de la aplicación",
"open-shell-settings-failed": "No se pudo abrir la configuración de la aplicación de escritorio",
"order-platforms-by": "Ordenar plataformas por",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Mode multijoueur",
"multiplayer-hint": "Affiche un bouton Rejoindre sur la page de ce jeu et garde le chat et la webcam visibles.",
"mute": "Couper le son",
"native-applies": "Ceci s'applique aussi à l'émulateur de cet appareil : {controls}.",
"native-browser-only": "Ceci ne s'applique qu'au lecteur du navigateur : {controls}.",
"native-cancel": "Annuler le lancement",
"native-cancel-failed": "Impossible d'annuler le lancement",
"native-canceled": "Lancement annulé",
"native-downloading": "Téléchargement {percent}%",
"native-error-download": "Impossible de télécharger {name}",
"native-error-no-emulator": "Aucun émulateur n'est configuré pour cette plateforme",
"native-error-running": "{name} est déjà en cours d'exécution",
"native-fetching-firmware": "Récupération de {firmware}",
"native-installing-core": "Installation de {core}",
"native-launch-failed": "Impossible de lancer {name}",
"native-preparing": "Préparation de {emulator}",
"native-running": "{name} est en cours d'exécution",
"native-save-archived": "La sauvegarde de {name} a été conservée à part, RomM en a une plus récente",
"native-save-downloaded": "Sauvegarde de {name} chargée depuis RomM",
"native-save-failed": "Impossible de synchroniser la sauvegarde de {name}",
"native-save-uploaded": "Sauvegarde de {name} envoyée à RomM",
"native-starting": "Lancement…",
"native-syncing-save": "Synchronisation de la sauvegarde…",
"native-syncing-states": "Synchronisation des états…",
"netplay": "Jeu en réseau",
"new-memory-card": "Nouvelle carte",
"new-slot": "+ Nouvel emplacement",
@@ -140,6 +161,9 @@
"pico8-screen": "Écran de jeu PICO-8",
"pico8-up": "Haut",
"play": "Jouer",
"play-in-browser": "Jouer dans le navigateur",
"play-native": "Jouer sur cet appareil",
"play-native-in": "Jouer dans {emulator}",
"play-on": "Diffuser sur {label}",
"powered-by": "Propulsé par",
"quick-state-loaded": "État rapide chargé",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Votre token a été créé. Choisissez comment le livrer :",
"delivery-intro-regenerate": "Votre token précédent a été révoqué et un nouveau a été généré. Choisissez comment le livrer :",
"description": "Description",
"desktop-shell": "Application de bureau",
"desktop-shell-desc": "Les chemins des émulateurs, le cache des ROM et l'emplacement de la bibliothèque sont définis dans la configuration propre à l'application, sur cette machine. Version {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Aucune plateforme.",
"no-tasks-in-history": "Aucune tâche dans l'historique",
"no-tokens-help": "Aucun token — créez-en un pour commencer à associer des appareils.",
"open-shell-settings": "Ouvrir les paramètres de l'application",
"open-shell-settings-failed": "Les paramètres de l'application de bureau n'ont pas pu être ouverts",
"order-platforms-by": "Trier les plateformes par",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Többjátékos mód",
"multiplayer-hint": "Csatlakozás gombot jelenít meg a játék oldalán, és láthatóan tartja a csevegést és a webkamerát.",
"mute": "Némítás",
"native-applies": "Ezek a készülék emulátorára is érvényesek: {controls}.",
"native-browser-only": "Ezek csak a böngészős lejátszóra érvényesek: {controls}.",
"native-cancel": "Indítás megszakítása",
"native-cancel-failed": "Az indítást nem sikerült megszakítani",
"native-canceled": "Indítás megszakítva",
"native-downloading": "Letöltés {percent}%",
"native-error-download": "A(z) {name} letöltése nem sikerült",
"native-error-no-emulator": "Ehhez a platformhoz nincs beállítva emulátor",
"native-error-running": "A(z) {name} már fut",
"native-fetching-firmware": "{firmware} letöltése",
"native-installing-core": "{core} telepítése",
"native-launch-failed": "A(z) {name} indítása nem sikerült",
"native-preparing": "{emulator} előkészítése",
"native-running": "A(z) {name} fut",
"native-save-archived": "A(z) {name} mentése külön került megőrzésre, a RomM-ban újabb előrehaladás van",
"native-save-downloaded": "A(z) {name} mentése betöltve a RomM-ból",
"native-save-failed": "A(z) {name} mentését nem sikerült szinkronizálni",
"native-save-uploaded": "A(z) {name} mentése elküldve a RomM-ba",
"native-starting": "Indítás…",
"native-syncing-save": "Mentés szinkronizálása…",
"native-syncing-states": "Állások szinkronizálása…",
"netplay": "Hálózati játék",
"new-memory-card": "Új kártya",
"new-slot": "+ Új hely",
@@ -140,6 +161,9 @@
"pico8-screen": "PICO-8 játékképernyő",
"pico8-up": "Fel",
"play": "Indítás",
"play-in-browser": "Játék a böngészőben",
"play-native": "Játék ezen az eszközön",
"play-native-in": "Játék a(z) {emulator} programban",
"play-on": "Streamelés a(z) {label} gépen",
"powered-by": "Üzemeltető:",
"quick-state-loaded": "Gyorsállás betöltve",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "A tokened létrejött. Válaszd ki, hogyan szeretnéd átadni:",
"delivery-intro-regenerate": "A korábbi tokened visszavonva, és új lett generálva. Válaszd ki, hogyan szeretnéd átadni:",
"description": "Description",
"desktop-shell": "Asztali alkalmazás",
"desktop-shell-desc": "Az emulátorok útvonalait, a ROM-gyorsítótárat és a könyvtár helyét az alkalmazás saját beállításai tartalmazzák ezen a gépen. Verzió: {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Nincsenek platformok.",
"no-tasks-in-history": "Nincsenek feladatok az előzményekben",
"no-tokens-help": "Nincsenek tokenek — hozz létre egyet az eszközök párosításához.",
"open-shell-settings": "Az alkalmazás beállításainak megnyitása",
"open-shell-settings-failed": "Az asztali alkalmazás beállításai nem nyithatók meg",
"order-platforms-by": "Platformok rendezése",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Modalità multigiocatore",
"multiplayer-hint": "Mostra un pulsante Partecipa nella pagina di questo gioco e mantiene visibili chat e webcam.",
"mute": "Disattiva audio",
"native-applies": "Valgono anche per l'emulatore di questo dispositivo: {controls}.",
"native-browser-only": "Valgono solo per il lettore nel browser: {controls}.",
"native-cancel": "Annulla avvio",
"native-cancel-failed": "Impossibile annullare l'avvio",
"native-canceled": "Avvio annullato",
"native-downloading": "Download {percent}%",
"native-error-download": "Non è stato possibile scaricare {name}",
"native-error-no-emulator": "Nessun emulatore è configurato per questa piattaforma",
"native-error-running": "{name} è già in esecuzione",
"native-fetching-firmware": "Recupero di {firmware}",
"native-installing-core": "Installazione di {core}",
"native-launch-failed": "Non è stato possibile avviare {name}",
"native-preparing": "Preparazione di {emulator}",
"native-running": "{name} è in esecuzione",
"native-save-archived": "Il salvataggio di {name} è stato conservato a parte, RomM ne ha uno più recente",
"native-save-downloaded": "Salvataggio di {name} caricato da RomM",
"native-save-failed": "Non è stato possibile sincronizzare il salvataggio di {name}",
"native-save-uploaded": "Salvataggio di {name} inviato a RomM",
"native-starting": "Avvio…",
"native-syncing-save": "Sincronizzazione del salvataggio…",
"native-syncing-states": "Sincronizzazione degli stati…",
"netplay": "Gioco in rete",
"new-memory-card": "Nuova card",
"new-slot": "+ Nuovo slot",
@@ -140,6 +161,9 @@
"pico8-screen": "Schermo di gioco PICO-8",
"pico8-up": "Su",
"play": "Gioca",
"play-in-browser": "Gioca nel browser",
"play-native": "Gioca su questo dispositivo",
"play-native-in": "Gioca in {emulator}",
"play-on": "Trasmetti su {label}",
"powered-by": "Powered by",
"quick-state-loaded": "Stato rapido caricato",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Il tuo token è stato creato. Scegli come consegnarlo:",
"delivery-intro-regenerate": "Il tuo token precedente è stato revocato e ne è stato generato uno nuovo. Scegli come consegnarlo:",
"description": "Description",
"desktop-shell": "Applicazione desktop",
"desktop-shell-desc": "I percorsi degli emulatori, la cache delle ROM e la posizione della libreria sono impostati nella configurazione dell'applicazione, su questa macchina. Versione {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Nessuna piattaforma.",
"no-tasks-in-history": "Nessuna attività nella cronologia",
"no-tokens-help": "Nessun token — creane uno per iniziare ad associare dispositivi.",
"open-shell-settings": "Apri le impostazioni dell'applicazione",
"open-shell-settings-failed": "Non è stato possibile aprire le impostazioni dell'app desktop",
"order-platforms-by": "Ordina piattaforme per",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "マルチプレイヤーモード",
"multiplayer-hint": "このゲームのページに参加ボタンを表示し、チャットとウェブカメラを表示したままにします。",
"mute": "ミュート",
"native-applies": "これらはこの端末のエミュレーターにも適用されます: {controls}。",
"native-browser-only": "これらはブラウザプレイヤーにのみ適用されます: {controls}。",
"native-cancel": "起動をキャンセル",
"native-cancel-failed": "起動をキャンセルできませんでした",
"native-canceled": "起動をキャンセルしました",
"native-downloading": "ダウンロード中 {percent}%",
"native-error-download": "{name} をダウンロードできませんでした",
"native-error-no-emulator": "このプラットフォーム用のエミュレーターが設定されていません",
"native-error-running": "{name} はすでに実行中です",
"native-fetching-firmware": "{firmware} を取得中",
"native-installing-core": "{core} をインストール中",
"native-launch-failed": "{name} を起動できませんでした",
"native-preparing": "{emulator} を準備中",
"native-running": "{name} を実行中です",
"native-save-archived": "{name} のセーブデータを別に保存しました。RomM にはより新しい進行状況があります",
"native-save-downloaded": "{name} のセーブデータを RomM から読み込みました",
"native-save-failed": "{name} のセーブデータを同期できませんでした",
"native-save-uploaded": "{name} のセーブデータを RomM に送信しました",
"native-starting": "起動中…",
"native-syncing-save": "セーブデータを同期中…",
"native-syncing-states": "ステートを同期中…",
"netplay": "ネットプレイ",
"new-memory-card": "新しいカード",
"new-slot": "+ 新しいスロット",
@@ -140,6 +161,9 @@
"pico8-screen": "PICO-8 のゲーム画面",
"pico8-up": "上",
"play": "プレイ",
"play-in-browser": "ブラウザでプレイ",
"play-native": "このデバイスでプレイ",
"play-native-in": "{emulator} でプレイ",
"play-on": "{label} でストリーミング",
"powered-by": "提供:",
"quick-state-loaded": "クイックステートをロードしました",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "トークンを作成しました。配信方法を選んでください:",
"delivery-intro-regenerate": "以前のトークンは無効化され、新しいトークンが生成されました。配信方法を選んでください:",
"description": "Description",
"desktop-shell": "デスクトップアプリ",
"desktop-shell-desc": "エミュレーターのパス、ROM キャッシュ、ライブラリの場所は、このマシン上のアプリ自身の設定で指定します。バージョン {version}。",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "プラットフォームがありません。",
"no-tasks-in-history": "履歴にタスクがありません",
"no-tokens-help": "トークンがありません — 作成してデバイスのペアリングを開始してください。",
"open-shell-settings": "アプリの設定を開く",
"open-shell-settings-failed": "デスクトップアプリの設定を開けませんでした",
"order-platforms-by": "プラットフォームの並び順",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "멀티플레이어 모드",
"multiplayer-hint": "이 게임 페이지에 참가 버튼을 표시하고 채팅과 웹캠을 계속 보이게 합니다.",
"mute": "음소거",
"native-applies": "이 설정은 이 기기의 에뮬레이터에도 적용됩니다: {controls}.",
"native-browser-only": "이 설정은 브라우저 플레이어에만 적용됩니다: {controls}.",
"native-cancel": "실행 취소",
"native-cancel-failed": "실행을 취소할 수 없습니다",
"native-canceled": "실행이 취소되었습니다",
"native-downloading": "다운로드 중 {percent}%",
"native-error-download": "{name}을(를) 다운로드할 수 없습니다",
"native-error-no-emulator": "이 플랫폼에 설정된 에뮬레이터가 없습니다",
"native-error-running": "{name}이(가) 이미 실행 중입니다",
"native-fetching-firmware": "{firmware} 가져오는 중",
"native-installing-core": "{core} 설치 중",
"native-launch-failed": "{name}을(를) 실행할 수 없습니다",
"native-preparing": "{emulator} 준비 중",
"native-running": "{name}이(가) 실행 중입니다",
"native-save-archived": "{name}의 저장 데이터를 별도로 보관했습니다. RomM에 더 최근 진행 상황이 있습니다",
"native-save-downloaded": "RomM에서 {name}의 저장 데이터를 불러왔습니다",
"native-save-failed": "{name}의 저장 데이터를 동기화할 수 없습니다",
"native-save-uploaded": "{name}의 저장 데이터를 RomM으로 보냈습니다",
"native-starting": "실행 중…",
"native-syncing-save": "저장 데이터 동기화 중…",
"native-syncing-states": "상태 저장 동기화 중…",
"netplay": "넷플레이",
"new-memory-card": "새 카드",
"new-slot": "+ 새 슬롯",
@@ -140,6 +161,9 @@
"pico8-screen": "PICO-8 게임 화면",
"pico8-up": "위",
"play": "실행",
"play-in-browser": "브라우저에서 플레이",
"play-native": "이 기기에서 플레이",
"play-native-in": "{emulator}에서 플레이",
"play-on": "{label}에서 스트리밍",
"powered-by": "제공",
"quick-state-loaded": "빠른 상태를 불러왔습니다",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "토큰이 생성되었습니다. 전달 방법을 선택하세요:",
"delivery-intro-regenerate": "이전 토큰이 폐기되고 새 토큰이 생성되었습니다. 전달 방법을 선택하세요:",
"description": "Description",
"desktop-shell": "데스크톱 앱",
"desktop-shell-desc": "에뮬레이터 경로, ROM 캐시, 라이브러리 위치는 이 컴퓨터의 앱 자체 설정에서 지정합니다. 버전 {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "플랫폼이 없습니다.",
"no-tasks-in-history": "히스토리에 작업이 없습니다",
"no-tokens-help": "토큰이 없습니다 — 장치 페어링을 시작하려면 토큰을 만드세요.",
"open-shell-settings": "앱 설정 열기",
"open-shell-settings-failed": "데스크톱 앱 설정을 열 수 없습니다",
"order-platforms-by": "플랫폼 정렬 기준",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Tryb wieloosobowy",
"multiplayer-hint": "Wyświetla przycisk Dołącz na stronie tej gry i utrzymuje widoczny czat oraz kamerę internetową.",
"mute": "Wycisz",
"native-applies": "Dotyczy to też emulatora na tym urządzeniu: {controls}.",
"native-browser-only": "Dotyczy to tylko odtwarzacza w przeglądarce: {controls}.",
"native-cancel": "Anuluj uruchamianie",
"native-cancel-failed": "Nie udało się anulować uruchamiania",
"native-canceled": "Uruchamianie anulowane",
"native-downloading": "Pobieranie {percent}%",
"native-error-download": "Nie udało się pobrać {name}",
"native-error-no-emulator": "Dla tej platformy nie skonfigurowano emulatora",
"native-error-running": "{name} jest już uruchomiona",
"native-fetching-firmware": "Pobieranie {firmware}",
"native-installing-core": "Instalowanie {core}",
"native-launch-failed": "Nie udało się uruchomić {name}",
"native-preparing": "Przygotowywanie {emulator}",
"native-running": "{name} jest uruchomiona",
"native-save-archived": "Zapis gry {name} zachowano osobno, RomM ma nowszy postęp",
"native-save-downloaded": "Wczytano zapis gry {name} z RomM",
"native-save-failed": "Nie udało się zsynchronizować zapisu gry {name}",
"native-save-uploaded": "Wysłano zapis gry {name} do RomM",
"native-starting": "Uruchamianie…",
"native-syncing-save": "Synchronizowanie zapisu…",
"native-syncing-states": "Synchronizowanie stanów…",
"netplay": "Gra sieciowa",
"new-memory-card": "Nowa karta",
"new-slot": "+ Nowy slot",
@@ -140,6 +161,9 @@
"pico8-screen": "Ekran gry PICO-8",
"pico8-up": "Góra",
"play": "Graj",
"play-in-browser": "Zagraj w przeglądarce",
"play-native": "Zagraj na tym urządzeniu",
"play-native-in": "Zagraj w {emulator}",
"play-on": "Strumieniuj na {label}",
"powered-by": "Zasilane przez",
"quick-state-loaded": "Wczytano szybki stan",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Twój token został utworzony. Wybierz sposób dostarczenia:",
"delivery-intro-regenerate": "Poprzedni token został unieważniony i wygenerowano nowy. Wybierz sposób dostarczenia:",
"description": "Description",
"desktop-shell": "Aplikacja na komputer",
"desktop-shell-desc": "Ścieżki emulatorów, pamięć podręczna ROM-ów i lokalizacja biblioteki są ustawiane we własnej konfiguracji aplikacji na tym komputerze. Wersja {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Brak platform.",
"no-tasks-in-history": "Brak zadań w historii",
"no-tokens-help": "Brak tokenów — utwórz jeden, aby rozpocząć parowanie urządzeń.",
"open-shell-settings": "Otwórz ustawienia aplikacji",
"open-shell-settings-failed": "Nie można otworzyć ustawień aplikacji desktopowej",
"order-platforms-by": "Sortuj platformy według",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Modo multijogador",
"multiplayer-hint": "Mostra um botão Entrar na página deste jogo e mantém o chat e a webcam visíveis.",
"mute": "Silenciar",
"native-applies": "Isto também se aplica ao emulador deste dispositivo: {controls}.",
"native-browser-only": "Isto se aplica apenas ao player do navegador: {controls}.",
"native-cancel": "Cancelar inicialização",
"native-cancel-failed": "Não foi possível cancelar a inicialização",
"native-canceled": "Inicialização cancelada",
"native-downloading": "Baixando {percent}%",
"native-error-download": "Não foi possível baixar {name}",
"native-error-no-emulator": "Nenhum emulador está configurado para esta plataforma",
"native-error-running": "{name} já está em execução",
"native-fetching-firmware": "Obtendo {firmware}",
"native-installing-core": "Instalando {core}",
"native-launch-failed": "Não foi possível iniciar {name}",
"native-preparing": "Preparando {emulator}",
"native-running": "{name} está em execução",
"native-save-archived": "O save de {name} foi guardado à parte, o RomM tem um mais recente",
"native-save-downloaded": "Save de {name} carregado do RomM",
"native-save-failed": "Não foi possível sincronizar o save de {name}",
"native-save-uploaded": "Save de {name} enviado ao RomM",
"native-starting": "Iniciando…",
"native-syncing-save": "Sincronizando o save…",
"native-syncing-states": "Sincronizando os states…",
"netplay": "Jogo em rede",
"new-memory-card": "Novo cartão",
"new-slot": "+ Novo slot",
@@ -140,6 +161,9 @@
"pico8-screen": "Tela de jogo do PICO-8",
"pico8-up": "Cima",
"play": "Jogar",
"play-in-browser": "Jogar no navegador",
"play-native": "Jogar neste dispositivo",
"play-native-in": "Jogar no {emulator}",
"play-on": "Transmitir em {label}",
"powered-by": "Desenvolvido com",
"quick-state-loaded": "State rápido carregado",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Seu token foi criado. Escolha como entregá-lo:",
"delivery-intro-regenerate": "Seu token anterior foi revogado e um novo foi gerado. Escolha como entregá-lo:",
"description": "Descrição",
"desktop-shell": "Aplicativo para desktop",
"desktop-shell-desc": "Os caminhos dos emuladores, o cache de ROMs e a localização da biblioteca são definidos na configuração do próprio aplicativo, nesta máquina. Versão {version}.",
"developer": "Desenvolvedor",
"device-auth-approve": "Aprovar",
"device-auth-approve-failed": "Falha ao aprovar o dispositivo.",
@@ -258,6 +260,8 @@
"no-platforms": "Nenhuma plataforma.",
"no-tasks-in-history": "Nenhuma tarefa no histórico",
"no-tokens-help": "Nenhum token — crie um para começar a parear dispositivos.",
"open-shell-settings": "Abrir as configurações do aplicativo",
"open-shell-settings-failed": "Não foi possível abrir as configurações do aplicativo de desktop",
"order-platforms-by": "Ordenar plataformas por",
"override-grant": "Concedido",
"override-grant-own": "Concedido (apenas itens próprios)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Mod multiplayer",
"multiplayer-hint": "Afișează un buton Alătură-te pe pagina acestui joc și păstrează vizibile chatul și camera web.",
"mute": "Dezactivează sunetul",
"native-applies": "Acestea se aplică și emulatorului de pe acest dispozitiv: {controls}.",
"native-browser-only": "Acestea se aplică doar playerului din browser: {controls}.",
"native-cancel": "Anulează lansarea",
"native-cancel-failed": "Lansarea nu a putut fi anulată",
"native-canceled": "Lansare anulată",
"native-downloading": "Se descarcă {percent}%",
"native-error-download": "{name} nu a putut fi descărcat",
"native-error-no-emulator": "Niciun emulator nu este configurat pentru această platformă",
"native-error-running": "{name} rulează deja",
"native-fetching-firmware": "Se obține {firmware}",
"native-installing-core": "Se instalează {core}",
"native-launch-failed": "{name} nu a putut fi lansat",
"native-preparing": "Se pregătește {emulator}",
"native-running": "{name} rulează",
"native-save-archived": "Salvarea pentru {name} a fost păstrată separat, RomM are una mai nouă",
"native-save-downloaded": "Salvarea pentru {name} a fost încărcată din RomM",
"native-save-failed": "Salvarea pentru {name} nu a putut fi sincronizată",
"native-save-uploaded": "Salvarea pentru {name} a fost trimisă către RomM",
"native-starting": "Se lansează…",
"native-syncing-save": "Se sincronizează salvarea…",
"native-syncing-states": "Se sincronizează stările…",
"netplay": "Joc în rețea",
"new-memory-card": "Card nou",
"new-slot": "+ Slot nou",
@@ -140,6 +161,9 @@
"pico8-screen": "Ecran de joc PICO-8",
"pico8-up": "Sus",
"play": "Joacă",
"play-in-browser": "Joacă în browser",
"play-native": "Joacă pe acest dispozitiv",
"play-native-in": "Joacă în {emulator}",
"play-on": "Redare în flux pe {label}",
"powered-by": "Susținut de",
"quick-state-loaded": "Stare rapidă încărcată",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Token-ul tău a fost creat. Alege cum să-l livrezi:",
"delivery-intro-regenerate": "Token-ul anterior a fost revocat și a fost generat unul nou. Alege cum să-l livrezi:",
"description": "Description",
"desktop-shell": "Aplicația desktop",
"desktop-shell-desc": "Căile emulatoarelor, memoria cache pentru ROM-uri și locația bibliotecii se configurează în setările proprii ale aplicației, pe această mașină. Versiunea {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Nicio platformă.",
"no-tasks-in-history": "Nu există sarcini în istoric",
"no-tokens-help": "Niciun token — creează unul pentru a începe asocierea dispozitivelor.",
"open-shell-settings": "Deschide setările aplicației",
"open-shell-settings-failed": "Setările aplicației desktop nu au putut fi deschise",
"order-platforms-by": "Ordonează platformele după",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Режим мультиплеера",
"multiplayer-hint": "Показывает кнопку «Присоединиться» на странице этой игры и оставляет чат и веб-камеру видимыми.",
"mute": "Отключить звук",
"native-applies": "Это также применяется к эмулятору на этом устройстве: {controls}.",
"native-browser-only": "Это применяется только к плееру в браузере: {controls}.",
"native-cancel": "Отменить запуск",
"native-cancel-failed": "Не удалось отменить запуск",
"native-canceled": "Запуск отменён",
"native-downloading": "Загрузка {percent}%",
"native-error-download": "Не удалось загрузить {name}",
"native-error-no-emulator": "Для этой платформы не настроен эмулятор",
"native-error-running": "{name} уже запущена",
"native-fetching-firmware": "Получение {firmware}",
"native-installing-core": "Установка {core}",
"native-launch-failed": "Не удалось запустить {name}",
"native-preparing": "Подготовка {emulator}",
"native-running": "{name} запущена",
"native-save-archived": "Сохранение для {name} сохранено отдельно, в RomM есть более новое",
"native-save-downloaded": "Сохранение для {name} загружено из RomM",
"native-save-failed": "Не удалось синхронизировать сохранение для {name}",
"native-save-uploaded": "Сохранение для {name} отправлено в RomM",
"native-starting": "Запуск…",
"native-syncing-save": "Синхронизация сохранения…",
"native-syncing-states": "Синхронизация состояний…",
"netplay": "Сетевая игра",
"new-memory-card": "Новая карта",
"new-slot": "+ Новый слот",
@@ -140,6 +161,9 @@
"pico8-screen": "Игровой экран PICO-8",
"pico8-up": "Вверх",
"play": "Играть",
"play-in-browser": "Играть в браузере",
"play-native": "Играть на этом устройстве",
"play-native-in": "Играть в {emulator}",
"play-on": "Стриминг на {label}",
"powered-by": "На базе",
"quick-state-loaded": "Быстрое состояние загружено",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Ваш токен создан. Выберите способ передачи:",
"delivery-intro-regenerate": "Ваш предыдущий токен отозван и создан новый. Выберите способ передачи:",
"description": "Description",
"desktop-shell": "Настольное приложение",
"desktop-shell-desc": "Пути к эмуляторам, кэш ROM и расположение библиотеки задаются в собственной конфигурации приложения на этом компьютере. Версия {version}.",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "Нет платформ.",
"no-tasks-in-history": "Нет задач в истории",
"no-tokens-help": "Нет токенов — создайте один, чтобы начать привязывать устройства.",
"open-shell-settings": "Открыть настройки приложения",
"open-shell-settings-failed": "Не удалось открыть настройки настольного приложения",
"order-platforms-by": "Сортировать платформы по",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "Çok oyunculu mod",
"multiplayer-hint": "Bu oyunun sayfasında bir Katıl düğmesi gösterir, sohbeti ve web kamerasını görünür tutar.",
"mute": "Sessize al",
"native-applies": "Bunlar bu cihazdaki emülatör için de geçerlidir: {controls}.",
"native-browser-only": "Bunlar yalnızca tarayıcı oynatıcısı için geçerlidir: {controls}.",
"native-cancel": "Başlatmayı iptal et",
"native-cancel-failed": "Başlatma iptal edilemedi",
"native-canceled": "Başlatma iptal edildi",
"native-downloading": "İndiriliyor {percent}%",
"native-error-download": "{name} indirilemedi",
"native-error-no-emulator": "Bu platform için yapılandırılmış bir emülatör yok",
"native-error-running": "{name} zaten çalışıyor",
"native-fetching-firmware": "{firmware} alınıyor",
"native-installing-core": "{core} yükleniyor",
"native-launch-failed": "{name} başlatılamadı",
"native-preparing": "{emulator} hazırlanıyor",
"native-running": "{name} çalışıyor",
"native-save-archived": "{name} kaydı ayrı olarak saklandı, RomM'de daha yeni bir kayıt var",
"native-save-downloaded": "{name} kaydı RomM'den yüklendi",
"native-save-failed": "{name} kaydı eşitlenemedi",
"native-save-uploaded": "{name} kaydı RomM'e gönderildi",
"native-starting": "Başlatılıyor…",
"native-syncing-save": "Kayıt eşitleniyor…",
"native-syncing-states": "Durumlar eşitleniyor…",
"netplay": "Ağ oyunu",
"new-memory-card": "Yeni kart",
"new-slot": "+ Yeni yuva",
@@ -140,6 +161,9 @@
"pico8-screen": "PICO-8 oyun ekranı",
"pico8-up": "Yukarı",
"play": "Oyna",
"play-in-browser": "Tarayıcıda oyna",
"play-native": "Bu cihazda oyna",
"play-native-in": "{emulator} ile oyna",
"play-on": "{label} üzerinde yayınla",
"powered-by": "Tarafından desteklenmektedir",
"quick-state-loaded": "Hızlı durum kaydı yüklendi",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "Tokenınız oluşturuldu. İletme yöntemini seçin:",
"delivery-intro-regenerate": "Önceki tokenınız iptal edildi ve yeni bir tane oluşturuldu. İletme yöntemini seçin:",
"description": "Description",
"desktop-shell": "Masaüstü uygulaması",
"desktop-shell-desc": "Emülatör yolları, ROM önbelleği ve kütüphane konumu bu makinedeki uygulamanın kendi yapılandırmasında belirlenir. Sürüm {version}.",
"developer": "Geliştirici",
"device-auth-approve": "Onayla",
"device-auth-approve-failed": "Cihaz onaylanamadı.",
@@ -258,6 +260,8 @@
"no-platforms": "Platform yok.",
"no-tasks-in-history": "Geçmişte görev yok",
"no-tokens-help": "İstemci API tokenı bulunamadı. Cihaz eşleştirmeye başlamak için bir tane oluşturun.",
"open-shell-settings": "Uygulama ayarlarını aç",
"open-shell-settings-failed": "Masaüstü uygulamasının ayarları açılamadı",
"order-platforms-by": "Platformları sırala",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "多人模式",
"multiplayer-hint": "在该游戏页面显示“加入”按钮,并保持聊天和摄像头可见。",
"mute": "静音",
"native-applies": "这些设置同样适用于本设备的模拟器:{controls}。",
"native-browser-only": "这些设置仅适用于浏览器播放器:{controls}。",
"native-cancel": "取消启动",
"native-cancel-failed": "无法取消启动",
"native-canceled": "已取消启动",
"native-downloading": "正在下载 {percent}%",
"native-error-download": "无法下载 {name}",
"native-error-no-emulator": "尚未为此平台配置模拟器",
"native-error-running": "{name} 已在运行",
"native-fetching-firmware": "正在获取 {firmware}",
"native-installing-core": "正在安装 {core}",
"native-launch-failed": "无法启动 {name}",
"native-preparing": "正在准备 {emulator}",
"native-running": "{name} 正在运行",
"native-save-archived": "{name} 的存档已另行保留,RomM 上有更新的进度",
"native-save-downloaded": "已从 RomM 加载 {name} 的存档",
"native-save-failed": "无法同步 {name} 的存档",
"native-save-uploaded": "已将 {name} 的存档发送到 RomM",
"native-starting": "正在启动…",
"native-syncing-save": "正在同步存档…",
"native-syncing-states": "正在同步即时存档…",
"netplay": "联机游戏",
"new-memory-card": "新建卡",
"new-slot": "+ 新建存档位",
@@ -140,6 +161,9 @@
"pico8-screen": "PICO-8 游戏画面",
"pico8-up": "上",
"play": "游玩",
"play-in-browser": "在浏览器中游玩",
"play-native": "在此设备上游玩",
"play-native-in": "在 {emulator} 中游玩",
"play-on": "在 {label} 上串流",
"powered-by": "技术支持",
"quick-state-loaded": "已加载快速即时存档",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "您的令牌已创建。请选择发送方式:",
"delivery-intro-regenerate": "您之前的令牌已被吊销,并已生成新令牌。请选择发送方式:",
"description": "描述",
"desktop-shell": "桌面客户端",
"desktop-shell-desc": "模拟器路径、ROM 缓存和库位置在本机客户端自己的配置中设置。版本 {version}。",
"developer": "开发者",
"device-auth-approve": "批准",
"device-auth-approve-failed": "批准设备失败。",
@@ -258,6 +260,8 @@
"no-platforms": "无平台。",
"no-tasks-in-history": "历史记录中无任务",
"no-tokens-help": "无令牌 — 创建一个以开始配对设备。",
"open-shell-settings": "打开客户端设置",
"open-shell-settings-failed": "无法打开桌面应用的设置",
"order-platforms-by": "平台排序方式",
"override-grant": "已授予",
"override-grant-own": "已授予(仅自己的条目)",

View File

@@ -120,6 +120,27 @@
"multiplayer": "多人模式",
"multiplayer-hint": "在此遊戲頁面顯示「加入」按鈕,並保持聊天與網路攝影機可見。",
"mute": "靜音",
"native-applies": "這些設定同樣適用於本機的模擬器:{controls}。",
"native-browser-only": "這些設定僅適用於瀏覽器播放器:{controls}。",
"native-cancel": "取消啟動",
"native-cancel-failed": "無法取消啟動",
"native-canceled": "已取消啟動",
"native-downloading": "正在下載 {percent}%",
"native-error-download": "無法下載 {name}",
"native-error-no-emulator": "尚未為此平台設定模擬器",
"native-error-running": "{name} 已在執行",
"native-fetching-firmware": "正在取得 {firmware}",
"native-installing-core": "正在安裝 {core}",
"native-launch-failed": "無法啟動 {name}",
"native-preparing": "正在準備 {emulator}",
"native-running": "{name} 正在執行",
"native-save-archived": "{name} 的存檔已另外保留,RomM 上有較新的進度",
"native-save-downloaded": "已從 RomM 載入 {name} 的存檔",
"native-save-failed": "無法同步 {name} 的存檔",
"native-save-uploaded": "已將 {name} 的存檔傳送到 RomM",
"native-starting": "正在啟動…",
"native-syncing-save": "正在同步存檔…",
"native-syncing-states": "正在同步即時存檔…",
"netplay": "連線遊戲",
"new-memory-card": "新增卡",
"new-slot": "+ 新增存檔格",
@@ -140,6 +161,9 @@
"pico8-screen": "PICO-8 遊戲畫面",
"pico8-up": "上",
"play": "遊玩",
"play-in-browser": "在瀏覽器中遊玩",
"play-native": "在此裝置上遊玩",
"play-native-in": "在 {emulator} 中遊玩",
"play-on": "在 {label} 上串流",
"powered-by": "技術提供",
"quick-state-loaded": "已載入快速即時存檔",

View File

@@ -97,6 +97,8 @@
"delivery-intro": "您的權杖已建立。請選擇傳遞方式:",
"delivery-intro-regenerate": "您先前的權杖已撤銷並已產生新權杖。請選擇傳遞方式:",
"description": "Description",
"desktop-shell": "桌面用戶端",
"desktop-shell-desc": "模擬器路徑、ROM 快取和媒體庫位置在本機用戶端自己的設定中指定。版本 {version}。",
"developer": "Developer",
"device-auth-approve": "Approve",
"device-auth-approve-failed": "Failed to approve device.",
@@ -258,6 +260,8 @@
"no-platforms": "沒有平台。",
"no-tasks-in-history": "歷史記錄中無任務",
"no-tokens-help": "沒有權杖 — 建立一個以開始配對裝置。",
"open-shell-settings": "開啟用戶端設定",
"open-shell-settings-failed": "無法開啟桌面應用程式的設定",
"order-platforms-by": "平台排序依據",
"override-grant": "Granted",
"override-grant-own": "Granted (own items only)",

View File

@@ -0,0 +1,275 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type {
PlatformSupportQuery,
RommNativeBridge,
} from "@/types/rommNative";
import {
canLaunchFullscreen,
canPickDisc,
canSyncSaves,
cancelNative,
fetchPlatformSupport,
hasCapability,
isNativeShell,
nativeErrorMessage,
openNativeSettings,
} from "./native";
// The shell's own cap on a bulk query, vendored in the service under test.
const MAX_PLATFORM_QUERIES = 512;
function queries(count: number): PlatformSupportQuery[] {
return Array.from({ length: count }, (_, i) => ({
platformSlug: `p${i}`,
cores: [],
}));
}
function supported(qs: PlatformSupportQuery[]) {
return Object.fromEntries(
qs.map((q) => [q.platformSlug, { supported: true, emulator: "RetroArch" }]),
);
}
function installBridge(bridge: Partial<RommNativeBridge>): void {
window.rommNative = bridge as RommNativeBridge;
}
beforeEach(() => {
delete window.rommNative;
vi.restoreAllMocks();
vi.spyOn(console, "error").mockImplementation(() => {});
});
describe("isNativeShell", () => {
it("is false in an ordinary browser tab", () => {
expect(isNativeShell()).toBe(false);
});
it("is false on a bridge that cannot launch", () => {
installBridge({ shellVersion: "0.1.0" });
expect(isNativeShell()).toBe(false);
});
});
describe("hasCapability", () => {
it("is false with no bridge, and on one that lists nothing", () => {
expect(hasCapability("save-sync")).toBe(false);
installBridge({ shellVersion: "0.1.0" });
expect(hasCapability("save-sync")).toBe(false);
});
it("reads the advertised list", () => {
installBridge({ shellVersion: "0.2.0", capabilities: ["save-sync"] });
expect(hasCapability("save-sync")).toBe(true);
});
});
describe("canSyncSaves", () => {
// A shell predating save sync still launches games; its saves just stay on
// this disk. Nothing is broken by asking it to move them.
it("is false on a shell too old to list capabilities", () => {
installBridge({ launch: vi.fn(), shellVersion: "0.1.0" });
expect(canSyncSaves()).toBe(false);
});
it("is true once the shell advertises it", () => {
installBridge({
launch: vi.fn(),
shellVersion: "0.2.0",
capabilities: ["save-sync"],
});
expect(canSyncSaves()).toBe(true);
});
});
describe("canLaunchFullscreen", () => {
// Such a shell starts the emulator however its own configuration says, so the
// page's switch stays the browser player's alone rather than claiming both.
it("is false on a shell that does not advertise it", () => {
installBridge({ launch: vi.fn(), capabilities: ["save-sync"] });
expect(canLaunchFullscreen()).toBe(false);
});
it("is true once the shell advertises it", () => {
installBridge({
launch: vi.fn(),
capabilities: ["launch-fullscreen"],
});
expect(canLaunchFullscreen()).toBe(true);
});
// Outside the shell there is no launch to make fullscreen.
it("is false with no bridge at all", () => {
expect(canLaunchFullscreen()).toBe(false);
});
});
describe("canPickDisc", () => {
// Such a shell boots a multi-disc set whole and changes disc in the
// emulator's own menu, so the page's selector must not claim it.
it("is false on a shell that does not advertise it", () => {
installBridge({ launch: vi.fn(), capabilities: ["save-sync"] });
expect(canPickDisc()).toBe(false);
});
it("is true once the shell advertises it", () => {
installBridge({ launch: vi.fn(), capabilities: ["disc-choice"] });
expect(canPickDisc()).toBe(true);
});
it("is false with no bridge at all", () => {
expect(canPickDisc()).toBe(false);
});
});
describe("fetchPlatformSupport — the bulk query", () => {
it("asks in batches no larger than the shell accepts", async () => {
const getPlatformSupportAll = vi
.fn()
.mockImplementation((qs: PlatformSupportQuery[]) =>
Promise.resolve(supported(qs)),
);
installBridge({ getPlatformSupportAll });
const answers = await fetchPlatformSupport(queries(1100));
expect(getPlatformSupportAll.mock.calls.map(([qs]) => qs.length)).toEqual([
MAX_PLATFORM_QUERIES,
MAX_PLATFORM_QUERIES,
1100 - MAX_PLATFORM_QUERIES * 2,
]);
expect(Object.keys(answers)).toHaveLength(1100);
});
// The shell rejects an oversized batch whole, so one refusal must not read as
// "no platform can be launched".
it("keeps the batches that answered when one is refused", async () => {
const getPlatformSupportAll = vi
.fn()
.mockRejectedValueOnce(new Error("too many"))
.mockImplementation((qs: PlatformSupportQuery[]) =>
Promise.resolve(supported(qs)),
);
installBridge({ getPlatformSupportAll });
const answers = await fetchPlatformSupport(queries(600));
expect(Object.keys(answers)).toHaveLength(600 - MAX_PLATFORM_QUERIES);
expect(answers.p600).toBeUndefined();
});
it("answers nothing, rather than throwing, without a bridge", async () => {
await expect(fetchPlatformSupport(queries(3))).resolves.toEqual({});
});
});
describe("fetchPlatformSupport — the per-platform fallback", () => {
it("falls back on a shell that predates the bulk method", async () => {
const getPlatformSupport = vi
.fn()
.mockResolvedValue({ supported: true, emulator: "PCSX2" });
installBridge({ getPlatformSupport });
const answers = await fetchPlatformSupport(queries(3));
expect(getPlatformSupport).toHaveBeenCalledTimes(3);
expect(answers.p0).toEqual({ supported: true, emulator: "PCSX2" });
});
// One call per platform, so a large library would otherwise open one
// renderer-to-main call per platform at once.
it("bounds how many it has in flight at once", async () => {
let inFlight = 0;
let peak = 0;
const getPlatformSupport = vi.fn().mockImplementation(async () => {
inFlight += 1;
peak = Math.max(peak, inFlight);
await Promise.resolve();
inFlight -= 1;
return { supported: false };
});
installBridge({ getPlatformSupport });
await fetchPlatformSupport(queries(1100));
expect(peak).toBeLessThanOrEqual(MAX_PLATFORM_QUERIES);
});
it("loses only the platform that could not be answered", async () => {
const getPlatformSupport = vi
.fn()
.mockRejectedValueOnce(new Error("no"))
.mockResolvedValue({ supported: true, emulator: "RetroArch" });
installBridge({ getPlatformSupport });
const answers = await fetchPlatformSupport(queries(3));
expect(answers.p0).toBeUndefined();
expect(Object.keys(answers)).toHaveLength(2);
});
});
describe("cancelNative", () => {
it("reports a request the shell never received", async () => {
installBridge({});
await expect(cancelNative(1)).resolves.toBe(false);
});
it("reports a request the shell threw on", async () => {
installBridge({ cancel: vi.fn().mockRejectedValue(new Error("nope")) });
await expect(cancelNative(1)).resolves.toBe(false);
});
// Delivery, not acceptance: the shell's cancel returns silently both when it
// knows no such launch and when the emulator has already started.
it("reports delivery when the shell takes the request", async () => {
installBridge({ cancel: vi.fn().mockResolvedValue(undefined) });
await expect(cancelNative(1)).resolves.toBe(true);
});
});
describe("openNativeSettings", () => {
it("answers false when the shell has no settings to open", async () => {
installBridge({});
await expect(openNativeSettings()).resolves.toBe(false);
});
it("answers false when the shell could not open them", async () => {
installBridge({
openSettings: vi.fn().mockRejectedValue(new Error("unwritable")),
});
await expect(openNativeSettings()).resolves.toBe(false);
});
it("answers true once the shell has opened them", async () => {
installBridge({ openSettings: vi.fn().mockResolvedValue(undefined) });
await expect(openNativeSettings()).resolves.toBe(true);
});
});
describe("nativeErrorMessage", () => {
// A LaunchFailure crossing the context bridge is a plain object, not an
// Error, and String() would render it as "[object Object]".
it("reads the message off a rejection that is not an Error", () => {
expect(
nativeErrorMessage({ code: "launch-failed", message: "no core" }),
).toBe("no core");
});
it("reads the message off an Error", () => {
expect(nativeErrorMessage(new Error("boom"))).toBe("boom");
});
it("falls back to the value itself when there is no message", () => {
expect(nativeErrorMessage("plain")).toBe("plain");
});
});

View File

@@ -0,0 +1,179 @@
// The only module that touches `window.rommNative`, the bridge the desktop shell
// injects. Every call feature-detects its own: a shell serves its own frontend.
import type {
LaunchRequest,
LaunchResult,
LaunchState,
PlatformSupport,
PlatformSupportQuery,
RommNativeBridge,
ShellCapability,
} from "@/types/rommNative";
function bridge(): RommNativeBridge | undefined {
return window.rommNative;
}
function hasMethod(name: keyof RommNativeBridge): boolean {
return typeof bridge()?.[name] === "function";
}
/** Whether this shell advertises a behaviour a method's presence cannot express.
* Read from the list, not `shellVersion`, which is for display only. */
export function hasCapability(name: ShellCapability): boolean {
return bridge()?.capabilities?.includes(name) === true;
}
/** Whether a native launch moves saves to and from the server. A shell without
* it leaves them on this disk. */
export function canSyncSaves(): boolean {
return isNativeShell() && hasCapability("save-sync");
}
/** Whether a native launch honours the page's full-screen choice, which is
* otherwise the browser player's alone. */
export function canLaunchFullscreen(): boolean {
return isNativeShell() && hasCapability("launch-fullscreen");
}
/** Whether a native launch honours the page's disc choice, which is otherwise
* the browser player's alone. Sent regardless: a shell drops unknown fields. */
export function canPickDisc(): boolean {
return isNativeShell() && hasCapability("disc-choice");
}
/** Whether the page is running inside the desktop shell at all. */
export function isNativeShell(): boolean {
return hasMethod("launch");
}
/** For display and support only. Behaviour is gated on the presence of the
* method being called, never on a parsed version. */
export function nativeShellVersion(): string | null {
return bridge()?.shellVersion ?? null;
}
/** The shell rejects a bulk query larger than this, whole, so a bigger library
* is asked in batches. Vendored from the shell's own limit. */
const MAX_PLATFORM_QUERIES = 512;
/** Ask which of these platforms the shell can launch, keyed by platform slug.
* Never throws: a failed probe means no native play, which is what it answers. */
export async function fetchPlatformSupport(
queries: PlatformSupportQuery[],
): Promise<Record<string, PlatformSupport>> {
const native = bridge();
if (!native || queries.length === 0) return {};
try {
if (typeof native.getPlatformSupportAll === "function") {
const bulk = native.getPlatformSupportAll.bind(native);
const answers: Record<string, PlatformSupport> = {};
for (let at = 0; at < queries.length; at += MAX_PLATFORM_QUERIES) {
const batch = queries.slice(at, at + MAX_PLATFORM_QUERIES);
try {
Object.assign(answers, await bulk(batch));
} catch (error) {
// One refused batch is not the rest of the library: a whole-batch
// rejection here would otherwise turn native play off everywhere.
console.error("[native] Could not probe a batch:", error);
}
}
return answers;
}
if (typeof native.getPlatformSupport !== "function") return {};
// One call per platform here, in the same batches: a full library would
// otherwise open a renderer-to-main call per platform at once.
const answers: Record<string, PlatformSupport> = {};
for (let at = 0; at < queries.length; at += MAX_PLATFORM_QUERIES) {
const batch = queries.slice(at, at + MAX_PLATFORM_QUERIES);
const settled = await Promise.all(
batch.map(async (query) => {
try {
return [query.platformSlug, await native.getPlatformSupport(query)];
} catch {
// One unanswerable platform should not lose the rest of the library.
return null;
}
}),
);
for (const entry of settled) {
if (entry) answers[entry[0] as string] = entry[1] as PlatformSupport;
}
}
return answers;
} catch (error) {
console.error("[native] Could not probe platform support:", error);
return {};
}
}
/** Start a ROM in a locally installed emulator. An older shell drops the error
* code crossing its IPC boundary, so it is read off the `failed` state. */
export function launchNative(request: LaunchRequest): Promise<LaunchResult> {
const native = bridge();
if (typeof native?.launch !== "function") {
return Promise.reject(new Error("The desktop shell cannot launch games."));
}
return native.launch(request);
}
/** Abort a still-downloading launch. Answers whether the request reached the
* shell: `cancel` is silent either way, so the outcome comes off the state. */
export async function cancelNative(romId: number): Promise<boolean> {
const native = bridge();
if (typeof native?.cancel !== "function") return false;
try {
await native.cancel(romId);
return true;
} catch (error) {
console.error("[native] Could not cancel the launch:", error);
return false;
}
}
/** The message out of anything the bridge throws, including a rejection that is
* a plain object rather than an Error. */
export function nativeErrorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
if (typeof error === "object" && error !== null && "message" in error) {
const { message } = error as { message: unknown };
if (typeof message === "string" && message !== "") return message;
}
return String(error);
}
/** Subscribe to launch progress. Returns an unsubscribe function, which is a
* no-op when there is no bridge to unsubscribe from. */
export function onNativeLaunchState(
listener: (state: LaunchState) => void,
): () => void {
const native = bridge();
if (typeof native?.onLaunchState !== "function") return () => {};
try {
return native.onLaunchState(listener);
} catch (error) {
console.error("[native] Could not subscribe to launch state:", error);
return () => {};
}
}
/** Whether this shell has settings to open, so an entry point for them can be
* hidden on one that does not. */
export function canOpenNativeSettings(): boolean {
return hasMethod("openSettings");
}
/** Ask the shell to show its own settings, answering whether it did, so a caller
* can tell a refusal from a press. */
export async function openNativeSettings(): Promise<boolean> {
const native = bridge();
if (typeof native?.openSettings !== "function") return false;
try {
await native.openSettings();
return true;
} catch (error) {
console.error("[native] Could not open the shell settings:", error);
return false;
}
}

View File

@@ -0,0 +1,632 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { SimpleRom } from "@/stores/roms";
import type {
LaunchRequest,
LaunchResult,
LaunchState,
PlatformSupport,
PlatformSupportQuery,
} from "@/types/rommNative";
const shellPresent = { value: true };
const fetchPlatformSupport = vi.fn(
async (
_queries: PlatformSupportQuery[],
): Promise<Record<string, PlatformSupport>> => ({}),
);
const launchNative = vi.fn(
async (_request: LaunchRequest): Promise<LaunchResult> => ({
romId: 1,
emulator: "RetroArch",
}),
);
// Resolves true by default: the shell taking the cancel is the ordinary case,
// and a test that wants a refusal says so.
const cancelNative = vi.fn(async (_romId: number): Promise<boolean> => true);
const unsubscribe = vi.fn();
// The shell's own launch-state stream, so a test can play back what it would
// send. Captured on install rather than passed in, exactly as the bridge does.
let emit: ((state: LaunchState) => void) | null = null;
// The bridge calls are stubbed; nativeErrorMessage is kept real, since what
// the store reports out of a rejection is exactly what it is for.
vi.mock("@/services/native", async (importOriginal) => ({
...(await importOriginal<typeof import("@/services/native")>()),
isNativeShell: () => shellPresent.value,
nativeShellVersion: () => "1.2.3",
fetchPlatformSupport,
launchNative,
cancelNative,
onNativeLaunchState: (listener: (state: LaunchState) => void) => {
emit = listener;
return unsubscribe;
},
}));
vi.mock("@/stores/config", () => ({ default: () => ({ config: {} }) }));
// A gallery card's rom carries no file entries, so the store fetches them.
const getRom = vi.fn(async (_args: { romId: number }) => ({
data: { files: [{ full_path: "psx/disc.chd", file_size_bytes: 700 }] },
}));
vi.mock("@/services/api/rom", () => ({ default: { getRom } }));
// The two rom-shape helpers are stubbed rather than reimplemented: what they
// answer is `utils`' own test. `soleFile` is the knob for "one file on disk".
const soleFile = {
value: null as { full_path: string; file_size_bytes: number } | null,
};
vi.mock("@/utils", () => ({
// Keyed off the rom handed in, like getSoleRomFile: the served name differs
// for a nested rom, so a test can tell which rom the store used.
getDownloadPath: ({ rom }: { rom: { files?: unknown[] } }) =>
(rom.files ?? []).length > 0
? "/api/roms/1/content/inner.sfc"
: "/api/roms/1/content/folder",
getDownloadFileName: () => "served-name.sfc",
// Keyed off the rom handed in, so a test can tell whether the store used the
// rom it was given or the one it fetched file entries for.
getSoleRomFile: (rom: { files?: unknown[] }) =>
(rom.files ?? []).length > 0 ? soleFile.value : null,
getSupportedEJSCores: () => ["snes9x"],
resolvePlatformSlug: (slug: string) => slug,
}));
const { useNativeStore } = await import("@/stores/native");
function makeRom(overrides: Partial<SimpleRom> = {}): SimpleRom {
return {
id: 1,
name: "Chrono Trigger",
fs_name: "Chrono Trigger.sfc",
fs_name_no_ext: "Chrono Trigger",
fs_size_bytes: 4194304,
full_path: "snes/Chrono Trigger.sfc",
platform_slug: "snes",
has_file_on_disk: true,
// As a single-rom endpoint answers. A gallery card passes `files: []`.
files: [{ full_path: "snes/game.sfc", file_size_bytes: 4194304 }],
...overrides,
} as unknown as SimpleRom;
}
beforeEach(() => {
setActivePinia(createPinia());
shellPresent.value = true;
emit = null;
fetchPlatformSupport.mockClear();
fetchPlatformSupport.mockResolvedValue({});
launchNative.mockClear();
launchNative.mockResolvedValue({ romId: 1, emulator: "RetroArch" });
cancelNative.mockClear();
cancelNative.mockResolvedValue(true);
getRom.mockClear();
getRom.mockResolvedValue({
data: { files: [{ full_path: "psx/disc.chd", file_size_bytes: 700 }] },
});
unsubscribe.mockClear();
soleFile.value = { full_path: "snes/game.sfc", file_size_bytes: 4194304 };
});
describe("useNativeStore.probe", () => {
it("caches the shell's answer behind the per-platform getters", async () => {
fetchPlatformSupport.mockResolvedValue({
snes: { supported: true, emulator: "RetroArch" },
ps3: { supported: false, reason: "unsupported-platform" },
});
const store = useNativeStore();
await store.probe(["snes", "ps3"]);
expect(store.isSupportedPlatform("snes")).toBe(true);
expect(store.labelForPlatform("snes")).toBe("RetroArch");
expect(store.isSupportedPlatform("ps3")).toBe(false);
});
it("answers for a slug asked in another case", async () => {
fetchPlatformSupport.mockResolvedValue({
SNES: { supported: true, emulator: "RetroArch" },
});
const store = useNativeStore();
await store.probe(["snes"]);
expect(store.isSupportedPlatform("SNES")).toBe(true);
expect(store.isSupportedPlatform("snes")).toBe(true);
});
// The library grows as platforms are scanned, and re-probing what is already
// answered would be an IPC call per boot per platform for nothing.
it("asks only about platforms it has no answer for", async () => {
fetchPlatformSupport.mockResolvedValue({
snes: { supported: true, emulator: "RetroArch" },
});
const store = useNativeStore();
await store.probe(["snes"]);
fetchPlatformSupport.mockResolvedValue({
ps2: { supported: true, emulator: "PCSX2" },
});
await store.probe(["snes", "ps2"]);
expect(fetchPlatformSupport).toHaveBeenLastCalledWith([
{ platformSlug: "ps2", cores: ["snes9x"] },
]);
expect(store.isSupportedPlatform("ps2")).toBe(true);
});
// An emulator installed while the page is open changes the answer, and the
// cached "no" would otherwise outlive it for the rest of the session.
it("re-asks about answered platforms when forced", async () => {
fetchPlatformSupport.mockResolvedValue({
ps2: { supported: false, reason: "no-emulator-configured" },
});
const store = useNativeStore();
await store.probe(["ps2"]);
fetchPlatformSupport.mockResolvedValue({
ps2: { supported: true, emulator: "PCSX2" },
});
await store.probe(["ps2"], { force: true });
expect(store.isSupportedPlatform("ps2")).toBe(true);
expect(store.labelForPlatform("ps2")).toBe("PCSX2");
});
// A forced probe the shell cannot answer must not take away an affordance
// that was working a moment ago.
it("keeps the answers it has when a forced re-ask comes back empty", async () => {
fetchPlatformSupport.mockResolvedValue({
snes: { supported: true, emulator: "RetroArch" },
});
const store = useNativeStore();
await store.probe(["snes"]);
fetchPlatformSupport.mockResolvedValue({});
await store.probe(["snes"], { force: true });
expect(store.isSupportedPlatform("snes")).toBe(true);
});
// A forced probe can start while the probe from mount is still in flight: the
// older reply landing last would undo a newly installed emulator's answer.
it("does not let a superseded probe overwrite a newer answer", async () => {
let answerOlder:
((answers: Record<string, PlatformSupport>) => void) | undefined;
fetchPlatformSupport.mockImplementationOnce(
() =>
new Promise((resolve) => {
answerOlder = resolve;
}),
);
const store = useNativeStore();
const older = store.probe(["snes"]);
fetchPlatformSupport.mockResolvedValue({
snes: { supported: true, emulator: "RetroArch" },
});
await store.probe(["snes"], { force: true });
answerOlder?.({
snes: { supported: false, reason: "no-emulator-configured" },
});
await older;
expect(store.isSupportedPlatform("snes")).toBe(true);
expect(store.labelForPlatform("snes")).toBe("RetroArch");
});
it("asks nothing at all outside the desktop shell", async () => {
shellPresent.value = false;
const store = useNativeStore();
await store.probe(["snes"]);
expect(fetchPlatformSupport).not.toHaveBeenCalled();
expect(store.isSupportedPlatform("snes")).toBe(false);
});
// An unprobed platform reading as unsupported is what keeps a Play button
// from appearing on a guess and then vanishing.
it("treats a platform it never asked about as unsupported", async () => {
const store = useNativeStore();
await store.probe(["snes"]);
expect(store.isSupportedPlatform("gba")).toBe(false);
expect(store.supportForPlatform("gba")).toBeNull();
});
});
describe("useNativeStore.launch", () => {
it("names the game, its cores and where the server keeps it", async () => {
const store = useNativeStore();
await store.launch(makeRom());
expect(launchNative).toHaveBeenCalledWith({
romId: 1,
downloadPath: "/api/roms/1/content/inner.sfc",
fileName: "served-name.sfc",
platformSlug: "snes",
cores: ["snes9x"],
name: "Chrono Trigger",
serverPath: "snes/game.sfc",
fileSize: 4194304,
});
});
// The shell resolves the first candidate it finds installed, and installs
// the first one it cannot find, so the page's pick has to lead the list.
it("puts the chosen core first and keeps the rest behind it", async () => {
const store = useNativeStore();
await store.launch(makeRom(), { core: "bsnes" });
expect(launchNative.mock.calls[0]?.[0].cores).toEqual(["bsnes", "snes9x"]);
});
it("names a chosen core once, however the platform lists it", async () => {
const store = useNativeStore();
await store.launch(makeRom(), { core: "snes9x" });
expect(launchNative.mock.calls[0]?.[0].cores).toEqual(["snes9x"]);
});
it("asks for a display mode only when the page answered", async () => {
const store = useNativeStore();
await store.launch(makeRom(), { fullscreen: true });
expect(launchNative.mock.calls[0]?.[0].fullscreen).toBe(true);
await store.launch(makeRom());
// Absent rather than false: a launch with nothing to say leaves the
// emulator's own configuration to decide.
expect(launchNative.mock.calls[1]?.[0]).not.toHaveProperty("fullscreen");
});
it("asks for a disc only when the page picked one", async () => {
const store = useNativeStore();
await store.launch(makeRom(), { disc: 102 });
expect(launchNative.mock.calls[0]?.[0].disc).toBe(102);
await store.launch(makeRom(), { disc: "all" });
expect(launchNative.mock.calls[1]?.[0].disc).toBe("all");
// A rom with one file has no disc to pick, and the shell looking for a set
// it does not have is the launch it performs anyway.
await store.launch(makeRom(), { disc: null });
expect(launchNative.mock.calls[2]?.[0]).not.toHaveProperty("disc");
await store.launch(makeRom());
expect(launchNative.mock.calls[3]?.[0]).not.toHaveProperty("disc");
});
// The rom's own fs_name is neither what a folder rom is served as nor what
// it is stored as, so the request carries what the helper resolved.
it("sends the name the endpoint will serve, not the rom's own", async () => {
const store = useNativeStore();
await store.launch(makeRom({ fs_name: "Art Of Fighting" }));
expect(launchNative.mock.calls[0]?.[0].fileName).toBe("served-name.sfc");
});
// Both the path and the name come from the fetched entries: a gallery card's
// rom carries none, and the two would then disagree about what is served.
it("builds the download path from the rom it fetched the files for", async () => {
const store = useNativeStore();
await store.launch(makeRom({ files: [] }));
expect(launchNative.mock.calls[0]?.[0].downloadPath).toBe(
"/api/roms/1/content/inner.sfc",
);
});
// `fs_name` is the served name for an ordinary rom but names the folder of a
// nested one, so a guess there caches the file under a name nothing opens.
it("refuses a nested rom whose files it could not read", async () => {
getRom.mockRejectedValueOnce(new Error("offline"));
const store = useNativeStore();
const refusal = await store.launch(
makeRom({
files: [],
has_nested_single_file: true,
} as Partial<SimpleRom>),
);
expect(refusal).toBeTruthy();
expect(launchNative).not.toHaveBeenCalled();
expect(store.isLaunching(1)).toBe(false);
});
it("launches an ordinary rom whose files it could not read", async () => {
getRom.mockRejectedValueOnce(new Error("offline"));
const store = useNativeStore();
const refusal = await store.launch(makeRom({ files: [] }));
expect(refusal).toBeNull();
expect(launchNative).toHaveBeenCalledTimes(1);
});
// A rom served as an archive built per request has no single path on disk, so
// claiming one would point the shell at a file that is not there.
it("offers no passthrough for a rom served as a built archive", async () => {
soleFile.value = null;
const store = useNativeStore();
await store.launch(makeRom());
const request = launchNative.mock.calls[0]?.[0];
expect(request?.serverPath).toBeUndefined();
expect(request?.fileSize).toBeUndefined();
});
// /api/roms omits file entries unless asked, so a rom straight off a gallery
// card cannot say what the download endpoint will serve it as.
it("fetches the file entries a gallery card's rom does not carry", async () => {
const store = useNativeStore();
await store.launch(makeRom({ files: [] }));
expect(getRom).toHaveBeenCalledWith({ romId: 1 });
// The fetched entries are what passthrough is then built from.
expect(launchNative.mock.calls[0]?.[0].serverPath).toBe("snes/game.sfc");
});
it("asks for nothing when the rom already carries its files", async () => {
const store = useNativeStore();
await store.launch(makeRom());
expect(getRom).not.toHaveBeenCalled();
expect(launchNative.mock.calls[0]?.[0].serverPath).toBe("snes/game.sfc");
});
// Nothing about reading the files may fail a launch: the shell can still
// download what the endpoint serves, it just cannot play it in place.
it("launches anyway when the files cannot be read", async () => {
getRom.mockRejectedValue(new Error("offline"));
const store = useNativeStore();
expect(await store.launch(makeRom({ files: [] }))).toBeNull();
expect(launchNative).toHaveBeenCalledTimes(1);
expect(launchNative.mock.calls[0]?.[0].serverPath).toBeUndefined();
});
it("resolves with nothing to report when the shell takes the launch", async () => {
const store = useNativeStore();
expect(await store.launch(makeRom())).toBeNull();
});
// No bridge, a malformed request, or a game already running: the shell
// rejects without ever reporting a state, so the caller has to.
it("reports a refusal the shell never explained", async () => {
launchNative.mockRejectedValue(new Error("Chrono Trigger is running."));
const store = useNativeStore();
expect(await store.launch(makeRom())).toBe("Chrono Trigger is running.");
});
it("reads the message off a LaunchFailure, which is not an Error", async () => {
// A shell carrying romm-desktop#11 rejects with a plain object, which
// String() renders as "[object Object]" for the user to read.
launchNative.mockRejectedValue({
name: "LaunchError",
code: "already-running",
message: "Chrono Trigger is already running.",
});
const store = useNativeStore();
expect(await store.launch(makeRom())).toBe(
"Chrono Trigger is already running.",
);
});
// A failure the shell did report carries an error code this rejection
// cannot, so it is left to the launch state to surface.
it("stays quiet when the shell explained the failure itself", async () => {
const store = useNativeStore();
store.install();
launchNative.mockImplementation(async () => {
emit?.({
romId: 1,
status: "failed",
error: { code: "emulator-not-found", message: "No RetroArch here." },
});
throw new Error("No RetroArch here.");
});
expect(await store.launch(makeRom())).toBeNull();
expect(store.launchStateFor(1)?.error?.code).toBe("emulator-not-found");
});
});
describe("useNativeStore launch state", () => {
it("reads as launching until the game reaches the emulator", () => {
const store = useNativeStore();
store.install();
emit?.({ romId: 1, status: "downloading", stage: "rom", progress: 0.5 });
expect(store.isLaunching(1)).toBe(true);
emit?.({ romId: 1, status: "running" });
expect(store.isLaunching(1)).toBe(false);
expect(store.launchStateFor(1)?.status).toBe("running");
});
it("subscribes once however often it is installed", () => {
const store = useNativeStore();
store.install();
const first = emit;
store.install();
expect(emit).toBe(first);
});
// The shell has no cancelled status: it aborts the transfer, so the launch
// fails and reports a failed download. That is the cancel, not news.
it("owns the failure its own cancel causes, once", async () => {
const store = useNativeStore();
store.install();
emit?.({ romId: 1, status: "downloading", stage: "rom" });
await store.cancel(1);
emit?.({
romId: 1,
status: "failed",
error: { code: "download-failed", message: "Launch cancelled" },
});
expect(store.launchStateFor(1)).toBeNull();
expect(store.consumeCancelled(1)).toBe(true);
// Answered once, so a later genuine failure still reports.
expect(store.consumeCancelled(1)).toBe(false);
});
// Delivery is not acceptance: the shell returns silently when the emulator
// has already started, so a launch that went on running must still report.
it("reports a failure that is not the cancelled transfer", async () => {
const store = useNativeStore();
store.install();
emit?.({ romId: 1, status: "downloading", stage: "rom" });
await store.cancel(1);
emit?.({
romId: 1,
status: "failed",
error: { code: "emulator-not-found", message: "gone" },
});
expect(store.consumeCancelled(1)).toBe(false);
expect(store.launchStateFor(1)?.error?.code).toBe("emulator-not-found");
});
it("drops the cancel when the game started anyway", async () => {
const store = useNativeStore();
store.install();
emit?.({ romId: 1, status: "downloading", stage: "rom" });
await store.cancel(1);
emit?.({ romId: 1, status: "running" });
expect(store.consumeCancelled(1)).toBe(false);
expect(store.launchStateFor(1)?.status).toBe("running");
});
it("does not swallow a failure for a launch nobody cancelled", () => {
const store = useNativeStore();
store.install();
emit?.({
romId: 1,
status: "failed",
error: { code: "emulator-not-found", message: "gone" },
});
expect(store.consumeCancelled(1)).toBe(false);
expect(store.launchStateFor(1)?.error?.code).toBe("emulator-not-found");
});
// The mark goes on only once the shell has taken the cancel, so a failure
// that arrives while the request is in flight is still the user's to see.
it("reports a failure that lands while a cancel is in flight", async () => {
const store = useNativeStore();
store.install();
// A no-op default rather than null: assigned inside the executor, which
// control-flow analysis cannot see, so a nullable here narrows to never.
let accept: (taken: boolean) => void = () => {};
cancelNative.mockImplementation(
() =>
new Promise<boolean>((resolve) => {
accept = resolve;
}),
);
const pending = store.cancel(1);
emit?.({
romId: 1,
status: "failed",
error: { code: "emulator-not-found", message: "No PCSX2 here." },
});
// Nothing has suppressed it: this failure is not the cancel's.
expect(store.consumeCancelled(1)).toBe(false);
accept(false);
expect(await pending).toBe(false);
});
it("leaves the launch alone when the shell refuses the cancel", async () => {
// A refused cancel changes nothing: claiming otherwise would clear a launch
// that is still coming, and the mark would swallow its real failure.
const store = useNativeStore();
store.install();
emit?.({ romId: 1, status: "downloading", progress: 0.5 });
cancelNative.mockResolvedValueOnce(false);
expect(await store.cancel(1)).toBe(false);
expect(store.launchStateFor(1)?.status).toBe("downloading");
// And the failure that follows is reported, not eaten as the cancel.
emit?.({
romId: 1,
status: "failed",
error: { code: "download-failed", message: "Connection lost." },
});
expect(store.consumeCancelled(1)).toBe(false);
});
it("drops the record on a cancel, which the shell never reports", async () => {
const store = useNativeStore();
store.install();
emit?.({ romId: 1, status: "downloading", stage: "rom" });
await store.cancel(1);
expect(cancelNative).toHaveBeenCalledWith(1);
expect(store.launchStateFor(1)).toBeNull();
expect(store.isLaunching(1)).toBe(false);
});
});
describe("useNativeStore save sync", () => {
// A save moves after the rom is ready and before the emulator starts, so a
// sync landing mid-launch must not read as the launch having ended.
it("files a save outcome without touching the launch around it", () => {
const store = useNativeStore();
store.install();
emit?.({ romId: 1, status: "downloading", stage: "rom" });
emit?.({ romId: 1, status: "sync", sync: { action: "downloaded" } });
expect(store.syncFor(1)).toEqual({ action: "downloaded" });
expect(store.launchStateFor(1)?.status).toBe("downloading");
expect(store.isLaunching(1)).toBe(true);
});
// The page watching for the next outcome must not be sent to the last one.
it("forgets the last save when the next launch starts", async () => {
const store = useNativeStore();
store.install();
emit?.({
romId: 1,
status: "sync",
sync: { action: "archived", slot: null },
});
await store.launch(makeRom());
expect(store.syncFor(1)).toBeNull();
});
it("has nothing to say about a rom the shell has not spoken about", () => {
const store = useNativeStore();
store.install();
expect(store.syncFor(2)).toBeNull();
expect(store.syncFor(null)).toBeNull();
});
});

View File

@@ -0,0 +1,375 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import romApi from "@/services/api/rom";
import {
canLaunchFullscreen,
canPickDisc,
cancelNative,
fetchPlatformSupport,
isNativeShell,
launchNative,
nativeErrorMessage,
nativeShellVersion,
onNativeLaunchState,
} from "@/services/native";
import storeConfig from "@/stores/config";
import type { SimpleRom } from "@/stores/roms";
import type {
LaunchState,
PlatformSupport,
SaveSyncOutcome,
} from "@/types/rommNative";
import {
getDownloadFileName,
getDownloadPath,
getSoleRomFile,
getSupportedEJSCores,
resolvePlatformSlug,
} from "@/utils";
import type { DiscSelection } from "@/v2/utils/playerDisc";
export type { LaunchState, PlatformSupport } from "@/types/rommNative";
/** What the play page has already settled about a session. Every field is
* optional: a gallery card with no panel behind it asks for none of it. */
export interface NativeLaunchChoice {
/** The core to try first. A name the shell cannot find is one it installs, so
* this is honoured even for a core the machine has never had. */
core?: string | null;
/** Whether to start the emulator fullscreen. Undefined asks for nothing,
* leaving the emulator's own configuration to decide. */
fullscreen?: boolean;
/** Which file of a multi-disc rom to boot, or ALL_DISCS for the whole set.
* Null and undefined both ask for nothing, which boots the set whole. */
disc?: DiscSelection;
}
// ── Store ─────────────────────────────────────────────────────────────────────
/** Native play through the RomM desktop shell. The getters answer synchronously
* and are never cached beyond the session: they describe the user's machine. */
export const useNativeStore = defineStore("native", () => {
const configStore = storeConfig();
/** Whether the page is running inside the shell at all. */
const available = ref(isNativeShell());
const shellVersion = ref(nativeShellVersion());
/** Whether a native launch takes the page's full-screen choice with it.
* Read once, like the two above: the bridge is injected before the app
* boots and a shell cannot gain a capability while its page is open. */
const honoursFullscreen = ref(canLaunchFullscreen());
/** Whether a launch takes the page's disc choice with it. Read once, like
* the others: a shell cannot gain a capability while its page is open. */
const honoursDisc = ref(canPickDisc());
// Null prototype: RomM keeps whatever slug a folder is named, so "constructor"
// and "toString" are slugs like any other, and on a plain object they would
// read as already answered and return an inherited value.
const support = ref<Record<string, PlatformSupport>>(
Object.create(null) as Record<string, PlatformSupport>,
);
// The probe that asked about each slug last, so an answer cannot outlive the
// request that superseded it: a focus re-probe overlaps the probe still in
// flight from mount, and the shell's answer changes between them.
let probeSeq = 0;
const askedAt = new Map<string, number>();
/** The shell's last word on each launch, keyed by ROM id. */
const launches = ref<Record<number, LaunchState>>({});
/** What happened to a save around each launch, keyed by ROM id. Kept apart
* from `launches` because it is not about the launch: the game has finished,
* and the save outlives the state that reported it. */
const syncs = ref<Record<number, SaveSyncOutcome>>({});
/** Display names, so launch feedback can name a game the shell identifies
* only by id. */
const names = ref<Record<number, string>>({});
/** Held from the click until `launch()` settles, so a button reads as busy
* before the shell has said anything about the launch. */
const starting = ref(new Set<number>());
/** Bumped per ROM on every state the shell sends, so `launch()` can tell a
* rejection the shell has already explained from one it has not. */
const stateCount = ref<Record<number, number>>({});
/** ROMs whose launch this page cancelled. The shell has no cancelled status:
* it aborts the transfer, which fails the launch, so the failure it then
* reports is the cancel and must not be surfaced as one. */
const cancelled = ref(new Set<number>());
let unsubscribe: (() => void) | null = null;
// ── Getters ────────────────────────────────────────────────────────────────
function supportForPlatform(
slug: string | null | undefined,
): PlatformSupport | null {
if (!slug) return null;
return support.value[slug.toLowerCase()] ?? null;
}
/** Whether the shell can launch this platform. An unprobed one reads as
* unsupported, so no affordance is ever offered on a guess. */
function isSupportedPlatform(slug: string | null | undefined): boolean {
return supportForPlatform(slug)?.supported === true;
}
/** What to call the emulator a launch would use, for any surface that names
* where the game runs. */
function labelForPlatform(slug: string | null | undefined): string | null {
return supportForPlatform(slug)?.emulator ?? null;
}
function launchStateFor(
romId: number | null | undefined,
): LaunchState | null {
if (romId == null) return null;
return launches.value[romId] ?? null;
}
/** What the shell said about this ROM's save, or null when it has said
* nothing since the last launch began. */
function syncFor(romId: number | null | undefined): SaveSyncOutcome | null {
if (romId == null) return null;
return syncs.value[romId] ?? null;
}
/** Whether a launch is still on its way to the emulator, and so still
* cancellable. A game that has started is the shell's business. */
function isLaunching(romId: number | null | undefined): boolean {
if (romId == null) return false;
return (
starting.value.has(romId) ||
launches.value[romId]?.status === "downloading"
);
}
function nameFor(romId: number): string {
return names.value[romId] ?? "";
}
/** Whether a cancel is outstanding for this ROM, answered once so a genuine
* failure later still reports. Any other ending clears the mark. */
function consumeCancelled(romId: number): boolean {
if (!cancelled.value.has(romId)) return false;
cancelled.value.delete(romId);
return true;
}
// ── Actions ────────────────────────────────────────────────────────────────
/** Start listening for launch progress. Idempotent, and a no-op without a
* shell to listen to. */
function install(): void {
if (unsubscribe) return;
unsubscribe = onNativeLaunchState((state) => {
stateCount.value = {
...stateCount.value,
[state.romId]: (stateCount.value[state.romId] ?? 0) + 1,
};
// A save moving is not the launch moving: filed apart and returned from,
// so a sync landing mid-launch cannot read as the launch having ended.
if (state.status === "sync") {
if (state.sync) {
syncs.value = { ...syncs.value, [state.romId]: state.sync };
}
return;
}
if (state.status !== "downloading") starting.value.delete(state.romId);
if (cancelled.value.has(state.romId)) {
// An aborted transfer is how a cancel the shell took comes back, so
// that failure belongs to the cancel and the record it dropped stays
// dropped.
if (
state.status === "failed" &&
state.error?.code === "download-failed"
)
return;
// Any other ending means the cancel never landed. The mark comes off
// so the launch reports itself, rather than being silenced by a
// cancellation that did not happen.
if (state.status !== "downloading") cancelled.value.delete(state.romId);
}
launches.value = { ...launches.value, [state.romId]: state };
});
}
/** Ask the shell which of these platforms it can launch, and cache the
* answers. Merged rather than cleared, so an affordance never blinks out.
*
* Args:
* force: re-ask about platforms already answered, for when the machine
* itself may have changed.
*/
async function probe(
slugs: string[],
{ force = false }: { force?: boolean } = {},
): Promise<void> {
install();
if (!available.value) return;
const wanted = new Set(
slugs
.filter(Boolean)
.map((slug) => slug.toLowerCase())
.filter((slug) => force || !(slug in support.value)),
);
if (wanted.size === 0) return;
const seq = ++probeSeq;
for (const slug of wanted) askedAt.set(slug, seq);
const answers = await fetchPlatformSupport(
[...wanted].map((slug) => ({
platformSlug: slug,
cores: getSupportedEJSCores(
resolvePlatformSlug(slug, configStore.config),
),
})),
);
const merged = Object.assign(
Object.create(null) as Record<string, PlatformSupport>,
support.value,
);
for (const [slug, answer] of Object.entries(answers)) {
const key = slug.toLowerCase();
// A slug a later probe has since asked about belongs to that probe.
if (askedAt.get(key) !== seq) continue;
merged[key] = answer;
}
support.value = merged;
}
/** The platform's cores with the page's choice at the front, named once. A
* core the platform map does not list is still honoured: the page offered
* it, and the shell's own preferences outrank this list anyway. */
function coresFor(rom: SimpleRom, chosen?: string | null): string[] {
const supported = getSupportedEJSCores(
resolvePlatformSlug(rom.platform_slug, configStore.config),
);
if (!chosen) return supported;
return [chosen, ...supported.filter((core) => core !== chosen)];
}
/** The rom with its file entries, fetched when the copy in hand has none.
* `/api/roms` omits them unless asked (`with_files`), so a rom off a gallery
* card cannot say what the download endpoint will serve it as. */
async function withRomFiles(rom: SimpleRom): Promise<SimpleRom> {
if ((rom.files ?? []).length > 0) return rom;
try {
const { data } = await romApi.getRom({ romId: rom.id });
return { ...rom, files: data.files };
} catch (error) {
console.error("[native] Could not read the rom's files:", error);
return rom;
}
}
/** Hand a ROM to the shell to launch, resolving with an error only when the
* shell never took the request: a launch it accepted and then failed is left
* to the launch state.
*
* Args:
* choice: what the play page has already asked the user, so a native launch
* honours the same answers as the in-browser one.
*/
async function launch(
rom: SimpleRom,
choice: NativeLaunchChoice = {},
): Promise<string | null> {
const before = stateCount.value[rom.id] ?? 0;
// A fresh launch is not the cancelled one, however the last ended.
cancelled.value.delete(rom.id);
// Nor does it carry the last launch's save outcome: a view watching for the
// next one must not be sent to the old one on the way in.
const { [rom.id]: _synced, ...withoutSync } = syncs.value;
syncs.value = withoutSync;
starting.value.add(rom.id);
names.value = {
...names.value,
[rom.id]: rom.name ?? rom.fs_name_no_ext,
};
// A gallery list is fetched without file entries, so a card's rom has none
// and both helpers below would answer from the rom's own name. Fetched
// rather than guessed.
const detailed = await withRomFiles(rom);
// A nested rom is served as the file inside it, so without the entries there
// is nothing to name the download and the shell caches an unopenable name.
if ((detailed.files ?? []).length === 0 && rom.has_nested_single_file) {
starting.value.delete(rom.id);
return "The rom's files could not be read.";
}
// Passthrough needs one real file to point at, which a rom served as a
// built-on-request archive does not have.
const soleFile = getSoleRomFile(detailed);
try {
await launchNative({
romId: rom.id,
downloadPath: getDownloadPath({ rom: detailed }),
// What the endpoint will actually serve, which for a folder rom is
// neither `fs_name` nor `fs_name` with an extension.
fileName: getDownloadFileName(detailed),
platformSlug: rom.platform_slug,
// The page's core first: the shell installs the first candidate it
// cannot find, so the rest are there for a core that is not published.
cores: coresFor(rom, choice.core),
name: rom.name ?? undefined,
// Sent whatever the shell advertises: an older one drops an unknown
// field and starts the emulator as its own config says, which is
// where it was before the page could ask.
...(choice.fullscreen === undefined
? {}
: { fullscreen: choice.fullscreen }),
// A rom with one file has no disc to pick, so the page's answer for it
// is not one to send: the shell would look for a disc set and find a
// single file, which is the launch it performs anyway.
...(choice.disc == null ? {} : { disc: choice.disc }),
// Lets a shell on the same machine as the server play the file where it
// already is. A shell without library-passthrough downloads instead.
...(soleFile
? {
serverPath: soleFile.full_path,
fileSize: soleFile.file_size_bytes,
}
: {}),
});
return null;
} catch (error) {
if ((stateCount.value[rom.id] ?? 0) > before) return null;
return nativeErrorMessage(error);
} finally {
starting.value.delete(rom.id);
}
}
/** Ask the shell to abort a launch, answering whether the request reached it.
* Delivery is not acceptance: the mark lands when the transfer aborts. */
async function cancel(romId: number): Promise<boolean> {
if (!(await cancelNative(romId))) return false;
cancelled.value.add(romId);
starting.value.delete(romId);
// The shell acknowledges a cancel by dropping the launch rather than by
// reporting a state for it, so the record has to go from here.
const { [romId]: _dropped, ...rest } = launches.value;
launches.value = rest;
return true;
}
return {
available,
shellVersion,
honoursFullscreen,
honoursDisc,
// Exposed for a caller that builds a function inside a computed and needs
// it rebuilt when the probe lands, the way streaming exposes its config.
support,
supportForPlatform,
isSupportedPlatform,
labelForPlatform,
launchStateFor,
syncFor,
isLaunching,
nameFor,
consumeCancelled,
install,
probe,
launch,
cancel,
};
});

195
frontend/src/types/rommNative.d.ts vendored Normal file
View File

@@ -0,0 +1,195 @@
// The `window.rommNative` bridge the RomM desktop shell injects into the page
// it loads, so the server's own frontend can launch a ROM in a locally
// installed emulator.
//
// Vendored: the canonical definition is `src/shared/types.ts` in
// rommapp/romm-desktop, which owns the contract. Keep the names and shapes
// identical to it so the two can be diffed. A stale copy here stays safe
// because `services/native.ts` feature-detects every call at runtime.
/** Why a launch could not be started. */
export type LaunchErrorCode =
| "unsupported-platform"
| "no-emulator-configured"
| "emulator-not-found"
| "download-failed"
| "already-running"
| "invalid-request"
| "launch-failed";
/** A launch as the renderer asks for it: it names the game and its candidate
* cores, never an executable. The shell resolves the emulator itself. */
export interface LaunchRequest {
romId: number;
/** Server-relative download path, as built by `getDownloadPath`. */
downloadPath: string;
/** Used to name the cached file, never used as a path on its own. */
fileName: string;
platformSlug: string;
/** Candidate libretro core names from the platform/core map. */
cores: string[];
/** Display name, used for window titles and logs. */
name?: string;
/** The ROM's path relative to the server's library root, as `full_path`
* reports it. Only ever joined onto the user's own library root, so a
* server on the same machine launches the file where it already is. */
serverPath?: string;
/** Size in bytes as the server reports it, checked against the local file
* before it stands in for a download. */
fileSize?: number;
/** Start the emulator fullscreen, so the play page's own choice covers both
* routes. Only a shell advertising `launch-fullscreen` acts on it, and only
* on its built-in RetroArch path; a configured emulator decides it in the
* arguments its owner wrote. */
fullscreen?: boolean;
/** Which of a multi-disc rom's files to boot, as the page's disc selector
* asks it: a rom file's id, or `"all"` for the whole set. Only a shell
* advertising `disc-choice` acts on it; one without always boots the set
* whole, which is where it was before the page could ask. */
disc?: number | "all";
}
export type LaunchStatus =
| "downloading"
| "running"
| "exited"
| "failed"
/** A save moved, after the emulator had already exited. Its own status rather
* than a stage, because it outlives the launch it belongs to: the exit is
* reported immediately and the upload settles afterwards. */
| "sync";
/** What happened to a save around one launch. */
export type SaveSyncAction =
/** The server's copy was written over the local one before the emulator ran. */
| "downloaded"
/** What the emulator wrote was sent to the save's slot. */
| "uploaded"
/** Nothing was replaced. The local bytes were kept as an archival save
* because the slot held progress this device had not seen. */
| "archived"
/** It was tried and did not work. The local file is untouched. */
| "failed";
export interface SaveSyncOutcome {
action: SaveSyncAction;
/** The slot the save moved through, absent for an archival save, which
* deliberately sits outside every slot. */
slot?: string | null;
/** Why, when the outcome was a failure. For logs, not for display: the
* action has a message of its own. */
detail?: string;
}
export interface LaunchState {
romId: number;
status: LaunchStatus;
/** What is being fetched while downloading. Absent means the ROM.
* "emulator" covers both fetching a standalone emulator and the wait while
* the user installs it, which has no progress to report. "save" is the save
* pull, after the ROM is ready and before the emulator starts, and "state"
* is the savestate restore, just before it does. */
stage?: "rom" | "core" | "emulator" | "firmware" | "save" | "state";
/** The core being installed, while stage is "core". */
core?: string;
/** The firmware file being fetched, while stage is "firmware". Its own field
* rather than borrowing `core`, so neither has to be read as the other. */
firmware?: string;
/** The file being fetched out of a multi-disc set, and its place in that set,
* so a transfer per disc is not read as one restarting at 0%. Not every file
* is a disc of its own: a sheet's tracks are fetched with it. */
file?: string;
fileIndex?: number;
fileCount?: number;
/** The emulator being set up, while stage is "emulator". */
emulator?: string;
/** 0..1 while downloading, absent otherwise. */
progress?: number;
/** Bytes transferred so far, while downloading. */
received?: number;
/** Total bytes, when the server declared a length. */
total?: number;
/** Smoothed transfer rate, once there are two samples to compare. */
bytesPerSecond?: number;
/** Set when status is "failed". */
error?: { code: LaunchErrorCode; message: string };
/** Process exit code, set when status is "exited". */
exitCode?: number | null;
/** What happened to a save, set when status is "sync". */
sync?: SaveSyncOutcome;
}
export interface LaunchResult {
romId: number;
/** The emulator that was started, for display. */
emulator: string;
}
/** Asks whether a platform can be launched, given the cores it supports. */
export interface PlatformSupportQuery {
platformSlug: string;
cores: string[];
}
/** Whether a given platform can be launched natively, and by what. */
export interface PlatformSupport {
supported: boolean;
/** Human-readable emulator name when supported. */
emulator?: string;
/** Set when unsupported, so the reason can be explained. */
reason?: Extract<
LaunchErrorCode,
"unsupported-platform" | "no-emulator-configured" | "emulator-not-found"
>;
/** The resolver's own message for the unsupported case, naming the paths it
* looked at. English only, so it belongs in a log rather than in the UI. */
detail?: string;
}
/** Behaviour the presence of a method cannot express: a `LaunchRequest` field
* the shell honours, a `LaunchState` field it populates, a change to what an
* existing method does, advertised on the bridge's `capabilities`. */
export type ShellCapability =
| "launch-stage"
| "library-passthrough"
| "platform-support-all"
| "firmware-mirror"
| "multi-disc"
/** Saves are moved between the server and the emulator around a native
* launch. Save states are a separate setting, and a shell without this
* leaves both sides of it undone. */
| "save-sync"
/** Save states travel both ways: the ones RomM holds for the emulator a
* launch runs are restored into their slots before it starts, reported as
* the "state" stage, and the ones the run writes go up after it exits. A
* shell without this only sends them. */
| "state-restore"
/** `LaunchRequest.disc` is honoured, so the page's disc selector covers a
* native launch too: one disc of a set is fetched and booted on its own. */
| "disc-choice"
/** `LaunchRequest.fullscreen` is honoured, so the page's own full-screen
* choice covers a native launch as well as the in-browser one. */
| "launch-fullscreen";
export interface RommNativeBridge {
readonly shellVersion: string;
readonly os: "darwin" | "win32" | "linux";
/** Plain strings rather than `ShellCapability`, so a newer shell's entries
* are readable here without being a type error. */
readonly capabilities: readonly string[];
launch(request: LaunchRequest): Promise<LaunchResult>;
cancel(romId: number): Promise<void>;
getPlatformSupport(query: PlatformSupportQuery): Promise<PlatformSupport>;
getPlatformSupportAll(
queries: PlatformSupportQuery[],
): Promise<Record<string, PlatformSupport>>;
/** Subscribe to launch progress. Returns an unsubscribe function. */
onLaunchState(listener: (state: LaunchState) => void): () => void;
openSettings(): Promise<void>;
}
declare global {
interface Window {
rommNative?: RommNativeBridge;
}
}

View File

@@ -1,6 +1,11 @@
import { describe, expect, it } from "vitest";
import type { SimpleRom } from "@/stores/roms";
import { getDownloadLink, getDownloadPath } from "./downloadPath";
import {
getDownloadFileName,
getDownloadLink,
getDownloadPath,
getSoleRomFile,
} from "./downloadPath";
import { makeRom } from "./rom.fixtures";
describe("getDownloadPath", () => {
@@ -130,3 +135,67 @@ describe("download URL encoding", () => {
);
});
});
describe("getDownloadFileName", () => {
it("names a flat single-file rom by its file", () => {
const rom = makeRom({
fs_name: "Maniac Mansion (1989).adf",
files: [
{ id: 19, file_name: "Maniac Mansion (1989).adf" },
] as SimpleRom["files"],
});
expect(getDownloadFileName(rom)).toBe("Maniac Mansion (1989).adf");
});
// The endpoint serves the sole file under its own name, so the folder's
// name would save the payload as something the emulator cannot open.
it("names a nested single-file rom by the file inside it", () => {
const rom = makeRom({
fs_name: "Art Of Fighting",
has_nested_single_file: true,
files: [{ id: 21, file_name: "aof.zip" }] as SimpleRom["files"],
});
expect(getDownloadFileName(rom)).toBe("aof.zip");
});
// Several files come back as an archive the endpoint builds, named for the
// rom, so the extension has to be there or nothing will open it.
it("names a multi-file rom as the archive it is served as", () => {
const rom = makeRom({
fs_name: "Final Fantasy VII",
has_multiple_files: true,
files: [
{ id: 1, file_name: "disc1.chd" },
{ id: 2, file_name: "disc2.chd" },
] as SimpleRom["files"],
});
expect(getDownloadFileName(rom)).toBe("Final Fantasy VII.zip");
});
it("falls back to the rom name when nothing is on disk", () => {
expect(getDownloadFileName(makeRom({ fs_name: "Ghost" }))).toBe("Ghost");
});
});
describe("getSoleRomFile", () => {
it("returns the one file a rom resolves to", () => {
const rom = makeRom({
files: [
{ id: 7, file_name: "game.sfc", full_path: "snes/game.sfc" },
] as SimpleRom["files"],
});
expect(getSoleRomFile(rom)?.full_path).toBe("snes/game.sfc");
});
// There is no single path to a payload the endpoint assembles per request.
it("returns nothing for a rom served as a built archive", () => {
const rom = makeRom({
files: [
{ id: 1, file_name: "disc1.chd" },
{ id: 2, file_name: "disc2.chd" },
] as SimpleRom["files"],
});
expect(getSoleRomFile(rom)).toBeNull();
expect(getSoleRomFile(makeRom({}))).toBeNull();
});
});

View File

@@ -1,3 +1,4 @@
import type { RomFileSchema } from "@/__generated__";
import type { SimpleRom } from "@/stores/roms";
/** Build the `/api` path that serves a ROM's content. */
@@ -37,6 +38,23 @@ export function getDownloadPath({
}`;
}
/** The name the content endpoint serves a whole rom under: the sole file's own
* name, or the rom's name with a zip extension, mirroring `get_rom_content`. */
export function getDownloadFileName(rom: SimpleRom): string {
const files = rom.files ?? [];
if (files.length === 1) return files[0].file_name;
// Nothing to serve; callers gate on a file being on disk.
if (files.length === 0) return rom.fs_name;
return `${rom.fs_name}.zip`;
}
/** The one file this rom resolves to on disk, or null when it resolves to
* several and the endpoint builds an archive instead. */
export function getSoleRomFile(rom: SimpleRom): RomFileSchema | null {
const files = rom.files ?? [];
return files.length === 1 ? files[0] : null;
}
export function getDownloadLink({
rom,
fileIDs = [],

View File

@@ -9,7 +9,12 @@ import type { Heartbeat } from "@/stores/heartbeat";
import storeNavigation from "@/stores/navigation";
import type { DetailedRom, SimpleRom } from "@/stores/roms";
export { getDownloadLink, getDownloadPath } from "@/utils/downloadPath";
export {
getDownloadFileName,
getDownloadLink,
getDownloadPath,
getSoleRomFile,
} from "@/utils/downloadPath";
/**
* Views configuration object.

View File

@@ -58,7 +58,7 @@ useGridNav(rootEl, {
<template>
<div ref="rootEl" class="game-actions">
<GameActionBtn
v-if="actions.canPlayInBrowser.value"
v-if="actions.canPlayLocally.value"
:rom="rom"
action="play"
:size="btnSize"

View File

@@ -8,7 +8,7 @@ vi.mock("vue-i18n", () => ({
}));
type Flags = {
canPlayInBrowser: boolean;
canPlayLocally: boolean;
canPlayStream: boolean;
canShareQR: boolean;
canOpenInFlashpoint: boolean;
@@ -29,7 +29,7 @@ let joinActionLabel = "";
let streamActionLabel = "";
const flags: Flags = {
canPlayInBrowser: true,
canPlayLocally: true,
canPlayStream: false,
canDownload: true,
canShareQR: false,
@@ -149,7 +149,7 @@ describe("GameActionsList: permission gating", () => {
describe("GameActionsList: playing", () => {
it("offers each way to play the caller is allowed", () => {
const wrapper = mountList({ canPlayInBrowser: true, canPlayStream: true });
const wrapper = mountList({ canPlayLocally: true, canPlayStream: true });
const shown = labels(wrapper);
expect(shown).toContain("rom.play");
expect(shown).toContain("rom.stream");
@@ -157,7 +157,7 @@ describe("GameActionsList: playing", () => {
it("renders the stream label the composable resolved", () => {
const wrapper = mountList(
{ canPlayInBrowser: false, canPlayStream: true },
{ canPlayLocally: false, canPlayStream: true },
"rom.join-session",
"rom.stream-on",
);
@@ -168,7 +168,7 @@ describe("GameActionsList: playing", () => {
it("offers neither when the ROM cannot be played", () => {
const shown = labels(
mountList({ canPlayInBrowser: false, canPlayStream: false }),
mountList({ canPlayLocally: false, canPlayStream: false }),
);
expect(shown).not.toContain("rom.play");
expect(shown).not.toContain("rom.stream");

View File

@@ -44,7 +44,7 @@ function run(fn: () => void | Promise<void>) {
<template>
<!-- Primary actions -->
<RMenuItem
v-if="actions.canPlayInBrowser.value"
v-if="actions.canPlayLocally.value"
:label="t('rom.play')"
icon="mdi-play"
@click="run(() => actions.play('local'))"

View File

@@ -482,7 +482,7 @@ function onStaticKeydown(e: KeyboardEvent) {
<div class="r-gc__overlay">
<div class="r-gc__overlay-center">
<GameActionBtn
v-if="actions?.canPlayInBrowser.value"
v-if="actions?.canPlayLocally.value"
:rom="rom"
action="play"
variant="emphasized"

View File

@@ -20,6 +20,9 @@ const heartbeat = ref({});
// The streaming route is a store lookup rather than an engine check: a
// container configured for the platform makes the rom streamable.
const streamContainer = ref<object | null>(null);
// Same for native: the desktop shell has already answered per platform, so the
// composable only reads the cached answer.
const nativeSupported = ref(false);
vi.mock("pinia", () => ({
storeToRefs: () => ({ value: heartbeat }),
@@ -31,6 +34,11 @@ vi.mock("@/stores/streaming", () => ({
containerForPlatform: () => streamContainer.value,
}),
}));
vi.mock("@/stores/native", () => ({
useNativeStore: () => ({
isSupportedPlatform: () => nativeSupported.value,
}),
}));
vi.mock("@/utils", () => ({
isEJSEmulationSupported: support.ejs,
isJsDosEmulationSupported: support.jsDos,
@@ -64,6 +72,7 @@ beforeEach(() => {
support.ruffle.mockClear();
support.jsDosBundle.mockClear();
streamContainer.value = null;
nativeSupported.value = false;
});
describe("useCanPlay", () => {
@@ -106,6 +115,7 @@ describe("useCanPlay", () => {
support.pico8Rom.mockReturnValue(true);
support.ruffle.mockReturnValue(true);
streamContainer.value = {};
nativeSupported.value = true;
const {
canPlay,
canPlayEJS,
@@ -113,6 +123,7 @@ describe("useCanPlay", () => {
canPlayPico8,
canPlayRuffle,
canPlayStream,
canPlayNative,
} = useCanPlay(() => null);
expect(canPlay.value).toBe(false);
@@ -121,6 +132,7 @@ describe("useCanPlay", () => {
expect(canPlayPico8.value).toBe(false);
expect(canPlayRuffle.value).toBe(false);
expect(canPlayStream.value).toBe(false);
expect(canPlayNative.value).toBe(false);
});
// Streaming runs the platform's real emulator in a container, so it makes a
@@ -145,6 +157,28 @@ describe("useCanPlay", () => {
expect(canPlay.value).toBe(false);
});
// The desktop shell runs a locally installed emulator, so it makes a rom
// playable on its own even where nothing on the server can touch it.
it("reports native support on its own flag", () => {
nativeSupported.value = true;
const { canPlay, canPlayNative } = useCanPlay(() => makeRom());
expect(canPlayNative.value).toBe(true);
expect(canPlay.value).toBe(true);
});
// The shell downloads the file from the server or reads it off disk, so it
// needs one just as the in-browser engines do.
it("refuses native play for a rom with no file on disk", () => {
nativeSupported.value = true;
const { canPlay, canPlayNative } = useCanPlay(() =>
makeRom({ has_file_on_disk: false }),
);
expect(canPlayNative.value).toBe(false);
expect(canPlay.value).toBe(false);
});
// A bare game folder or plain archive makes js-dos panic with
// "Broken bundle", so offering Play would hand the user a dead player.
it("refuses js-dos for a rom that is not a bundle", () => {

View File

@@ -6,14 +6,17 @@
// "Playable" means EJS, js-dos, PICO-8, or Ruffle can run the platform on this
// server (admin toggles + platform support + WebGL availability) and there
// is a file to boot, or a streaming container is configured for the
// platform. A physical game or one missing from the filesystem has nothing
// platform, or the desktop shell has a locally installed emulator for it.
// A physical game or one missing from the filesystem has nothing
// to hand the emulator, and js-dos additionally needs the file to be one of
// its own bundles. The individual flags are exposed so the play action can
// pick the right route (EJS vs js-dos vs PICO-8 vs Ruffle vs Stream).
// pick the right route (EJS vs js-dos vs PICO-8 vs Ruffle vs Stream vs
// Native).
import { storeToRefs } from "pinia";
import { computed, type ComputedRef } from "vue";
import storeConfig from "@/stores/config";
import storeHeartbeat from "@/stores/heartbeat";
import { useNativeStore } from "@/stores/native";
import type { SimpleRom } from "@/stores/roms";
import { useStreamingStore } from "@/stores/streaming";
import {
@@ -32,10 +35,12 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): {
canPlayPico8: ComputedRef<boolean>;
canPlayRuffle: ComputedRef<boolean>;
canPlayStream: ComputedRef<boolean>;
canPlayNative: ComputedRef<boolean>;
} {
const heartbeatStore = storeHeartbeat();
const configStore = storeConfig();
const streamingStore = useStreamingStore();
const nativeStore = useNativeStore();
const { value: heartbeat } = storeToRefs(heartbeatStore);
const supportedBy = (check: typeof isEJSEmulationSupported) =>
@@ -68,13 +73,22 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): {
return streamingStore.containerForPlatform(rom.platform_slug) !== null;
});
// The shell either downloads the file or reads it off disk, so the same
// "something to boot" rule applies.
const canPlayNative = computed(() => {
const rom = getRom();
if (!rom?.has_file_on_disk) return false;
return nativeStore.isSupportedPlatform(rom.platform_slug);
});
const canPlay = computed(
() =>
canPlayEJS.value ||
canPlayJsDos.value ||
canPlayPico8.value ||
canPlayRuffle.value ||
canPlayStream.value,
canPlayStream.value ||
canPlayNative.value,
);
return {
@@ -84,5 +98,6 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): {
canPlayPico8,
canPlayRuffle,
canPlayStream,
canPlayNative,
};
}

View File

@@ -13,6 +13,7 @@ const canPlayEJS = { value: true };
const canPlayJsDos = { value: false };
const canPlayPico8 = { value: false };
const canPlayRuffle = { value: false };
const canPlayNative = { value: false };
const streamContainer = { value: null as object | null };
const joinableSession = {
value: null as { host_username: string | null } | null,
@@ -78,6 +79,7 @@ vi.mock("@/v2/composables/useCanPlay", () => ({
canPlayJsDos,
canPlayPico8,
canPlayRuffle,
canPlayNative,
canPlayStream: {
get value() {
return (
@@ -134,6 +136,7 @@ beforeEach(() => {
canPlayJsDos.value = false;
canPlayPico8.value = false;
canPlayRuffle.value = false;
canPlayNative.value = false;
streamContainer.value = null;
joinableSession.value = null;
grantedActions.value = null;
@@ -340,6 +343,34 @@ describe("useGameActions.play — launch confirmation", () => {
expect(push).toHaveBeenCalledWith("/rom/1/jsdos");
});
it("opens the play page for a platform only the desktop shell can run", async () => {
canPlayEJS.value = false;
canPlayNative.value = true;
const actions = useGameActions(() => makeRom());
await actions.play();
expect(push).toHaveBeenCalledWith("/rom/1/ejs");
});
// The shell's emulator is offered from the same page a core plays on, so
// where both can run the game there is still one route to open.
it("opens the same page when a core can run it too", async () => {
canPlayNative.value = true;
const actions = useGameActions(() => makeRom());
await actions.play();
expect(push).toHaveBeenCalledWith("/rom/1/ejs");
});
it("offers the Play button wherever either route can run the game", () => {
canPlayEJS.value = false;
expect(useGameActions(() => makeRom()).canPlayLocally.value).toBe(false);
canPlayNative.value = true;
expect(useGameActions(() => makeRom()).canPlayLocally.value).toBe(true);
});
it("offers neither streaming nor download without a file behind the rom", () => {
streamContainer.value = {};
const fileless = { ...makeRom(), has_file_on_disk: false } as SimpleRom;

View File

@@ -92,6 +92,7 @@ export function useGameActions(
canPlayPico8,
canPlayRuffle,
canPlayStream,
canPlayNative,
} = useCanPlay(getRom);
const streamingStore = useStreamingStore();
@@ -105,6 +106,13 @@ export function useGameActions(
canPlayRuffle.value,
);
// Whether the Play button has a play page to open. The desktop shell's own
// emulator is offered from that page alongside the in-browser core, so a
// platform only the shell can run still needs the button.
const canPlayLocally = computed(
() => canPlayInBrowser.value || canPlayNative.value,
);
// Download, the copied link and the QR code all resolve to the download
// endpoint, which has nothing to serve without a file behind the rom.
const canDownload = computed(() => Boolean(getRom()?.has_file_on_disk));
@@ -360,6 +368,9 @@ export function useGameActions(
else if (canPlayEJS.value) slug = "ejs";
else if (canPlayPico8.value) slug = "pico8";
else if (canPlayRuffle.value) slug = "ruffle";
// Last, because the play page offers the native launch beside whichever
// in-browser core the branches above would have picked.
else if (canPlayNative.value) slug = "ejs";
return slug ? `/rom/${rom.id}/${slug}` : null;
}
@@ -571,7 +582,7 @@ export function useGameActions(
canDownload,
canPlay,
canPlayStream,
canPlayInBrowser,
canPlayLocally,
streamLabel,
streamActionLabel,
canJoinStream,

View File

@@ -0,0 +1,157 @@
import { mount } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent } from "vue";
import type { LaunchState } from "@/types/rommNative";
import { installNativeLaunchFeedback } from "./index";
// The shell's own launch-state stream, so a test can play back what it sends.
let emit: ((state: LaunchState) => void) | null = null;
const unsubscribe = vi.fn();
vi.mock("@/services/native", () => ({
onNativeLaunchState: (listener: (state: LaunchState) => void) => {
emit = listener;
return unsubscribe;
},
}));
const install = vi.fn();
const nameFor = vi.fn(() => "Chrono Trigger");
const consumeCancelled = vi.fn(() => false);
vi.mock("@/stores/native", () => ({
useNativeStore: () => ({ install, nameFor, consumeCancelled }),
}));
const success = vi.fn();
const error = vi.fn();
const warning = vi.fn();
const info = vi.fn();
vi.mock("@/v2/composables/useSnackbar", () => ({
useSnackbar: () => ({ success, error, warning, info }),
}));
const t = vi.fn((key: string) => key);
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t }) }));
// The composable only runs inside a component scope, like AppLayout's. The
// wrapper is kept so each test's subscription dies with it.
let wrapper: ReturnType<typeof mount> | null = null;
function feedback() {
wrapper = mount(
defineComponent({
setup() {
installNativeLaunchFeedback();
return () => null;
},
}),
);
}
describe("installNativeLaunchFeedback", () => {
beforeEach(() => {
setActivePinia(createPinia());
emit = null;
install.mockClear();
nameFor.mockClear();
nameFor.mockImplementation(() => "Chrono Trigger");
consumeCancelled.mockClear();
success.mockClear();
error.mockClear();
warning.mockClear();
info.mockClear();
t.mockClear();
vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
vi.restoreAllMocks();
});
it("subscribes on install", () => {
feedback();
expect(install).toHaveBeenCalledTimes(1);
expect(emit).not.toBeNull();
});
it("raises the save the shell pulled, naming the game", () => {
feedback();
emit?.({ romId: 7, status: "sync", sync: { action: "downloaded" } });
expect(success).toHaveBeenCalledWith("play.native-save-downloaded", {
icon: "mdi-download-outline",
});
expect(t).toHaveBeenCalledWith("play.native-save-downloaded", {
name: "Chrono Trigger",
});
});
it("raises the save the shell sent", () => {
feedback();
emit?.({ romId: 7, status: "sync", sync: { action: "uploaded" } });
expect(success).toHaveBeenCalledWith("play.native-save-uploaded", {
icon: "mdi-upload-outline",
});
});
// An archival save is the only user-visible consequence of a conflict, so it
// is a warning rather than another success among the successes.
it("warns when the shell kept a save aside", () => {
feedback();
emit?.({ romId: 7, status: "sync", sync: { action: "archived" } });
expect(warning).toHaveBeenCalledWith("play.native-save-archived", {
icon: "mdi-archive-outline",
});
expect(success).not.toHaveBeenCalled();
});
it("reports a save the shell could not move, and its reason", () => {
feedback();
emit?.({
romId: 7,
status: "sync",
sync: { action: "failed", detail: "409 from /api/saves" },
});
expect(error).toHaveBeenCalledWith("play.native-save-failed", {
icon: "mdi-alert-circle-outline",
});
expect(console.error).toHaveBeenCalledWith(
"[native] Save sync failed:",
"409 from /api/saves",
);
});
// A save moving is not a launch ending: the emulator has already exited, and
// nothing about the launch is worth repeating.
it("says nothing about the launch the save moved around", () => {
feedback();
emit?.({ romId: 7, status: "sync", sync: { action: "downloaded" } });
expect(success).not.toHaveBeenCalledWith(
"play.native-running",
expect.anything(),
);
expect(consumeCancelled).not.toHaveBeenCalled();
});
it("stays quiet on a sync status that carries no outcome", () => {
feedback();
emit?.({ romId: 7, status: "sync" });
expect(success).not.toHaveBeenCalled();
expect(warning).not.toHaveBeenCalled();
expect(error).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,108 @@
// installNativeLaunchFeedback — the app-level voice of the desktop shell's
// launches. Mounted once from AppLayout, next to the other install* hooks.
//
// Progress lives on the native Play button itself (`nativeActionLabel` in
// useGameActions); this speaks only at the two endings worth a toast. The
// subscription is app-wide because a per-ROM one would mean a listener, and a
// toast, per card in a virtualised gallery.
import { onScopeDispose } from "vue";
import { useI18n } from "vue-i18n";
import { onNativeLaunchState } from "@/services/native";
import { useNativeStore } from "@/stores/native";
import type { LaunchErrorCode, SaveSyncAction } from "@/types/rommNative";
import { useSnackbar } from "@/v2/composables/useSnackbar";
/** Several codes share one message: from the user's side a platform with no
* emulator, none configured, and one gone missing are the same problem. What
* tells them apart is the shell's `detail`, which is English. */
const ERROR_KEYS: Record<LaunchErrorCode, string> = {
"unsupported-platform": "play.native-error-no-emulator",
"no-emulator-configured": "play.native-error-no-emulator",
"emulator-not-found": "play.native-error-no-emulator",
"download-failed": "play.native-error-download",
"already-running": "play.native-error-running",
"invalid-request": "play.native-launch-failed",
"launch-failed": "play.native-launch-failed",
};
/** What each save outcome says. An archival save is the only user-visible
* consequence of a conflict, and the one worth interrupting for: the slot holds
* newer progress, so the save the emulator just wrote is not the one RomM will
* offer next time. */
const SAVE_KEYS: Record<SaveSyncAction, string> = {
downloaded: "play.native-save-downloaded",
uploaded: "play.native-save-uploaded",
archived: "play.native-save-archived",
failed: "play.native-save-failed",
};
const SAVE_ICONS: Record<SaveSyncAction, string> = {
downloaded: "mdi-download-outline",
uploaded: "mdi-upload-outline",
archived: "mdi-archive-outline",
failed: "mdi-alert-circle-outline",
};
export function installNativeLaunchFeedback(): void {
const { t } = useI18n();
const snackbar = useSnackbar();
const nativeStore = useNativeStore();
nativeStore.install();
const unsubscribe = onNativeLaunchState((state) => {
const name = nativeStore.nameFor(state.romId);
// Not a launch state, and handled before the two that end a launch: the
// emulator has already exited by the time a save moves, so this arrives on a
// launch the page is finished with.
if (state.status === "sync") {
const outcome = state.sync;
if (!outcome) return;
if (outcome.detail) {
console.error("[native] Save sync failed:", outcome.detail);
}
const message = t(SAVE_KEYS[outcome.action], { name });
const icon = SAVE_ICONS[outcome.action];
if (outcome.action === "failed") {
snackbar.error(message, { icon });
} else if (outcome.action === "archived") {
snackbar.warning(message, { icon });
} else {
snackbar.success(message, { icon });
}
return;
}
if (state.status !== "running" && state.status !== "failed") return;
if (state.status === "running") {
snackbar.success(t("play.native-running", { name }), {
icon: "mdi-desktop-classic",
});
return;
}
// A cancel the shell took reaches the frontend as an aborted download, and
// the store leaves the mark on only for that one failure. So this is the
// cancellation landing, and the only place it can honestly be reported.
if (nativeStore.consumeCancelled(state.romId)) {
snackbar.info(t("play.native-canceled"), {
icon: "mdi-close-circle-outline",
});
return;
}
if (state.error?.message) {
console.error("[native] Launch failed:", state.error.message);
}
snackbar.error(
t(ERROR_KEYS[state.error?.code ?? "launch-failed"], { name }),
{
icon: "mdi-alert-circle-outline",
},
);
});
onScopeDispose(unsubscribe);
}

View File

@@ -32,6 +32,17 @@ vi.mock("@/stores/heartbeat", () => ({
vi.mock("@/stores/config", () => ({
default: () => ({ config: { PLATFORMS_VERSIONS: {} } }),
}));
// Native support is a property of the machine the page is open on, so it is a
// knob here like the others. `support` is read only to make the returned
// function rebuild when the probe lands.
const nativeSlugs = new Set<string>();
vi.mock("@/stores/native", () => ({
useNativeStore: () => ({
support: {},
isSupportedPlatform: (slug: string | null | undefined) =>
Boolean(slug) && nativeSlugs.has(slug as string),
}),
}));
// A Pinia setup store unwraps its refs on the instance, so `config` here is
// the plain object the composable reads, not a ref.
function mockContainerFor(slug: string | null | undefined) {
@@ -66,6 +77,7 @@ vi.mock("@/locales", () => ({
}));
beforeEach(() => {
nativeSlugs.clear();
ejsSlugs.clear();
ruffleSlugs.clear();
dosboxSlugs.clear();
@@ -126,6 +138,20 @@ describe("usePlatformPlayable", () => {
});
describe("usePlatformPlayableChecker", () => {
it("reports a platform the desktop shell can launch", () => {
// PS2 has no in-browser core and no container, and is still playable
// inside the shell, which is what the platform index has to sort on.
nativeSlugs.add("ps2");
const { isPlayable, isStreamable, isNativeSupported } =
usePlatformPlayableChecker();
expect(isPlayable.value("ps2")).toBe(false);
expect(isStreamable.value("ps2")).toBe(false);
expect(isNativeSupported.value("ps2")).toBe(true);
expect(isNativeSupported.value("snes")).toBe(false);
expect(isNativeSupported.value(null)).toBe(false);
});
it("agrees with the reactive form for the same slug", () => {
ejsSlugs.add("snes");
streamContainers.set("ps2", { label: "PCSX2", emulator: "pcsx2" });

View File

@@ -23,6 +23,7 @@ import { computed, type ComputedRef } from "vue";
import i18n from "@/locales";
import storeConfig, { type Config } from "@/stores/config";
import storeHeartbeat, { type Heartbeat } from "@/stores/heartbeat";
import { useNativeStore } from "@/stores/native";
import { useStreamingStore } from "@/stores/streaming";
import {
getSupportedEJSCores,
@@ -105,10 +106,12 @@ export function usePlatformPlayableChecker(): {
(slug: string | null | undefined) => PlatformEmulator
>;
isStreamable: ComputedRef<(slug: string | null | undefined) => boolean>;
isNativeSupported: ComputedRef<(slug: string | null | undefined) => boolean>;
} {
const heartbeatStore = storeHeartbeat();
const configStore = storeConfig();
const streamingStore = useStreamingStore();
const nativeStore = useNativeStore();
const { value: heartbeat } = storeToRefs(heartbeatStore);
// Expose computed functions so callers that consume them inside another
@@ -134,7 +137,16 @@ export function usePlatformPlayableChecker(): {
cfg.enabled && streamingStore.containerForPlatform(slug) !== null;
});
return { isPlayable, getEmulator, isStreamable };
// Whether the desktop shell can launch this platform locally. Deliberately
// not folded into `mode`: the badge answers a question about the server, and
// this one is about the machine the page is open on.
const isNativeSupported = computed(() => {
const probed = nativeStore.support;
return (slug: string | null | undefined): boolean =>
Boolean(probed) && nativeStore.isSupportedPlatform(slug);
});
return { isPlayable, getEmulator, isStreamable, isNativeSupported };
}
/** Human-readable tooltip for the play badge / column. Shared by every

View File

@@ -9,6 +9,7 @@
// Per-ROM action menus are not app-wide: each GameCard owns its own
// `MoreMenu` dropdown on the three-dots button. Right-click is left to
// the browser so "Open in new tab" etc. keep working.
import { useEventListener, useThrottleFn } from "@vueuse/core";
import {
defineAsyncComponent,
onBeforeUnmount,
@@ -19,6 +20,7 @@ import {
} from "vue";
import { useRouter } from "vue-router";
import storeCollections from "@/stores/collections";
import { useNativeStore } from "@/stores/native";
import storePlatforms from "@/stores/platforms";
import storePlaying from "@/stores/playing";
import { useStreamingStore } from "@/stores/streaming";
@@ -36,6 +38,7 @@ import { installGalleryProvenance } from "@/v2/composables/useGalleryProvenance"
import { useGamepad } from "@/v2/composables/useGamepad";
import { useGlobalHotkeys } from "@/v2/composables/useGlobalHotkeys";
import { useInputModality } from "@/v2/composables/useInputModality";
import { installNativeLaunchFeedback } from "@/v2/composables/useNativeLaunch";
import { installOverlayRouteDismiss } from "@/v2/composables/useOverlayRouteDismiss";
import { installPendingAssetSync } from "@/v2/composables/usePendingAssetSync";
import { prefetchPlatformIcons } from "@/v2/composables/usePlatformIconCache";
@@ -77,9 +80,48 @@ watch(
const collectionsStore = storeCollections();
const platformsStore = storePlatforms();
const streamingStore = useStreamingStore();
const nativeStore = useNativeStore();
const playingStore = storePlaying();
// Snackbars for launches handed to the desktop shell. Installed in setup
// because it injects the emitter; a no-op outside the shell.
installNativeLaunchFeedback();
// The native answer is per-platform, so unlike the streaming config the probe
// needs the platform list. It watches for that list rather than hanging off
// one fetch, because `fetchPlatforms` resolves empty when another view already
// has one in flight. Re-probing is cheap: the store skips slugs it has
// answered.
watch(
// Serialized rather than joined: a slug comes from a folder name and may
// contain a comma, so ["a,b"] and ["a", "b"] would compare equal and a list
// that changed between them would never be probed.
() => JSON.stringify(platformsStore.allPlatforms.map((p) => p.slug)),
() => {
const slugs = platformsStore.allPlatforms.map((p) => p.slug);
if (slugs.length === 0) return;
void nativeStore.probe(slugs);
},
{ immediate: true },
);
// The answer describes the user's machine, so installing an emulator (through
// the shell's own settings or anywhere else) changes it with nothing here to
// notice. Re-asked when the window comes back, which is when whatever did the
// installing has just been in front. Throttled because alt-tabbing is cheap
// and the shell answers this off the filesystem; a no-op outside the shell.
const NATIVE_REPROBE_THROTTLE_MS = 10_000;
useEventListener(
window,
"focus",
useThrottleFn(() => {
const slugs = platformsStore.allPlatforms.map((p) => p.slug);
if (slugs.length === 0) return;
void nativeStore.probe(slugs, { force: true });
}, NATIVE_REPROBE_THROTTLE_MS),
);
// Developer debug overlay — opt-in via Settings → Developer (per-device).
// Lazily loaded so its chunk (and the vueuse perf hooks it pulls in) is only
// fetched once the toggle is on, keeping it out of the default bundle.

View File

@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { joinNames } from "./lists";
describe("joinNames", () => {
it("joins in the reader's language, not with a hardcoded separator", () => {
const names = ["File", "Core", "Full screen"];
expect(joinNames(names, "en_US")).toBe("File, Core, and Full screen");
expect(joinNames(names, "de_DE")).toBe("File, Core und Full screen");
expect(joinNames(names, "ja_JP")).toBe("File、Core、Full screen");
});
it("leaves one name alone and answers nothing for none", () => {
expect(joinNames(["Core"], "en_US")).toBe("Core");
expect(joinNames([], "en_US")).toBe("");
});
// A phrase is not worth a render error, and the names are still the names.
it("falls back to a plain list for a locale Intl will not take", () => {
expect(joinNames(["File", "Core"], "not a locale")).toBe("File, Core");
});
it("takes the runtime's own locale when the caller has none", () => {
expect(joinNames(["File", "Core"], null)).toContain("File");
});
});

View File

@@ -0,0 +1,31 @@
// Joining a handful of already-translated names into a phrase the reader's
// language would actually use: "File, Core and Full screen", and whatever the
// equivalent is elsewhere.
//
// Here rather than in the locale files because the alternative is a key per
// combination of names, which multiplies every time a name is added and has to
// be retranslated in all 18 locales when it does.
/**
* The names as one phrase, in the order given.
*
* `locale` is the app's own locale tag, which is named with an underscore
* (`en_US`) where Intl wants a hyphen, so it is converted rather than passed
* through. Omitting it falls back to the runtime's default locale.
*/
export function joinNames(
names: readonly string[],
locale?: string | null,
): string {
if (names.length < 2) return names[0] ?? "";
try {
return new Intl.ListFormat(locale?.replace("_", "-") ?? undefined, {
style: "long",
type: "conjunction",
}).format(names);
} catch {
// An unrecognised tag throws, and a phrase is not worth a render error.
// The same names in the same order, with a plainer separator.
return names.join(", ");
}
}

View File

@@ -101,8 +101,9 @@ vi.mock("@/v2/composables/useGalleryViewModeUrl", () => ({
}));
// Slugs the mocked composable treats as streaming-capable.
const { streamableSlugs } = vi.hoisted(() => ({
const { streamableSlugs, nativeSlugs } = vi.hoisted(() => ({
streamableSlugs: new Set<string>(),
nativeSlugs: new Set<string>(),
}));
vi.mock("@/v2/composables/usePlatformPlayable", () => ({
@@ -111,6 +112,9 @@ vi.mock("@/v2/composables/usePlatformPlayable", () => ({
isStreamable: ref((slug: string | null | undefined) =>
slug ? streamableSlugs.has(slug) : false,
),
isNativeSupported: ref((slug: string | null | undefined) =>
slug ? nativeSlugs.has(slug) : false,
),
}),
}));
@@ -146,6 +150,7 @@ describe("PlatformsIndex", () => {
galleryModeState.groupBy = "none";
galleryModeState.layout = "grid";
streamableSlugs.clear();
nativeSlugs.clear();
searchState.term = "";
});
@@ -181,6 +186,23 @@ describe("PlatformsIndex", () => {
expect(wrapper.text()).toContain("platform.no-platforms-with-games");
});
// Inside the desktop shell a platform with no in-browser core and no
// container is still playable, PS2 being the case the feature exists for.
it("counts a native-only platform as playable when grouping by playable", () => {
galleryModeState.groupBy = "playable";
nativeSlugs.add("ps2");
const platforms = storePlatforms();
platforms.set([platform(1, "PlayStation 2", 5, { slug: "ps2" })]);
const wrapper = mount(PlatformsIndex);
const headings = wrapper
.findAll(".r-v2-pidx__group-heading")
.map((h) => h.text());
expect(headings).toContain("platform.playable");
expect(headings).not.toContain("platform.not-playable");
});
it("counts a streaming-only platform as playable when grouping by playable", () => {
galleryModeState.groupBy = "playable";
streamableSlugs.add("dreamcast");

View File

@@ -53,7 +53,8 @@ const phase = useLoadingPhase(
const { groupBy, layout } = useGalleryMode();
useGalleryViewModeUrl();
const searchTerm = useTileSearchUrl();
const { isPlayable, isStreamable } = usePlatformPlayableChecker();
const { isPlayable, isStreamable, isNativeSupported } =
usePlatformPlayableChecker();
// Empty (0-game) platforms are leftovers: rows whose folder vanished from
// disk, whose ROMs were all deleted, or that a config exclusion keeps out
@@ -110,14 +111,20 @@ useWrapGridNav(gridRoot, { cellSelector: ".plat-tile" });
// Pre-compute the play flag per platform: sort comparator and every row
// read this map so the column, the badge on the tile, and the playable
// bucket all agree on a single source of truth. "Playable" here means by
// any means: in this tab through EmulatorJS or Ruffle, or on a configured
// streaming container.
// any means: in this tab through EmulatorJS or Ruffle, on a configured
// streaming container, or in a local emulator when the desktop shell is
// there to launch one -- a platform with no in-browser core at all, PS2
// being the example, is playable inside the shell and has to sort as such.
const playableById = computed(() => {
const playableFn = isPlayable.value;
const streamableFn = isStreamable.value;
const nativeFn = isNativeSupported.value;
const map = new Map<number | string, boolean>();
for (const p of allPlatforms.value) {
map.set(p.id, playableFn(p.slug) || streamableFn(p.slug));
map.set(
p.id,
playableFn(p.slug) || streamableFn(p.slug) || nativeFn(p.slug),
);
}
return map;
});

View File

@@ -0,0 +1,641 @@
import { RBtn, RSelect } from "@v2/lib";
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { readFileSync } from "node:fs";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent } from "vue";
import type { DetailedRom } from "@/stores/roms";
import type { LaunchState, SaveSyncOutcome } from "@/types/rommNative";
import EmulatorJS from "./EmulatorJS.vue";
const mocks = vi.hoisted(() => ({
getRom: vi.fn(),
getFirmware: vi.fn(),
launch: vi.fn(),
cancel: vi.fn(),
canPlayEJS: true,
canPlayNative: false,
emulator: null as string | null,
launching: false,
launchState: null as LaunchState | null,
/** What the platform's core map offers, which is what the setup panel lists
* and what the first core resolves from. */
cores: [] as string[],
/** Whether the shell takes the page's full-screen answer with it. */
honoursFullscreen: false,
/** Whether the shell takes the page's disc answer with it. */
honoursDisc: false,
// A box, like syncOutcome: the preference is a ref the view keeps, so a test
// that flips it has to write through the same object.
fullscreen: { value: false },
// A box rather than the value: the store's getter has to read something the
// watcher can track, so the mock swaps this for a reactive object.
syncOutcome: { value: null as SaveSyncOutcome | null },
}));
vi.mock("vue-i18n", () => ({
useI18n: () => ({
// Rendered params matter to the progress readout, so they are kept.
t: (key: string, params?: Record<string, unknown>) =>
params ? `${key}:${Object.values(params).join(",")}` : key,
// Read by the setup note, which joins the names of the controls a native
// launch carries into one phrase.
locale: { value: "en_US" },
}),
}));
vi.mock("@/services/api/rom", () => ({ default: { getRom: mocks.getRom } }));
vi.mock("@/services/api/firmware", () => ({
default: { getFirmware: mocks.getFirmware },
}));
vi.mock("@/services/api/save", () => ({
AUTOSAVE_SLOT: "autosave",
SAVE_SLOT_MAX_LENGTH: 32,
}));
vi.mock("@/stores/config", () => ({
default: () => ({
config: { EJS_NETPLAY_ENABLED: false },
getEJSDefaultCore: () => null,
getEJSCoreOptions: () => ({}),
}),
}));
vi.mock("@/stores/playing", async () => {
const { ref } = await import("vue");
return { default: () => ({ playing: ref(false) }) };
});
vi.mock("@/stores/native", async () => {
const { reactive } = await import("vue");
Object.assign(mocks, { syncOutcome: reactive(mocks.syncOutcome) });
return {
useNativeStore: () => ({
isLaunching: () => mocks.launching,
labelForPlatform: () => mocks.emulator,
launchStateFor: () => mocks.launchState,
syncFor: () => mocks.syncOutcome.value,
honoursFullscreen: mocks.honoursFullscreen,
honoursDisc: mocks.honoursDisc,
launch: mocks.launch,
cancel: mocks.cancel,
}),
};
});
vi.mock("@/utils", () => ({
areThreadsRequiredForEJSCore: () => false,
formatRelativeDate: (value: string) => value,
getSupportedEJSCores: () => mocks.cores,
FRONTEND_RESOURCES_PATH: "/assets/romm/resources",
}));
vi.mock("@/v2/composables/useCanPlay", async () => {
const { computed } = await import("vue");
return {
useCanPlay: () => ({
canPlayEJS: computed(() => mocks.canPlayEJS),
canPlayNative: computed(() => mocks.canPlayNative),
}),
};
});
vi.mock("@/v2/composables/useActivityPresence", () => ({
useActivityPresence: () => ({
start: vi.fn(),
stopHeartbeat: vi.fn(),
emitStop: vi.fn(),
}),
}));
vi.mock("@/v2/composables/useCoverArt", async () => {
const { computed } = await import("vue");
return {
useCoverArt: () => ({
style: computed(() => "cover_path"),
coverUrl: computed(() => null),
fallbackUrl: computed(() => null),
}),
};
});
vi.mock("@/v2/composables/useFullscreenFallback", () => ({
useFullscreenFallback: vi.fn(),
}));
vi.mock("@/v2/composables/useFullscreenPref", async () => {
const { reactive } = await import("vue");
Object.assign(mocks, { fullscreen: reactive(mocks.fullscreen) });
return { useFullscreenPref: () => ({ fullscreenOnPlay: mocks.fullscreen }) };
});
vi.mock("@/v2/composables/useInputModality", async () => {
const { ref } = await import("vue");
return { useInputModality: () => ({ modality: ref("mouse") }) };
});
vi.mock("@/v2/composables/usePlaySession", () => ({
usePlaySession: () => ({ start: vi.fn(), flush: vi.fn() }),
}));
vi.mock("@/v2/composables/usePlayerHero", async () => {
const { computed, ref } = await import("vue");
return {
usePlayerHero: (rom: { value: DetailedRom | null }) => ({
romId: 7,
heroRom: ref(rom.value ?? ROM),
title: computed(() => ROM.name),
platformLabel: computed(() => "PlayStation 2"),
}),
};
});
vi.mock("@/v2/composables/usePlayerNav", () => ({
usePlayerNav: () => ({ backToRom: vi.fn(), backToPlatform: vi.fn() }),
}));
vi.mock("@/v2/composables/useSnackbar", () => ({
useSnackbar: () => ({
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
}),
}));
vi.mock("@/v2/composables/useStageActive", () => ({ useStageActive: vi.fn() }));
vi.mock("@/v2/composables/useUnloadGuard", () => ({ useUnloadGuard: vi.fn() }));
const ROM = {
id: 7,
name: "Shadow of the Colossus",
platform_id: 4,
platform_slug: "ps2",
has_file_on_disk: true,
files: [],
user_saves: [],
user_states: [],
user_screenshots: [],
} as unknown as DetailedRom;
// Two discs, so the panel renders its disc selector and there is a pick to
// carry. Ids rather than names: a pick is a rom file's id.
const DISC_SET = {
...ROM,
files: [
{ id: 101, file_name: "Game (Disc 1).chd" },
{ id: 102, file_name: "Game (Disc 2).chd" },
],
} as unknown as DetailedRom;
// A scraped bezel, which is what puts the panel's bezel switch on screen.
const BEZELED_ROM = {
...ROM,
ss_metadata: { bezel_path: "roms/7/bezel/bezel.png" },
} as unknown as DetailedRom;
// One BIOS file for the platform, which is what puts the firmware picker on
// screen. Its contents do not matter: the panel lists what the server returns.
const FIRMWARE_SET = [{ id: 3, file_name: "scph1001.bin" }];
// The launch flourish reaches into the cover, so the stub has to answer.
const GameCoverStub = defineComponent({
setup(_, { expose }) {
expose({ playLoad: () => 0 });
return () => null;
},
});
async function launchScreen(): Promise<VueWrapper> {
const wrapper = mount(EmulatorJS, {
shallow: true,
global: {
renderStubDefaultSlot: true,
stubs: { GameCover: GameCoverStub },
},
});
await flushPromises();
return wrapper;
}
function playLabels(wrapper: VueWrapper): string[] {
return wrapper.findAll(".r-v2-ejs__play").map((btn) => btn.text());
}
function playDisabled(wrapper: VueWrapper): unknown[] {
return wrapper
.findAllComponents(RBtn)
.filter((btn) => btn.classes().includes("r-v2-ejs__play"))
.map((btn) => btn.props("disabled"));
}
function cancelBtn(wrapper: VueWrapper) {
return wrapper
.findAllComponents(RBtn)
.find((btn) => btn.classes().includes("r-v2-ejs__native-cancel"));
}
function playIcons(wrapper: VueWrapper): unknown[] {
return wrapper
.findAllComponents(RBtn)
.filter((btn) => btn.classes().includes("r-v2-ejs__play"))
.map((btn) => btn.props("prependIcon"));
}
// One line per route, which is what the panel draws.
function noteLines(wrapper: VueWrapper): string[] {
return wrapper.findAll(".r-v2-ejs__setup-note").map((line) => line.text());
}
beforeEach(() => {
mocks.getRom.mockResolvedValue({ data: ROM });
mocks.getFirmware.mockResolvedValue({ data: [] });
mocks.launch.mockResolvedValue(null);
mocks.cancel.mockResolvedValue(true);
mocks.canPlayEJS = true;
mocks.canPlayNative = false;
mocks.emulator = null;
mocks.launching = false;
mocks.launchState = null;
mocks.syncOutcome.value = null;
mocks.cores = [];
mocks.honoursFullscreen = false;
mocks.honoursDisc = false;
mocks.fullscreen.value = false;
});
describe("EmulatorJS launch screen — play routes", () => {
it("offers only the in-browser route outside the desktop shell", async () => {
expect(playLabels(await launchScreen())).toEqual(["play.play"]);
});
it("puts the native launch above the in-browser one, and names both", async () => {
mocks.canPlayNative = true;
mocks.emulator = "PCSX2";
expect(playLabels(await launchScreen())).toEqual([
"play.play-native-in:PCSX2",
"play.play-in-browser",
]);
});
// The shell sends "RetroArch (snes9x)" / "PCSX2 (to install)"; the qualifier
// does not fit beside the label and overflowed the button.
it.each([
["RetroArch (snes9x)", "play.play-native-in:RetroArch"],
["PCSX2 (to install)", "play.play-native-in:PCSX2"],
["RetroArch (Flatpak)", "play.play-native-in:RetroArch"],
["PCSX2", "play.play-native-in:PCSX2"],
])("names %s on the button as %s", async (emulator, expected) => {
mocks.canPlayNative = true;
mocks.emulator = emulator;
expect(playLabels(await launchScreen())[0]).toBe(expected);
});
it("falls back to an unnamed native label when no emulator resolves", async () => {
mocks.canPlayNative = true;
expect(playLabels(await launchScreen())[0]).toBe("play.play-native");
});
it("keeps the play glyph on the launch and marks the other for the browser", async () => {
mocks.canPlayNative = true;
expect(playIcons(await launchScreen())).toEqual(["mdi-play", "mdi-web"]);
});
it("leaves the play glyph on the lone in-browser button", async () => {
expect(playIcons(await launchScreen())).toEqual(["mdi-play"]);
});
it("hands the rom to the shell when the native button is pressed", async () => {
mocks.canPlayNative = true;
const wrapper = await launchScreen();
await wrapper.findAll(".r-v2-ejs__play")[0].trigger("click");
// No core map for the platform is no core to ask for, which leaves the
// shell to resolve one from the candidates it is given.
expect(mocks.launch).toHaveBeenCalledWith(ROM, {
core: undefined,
fullscreen: false,
// A rom of one file has no disc to pick, and the default for one that
// does is its first file rather than a set nobody asked for.
disc: null,
});
});
// The setup panel sits beside both buttons, so a choice made in it that only
// reached one of them would be a panel that lies about half the page.
it("sends the panel's core and full-screen answers with the launch", async () => {
mocks.canPlayNative = true;
mocks.cores = ["mgba", "vba_next"];
mocks.fullscreen.value = true;
const wrapper = await launchScreen();
await wrapper.findAll(".r-v2-ejs__play")[0].trigger("click");
expect(mocks.launch).toHaveBeenCalledWith(ROM, {
core: "mgba",
fullscreen: true,
disc: null,
});
});
// Without this the shell fetches all four discs of a game the player picked
// disc two of, and boots the playlist rather than the disc.
it("sends the panel's disc answer with the launch", async () => {
mocks.canPlayNative = true;
mocks.getRom.mockResolvedValue({ data: DISC_SET });
const wrapper = await launchScreen();
const discs = wrapper
.findAllComponents(RSelect)
.filter((select) => select.props("label") === "rom.file");
await discs[0].setValue(102);
await wrapper.findAll(".r-v2-ejs__play")[0].trigger("click");
expect(mocks.launch).toHaveBeenCalledWith(DISC_SET, {
core: undefined,
fullscreen: false,
disc: 102,
});
});
});
describe("EmulatorJS launch screen — what the setup panel claims", () => {
beforeEach(() => {
mocks.canPlayNative = true;
mocks.cores = ["mgba", "vba_next"];
});
it("names every control on screen that the shell takes with it", async () => {
mocks.honoursFullscreen = true;
mocks.honoursDisc = true;
mocks.getRom.mockResolvedValue({ data: DISC_SET });
const note = noteLines(await launchScreen());
// In the order the panel renders them, which is the order they are read in.
expect(note).toEqual([
"play.native-applies:rom.file, common.core, and play.full-screen",
]);
});
it("claims only the core on a shell that cannot take the rest", async () => {
expect(noteLines(await launchScreen())).toEqual([
"play.native-applies:common.core",
]);
});
// A shell without disc-choice boots the set whole, so the selector above it
// is the browser player's alone and the line must not claim it.
it("leaves out a disc the shell would not honour", async () => {
mocks.honoursDisc = false;
mocks.getRom.mockResolvedValue({ data: DISC_SET });
expect(noteLines(await launchScreen())).toEqual([
"play.native-applies:common.core",
]);
});
it("says nothing about a route the page is not offering", async () => {
mocks.canPlayNative = false;
expect(noteLines(await launchScreen())).toEqual([]);
});
// The bug this guards: a note that only ever claimed what carries would leave
// a panel of BIOS and bezel with no note at all, reading as fully shared.
it("names the controls the shell leaves behind", async () => {
mocks.cores = ["mgba"];
mocks.getFirmware.mockResolvedValue({ data: FIRMWARE_SET });
expect(noteLines(await launchScreen())).toEqual([
"play.native-browser-only:common.firmware",
]);
});
it("names the bezel the browser player draws for itself", async () => {
mocks.cores = ["mgba"];
mocks.getRom.mockResolvedValue({ data: BEZELED_ROM });
expect(noteLines(await launchScreen())).toEqual([
"play.native-browser-only:play.show-bezel",
]);
});
// Two lines, not one run-on: the reader has to be able to tell which
// controls stay with which route.
it("says both halves, one line each, in the order the panel renders them", async () => {
mocks.getFirmware.mockResolvedValue({ data: FIRMWARE_SET });
mocks.getRom.mockResolvedValue({ data: BEZELED_ROM });
expect(noteLines(await launchScreen())).toEqual([
"play.native-applies:common.core",
"play.native-browser-only:common.firmware and play.show-bezel",
]);
});
// Nothing on screen carries over and nothing on it is EmulatorJS' own: one
// core, one file, the full-screen switch, and no bezel or BIOS to name.
it("says nothing when the panel offers nothing to choose", async () => {
mocks.cores = ["mgba"];
expect(noteLines(await launchScreen())).toEqual([]);
});
});
describe("EmulatorJS launch screen — a platform only the shell can run", () => {
beforeEach(() => {
mocks.canPlayEJS = false;
mocks.canPlayNative = true;
});
it("drops everything EmulatorJS owns, leaving the native launch", async () => {
const wrapper = await launchScreen();
expect(playLabels(wrapper)).toEqual(["play.play-native"]);
expect(wrapper.find(".r-v2-ejs__resume").exists()).toBe(false);
expect(wrapper.find(".r-v2-ejs__setup").exists()).toBe(false);
expect(wrapper.find(".r-v2-ejs__brand").exists()).toBe(false);
});
});
describe("EmulatorJS launch screen — a launch in flight", () => {
beforeEach(() => {
mocks.canPlayNative = true;
mocks.launching = true;
});
it("reads the shell's progress off the button and offers a cancel", async () => {
mocks.launchState = {
romId: 7,
status: "downloading",
progress: 0.42,
} as LaunchState;
const wrapper = await launchScreen();
expect(playLabels(wrapper)[0]).toBe("play.native-downloading:42");
expect(wrapper.text()).toContain("play.native-cancel");
});
it("drops the qualifier from the emulator the shell is setting up", async () => {
mocks.launchState = {
romId: 7,
status: "downloading",
stage: "emulator",
emulator: "RetroArch (snes9x)",
} as LaunchState;
expect(playLabels(await launchScreen())[0]).toBe(
"play.native-preparing:RetroArch",
);
});
it("names the stage the shell reports over the raw percentage", async () => {
mocks.launchState = {
romId: 7,
status: "downloading",
stage: "firmware",
firmware: "scph5501.bin",
progress: 0.1,
} as LaunchState;
expect(playLabels(await launchScreen())[0]).toBe(
"play.native-fetching-firmware:scph5501.bin",
);
});
// No percentage for either: whether anything moves is the server's answer,
// and these are megabytes where the percentage is for gigabytes.
it.each([
["save", "play.native-syncing-save"],
["state", "play.native-syncing-states"],
])("names the %s sync rather than counting bytes", async (stage, label) => {
mocks.launchState = {
romId: 7,
status: "downloading",
stage,
progress: 0.1,
} as LaunchState;
expect(playLabels(await launchScreen())[0]).toBe(label);
});
// Booting a core here would run a second session for the same game while the
// shell is still fetching it.
it("closes the in-browser route while the shell is working", async () => {
expect(playDisabled(await launchScreen())).toEqual([true, true]);
});
// The control stays on screen while the shell answers, so a second press
// would ask twice and report twice.
it("asks once however often the cancel is pressed", async () => {
let release: () => void = () => {};
mocks.cancel.mockImplementation(
() =>
new Promise<boolean>((resolve) => {
release = () => resolve(true);
}),
);
const wrapper = await launchScreen();
const cancel = cancelBtn(wrapper);
await cancel?.trigger("click");
await cancel?.trigger("click");
release();
await flushPromises();
expect(mocks.cancel).toHaveBeenCalledTimes(1);
});
it("asks the shell to abort when the cancel is pressed", async () => {
const wrapper = await launchScreen();
await cancelBtn(wrapper)?.trigger("click");
expect(mocks.cancel).toHaveBeenCalledWith(7);
});
});
// The shell moves saves on the server before the emulator starts and after it
// exits, so the list this page fetched on mount is stale once a launch is done.
describe("EmulatorJS launch screen — a save the shell moved", () => {
function slotItems(wrapper: VueWrapper): unknown[] {
const select = wrapper
.findAllComponents(RSelect)
.find((c) => c.props("info") === "play.slot-tooltip");
return (select?.props("items") as unknown[]) ?? [];
}
// Not the call count: earlier wrappers' watchers are still live on the same
// mock store, so one outcome re-reads every rom on screen.
it("re-reads the rom once the shell reports what happened to the save", async () => {
const wrapper = await launchScreen();
expect(slotItems(wrapper)).toHaveLength(2);
mocks.getRom.mockResolvedValue({
data: { ...ROM, user_saves: [{ slot: "slots/2" }] },
});
mocks.syncOutcome.value = { action: "uploaded" };
await flushPromises();
expect(slotItems(wrapper)).toHaveLength(3);
});
// A pull changes nothing on the server, and it lands before the emulator
// starts, when the panel behind the progress readout is still the user's.
it("leaves the list and the choices alone for a pull", async () => {
const wrapper = await launchScreen();
const slot = wrapper
.findAllComponents(RSelect)
.find((c) => c.props("info") === "play.slot-tooltip");
await slot?.setValue({ kind: "existing", slot: "slots/2" });
await flushPromises();
mocks.getRom.mockResolvedValue({
data: { ...ROM, user_saves: [{ slot: "slots/2" }] },
});
mocks.syncOutcome.value = { action: "downloaded" };
await flushPromises();
expect(slotItems(wrapper)).toHaveLength(2);
expect(slot?.props("modelValue")).toEqual({
kind: "existing",
slot: "slots/2",
});
});
it("leaves the save list alone when the shell says nothing", async () => {
const wrapper = await launchScreen();
await flushPromises();
expect(slotItems(wrapper)).toHaveLength(2);
});
});
// An icon class the font does not define renders as an empty circle rather
// than failing, so the name alone is never evidence that a glyph exists.
describe("the native affordances' icons", () => {
const MDI_CSS = readFileSync(
"node_modules/@mdi/font/css/materialdesignicons.css",
"utf8",
);
it.each([
"mdi-play",
"mdi-web",
"mdi-loading",
"mdi-spin",
"mdi-close-circle-outline",
"mdi-desktop-classic",
])("%s is a real class in the bundled font", (name) => {
// Matched on the rule the font actually declares, not the bare name, or
// "mdi-play" would be satisfied by "mdi-playlist-play".
expect(MDI_CSS).toMatch(new RegExp(`\\.${name}::?before`));
});
});

View File

@@ -4,8 +4,12 @@
// resolution) is ported verbatim from `src/views/Player/EmulatorJS/Base.vue`
// so behaviour stays identical; only the chrome is v2.
//
// Inside the RomM desktop shell the hero leads with the native launch, above
// the in-browser one; a platform the shell alone can run opens this page with
// the hero by itself, since nothing EmulatorJS owns applies to that launch.
//
// Layout — three columns:
// 1. Hero: cover + title + Play CTA + back links.
// 1. Hero: cover + title + play CTAs + back links.
// 2. Resume: tabs (Saves/States), big <AssetPreview> of the selected
// asset, and an <AssetStrip> below to swap between options inline.
// 3. Setup: disc / core / firmware + fullscreen + clear-cache.
@@ -44,6 +48,7 @@ import firmwareApi from "@/services/api/firmware";
import romApi from "@/services/api/rom";
import { AUTOSAVE_SLOT, SAVE_SLOT_MAX_LENGTH } from "@/services/api/save";
import storeConfig from "@/stores/config";
import { useNativeStore } from "@/stores/native";
import storePlaying from "@/stores/playing";
import type { DetailedRom } from "@/stores/roms";
import type { Events } from "@/types/emitter";
@@ -57,6 +62,7 @@ import AssetList from "@/v2/components/shared/AssetList.vue";
import AssetStrip from "@/v2/components/shared/AssetStrip.vue";
import GameCover from "@/v2/components/shared/GameCover.vue";
import { useActivityPresence } from "@/v2/composables/useActivityPresence";
import { useCanPlay } from "@/v2/composables/useCanPlay";
import { useCoverArt } from "@/v2/composables/useCoverArt";
import { useFullscreenFallback } from "@/v2/composables/useFullscreenFallback";
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
@@ -74,6 +80,7 @@ import { useSnackbar } from "@/v2/composables/useSnackbar";
import { useStageActive } from "@/v2/composables/useStageActive";
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
import type { AssetType } from "@/v2/utils/assets";
import { joinNames } from "@/v2/utils/lists";
import {
resolveBezelHost,
resolveBezelUrl,
@@ -125,11 +132,12 @@ const Player = defineAsyncComponent(
() => import("@/views/Player/EmulatorJS/Player.vue"),
);
const { t } = useI18n();
const { t, locale } = useI18n();
const snackbar = useSnackbar();
const emitter = inject<Emitter<Events>>("emitter");
const playingStore = storePlaying();
const configStore = storeConfig();
const nativeStore = useNativeStore();
const { playing } = storeToRefs(playingStore);
const { fullscreenOnPlay } = useFullscreenPref();
useFullscreenFallback();
@@ -159,7 +167,9 @@ const {
} = useIsolatedLaunch<LaunchIntent>("ejs", romId, isLaunchIntent);
const playReady = computed(() => !!rom.value && !relaunching.value);
usePlayFocus(".r-v2-ejs__play", playReady, gameRunning);
// The first CTA is the native launch where the desktop shell offers one; a
// launch in flight disables it, so the in-browser route takes the focus.
usePlayFocus(".r-v2-ejs__play:not([disabled])", playReady, gameRunning);
// The EmulatorJS loader declares top-level classes, so a document it reached
// cannot host another launch. Tracked from the injection, which a departure
@@ -270,6 +280,159 @@ useEventListener(document, "fullscreenchange", () => {
bezelHost.value = resolveBezelHost(document.fullscreenElement);
});
const { canPlayEJS, canPlayNative } = useCanPlay(() => heroRom.value);
// A platform the shell can run but no in-browser core can. Everything this
// page offers besides the hero belongs to EmulatorJS, so none of it is shown.
const nativeOnly = computed(() => canPlayNative.value && !canPlayEJS.value);
const nativeLaunching = computed(() => nativeStore.isLaunching(romId));
// The shell qualifies the emulator with the core it would load, or with a hint
// that it has yet to be installed ("RetroArch (snes9x)", "PCSX2 (to install)").
// The button names the emulator alone: the qualifier does not fit beside it,
// and the launch's own progress readout says what is being set up.
function emulatorName(label: string | null | undefined): string {
return (label ?? "").replace(/\s*\([^()]*\)\s*$/, "").trim();
}
const nativeEmulator = computed(() =>
emulatorName(nativeStore.labelForPlatform(heroRom.value?.platform_slug)),
);
// The controls above that a native launch takes with it, in the order they are
// rendered. Only those actually on screen: a choice nobody was offered needs no
// explaining, and one the shell does not advertise is not carried at all.
const nativeCarriedControls = computed(() => {
const carried: string[] = [];
if (nativeStore.honoursDisc && bootableRomFiles.value.length > 1) {
carried.push(t("rom.file"));
}
if (supportedCores.value.length > 1) carried.push(t("common.core"));
if (nativeStore.honoursFullscreen) carried.push(t("play.full-screen"));
return carried;
});
// The controls above that stay with the in-browser player, in the order they
// are rendered. Both are EmulatorJS' own: the BIOS it loads into its core, and
// the bezel it draws over the canvas.
const nativeBrowserOnlyControls = computed(() => {
const browserOnly: string[] = [];
if (firmwareOptions.value.length > 0) {
browserOnly.push(t("common.firmware"));
}
if (bezelUrl.value) browserOnly.push(t("play.show-bezel"));
return browserOnly;
});
// What the settings panel says about the other route, one line per route.
// Empty outside the shell and on a platform with no in-browser core at all,
// where the panel is not rendered. Either half can stand alone: a panel whose
// every control stays behind says only that, and one with nothing left behind
// says only what carries.
const nativeSettingsLines = computed(() => {
if (!canPlayNative.value || nativeOnly.value) return [];
const lines: string[] = [];
const carried = nativeCarriedControls.value;
if (carried.length > 0) {
// Not named after the emulator: what the line has to say is which of these
// controls survive the choice of player, and the buttons above have already
// named the emulator.
lines.push(
t("play.native-applies", { controls: joinNames(carried, locale.value) }),
);
}
const browserOnly = nativeBrowserOnlyControls.value;
if (browserOnly.length > 0) {
lines.push(
t("play.native-browser-only", {
controls: joinNames(browserOnly, locale.value),
}),
);
}
return lines;
});
// The native button is its own progress readout, so while the shell works the
// label says what it is waiting for.
const nativeLabel = computed(() => {
if (!nativeLaunching.value) {
return nativeEmulator.value
? t("play.play-native-in", { emulator: nativeEmulator.value })
: t("play.play-native");
}
const state = nativeStore.launchStateFor(romId);
if (state?.stage === "core" && state.core) {
return t("play.native-installing-core", { core: state.core });
}
// Named rather than left to the percentage below, which is absent whenever
// the server declares no length.
if (state?.stage === "firmware" && state.firmware) {
return t("play.native-fetching-firmware", { firmware: state.firmware });
}
if (state?.stage === "emulator") {
return t("play.native-preparing", {
emulator: emulatorName(state.emulator) || nativeEmulator.value,
});
}
// No percentage: whether anything moves is the server's answer, and a save is
// kilobytes, so the wait is the round trip rather than the transfer.
if (state?.stage === "save") {
return t("play.native-syncing-save");
}
// Same reasoning as the save: whether anything moves is the server's answer,
// and a state is megabytes rather than the gigabytes a percentage is for.
if (state?.stage === "state") {
return t("play.native-syncing-states");
}
if (state?.progress != null) {
return t("play.native-downloading", {
percent: Math.round(state.progress * 100),
});
}
return t("play.native-starting");
});
// A launch the shell accepted reports itself through the launch state (see
// `installNativeLaunchFeedback`), so only a request it never took is surfaced
// here. The refusal's own wording is English, hence the console.
async function onPlayNative() {
if (!rom.value) return;
// Remembered for both routes: the core and the disc are choices about this
// game, not about which player runs it.
rememberCore(romId, rom.value.platform_slug, selectedCore.value);
rememberDisc(romId, selectedDisc.value);
const refusal = await nativeStore.launch(rom.value, {
core: selectedCore.value,
fullscreen: fullscreenOnPlay.value,
disc: selectedDisc.value,
});
if (!refusal) return;
console.error("[native] The shell refused the launch:", refusal);
snackbar.error(t("play.native-launch-failed", { name: title.value }), {
icon: "mdi-alert-circle-outline",
});
}
// Held from the click until the request settles: the control stays on screen
// while the shell answers, and a second press would ask twice and report twice.
const cancelling = ref(false);
// Whether the launch actually stopped is the shell's to say, and it says it by
// aborting the transfer (see `installNativeLaunchFeedback`). Only a request
// that never reached it is reported from here.
async function onCancelNative() {
if (cancelling.value) return;
cancelling.value = true;
try {
if (!(await nativeStore.cancel(romId))) {
snackbar.error(t("play.native-cancel-failed"));
}
} finally {
cancelling.value = false;
}
}
async function onPlay() {
if (rom.value) {
rememberCore(romId, rom.value.platform_slug, selectedCore.value);
@@ -381,6 +544,36 @@ watch(selectedCore, (newSelectedCore) => {
if (armed?.emulator && armed.emulator !== newSelectedCore) unselectState();
});
// A native launch moves saves on the server's side of this page, so the rom
// fetched on mount goes stale. Re-read it: it carries the save list.
async function refreshRomAfterSync(): Promise<void> {
try {
const { data } = await romApi.getRom({ romId });
rom.value = data;
resume.value = defaultResumeSelection(
data.user_saves,
compatibleStates.value,
);
slotChoice.value = existingSlot(preferredSlot(data.user_saves));
isSavesTabSelected.value = !resume.value.state;
} catch (error) {
// The old list is kept: a save list that is a launch out of date is not
// worth an error on top of whatever the launch itself reported.
console.error("[native] Could not re-read the rom:", error);
}
}
// Only what the shell wrote to the server is worth re-reading: a pull writes
// nothing back, and re-reading it would cost the user their slot and tab.
watch(
() => nativeStore.syncFor(romId),
(outcome) => {
if (!outcome) return;
if (outcome.action === "uploaded" || outcome.action === "archived")
void refreshRomAfterSync();
},
);
onMounted(async () => {
const romResponse = await romApi.getRom({
romId,
@@ -569,8 +762,11 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
:class="{ 'r-v2-ejs--config': !gameRunning }"
>
<!-- Pre-game configuration -->
<div v-if="!gameRunning" class="r-v2-ejs__config">
<!-- Hero: cover + title + Play CTA -->
<div
v-if="!gameRunning"
:class="nativeOnly ? 'r-v2-ejs__solo' : 'r-v2-ejs__config'"
>
<!-- Hero: cover + title + play CTAs -->
<RCard class="r-v2-ejs__panel r-v2-ejs__hero" variant="flat">
<div
class="r-v2-ejs__cover"
@@ -593,18 +789,52 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
<h1 class="r-v2-ejs__title">{{ title }}</h1>
<p class="r-v2-ejs__subtitle">{{ platformLabel }}</p>
</div>
<!-- Someone who has an emulator installed on this machine came to the
page for it, so it leads and keeps the play glyph; the in-browser
route follows, marked for the browser. -->
<RBtn
v-if="canPlayNative"
size="x-large"
variant="flat"
color="primary"
block
prepend-icon="mdi-play"
:prepend-icon="nativeLaunching ? 'mdi-loading mdi-spin' : 'mdi-play'"
class="r-v2-ejs__play"
:loading="!rom"
:disabled="!playReady || nativeLaunching"
@click="onPlayNative"
>
{{ nativeLabel }}
</RBtn>
<!-- Its own control rather than a second press on the button above, so
neither changes meaning under the pointer. -->
<RBtn
v-if="nativeLaunching"
variant="text"
size="small"
color="error"
block
class="r-v2-ejs__native-cancel"
prepend-icon="mdi-close-circle-outline"
:disabled="cancelling"
@click="onCancelNative"
>
{{ t("play.native-cancel") }}
</RBtn>
<RBtn
v-if="!nativeOnly"
size="x-large"
:variant="canPlayNative ? 'outlined' : 'flat'"
:color="canPlayNative ? undefined : 'primary'"
block
:prepend-icon="canPlayNative ? 'mdi-web' : 'mdi-play'"
class="r-v2-ejs__play"
:class="{ 'r-v2-ejs__play--secondary': canPlayNative }"
:loading="!playReady"
:disabled="!playReady"
:disabled="!playReady || nativeLaunching"
@click="onPlay"
>
{{ t("play.play") }}
{{ canPlayNative ? t("play.play-in-browser") : t("play.play") }}
</RBtn>
<div class="r-v2-ejs__hero-links">
<RBtn
@@ -629,7 +859,11 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
<!-- Resume: tabs, then preview over the saves list, or the states grid
beside the preview on wide screens. -->
<RCard class="r-v2-ejs__panel r-v2-ejs__resume" variant="flat">
<RCard
v-if="!nativeOnly"
class="r-v2-ejs__panel r-v2-ejs__resume"
variant="flat"
>
<div class="r-v2-ejs__panel-head">
<RSliderBtnGroup
variant="tab"
@@ -753,7 +987,11 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
</RCard>
<!-- Setup: disc / core / firmware / fullscreen / clear cache -->
<RCard class="r-v2-ejs__panel r-v2-ejs__setup" variant="flat">
<RCard
v-if="!nativeOnly"
class="r-v2-ejs__panel r-v2-ejs__setup"
variant="flat"
>
<div class="r-v2-ejs__panel-head r-v2-ejs__panel-head--label">
<RIcon icon="mdi-cog-outline" size="14" />
<span>{{ t("common.settings") }}</span>
@@ -802,6 +1040,17 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
v-model="showBezel"
:label="t('play.show-bezel')"
/>
<!-- Which of the above the native route takes with it, one line per
route. Said here rather than left to be discovered: the rest of
this panel is EmulatorJS' own, and a choice that silently applies
to one player and not the other is worse than a line of text. -->
<p
v-for="line in nativeSettingsLines"
:key="line"
class="r-v2-ejs__setup-note"
>
{{ line }}
</p>
</div>
<div class="r-v2-ejs__setup-foot">
<RBtn
@@ -816,7 +1065,7 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
</div>
</RCard>
<div class="r-v2-ejs__brand">
<div v-if="!nativeOnly" class="r-v2-ejs__brand">
<span>{{ t("play.powered-by") }}</span>
<img
src="/assets/emulatorjs/emulatorjs-logotype.svg"
@@ -882,6 +1131,16 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
align-items: stretch;
}
/* Native-only: the hero is the whole page, so it gets its own wrapper rather
than a column of the grid above and the breakpoint rules that reshape it. */
.r-v2-ejs__solo {
display: grid;
grid-template-columns: minmax(0, 380px);
justify-content: center;
max-width: 1280px;
margin: 0 auto;
}
/* Shared glass-panel skin — single visual vocabulary across panels. */
.r-v2-ejs__panel {
background: var(--r-color-bg-elevated) !important;
@@ -977,6 +1236,21 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
box-shadow: 0 10px 24px
color-mix(in srgb, var(--r-color-brand-primary) 35%, transparent);
}
/* The in-browser route below a native launch, which holds the brand glow. */
.r-v2-ejs__play--secondary {
box-shadow: none;
}
/* Secondary in weight, not in reach: `small` is 32px and touch wants 44px. */
.r-v2-ejs__native-cancel {
min-height: var(--r-touch-target);
}
/* A user-configured emulator can be named anything, so the label is clipped
rather than allowed to run out of the button. */
.r-v2-ejs__play :deep(.r-btn__label) {
display: block;
overflow: hidden;
text-overflow: ellipsis;
}
.r-v2-ejs__hero-links {
display: flex;
flex-direction: column;
@@ -1116,6 +1390,11 @@ html[data-bp~="md-and-up"]
gap: 12px;
flex: 1;
}
.r-v2-ejs__setup-note {
margin: 0;
font-size: var(--r-font-size-xs);
color: var(--r-color-fg-faint);
}
.r-v2-ejs__setup-foot {
border-top: 1px solid var(--r-color-border);
padding: 6px 10px 10px;

View File

@@ -8,8 +8,9 @@
// 4. Gallery (toggle grid + boxart RSelect prefix-label +
// advanced per-page boxart overrides)
// 5. Gameplay (launch-confirmation toggle)
// 6. Virtual collections (RSelect prefix-label)
// 7. UI version (v2-only, beta — kept last)
// 6. Desktop shell (only inside it — opens its own settings)
// 7. Virtual collections (RSelect prefix-label)
// 8. UI version (v2-only, beta — kept last)
//
// The v1 "Platforms drawer" section was removed (no equivalent in v2).
// `useUISettings` still exposes `platformsGroupBy` for v1 — we just
@@ -19,7 +20,9 @@ import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useUISettings } from "@/composables/useUISettings";
import { useUiVersion } from "@/composables/useUiVersion";
import { canOpenNativeSettings, openNativeSettings } from "@/services/native";
import storeCollections from "@/stores/collections";
import { useNativeStore } from "@/stores/native";
import CrtWarmup from "@/v2/components/AppShell/CrtWarmup.vue";
import WidgetReorderList from "@/v2/components/Home/Widgets/WidgetReorderList.vue";
import SettingsSection from "@/v2/components/Settings/SettingsSection.vue";
@@ -30,11 +33,26 @@ import { isBoxartStyle } from "@/v2/composables/useCoverArt";
import { useCrtMode } from "@/v2/composables/useCrtMode";
import { useDebugMode } from "@/v2/composables/useDebugMode";
import { useReducedMotion } from "@/v2/composables/useReducedMotion";
import { useSnackbar } from "@/v2/composables/useSnackbar";
const { t } = useI18n();
const uiVersion = useUiVersion();
const { enabled: debugEnabled } = useDebugMode();
const collectionsStore = storeCollections();
const nativeStore = useNativeStore();
const snackbar = useSnackbar();
// The shell's settings are a file on the user's own machine, so this only asks
// it to open them: RomM never reads or writes what is in there.
const showShellSettings = nativeStore.available && canOpenNativeSettings();
// A missing or unwritable configuration fails inside the shell, where the user
// cannot see it, so the button would otherwise look like it does nothing.
async function onOpenShellSettings() {
if (!(await openNativeSettings())) {
snackbar.error(t("settings.open-shell-settings-failed"));
}
}
const {
theme: selectedTheme,
@@ -454,6 +472,30 @@ function onVirtualCollectionTypeChange(value: unknown) {
</div>
</SettingsSection>
<SettingsSection
v-if="showShellSettings"
:title="t('settings.desktop-shell')"
icon="mdi-desktop-classic"
>
<div class="r-v2-ui__field">
<p class="r-v2-ui__desc">
{{
t("settings.desktop-shell-desc", {
version: nativeStore.shellVersion ?? "",
})
}}
</p>
<RBtn
variant="outlined"
size="small"
prepend-icon="mdi-cog-outline"
@click="onOpenShellSettings"
>
{{ t("settings.open-shell-settings") }}
</RBtn>
</div>
</SettingsSection>
<!-- Virtual collections -->
<SettingsSection
:title="t('common.virtual-collections')"