From 08852917f91e79662982fa41c18a8ea84cd96bd8 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Tue, 22 Sep 2026 23:46:40 -0400 Subject: [PATCH] feat: Offer the desktop shell's emulator from the save/state play page (#4541) --- frontend/src/locales/bg_BG/play.json | 24 + frontend/src/locales/bg_BG/settings.json | 4 + frontend/src/locales/cs_CZ/play.json | 24 + frontend/src/locales/cs_CZ/settings.json | 4 + frontend/src/locales/de_DE/play.json | 24 + frontend/src/locales/de_DE/settings.json | 4 + frontend/src/locales/en_GB/play.json | 24 + frontend/src/locales/en_GB/settings.json | 4 + frontend/src/locales/en_US/play.json | 24 + frontend/src/locales/en_US/settings.json | 4 + frontend/src/locales/es_ES/play.json | 24 + frontend/src/locales/es_ES/settings.json | 4 + frontend/src/locales/fr_FR/play.json | 24 + frontend/src/locales/fr_FR/settings.json | 4 + frontend/src/locales/hu_HU/play.json | 24 + frontend/src/locales/hu_HU/settings.json | 4 + frontend/src/locales/it_IT/play.json | 24 + frontend/src/locales/it_IT/settings.json | 4 + frontend/src/locales/ja_JP/play.json | 24 + frontend/src/locales/ja_JP/settings.json | 4 + frontend/src/locales/ko_KR/play.json | 24 + frontend/src/locales/ko_KR/settings.json | 4 + frontend/src/locales/pl_PL/play.json | 24 + frontend/src/locales/pl_PL/settings.json | 4 + frontend/src/locales/pt_BR/play.json | 24 + frontend/src/locales/pt_BR/settings.json | 4 + frontend/src/locales/ro_RO/play.json | 24 + frontend/src/locales/ro_RO/settings.json | 4 + frontend/src/locales/ru_RU/play.json | 24 + frontend/src/locales/ru_RU/settings.json | 4 + frontend/src/locales/tr_TR/play.json | 24 + frontend/src/locales/tr_TR/settings.json | 4 + frontend/src/locales/zh_CN/play.json | 24 + frontend/src/locales/zh_CN/settings.json | 4 + frontend/src/locales/zh_TW/play.json | 24 + frontend/src/locales/zh_TW/settings.json | 4 + frontend/src/services/native.test.ts | 275 ++++++++ frontend/src/services/native.ts | 179 +++++ frontend/src/stores/native.test.ts | 632 +++++++++++++++++ frontend/src/stores/native.ts | 375 ++++++++++ frontend/src/types/rommNative.d.ts | 195 ++++++ frontend/src/utils/downloadPath.test.ts | 71 +- frontend/src/utils/downloadPath.ts | 18 + frontend/src/utils/index.ts | 7 +- .../v2/components/GameActions/GameActions.vue | 2 +- .../GameActions/GameActionsList.test.ts | 10 +- .../GameActions/GameActionsList.vue | 2 +- .../src/v2/components/GameCard/GameCard.vue | 2 +- .../v2/composables/useCanPlay/index.test.ts | 34 + .../src/v2/composables/useCanPlay/index.ts | 21 +- .../composables/useGameActions/index.test.ts | 31 + .../v2/composables/useGameActions/index.ts | 13 +- .../composables/useNativeLaunch/index.test.ts | 157 +++++ .../v2/composables/useNativeLaunch/index.ts | 108 +++ .../usePlatformPlayable/index.test.ts | 26 + .../composables/usePlatformPlayable/index.ts | 14 +- frontend/src/v2/layouts/AppLayout.vue | 42 ++ frontend/src/v2/utils/lists.test.ts | 26 + frontend/src/v2/utils/lists.ts | 31 + frontend/src/v2/views/PlatformsIndex.test.ts | 24 +- frontend/src/v2/views/PlatformsIndex.vue | 15 +- .../src/v2/views/Player/EmulatorJS.test.ts | 641 ++++++++++++++++++ frontend/src/v2/views/Player/EmulatorJS.vue | 301 +++++++- .../src/v2/views/Settings/UserInterface.vue | 46 +- 64 files changed, 3769 insertions(+), 33 deletions(-) create mode 100644 frontend/src/services/native.test.ts create mode 100644 frontend/src/services/native.ts create mode 100644 frontend/src/stores/native.test.ts create mode 100644 frontend/src/stores/native.ts create mode 100644 frontend/src/types/rommNative.d.ts create mode 100644 frontend/src/v2/composables/useNativeLaunch/index.test.ts create mode 100644 frontend/src/v2/composables/useNativeLaunch/index.ts create mode 100644 frontend/src/v2/utils/lists.test.ts create mode 100644 frontend/src/v2/utils/lists.ts create mode 100644 frontend/src/v2/views/Player/EmulatorJS.test.ts diff --git a/frontend/src/locales/bg_BG/play.json b/frontend/src/locales/bg_BG/play.json index f71ea2ab8..31a60338f 100644 --- a/frontend/src/locales/bg_BG/play.json +++ b/frontend/src/locales/bg_BG/play.json @@ -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": "Бързият запис от слота е зареден", diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index cb312aefc..7f762a8fc 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -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)", diff --git a/frontend/src/locales/cs_CZ/play.json b/frontend/src/locales/cs_CZ/play.json index 574185b81..fe6bdbea3 100644 --- a/frontend/src/locales/cs_CZ/play.json +++ b/frontend/src/locales/cs_CZ/play.json @@ -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", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index d804f1d35..9807989e0 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -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)", diff --git a/frontend/src/locales/de_DE/play.json b/frontend/src/locales/de_DE/play.json index 072406fda..5d90bcc4b 100644 --- a/frontend/src/locales/de_DE/play.json +++ b/frontend/src/locales/de_DE/play.json @@ -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", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index 3ef8faaab..b9bff3853 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -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)", diff --git a/frontend/src/locales/en_GB/play.json b/frontend/src/locales/en_GB/play.json index b591d7c4c..ae828778e 100644 --- a/frontend/src/locales/en_GB/play.json +++ b/frontend/src/locales/en_GB/play.json @@ -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", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index c2db5cd6c..a8ce4109f 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -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)", diff --git a/frontend/src/locales/en_US/play.json b/frontend/src/locales/en_US/play.json index 4a00dc5f5..d70fe9c3c 100644 --- a/frontend/src/locales/en_US/play.json +++ b/frontend/src/locales/en_US/play.json @@ -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", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index 362b1d5a6..68eeb8cba 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -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)", diff --git a/frontend/src/locales/es_ES/play.json b/frontend/src/locales/es_ES/play.json index 19c0ea46a..8b66f339e 100644 --- a/frontend/src/locales/es_ES/play.json +++ b/frontend/src/locales/es_ES/play.json @@ -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", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index 96e7f27eb..d8f333225 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -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)", diff --git a/frontend/src/locales/fr_FR/play.json b/frontend/src/locales/fr_FR/play.json index 586671cf1..0c2bdc260 100644 --- a/frontend/src/locales/fr_FR/play.json +++ b/frontend/src/locales/fr_FR/play.json @@ -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é", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index d7db413c4..b221cbb26 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -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)", diff --git a/frontend/src/locales/hu_HU/play.json b/frontend/src/locales/hu_HU/play.json index 8e506fd07..7f8dc461b 100644 --- a/frontend/src/locales/hu_HU/play.json +++ b/frontend/src/locales/hu_HU/play.json @@ -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", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index ef561b005..bd45a1154 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -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)", diff --git a/frontend/src/locales/it_IT/play.json b/frontend/src/locales/it_IT/play.json index 56be1b71b..e643a9f81 100644 --- a/frontend/src/locales/it_IT/play.json +++ b/frontend/src/locales/it_IT/play.json @@ -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", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index 58916fdf5..8621d0c73 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -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)", diff --git a/frontend/src/locales/ja_JP/play.json b/frontend/src/locales/ja_JP/play.json index cb3fd858f..a17cb9978 100644 --- a/frontend/src/locales/ja_JP/play.json +++ b/frontend/src/locales/ja_JP/play.json @@ -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": "クイックステートをロードしました", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 7670da23f..3454c575f 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -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)", diff --git a/frontend/src/locales/ko_KR/play.json b/frontend/src/locales/ko_KR/play.json index 67745c117..35183adbd 100644 --- a/frontend/src/locales/ko_KR/play.json +++ b/frontend/src/locales/ko_KR/play.json @@ -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": "빠른 상태를 불러왔습니다", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 55f25a111..19b6b46bc 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -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)", diff --git a/frontend/src/locales/pl_PL/play.json b/frontend/src/locales/pl_PL/play.json index aa34d69b7..e3ec209de 100644 --- a/frontend/src/locales/pl_PL/play.json +++ b/frontend/src/locales/pl_PL/play.json @@ -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", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 099c89187..8b360915c 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -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)", diff --git a/frontend/src/locales/pt_BR/play.json b/frontend/src/locales/pt_BR/play.json index b126fc3b3..c2a2dcd28 100644 --- a/frontend/src/locales/pt_BR/play.json +++ b/frontend/src/locales/pt_BR/play.json @@ -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", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index a2ed4a20e..fe3829f7c 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -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)", diff --git a/frontend/src/locales/ro_RO/play.json b/frontend/src/locales/ro_RO/play.json index 310c8cf1b..99e33153f 100644 --- a/frontend/src/locales/ro_RO/play.json +++ b/frontend/src/locales/ro_RO/play.json @@ -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ă", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index 00dbe1872..e46ef94f4 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -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)", diff --git a/frontend/src/locales/ru_RU/play.json b/frontend/src/locales/ru_RU/play.json index f68f7fa80..343757ad4 100644 --- a/frontend/src/locales/ru_RU/play.json +++ b/frontend/src/locales/ru_RU/play.json @@ -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": "Быстрое состояние загружено", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index 79adbd1a8..0a0385e7f 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -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)", diff --git a/frontend/src/locales/tr_TR/play.json b/frontend/src/locales/tr_TR/play.json index 7649e0034..86c8cac2c 100644 --- a/frontend/src/locales/tr_TR/play.json +++ b/frontend/src/locales/tr_TR/play.json @@ -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", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index 9c6a15ead..6d417f8d6 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -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)", diff --git a/frontend/src/locales/zh_CN/play.json b/frontend/src/locales/zh_CN/play.json index 4bb386bb1..79797ff23 100644 --- a/frontend/src/locales/zh_CN/play.json +++ b/frontend/src/locales/zh_CN/play.json @@ -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": "已加载快速即时存档", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index c115526a5..66db3dc49 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -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": "已授予(仅自己的条目)", diff --git a/frontend/src/locales/zh_TW/play.json b/frontend/src/locales/zh_TW/play.json index 4616d70cb..f229ffd84 100644 --- a/frontend/src/locales/zh_TW/play.json +++ b/frontend/src/locales/zh_TW/play.json @@ -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": "已載入快速即時存檔", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 0731ccec9..9fa68eed6 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -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)", diff --git a/frontend/src/services/native.test.ts b/frontend/src/services/native.test.ts new file mode 100644 index 000000000..147f2d46b --- /dev/null +++ b/frontend/src/services/native.test.ts @@ -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): 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"); + }); +}); diff --git a/frontend/src/services/native.ts b/frontend/src/services/native.ts new file mode 100644 index 000000000..94ed6d764 --- /dev/null +++ b/frontend/src/services/native.ts @@ -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> { + const native = bridge(); + if (!native || queries.length === 0) return {}; + + try { + if (typeof native.getPlatformSupportAll === "function") { + const bulk = native.getPlatformSupportAll.bind(native); + const answers: Record = {}; + 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 = {}; + 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 { + 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 { + 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 { + 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; + } +} diff --git a/frontend/src/stores/native.test.ts b/frontend/src/stores/native.test.ts new file mode 100644 index 000000000..3c3639e36 --- /dev/null +++ b/frontend/src/stores/native.test.ts @@ -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> => ({}), +); +const launchNative = vi.fn( + async (_request: LaunchRequest): Promise => ({ + 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 => 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()), + 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 { + 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) => 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), + ); + + 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((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(); + }); +}); diff --git a/frontend/src/stores/native.ts b/frontend/src/stores/native.ts new file mode 100644 index 000000000..c55d50146 --- /dev/null +++ b/frontend/src/stores/native.ts @@ -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>( + Object.create(null) as Record, + ); + // 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(); + + /** The shell's last word on each launch, keyed by ROM id. */ + const launches = ref>({}); + /** 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>({}); + /** Display names, so launch feedback can name a game the shell identifies + * only by id. */ + const names = ref>({}); + /** 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()); + /** 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>({}); + /** 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()); + + 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 { + 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, + 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 { + 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 { + 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 { + 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, + }; +}); diff --git a/frontend/src/types/rommNative.d.ts b/frontend/src/types/rommNative.d.ts new file mode 100644 index 000000000..15bb108a4 --- /dev/null +++ b/frontend/src/types/rommNative.d.ts @@ -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; + cancel(romId: number): Promise; + getPlatformSupport(query: PlatformSupportQuery): Promise; + getPlatformSupportAll( + queries: PlatformSupportQuery[], + ): Promise>; + /** Subscribe to launch progress. Returns an unsubscribe function. */ + onLaunchState(listener: (state: LaunchState) => void): () => void; + openSettings(): Promise; +} + +declare global { + interface Window { + rommNative?: RommNativeBridge; + } +} diff --git a/frontend/src/utils/downloadPath.test.ts b/frontend/src/utils/downloadPath.test.ts index 4f1d112a1..3651d3b18 100644 --- a/frontend/src/utils/downloadPath.test.ts +++ b/frontend/src/utils/downloadPath.test.ts @@ -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(); + }); +}); diff --git a/frontend/src/utils/downloadPath.ts b/frontend/src/utils/downloadPath.ts index 3c00ef000..ef4b9abce 100644 --- a/frontend/src/utils/downloadPath.ts +++ b/frontend/src/utils/downloadPath.ts @@ -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 = [], diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts index 1be356bd7..f713129bd 100644 --- a/frontend/src/utils/index.ts +++ b/frontend/src/utils/index.ts @@ -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. diff --git a/frontend/src/v2/components/GameActions/GameActions.vue b/frontend/src/v2/components/GameActions/GameActions.vue index 585c61ab5..e9d36b48c 100644 --- a/frontend/src/v2/components/GameActions/GameActions.vue +++ b/frontend/src/v2/components/GameActions/GameActions.vue @@ -58,7 +58,7 @@ useGridNav(rootEl, {