diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..a20a3fce --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +tools/build-mgba/*.sh text eol=lf diff --git a/.gitignore b/.gitignore index ffdb65a6..9e961058 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,8 @@ tools/**/out/ tools/**/bin/ tools/**/obj/ tools/**/build/ +tools/build-melonds/android-arm64/ +tools/build-melonds/android-arm64-app/ /pkhex/ /PKSafe/ src/PKForge.App/Resources/Raw/sgdb.key diff --git a/.gitmodules b/.gitmodules index f6a34dfc..8432d884 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,9 @@ [submodule "external/PKHeX-Plugins"] path = external/PKHeX-Plugins url = https://github.com/santacrab2/PKHeX-Plugins.git +[submodule "external/melonDS"] + path = external/melonDS + url = https://github.com/melonDS-emu/melonDS.git +[submodule "external/azahar"] + path = external/azahar + url = https://github.com/azahar-emu/azahar.git diff --git a/README.md b/README.md index f687b9a0..26f2ba52 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ --- -**PKForge** relie vos ROMs à vos émulateurs, lit vos sauvegardes pour en tirer trophées +**PKForge** intègre progressivement l'émulation Pokémon, lit vos sauvegardes pour en tirer trophées et musée, et transforme le second écran de votre console en companion de jeu. Construit sur [PKHeX.Core](https://github.com/kwsch/PKHeX) et l' [Auto Legality Mod](https://github.com/santacrab2/PKHeX-Plugins), tout fonctionne @@ -27,10 +27,15 @@ hors-ligne, sur la console elle-même. - **Bibliothèque de jeux** : les 37 jeux Pokémon (Gen 1 → 9) en cartes avec artwork, label coloré possédée/absente, et scan automatique de l'arborescence ES-DE (`/storage/emulated/0/ROMs/`) — dumps No-Intro, français et anglais reconnus. -- **Liaison console → émulateur** (style Cocoon) : un tap par console choisit - l'émulateur qui lance ses ROMs. RetroArch, melonDS, Azahar, Eden, Dolphin, DraStic, - Pizza Boy, Linkboy détectés automatiquement. -- **Play** : le jeu démarre directement dans le bon émulateur, sans passer par son menu. +- **Cœurs intégrés** : GB/GBC/GBA et DS `.nds` démarrent dans PKForge, sans lancer + une autre application. Les anciens choix DS vers melonDS/DraStic sont ignorés et + corrigés au prochain lancement. Les jeux DS `.zip` sont acceptés s'ils contiennent + une seule ROM `.nds`; les archives multi-ROM, `.7z` et les jeux DSi restent à intégrer. +- **Compatibilité transitoire** : les jeux des consoles qui n'ont pas encore de cœur + PKForge peuvent toujours être lancés par RetroArch, Azahar, Eden ou Dolphin. + Ces intégrations externes ne sont pas l'objectif final. +- **Play** : les consoles intégrées restent dans PKForge; les plateformes en attente + conservent leur parcours externe temporaire. ### 🏆 Trophées & progression - **Trophées maison** (~30 par jeu) : paliers de dex, shinies, temps de jeu, @@ -42,43 +47,96 @@ hors-ligne, sur la console elle-même. détectés et annoncés par notification. ### 🏛️ Musée & banque -- **Musée** : le Pokédex par jeu (vu / capturé / chromatique) lu depuis vos sauvegardes. +- **Musée** : une entrée par sauvegarde liée, avec la grille Pokédex en lecture seule, + les états vus/capturés et les chromatiques actuellement stockés dans le jeu. La fiche + de l'espèce sélectionnée s'affiche aussi sur l'écran secondaire. - **Banque** : stockage inter-générations, import/export `.pk`, éditeur complet, autopilot living dex. +- **Échange entre jeux** : aperçu de conversion et de légalité, écriture destination + avant libération de la source, retour arrière vérifié si la source refuse l'écriture. - **Écran secondaire** : trophées, boîtes et journal Poképark sur l'écran Thor. ## 🗺️ Roadmap ### ✅ Fait - [x] Onglet Émulateurs + liaison par console (style Cocoon) -- [x] Bibliothèque de ROMs avec scan ES-DE et catalogue complet Gen 1-9 -- [x] Launcher Play (RetroArch, melonDS, Azahar, Eden + détection étendue) -- [x] **GB/GBC/GBA joués nativement dans l'app, uniquement** : cœur mGBA embarqué - (`libpkforge_mgba.so`, arm64), rendu SkiaSharp pixel-crisp à 59,7275 Hz, - audio 32768 Hz, sauvegardes `.sav` mappées. Les liaisons émulateur externes - pour GB/GBC/GBA sont retirées : ces jeux se lancent dans PKForge, point. -- [x] **Companion live (modèle PokéDaisy)** : pendant qu'un jeu GBA tourne dans - l'app, le second écran lit la mémoire de la console en direct — dex, équipe, - temps de jeu — rafraîchi chaque seconde +- [x] Bibliothèque de ROMs avec scan ES-DE, recherche par jeu/fichier, prise en charge + de plusieurs fichiers pour une même édition et navigation à la manette +- [x] Parcours externe temporaire pour les consoles dont le cœur PKForge reste à intégrer +- [x] **GB/GBC/GBA joués dans l'app, uniquement** : cœur mGBA embarqué + (`libpkforge_mgba.so`, arm64), ROMs locales ou choisies via Android, rendu + SkiaSharp pixel-crisp au rythme de la console, audio 32768 Hz et sauvegardes + batterie `.sav` persistantes. Une sauvegarde liée est synchronisée à la sortie + et lors de la mise en arrière-plan. + L'image peut remplir l'écran, conserver les pixels entiers ou être réduite + à 90/75 %; le plein écran est activé par défaut. Pause, états rapides, + vitesse ×1/×2/×3/×4, commandes tactiles et manettes sont accessibles pendant le jeu; + la vitesse est aussi réglable depuis les options du compagnon sur l'écran secondaire; + l'audio est coupé en accéléré. Ces consoles + ne sont plus envoyées à un émulateur externe. +- [x] **Compagnon GB/GBC/GBA** : équipe (sprites de forme, chromatiques, œufs, noms, + niveaux, PV et statuts), Pokédex, temps de jeu et sac en lecture seule + (poches, noms, quantités) depuis + la dernière sauvegarde valide. GB/GBC/GBA sont analysées avec les formats + de sauvegarde de chaque génération; les pages visibles et la page d'accueil sont + réglables. Les changements non sauvegardés en jeu ne sont pas encore lus. - [x] **Companion de jeu externe (modèle polling .sav)** : pendant qu'un jeu tourne dans un - émulateur tiers (melonDS, RetroArch DS…), le second écran surveille le fichier de - sauvegarde écrit par l'émulateur (stat toutes les 5 s, relecture après flush stable), - le parse et affiche dex, équipe, temps de sauvegarde, chrono de session et points de - restauration — sans jamais toucher au premier écran ni à la sauvegarde en direct + émulateur tiers, le second écran surveille sa sauvegarde (stat toutes les 5 s, + relecture après flush stable) et affiche dex, équipe, temps de sauvegarde, temps de + session. Le companion reste en lecture seule. - [x] Trophées maison par scan de sauvegardes + trophées manuels +- [x] Musée en lecture seule : Pokédex distinct par sauvegarde liée, grille par jeu, + états vus/capturés, marques des chromatiques stockés et fiche sur l'écran secondaire +- [x] Échange entre sauvegardes : aperçu avant écriture et transfert en saga; un échec + de libération de la source tente un retour arrière après comparaison des cases de + destination avec le reçu exact du transfert - [x] RetroAchievements (Gen 1-5) avec cache hors-ligne - [x] Watcher automatique + notifications de déblocage - [x] Écran secondaire : ladder de trophées pendant la page Trophées - [x] Interface française par défaut (anglais disponible) ### 🚧 En cours +- [ ] **Points de restauration du compagnon externe** : les règles de filtrage Domain existent, + mais la vue ne liste/crée/restaure pas encore les backups du `.sav` de l'émulateur. + La restauration doit attendre l'arrêt de l'émulateur pour éviter qu'il réécrive sa RAM + sur le fichier restauré. +- [ ] **DS Gen 4-5 : valider le cœur intégré de bout en bout** : melonDS 1.1 arm64 est + compilé dans PKForge pour les ROM `.nds` et les archives `.zip` qui contiennent une + seule ROM `.nds`. L'écran haut s'affiche sur + l'écran principal et l'écran tactile bas sur la dalle secondaire lorsqu'Android en expose + une; sur un appareil à écran unique, les deux restent empilés. Boutons, stylet, audio, + vitesse ×1/×2/×3/×4 (audio coupé en accéléré), sauvegarde batterie et état rapide sont reliés à l'interface. La route Play ignore les + anciennes liaisons externes. Il reste la validation sur AYN Thor avec des jeux réels et la + vérification des sauvegardes en jeu. Les archives contenant plusieurs `.nds`, `.7z`, + DSiWare, Wi-Fi et microphone ne sont pas encore pris en charge. +- [ ] **Données du compagnon DS Gen 4-5** : équipe, Pokédex, temps de jeu et sac lus depuis + l'image batterie melonDS uniquement quand le format et ses checksums sont valides; + l'instantané publié au compagnon décrit la dernière sauvegarde, pas la RAM non + sauvegardée. La lecture et le flux sont prêts; il reste la validation avec des saves + réelles. +- [ ] **Compagnon DS pendant l'émulation** : les données live sont lues depuis la sauvegarde, + mais la page compagnon n'est pas affichée pendant la session. L'écran inférieur reste + rendu sur le second panneau de la Thor; concevoir une présentation accessible sans + recouvrir l'un des deux écrans et la valider sur appareil. +- [ ] **3DS Gen 6-7 : cœur embarqué en préparation** : le code source Azahar + `2127.0-alpha1` est épinglé et le script Android arm64 prépare son cœur libretro + avec OpenGL et Vulkan comme dans sa configuration Android. Le cœur et le frontend ne + sont pas encore reliés au parcours de jeu; l'émulation intégrée, les commandes, l'audio, + le rendu dans l'app, l'écran tactile, les sauvegardes et les fichiers système restent + à implémenter. - [ ] **Intégration des mods** : Radical Red, Unbound, GS Chronicles… détectés et lancés depuis l'app avec leurs réglages dédiés - [ ] Traduction française complète des surfaces restantes (box browser, éditeurs) ### 🔮 Planifié -- [ ] Cœur DS embarqué (melonDS) pour les jeux DS natifs -- [ ] Musée (grille Pokédex) sur l'écran secondaire +- [ ] **Émulation Pokémon sans dépendance à un émulateur tiers** : intégrer un cœur PKForge + pour chaque console ayant reçu un jeu Pokémon — GB, GBC, GBA, DS, 3DS, Nintendo 64, + GameCube, Wii, Wii U, Switch et Pokémon mini — puis retirer le lancement externe du + parcours Pokémon. Construire et valider chaque plateforme séparément : cœur natif, + rendu, commandes, audio, sauvegardes/états, cycle de vie Android et tests sur appareils. + Les consoles de salon et systèmes historiques suivront selon leur faisabilité technique + et leurs contraintes de licence. +- [ ] Grille complète du Musée sur l'écran secondaire (la fiche de l'espèce sélectionnée y est affichée) - [ ] Watcher en arrière-plan (WorkManager) — scans sans l'app ouverte - [ ] Mises à jour in-app des définitions de trophées et du catalogue - [ ] Social : partage de progression, classements entre amis @@ -103,6 +161,15 @@ dotnet test tests/PKForge.Domain.Tests --configuration Release dotnet build src/PKForge.App/PKForge.App.csproj -f net10.0-android ``` +Le cœur DS natif est épinglé comme sous-module melonDS. Pour le reconstruire sur Windows +avec un NDK installé, exécute `powershell -File tools/build-melonds/build.ps1`. +Le script construit le cœur arm64, retire les symboles de débogage et le place dans l'APK. + +Le cœur 3DS préparatoire est épinglé sur Azahar `2127.0-alpha1`. Après installation de +ses sous-modules et d'un NDK Android arm64, son cœur libretro se construit avec +`powershell -File tools/build-azahar/build.ps1`. Cette étape ne rend pas encore les ROMs +3DS jouables dans PKForge; le frontend intégré reste à construire. + - **Domain** : règles pures (trophées, parsing des ROMs, catalogues) — testées xunit - **Infrastructure** : persistance JSON atomique - **App** : .NET MAUI 10 (net10.0-android), MVVM, double écran @@ -111,7 +178,11 @@ dotnet build src/PKForge.App/PKForge.App.csproj -f net10.0-android GPLv3 — voir [LICENSE](LICENSE). Basé sur [PKForge](https://github.com/sofianeelhor/PKForge) et -[PKHeX](https://github.com/kwsch/PKHeX). +[PKHeX](https://github.com/kwsch/PKHeX). L'émulation DS embarquée utilise +[melonDS](https://github.com/melonDS-emu/melonDS) 1.1; son code source et sa licence GPL-3.0 +sont conservés dans `external/melonDS`. Le cœur 3DS préparatoire est dérivé d' +[Azahar](https://github.com/azahar-emu/azahar) et sa licence GPL-3.0 est conservée dans +`external/azahar`. Non affilié à Nintendo, Game Freak ou The Pokémon Company. diff --git a/external/azahar b/external/azahar new file mode 160000 index 00000000..5f3306d1 --- /dev/null +++ b/external/azahar @@ -0,0 +1 @@ +Subproject commit 5f3306d13cab40bbd5cf38f2cf3ae8b6e6eedca6 diff --git a/external/melonDS b/external/melonDS new file mode 160000 index 00000000..b86390e4 --- /dev/null +++ b/external/melonDS @@ -0,0 +1 @@ +Subproject commit b86390e4428bf38ce4c1ce0e9ca446d6d25955e8 diff --git a/prd.json b/prd.json index 83369091..bbfdd235 100644 --- a/prd.json +++ b/prd.json @@ -1,6 +1,6 @@ { "project": "PKForge", - "branchName": "ralph/external-companion", + "branchName": "codex/roadmap-sync", "description": "Companion de jeu externe (run Ralph) : garder le second écran de l'AYN Thor vivant pendant qu'un émulateur tiers tourne au premier plan. Contrairement au companion PokéDaisy natif (lecture directe de la mémoire du cœur mGBA), celui-ci est alimenté par le polling du fichier de sauvegarde .sav que l'émulateur externe écrit sur disque : stats live, dex, points de restauration.", "userStories": [ { @@ -78,8 +78,8 @@ "Logique domaine pure testée (nommage, horodatage, ordre) ; build App et tests Domain passent" ], "priority": 5, - "passes": true, - "notes": "Domain rules pure + testées: RestorePointRules.ForGame (filtre BelongsTo, newest-first), OrderNewestFirst, NameFor(kind, utc, fr) nommage horodaté invariant (FR/EN). App: ExternalRestorePointService (DI) — ListForAsync via IBackupService.ListAsync + BelongsTo(savePath, snapshot); CreatePointAsync = backup atomique nommé/horodaté via IBackupService.CreateAsync(documentId=savePath), jamais d'écriture in-place; RestoreAsync = PadMenu.ConfirmAsync obligatoire (destructif) + safety backup de la save courante + ReadAsync(hash-check) + écriture atomique temp+move. Chaînes UI FR/EN dans AppStrings. 8 tests Domain. CI: tests Release + build APK. Manuel on device (US-007 branche la vue companion): depuis le companion d'un jeu externe, créer un point, le voir listé en tête, restaurer avec confirmation → le .sav est remplacé et un point de sécurité existe; aucun crash si le point est corrompu." + "passes": false, + "notes": "Audit du 2026-11-20 : les règles pures Domain sont présentes et testées, mais le service App n'était enregistré sans aucun appel depuis la vue; les critères de liste/création/restauration n'étaient donc pas accessibles. Le service App et ses chaînes inutilisées ont été retirés. La vue compagnon n'affiche plus de backups non filtrés. À reprendre avec un flux UI lié au .sav externe et une restauration qui n'écrase pas les changements en RAM d'un émulateur encore actif." }, { "id": "US-006", @@ -109,8 +109,8 @@ "AGENTS.md et progress.txt contiennent les apprentissages réutilisables de la run" ], "priority": 7, - "passes": true, - "notes": "Finalization. Companion view: GameCompanionView.ShowExternal(ExternalCompanionSnapshot, PlaySessionStats?) renders dex/party/save-playtime/session-chrono/total on the lower screen; SecondScreenBoxPage.SwapCoreAsync feeds it from IGameCompanionStore.External + IExternalCompanionStateStore.RomPath + IPlaySessionStore, and reacts to the External PropertyChanged — the overlay lives only on the second screen, never over the emulator's first screen, and is read-only. README: 'Companion de jeu externe (modèle polling .sav)' moved En cours -> Fait. AGENTS.md created at repo root with the run's reusable patterns. All UI strings FR-default/EN in AppStrings. Full CI: Domain tests Release + App net10.0-android build. Manual on device: launch a DS game in melonDS -> lower screen shows the external companion and refreshes within ~10 s of an in-game save, first screen untouched; back in PKForge -> companion stops, trophy scan runs." + "passes": false, + "notes": "Audit du 2026-11-20 : la vue companion externe, le README et les chaînes sont prêts, mais US-005 reste ouverte; la finalisation globale ne passe donc pas. Reprendre après la liste, la création et la restauration sécurisée des points externes. Validation appareil encore requise : lancer un jeu DS dans melonDS, vérifier le companion sur l'écran inférieur et l'émulateur intact sur le premier écran, puis revenir dans PKForge et vérifier l'arrêt du companion et le scan de trophées." } ] } diff --git a/progress.txt b/progress.txt index d12eb888..c79cd80d 100644 --- a/progress.txt +++ b/progress.txt @@ -131,3 +131,22 @@ null path). prd.json: US-004 passes=true. progress.txt: appended learnings." && - Le companion reste **read-only** côté vue : les actions destructives (restore) passent par `PadMenu.ConfirmAsync` sur le host, jamais en direct depuis le 2ᵉ écran. - Historique git de la run : uniquement des commits conventionnels `feat: US-00X - ...` + `fix:`/`docs:` — aucun WIP. --- + +## 2026-11-20 - Revue avant APK 3.1.15 +- Mise à jour de `main` sur la dernière tête `origin/main` (`0497d5e`), en conservant le travail local d'émulation et en fusionnant le compagnon externe avec les options de vitesse du compagnon embarqué. +- Vérification de code : aucune méthode privée inutilisée détectée par IDE0051. `git diff --check` ne signale pas d'erreur de whitespace; il reste un avertissement de conversion CRLF/LF attendu sur le script natif. +- Revue de US-005 : les règles Domain ont des tests, mais `ExternalRestorePointService` n'était appelé par aucune vue. Le compagnon chargeait par ailleurs les backups sans les filtrer par sauvegarde. Retrait du service App injoignable et de ses chaînes mortes; limitation de la liste affichée aux backups ayant le `SaveDocumentId` exact d'une sauvegarde embarquée. Les liens de bibliothèque et les émulateurs externes n'affichent pas de points non vérifiés. +- US-005 repassée à `passes: false` et README corrigé. La restauration externe reste à intégrer après conception d'un flux qui attend l'arrêt de l'émulateur avant de remplacer le `.sav`. +- APK Release Android arm64 construit avec succès (0 avertissement, 0 erreur), version `3.1.15` / code `325`; signature v1/v2/v3 vérifiée et alignement zip vérifié. Aucun appareil ADB n'était connecté pour un essai sur Thor. +--- +## 2026-11-20 - Synchronisation de la roadmap et pré-merge +- Roadmaps recensées : `README.md` (état produit), `prd.json` (stories) et ce journal append-only. README distingue les fonctions livrées des validations Thor/saves réelles encore ouvertes; US-005 et US-007 restent `passes: false`, DS Gen 4-5 reste à valider sur appareil, companion DS simultané reste à concevoir, 3DS n'est pas présenté comme intégré. `prd.json.branchName` suit la branche de cette livraison. +- Review : `ShowdownTeamService.Split` ignore maintenant les séparateurs initiaux laissés par les en-têtes Showdown filtrés. Le test normalise ses fins de ligne avec `ReplaceLineEndings`, quel que soit le checkout LF/CRLF. Les tests d'émulation définissent explicitement les cœurs présents et couvrent la route DS intégrée. +- Vérifications Release : Domain 1 095/1 095; Engine 992/992. Build Android Debug `net10.0-android` réussi (0 avertissement, 0 erreur). Validation manuelle sur AYN Thor et saves DS réelles toujours en attente. +--- +## 2026-11-20 - APK de test après revue +- APK Release `3.1.15` / code `325` reconstruit après les corrections : `artifacts/PKForge-3.1.15-android-arm64.apk` (82 585 907 octets). Signature Android Debug présente, zipalign validé, `libpkforge_mgba.so` et `libpkforge_melonds.so` inclus. Aucun APK ajouté au dépôt. +--- +## 2026-11-20 - APK final après régénération mGBA CI +- Le bot PKForge CI a ajouté un commit ne modifiant que `libpkforge_mgba.so` (`d39c0fc`). APK Release reconstruit depuis cette tête : `artifacts/PKForge-3.1.15-android-arm64.apk` (82 251 161 octets), signature installable, zipalign et présence des cœurs mGBA/melonDS vérifiés. Le changement est limité au binaire natif. +--- diff --git a/src/PKForge.App/Libraries/arm64-v8a/libpkforge_melonds.so b/src/PKForge.App/Libraries/arm64-v8a/libpkforge_melonds.so new file mode 100644 index 00000000..a33201bc Binary files /dev/null and b/src/PKForge.App/Libraries/arm64-v8a/libpkforge_melonds.so differ diff --git a/src/PKForge.App/Libraries/arm64-v8a/libpkforge_mgba.so b/src/PKForge.App/Libraries/arm64-v8a/libpkforge_mgba.so index 078f970a..e602d816 100755 Binary files a/src/PKForge.App/Libraries/arm64-v8a/libpkforge_mgba.so and b/src/PKForge.App/Libraries/arm64-v8a/libpkforge_mgba.so differ diff --git a/src/PKForge.App/MauiProgram.cs b/src/PKForge.App/MauiProgram.cs index bc36f7be..001215e1 100644 --- a/src/PKForge.App/MauiProgram.cs +++ b/src/PKForge.App/MauiProgram.cs @@ -22,6 +22,7 @@ public static MauiApp CreateMauiApp() Views.CapsuleSkin.Register(); // Probe the embedded mGBA shim once: GB/GBC/GBA play in-app only when it is packed. Domain.EmulatorCatalog.EmbeddedCoreAvailable = Platforms.Android.EmbeddedGameSession.IsAvailable; + Domain.EmulatorCatalog.EmbeddedDsCoreAvailable = Platforms.Android.NintendoDsGameSession.IsAvailable; #endif builder.UseMauiApp().UseSkiaSharp() .ConfigureFonts(fonts => @@ -102,7 +103,6 @@ public static MauiApp CreateMauiApp() builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); - builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(new Infrastructure.JsonConsoleEmulatorStore( Path.Combine(FileSystem.AppDataDirectory, "console-emulators.json"))); @@ -117,7 +117,9 @@ public static MauiApp CreateMauiApp() builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); - builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(sp => sp.GetRequiredService()); + builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -138,6 +140,7 @@ public static MauiApp CreateMauiApp() builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddTransient(); App.Trace("builder.Build()"); return builder.Build(); diff --git a/src/PKForge.App/PKForge.App.csproj b/src/PKForge.App/PKForge.App.csproj index 51a8a054..d0b48f13 100644 --- a/src/PKForge.App/PKForge.App.csproj +++ b/src/PKForge.App/PKForge.App.csproj @@ -10,9 +10,9 @@ true org.pkforge.app PKForge - 311 - 3.1.1 - android-arm64 + 325 + 3.1.15 + android-arm64 true @@ -76,6 +76,7 @@ + @@ -84,10 +85,13 @@ - + + + + + diff --git a/src/PKForge.App/Platforms/Android/AndroidEmulatorLauncher.cs b/src/PKForge.App/Platforms/Android/AndroidEmulatorLauncher.cs index 04cee2ff..5d320554 100644 --- a/src/PKForge.App/Platforms/Android/AndroidEmulatorLauncher.cs +++ b/src/PKForge.App/Platforms/Android/AndroidEmulatorLauncher.cs @@ -43,6 +43,13 @@ public async Task LaunchAsync(RomLink link, CancellationToken cancellation Services.AppLog.Info("launch", "Embedded launch requested on the external launcher; the views route it to EmbeddedGameSession instead."); return false; } + if (RomLinkRules.MustRunInApp(link.Generation, link.RomFileName)) + { + Services.AppLog.Error("launch", + $"Rejected external handoff for an integrated Pokémon ROM: Gen {link.Generation}, {link.RomFileName}.", + new InvalidOperationException("This ROM must be launched through PKForge's embedded core.")); + return false; + } var app = EmulatorCatalog.App(link.Emulator); var package = app.PackageIds.FirstOrDefault(IsInstalled) ?? app.PrimaryPackage; if (!IsInstalled(package)) diff --git a/src/PKForge.App/Platforms/Android/EmbeddedEngine.cs b/src/PKForge.App/Platforms/Android/EmbeddedEngine.cs index c978ca55..b2261a53 100644 --- a/src/PKForge.App/Platforms/Android/EmbeddedEngine.cs +++ b/src/PKForge.App/Platforms/Android/EmbeddedEngine.cs @@ -1,14 +1,15 @@ using System.Diagnostics; using System.Runtime.InteropServices; using Android.Media; +using PKForge.Domain; using SkiaSharp; namespace PKForge.App.Platforms.Android; /// -/// Drives an on its own thread at the GBA's exact frame -/// rate (59.7275 Hz — the hardware's, not 60), and hands each finished frame to -/// the UI as a ready-to-draw SKBitmap. The UI thread never touches the core; +/// Drives an on its own thread at the handheld's frame +/// rate (about 59.7275 Hz), and hands each finished frame to the UI as a +/// ready-to-draw SKBitmap. The UI thread never touches the core; /// the engine never touches the UI except through the frame event. /// internal sealed class EmbeddedEngine : IDisposable @@ -21,17 +22,24 @@ internal sealed class EmbeddedEngine : IDisposable private readonly MgbaCore _core; private readonly Thread _thread; private readonly CancellationTokenSource _cancel = new(); + private readonly ManualResetEventSlim _resume = new(initialState: true); + private readonly object _coreGate = new(); + private readonly object _lifecycleGate = new(); + private readonly object _audioGate = new(); private readonly object _frameGate = new(); private SKBitmap? _frame; private SKImage? _frameImage; - // The GBA's audio: 32768 Hz stereo, ~548 samples per frame. + // mGBA's audio output: 32768 Hz stereo, about 548 samples per frame. private const int AudioFramesPerDrain = 1024; private readonly short[] _audioScratch = new short[AudioFramesPerDrain * 2]; private readonly Java.Nio.ByteBuffer _audioBuffer; private readonly AudioTrack? _track; private volatile uint _keysPending; private readonly object _keyGate = new(); + private int _speedMultiplier = 1; + private volatile bool _audioEnabled = true; + private volatile bool _disposed; /// Raised on the emu thread after each frame; the UI marshals itself. public event Action? FrameProduced; @@ -72,6 +80,8 @@ public EmbeddedEngine(MgbaCore core) } catch (Exception) { + try { _track?.Stop(); } catch (Exception) { } + try { _track?.Release(); } catch (Exception) { } _track = null; // no audio device: the game still plays, silently } } @@ -84,6 +94,111 @@ public void SetKeys(uint bitmask) lock (_keyGate) _keysPending = bitmask; } + public void SetPaused(bool paused) + { + lock (_lifecycleGate) + { + if (_disposed) return; + if (paused) + { + _resume.Reset(); + lock (_audioGate) + try { _track?.Pause(); } catch (Exception) { } + lock (_coreGate) { } // wait until any in-flight frame has finished + } + else + { + _resume.Set(); + if (Volatile.Read(ref _speedMultiplier) == 1) + lock (_audioGate) + try { _track?.Play(); } catch (Exception) { } + } + } + } + + public void SetSpeedMultiplier(int multiplier) + { + if (multiplier is < 1 or > 4) + throw new ArgumentOutOfRangeException(nameof(multiplier), "The emulation speed must be between ×1 and ×4."); + + var previous = Interlocked.Exchange(ref _speedMultiplier, multiplier); + if (previous == multiplier || _track is null) return; + + lock (_audioGate) + { + try + { + if (multiplier > 1) + { + _track.Pause(); + _track.Flush(); + } + else if (_resume.IsSet) + { + _track.Play(); + } + } + catch (Exception error) + { + Services.AppLog.Warn("embedded", $"Could not update audio for emulation speed ×{multiplier}: {error.Message}"); + } + } + } + + public bool ReadBytes(uint address, Span destination) + { + lock (_coreGate) + return !_disposed && _core.ReadBytes(address, destination); + } + + public LiveCompanionSnapshot? ReadLiveCompanion( + int generation, + int maxSpecies, + string romFileName) + { + lock (_coreGate) + { + if (_disposed) return null; + + // mGBA's savedata clone is the canonical battery image for each cartridge + // type. The GBA flash save can be 128 KiB while its bus window is only 64 KiB. + var saveRam = new byte[0x20000]; + var saveSize = _core.CopySavedata(saveRam); + if (saveSize <= 0) return null; + if (saveSize != saveRam.Length) Array.Resize(ref saveRam, saveSize); + + if (generation is 1 or 2) + return LiveGen12SaveReader.Read(saveRam, generation, _core.GameTitle, _core.GameCode, romFileName); + if (generation != 3 || saveSize < 0x1C000) + return null; + + // A partially written Gen 3 save must not be surfaced to the companion. + var companionData = LiveGen3SaveReader.Read(saveRam, _core.GameCode); + if (companionData is null) return null; + var snapshot = LiveGbaCompanion.Read(_core.GameTitle, _core.GameCode, saveRam, maxSpecies); + if (snapshot is null) return null; + return snapshot with { Party = companionData.Party, Bag = companionData.Bag }; + } + } + + public bool SaveState(string path) + { + lock (_coreGate) + return !_disposed && _core.IsRunning && _core.SaveState(path); + } + + public bool LoadState(string path) + { + lock (_coreGate) + return !_disposed && _core.IsRunning && _core.LoadState(path); + } + + public bool FlushSave(string path) + { + lock (_coreGate) + return !_disposed && _core.IsRunning && _core.FlushSave(path); + } + /// Draws the newest frame into the canvas, scaled to fit, pixel-crisp. public void Draw(SKCanvas canvas, SKRect destination) { @@ -99,61 +214,106 @@ public void Draw(SKCanvas canvas, SKRect destination) private void RunLoop() { - var (width, height) = _core.VideoSize; - var frame = new SKBitmap(width, height, SKColorType.Rgba8888, SKAlphaType.Opaque); - var periodTicks = Stopwatch.Frequency / FramesPerSecond; - // The deadline accumulates: each frame is due periodTicks after the last - // one, so per-frame jitter never accumulates into drift (audio stays in - // sync over hours). - long deadline = Stopwatch.GetTimestamp(); - - while (!_cancel.IsCancellationRequested) + try { - // Latch the newest input, drop anything older (a toggle during a frame). - uint keys; - lock (_keyGate) keys = _keysPending; - _core.SetKeys(keys); - _core.RunFrame(); + var (width, height) = _core.VideoSize; + var frame = new SKBitmap(width, height, SKColorType.Rgba8888, SKAlphaType.Opaque); + lock (_frameGate) _frame = frame; + var basePeriodTicks = Stopwatch.Frequency / FramesPerSecond; + var frameCount = 0; + // Keep fractional clock ticks so timing error does not accumulate. + double deadline = Stopwatch.GetTimestamp(); - // The frame is mGBA's 0x00BBGGRR little-endian: bytes R,G,B,X — the - // bitmap's Rgba8888 row layout, copied as-is. - _core.CopyFrame(MemoryMarshal.Cast(frame.GetPixelSpan())); - - lock (_frameGate) + while (!_cancel.IsCancellationRequested) { - _frameImage?.Dispose(); - _frame = frame; - _frameImage = SKImage.FromBitmap(frame); - } - FrameProduced?.Invoke(); + if (!_resume.IsSet) + { + _resume.Wait(TimeSpan.FromMilliseconds(50)); + deadline = Stopwatch.GetTimestamp(); + continue; + } - // Drain this frame's audio into the track: the audio clock paces the - // loop when the track's buffer fills (writes block), which is the - // PokeDaisy-verified pattern — the game can never outrun its sound. - var frames = _core.ReadAudio(_audioScratch, AudioFramesPerDrain); - if (frames > 0 && _track is not null) - { - _audioBuffer.Rewind(); - _audioBuffer.AsShortBuffer().Put(_audioScratch, 0, frames * 2); - _audioBuffer.Rewind(); - // The track is in bytes: frames × 2 channels × 2 bytes. - _track.Write(_audioBuffer, frames * 4, WriteMode.Blocking); - } + var speedMultiplier = Volatile.Read(ref _speedMultiplier); + var framePeriodTicks = basePeriodTicks / speedMultiplier; + var publishFrame = ++frameCount % speedMultiplier == 0; - // Pace to the hardware rate. Sleep granularity (~15 ms on some - // kernels) is corrected by measuring and carrying the error forward. - deadline += (long)periodTicks; - var remaining = TimeSpan.FromSeconds((double)(deadline - Stopwatch.GetTimestamp()) / Stopwatch.Frequency); - if (remaining > TimeSpan.Zero) - { - // Sleep with a 1 ms margin, then spin the sub-millisecond slice: - // Sleep alone drifts with the scheduler's granularity. - Thread.Sleep(remaining + TimeSpan.FromMilliseconds(1)); - while (Stopwatch.GetTimestamp() < deadline) - Thread.SpinWait(64); + int audioFrames; + lock (_coreGate) + { + if (_cancel.IsCancellationRequested) break; + if (!_resume.IsSet) continue; + + // Latch the newest input, dropping anything older (a toggle during a frame). + uint keys; + lock (_keyGate) keys = _keysPending; + _core.SetKeys(keys); + _core.RunFrame(); + + // mGBA's color_t is 0x00BBGGRR: bytes R,G,B,X match Rgba8888. + if (publishFrame) + _core.CopyFrame(MemoryMarshal.Cast(frame.GetPixelSpan())); + audioFrames = _core.ReadAudio(_audioScratch, AudioFramesPerDrain); + } + + if (publishFrame) + { + lock (_frameGate) + { + _frameImage?.Dispose(); + _frameImage = SKImage.FromBitmap(frame); + } + try { FrameProduced?.Invoke(); } + catch (Exception error) { Services.AppLog.Warn("embedded", $"A frame listener failed: {error.Message}"); } + } + + // The audio clock paces the loop when AudioTrack's buffer fills. + if (audioFrames > 0 && _track is not null && _audioEnabled && speedMultiplier == 1) + { + lock (_audioGate) + { + if (Volatile.Read(ref _speedMultiplier) == 1) + { + try + { + _audioBuffer.Rewind(); + _audioBuffer.AsShortBuffer().Put(_audioScratch, 0, audioFrames * 2); + _audioBuffer.Rewind(); + if (_track.Write(_audioBuffer, audioFrames * 4, WriteMode.Blocking) < 0) + { + _audioEnabled = false; + Services.AppLog.Warn("embedded", "Game audio stopped after an AudioTrack write error."); + } + } + catch (Exception error) + { + _audioEnabled = false; + Services.AppLog.Warn("embedded", $"Game audio stopped: {error.Message}"); + } + } + } + } + + // Carry timing error forward so scheduling jitter does not accumulate. + deadline += framePeriodTicks; + var remaining = TimeSpan.FromSeconds((deadline - Stopwatch.GetTimestamp()) / Stopwatch.Frequency); + if (remaining > TimeSpan.Zero) + { + // Sleep with a 1 ms margin, then spin the sub-millisecond slice. + var coarseSleep = remaining - TimeSpan.FromMilliseconds(1); + if (coarseSleep > TimeSpan.Zero) Thread.Sleep(coarseSleep); + while (Stopwatch.GetTimestamp() < deadline && !_cancel.IsCancellationRequested) + Thread.SpinWait(64); + } + else if (remaining < TimeSpan.FromMilliseconds(-100)) + { + deadline = Stopwatch.GetTimestamp(); // recover without unbounded catch-up at higher speeds + } } } - frame.Dispose(); + catch (Exception error) + { + Services.AppLog.Error("embedded", "The emulation thread stopped", error); + } } private void DisposeFrame() @@ -169,11 +329,24 @@ private void DisposeFrame() public void Dispose() { + lock (_lifecycleGate) + { + if (_disposed) return; + _disposed = true; + } _cancel.Cancel(); - try { _thread.Join(500); } catch (ThreadStateException) { } + _resume.Set(); + try { _track?.Stop(); } catch (Exception) { } + try + { + if (_thread.ThreadState != System.Threading.ThreadState.Unstarted) + _thread.Join(); + } + catch (ThreadStateException) { } + FrameProduced = null; DisposeFrame(); - _track?.Stop(); - _track?.Release(); + try { _track?.Release(); } catch (Exception) { } + _resume.Dispose(); _cancel.Dispose(); } } diff --git a/src/PKForge.App/Platforms/Android/EmbeddedGameSession.cs b/src/PKForge.App/Platforms/Android/EmbeddedGameSession.cs index bf7cc4a5..8b43e41c 100644 --- a/src/PKForge.App/Platforms/Android/EmbeddedGameSession.cs +++ b/src/PKForge.App/Platforms/Android/EmbeddedGameSession.cs @@ -1,18 +1,31 @@ +using System.Security.Cryptography; +using System.IO.Compression; +using System.Text; using PKForge.Domain; using SkiaSharp; namespace PKForge.App.Platforms.Android; +public sealed record EmbeddedGameStartResult(IEmbeddedGameSession? Session, string? Error); + /// /// One running game: the core plus its engine, owned together. Created by the /// Play flow when the embedded library is present; disposed when the player /// leaves the game screen. The pages and the second-screen companion both read /// through this facade. /// -public sealed class EmbeddedGameSession : IDisposable +public sealed class EmbeddedGameSession : IEmbeddedGameSession, IDisposable { private readonly MgbaCore _core; + private readonly string _romFileName; + private readonly string _batterySavePath; + private readonly string? _linkedSaveSyncMarkerPath; + private readonly string? _linkedSaveDocumentId; + private readonly ISaveFileAccess? _saveFileAccess; + private readonly object _disposeGate = new(); + private readonly SemaphoreSlim _saveSyncGate = new(1, 1); private EmbeddedEngine? _engine; + private Task? _closeTask; /// Raised on the emu thread after each frame; no-ops once disposed. public event Action? FrameProduced @@ -24,11 +37,35 @@ public event Action? FrameProduced public (int Width, int Height) VideoSize => _core.VideoSize; public string GameTitle => _core.GameTitle; public string GameCode => _core.GameCode; + public int Generation { get; } + public string QuickStatePath { get; } + public bool HasQuickState => File.Exists(QuickStatePath); + public bool HasSaveConflict { get; private set; } + public bool SupportsTouchScreen => false; + public bool SupportsLiveCompanion => true; + public bool IsNintendoDs => false; - private EmbeddedGameSession(MgbaCore core, EmbeddedEngine engine) + private EmbeddedGameSession( + MgbaCore core, + EmbeddedEngine engine, + string romPath, + string? romFileName, + string batterySavePath, + int generation, + string? linkedSaveDocumentId, + ISaveFileAccess? saveFileAccess, + bool hasSaveConflict) { _core = core; + _romFileName = romFileName ?? Path.GetFileName(romPath); _engine = engine; + _batterySavePath = batterySavePath; + _linkedSaveSyncMarkerPath = linkedSaveDocumentId is null ? null : batterySavePath + ".synced"; + _linkedSaveDocumentId = linkedSaveDocumentId; + _saveFileAccess = saveFileAccess; + Generation = generation; + QuickStatePath = StatePathForRom(romPath, romFileName); + HasSaveConflict = hasSaveConflict; } /// True when libpkforge_mgba.so is packed in this APK (the embedded core can run). @@ -39,86 +76,508 @@ public static bool IsAvailable { try { - var core = new MgbaCore(); + var available = MgbaNative.CoreAvailable() != 0; + Domain.EmulatorCatalog.EmbeddedCoreAvailable = available; + return available; + } + catch (DllNotFoundException) { } + catch (EntryPointNotFoundException) { } + catch (BadImageFormatException) { } + Domain.EmulatorCatalog.EmbeddedCoreAvailable = false; + return false; + } + } + + /// The battery save path for a ROM or a linked save document. + public static string SavePathForRom(string romPath, string? saveDocumentId = null) + { + if (!string.IsNullOrWhiteSpace(saveDocumentId)) + return PrivateFilePath("linked-saves", saveDocumentId, ".sav"); + if (IsContentUri(romPath)) + return PrivateFilePath("battery-saves", romPath, ".sav"); + if (Uri.TryCreate(romPath, UriKind.Absolute, out var fileUri) && fileUri.IsFile) + romPath = fileUri.LocalPath; + return Path.ChangeExtension(romPath, ".sav") + ?? throw new ArgumentException("The ROM path cannot produce a battery save path.", nameof(romPath)); + } + + /// + /// Loads a supported Gen 1-5 ROM (and its save when given) and starts the emulation + /// thread. Failure is returned to the caller; integrated generations never fall back + /// to an external emulator. + /// + public static EmbeddedGameStartResult TryStart( + string romPath, + int generation = 0, + string? romFileName = null, + string? linkedSaveDocumentId = null, + ISaveFileAccess? saveFileAccess = null) + { + var sourceName = romFileName ?? Path.GetFileName(romPath); + if (!RomLinkRules.UsesIntegratedCore(generation)) + generation = RomLinkRules.ResolveIntegratedGeneration(generation, sourceName); + if (!RomLinkRules.UsesIntegratedCore(generation)) + return new EmbeddedGameStartResult(null, + $"PKForge n'a pas encore de cœur intégré pour la génération {generation}."); + if (!RomLinkRules.IsSupportedEmbeddedFormat(generation, sourceName)) + { + var expected = generation switch + { + 1 or 2 => ".gb ou .gbc", + 3 => ".gba", + 4 or 5 => ".nds ou .zip contenant une seule ROM .nds", + _ => "un format pris en charge", + }; + return new EmbeddedGameStartResult(null, + $"Format ROM non pris en charge par le cœur intégré : {Path.GetExtension(sourceName)}. Format attendu : {expected}."); + } + + if (generation is 4 or 5) + return NintendoDsGameSession.TryStart(romPath, generation, romFileName, linkedSaveDocumentId, saveFileAccess); + + MgbaCore? core = null; + EmbeddedEngine? engine = null; + try + { + var localRomPath = MaterializeRom(romPath, romFileName); + var savePath = SavePathForRom(romPath, linkedSaveDocumentId); + Directory.CreateDirectory(Path.GetDirectoryName(savePath)!); + var hasSaveConflict = false; + if (linkedSaveDocumentId is not null) + { + if (saveFileAccess is null) + throw new InvalidOperationException("The linked save file service is unavailable."); + var originalSave = saveFileAccess.ReadAsync(linkedSaveDocumentId).AsTask().GetAwaiter().GetResult(); + hasSaveConflict = ReconcileLinkedSave(savePath, savePath + ".synced", originalSave.ToArray()); + } + + core = new MgbaCore(); + if (!core.Load(localRomPath, savePath)) + { + var reason = core.LoadError ?? "mGBA n'a pas pu charger cette ROM."; + Services.AppLog.Error("embedded", $"Could not load {Path.GetFileName(romPath)}: {reason}", new InvalidOperationException(reason)); core.Dispose(); - Domain.EmulatorCatalog.EmbeddedCoreAvailable = true; - return true; + return new EmbeddedGameStartResult(null, reason); } - catch (DllNotFoundException) { return false; } - catch (EntryPointNotFoundException) { return false; } + engine = new EmbeddedEngine(core); + var session = new EmbeddedGameSession( + core, engine, romPath, romFileName, savePath, generation, linkedSaveDocumentId, saveFileAccess, hasSaveConflict); + engine.Start(); + return new EmbeddedGameStartResult(session, null); + } + catch (DllNotFoundException error) + { + var reason = $"Android n'a pas pu charger le cœur mGBA : {error.Message}"; + Services.AppLog.Error("embedded", reason, error); + engine?.Dispose(); + core?.Dispose(); + return new EmbeddedGameStartResult(null, reason); + } + catch (EntryPointNotFoundException error) + { + const string reason = "Le cœur mGBA de l'APK est trop ancien pour cette version de PKForge."; + Services.AppLog.Error("embedded", reason, error); + engine?.Dispose(); + core?.Dispose(); + return new EmbeddedGameStartResult(null, reason); + } + catch (BadImageFormatException error) + { + const string reason = "L'architecture du cœur mGBA ne correspond pas à cet appareil. Installe l'APK arm64."; + Services.AppLog.Error("embedded", reason, error); + engine?.Dispose(); + core?.Dispose(); + return new EmbeddedGameStartResult(null, reason); + } + catch (Exception error) + { + Services.AppLog.Error("embedded", $"Could not start {Path.GetFileName(romPath)}", error); + engine?.Dispose(); + core?.Dispose(); + return new EmbeddedGameStartResult(null, $"{error.GetType().Name}: {error.Message}"); } } - /// The save file mGBA's convention names for a ROM (same name, .sav), when it exists. - public static string? SavePathForRom(string romPath) + internal static string StatePathForRom(string romPath, string? romFileName) { + var fileName = Path.GetFileNameWithoutExtension(romFileName ?? romPath); + return PrivateFilePath("states", romPath, ".ss0", fileName); + } + + internal static string PrivateFilePath(string folder, string identity, string extension, string? prefix = null) + { + var hash = HashIdentity(identity); + var safePrefix = string.IsNullOrWhiteSpace(prefix) ? "game" : SafeFileName(prefix); + return Path.Combine(FileSystem.AppDataDirectory, "emulator", folder, $"{safePrefix}-{hash}{extension}"); + } + + internal static string HashIdentity(string identity) => + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity)))[..16]; + + internal static bool IsContentUri(string value) => + Uri.TryCreate(value, UriKind.Absolute, out var uri) + && uri.Scheme.Equals("content", StringComparison.OrdinalIgnoreCase); + + internal static string MaterializeRom(string romPath, string? romFileName) + { + if (!IsContentUri(romPath)) + { + if (Uri.TryCreate(romPath, UriKind.Absolute, out var fileUri) + && fileUri.IsFile) + return fileUri.LocalPath; + return romPath; + } + + var directory = Path.Combine(FileSystem.CacheDirectory, "embedded-roms"); + Directory.CreateDirectory(directory); + var name = SafeFileName(romFileName ?? "game.gba"); + var extension = Path.GetExtension(name); + var stem = Path.GetFileNameWithoutExtension(name); + var path = Path.Combine(directory, $"{stem}-{HashIdentity(romPath)}{extension}"); + var temporaryPath = $"{path}.{Guid.NewGuid():N}.tmp"; try { - var save = Path.ChangeExtension(romPath, ".sav"); - return File.Exists(save) ? save : null; + var uri = global::Android.Net.Uri.Parse(romPath) + ?? throw new ArgumentException("The ROM document URI is invalid.", nameof(romPath)); + using var input = global::Android.App.Application.Context.ContentResolver?.OpenInputStream(uri) + ?? throw new IOException("The ROM document provider could not open this file."); + using (var output = File.Create(temporaryPath)) + input.CopyTo(output); + File.Move(temporaryPath, path, overwrite: true); + return path; } - catch (ArgumentException) + catch { - return null; + try { File.Delete(temporaryPath); } catch (IOException) { } + throw; } } - /// - /// Loads a ROM (and its save when given) and starts the emu thread. Returns - /// null when the embedded core is unavailable (no library) or the file is not - /// a GBA/GB ROM — the caller shows a message instead of launching an external app. - /// - public static EmbeddedGameSession? TryStart(string romPath, string? savePath) + /// Materializes a DS ROM or extracts the only .nds entry from a ZIP into app cache. + internal static string MaterializeNintendoDsRom(string romPath, string? romFileName) { + var sourceName = romFileName ?? Path.GetFileName(romPath); + var extension = Path.GetExtension(sourceName); + var localPath = MaterializeRom(romPath, sourceName); + if (extension.Equals(".nds", StringComparison.OrdinalIgnoreCase)) + return localPath; + if (!extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("Sélectionne un fichier .nds ou une archive .zip."); + + using var source = File.OpenRead(localPath); + using var archive = new ZipArchive(source, ZipArchiveMode.Read, leaveOpen: false); + var entries = archive.Entries + .Where(entry => !entry.FullName.EndsWith('/') && + Path.GetExtension(entry.FullName).Equals(".nds", StringComparison.OrdinalIgnoreCase)) + .ToArray(); + if (entries.Length == 0) + throw new InvalidDataException("L'archive ne contient aucune ROM .nds."); + if (entries.Length > 1) + throw new InvalidDataException("L'archive contient plusieurs ROM .nds; conserve uniquement le jeu à lancer."); + + var rom = entries[0]; + const long maximumRomSize = 512L * 1024 * 1024; + if (rom.Length <= 0 || rom.Length > maximumRomSize) + throw new InvalidDataException("La taille décompressée de la ROM dépasse la limite acceptée."); + + var cacheDirectory = Path.Combine(FileSystem.CacheDirectory, "embedded-roms", "nds"); + Directory.CreateDirectory(cacheDirectory); + var cacheIdentity = $"{romPath}\n{rom.FullName}"; + var outputPath = Path.Combine(cacheDirectory, $"{HashIdentity(cacheIdentity)}.nds"); + var temporaryPath = $"{outputPath}.{Guid.NewGuid():N}.tmp"; try { - var core = new MgbaCore(); - if (!core.Load(romPath, savePath)) { core.Dispose(); return null; } - var engine = new EmbeddedEngine(core); - var session = new EmbeddedGameSession(core, engine); - engine.Start(); - return session; + using var input = rom.Open(); + using (var output = File.Create(temporaryPath)) + { + var buffer = new byte[64 * 1024]; + long copied = 0; + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) != 0) + { + copied += read; + if (copied > maximumRomSize || copied > rom.Length) + throw new InvalidDataException("L'entrée .nds décompressée dépasse sa taille annoncée."); + output.Write(buffer, 0, read); + } + + if (copied != rom.Length) + throw new InvalidDataException("La ROM .nds extraite est incomplète."); + } + + File.Move(temporaryPath, outputPath, overwrite: true); + return outputPath; } - catch (DllNotFoundException) + catch { - return null; // the .so is not packed in this build — no embedded play + try { File.Delete(temporaryPath); } catch (IOException) { } + throw; } - catch (EntryPointNotFoundException) + } + + internal static string SafeFileName(string value) + { + var fileName = Path.GetFileName(value); + if (string.IsNullOrWhiteSpace(fileName)) return "game"; + foreach (var invalidCharacter in Path.GetInvalidFileNameChars()) + fileName = fileName.Replace(invalidCharacter, '_'); + return fileName; + } + + internal static bool ReconcileLinkedSave(string savePath, string markerPath, byte[] linkedBytes) + { + if (!File.Exists(savePath)) { - return null; // the .so is older than the shim — no embedded play + WriteFileAtomically(savePath, linkedBytes); + TryWriteSyncMarker(markerPath, linkedBytes); + return false; + } + + var localBytes = File.ReadAllBytes(savePath); + if (localBytes.AsSpan().SequenceEqual(linkedBytes)) + { + TryWriteSyncMarker(markerPath, linkedBytes); + return false; + } + + var marker = ReadSyncMarker(markerPath); + if (marker is not null) + { + var localMatchesMarker = ContentHash(localBytes).Equals(marker, StringComparison.Ordinal); + var linkedMatchesMarker = ContentHash(linkedBytes).Equals(marker, StringComparison.Ordinal); + if (localMatchesMarker && !linkedMatchesMarker) + { + WriteFileAtomically(savePath, linkedBytes); + TryWriteSyncMarker(markerPath, linkedBytes); + return false; + } + if (linkedMatchesMarker && !localMatchesMarker) + return false; // The private copy contains progress not yet written through SAF. + } + + Services.AppLog.Warn("embedded", "The linked save and private game save both changed; preserving both copies."); + return true; + } + + internal static string ContentHash(ReadOnlySpan bytes) => + Convert.ToHexString(SHA256.HashData(bytes)); + + internal static string? ReadSyncMarker(string markerPath) + { + try + { + return File.Exists(markerPath) ? File.ReadAllText(markerPath).Trim() : null; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + Services.AppLog.Warn("embedded", $"Could not read the linked save marker: {error.Message}"); + return null; + } + } + + internal static void TryWriteSyncMarker(string markerPath, byte[] bytes) + { + try { WriteFileAtomically(markerPath, Encoding.ASCII.GetBytes(ContentHash(bytes))); } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + Services.AppLog.Warn("embedded", $"Could not update the linked save marker: {error.Message}"); + } + } + + internal static void WriteFileAtomically(string path, byte[] bytes) + { + var directory = Path.GetDirectoryName(path)!; + Directory.CreateDirectory(directory); + var temporaryPath = Path.Combine(directory, $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp"); + try + { + File.WriteAllBytes(temporaryPath, bytes); + File.Move(temporaryPath, path, overwrite: true); + } + finally + { + try { File.Delete(temporaryPath); } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) { } } } /// Sets the held buttons (thread-safe). public void SetKeys(uint bitmask) => _engine?.SetKeys(bitmask); + public void SetTouchScreen(bool down, int x, int y) { } + /// Draws the newest frame, pixel-crisp. public void Draw(SKCanvas canvas, SKRect destination) => _engine?.Draw(canvas, destination); /// Reads the live game memory — the companion's data bridge. - public bool ReadBytes(uint address, Span destination) => _core.ReadBytes(address, destination); + public bool ReadBytes(uint address, Span destination) => + _engine?.ReadBytes(address, destination) == true; /// - /// The live companion snapshot (dex, party, playtime) read from the running - /// core's save RAM. Null when the game isn't a Gen 3 GBA title or the memory - /// is unreadable. Gen 1/2 (GB/GBC) saves live elsewhere and are not read live. + /// The companion snapshot read from the running core's battery-save image. The + /// game writes that image when it saves; unsaved changes remain in emulated RAM. /// - public LiveGbaCompanion.LiveCompanionSnapshot? ReadLiveCompanion() + public LiveCompanionSnapshot? ReadLiveCompanion() + { + var maxSpecies = Generation switch + { + 1 => 151, + 2 => 251, + 3 => MaxSpeciesGen3, + _ => 0, + }; + return maxSpecies == 0 + ? null + : _engine?.ReadLiveCompanion(Generation, maxSpecies, _romFileName); + } + + /// Pauses or resumes emulation while keeping the loaded game and battery save open. + public void SetPaused(bool paused) => _engine?.SetPaused(paused); + + public void SetSpeedMultiplier(int multiplier) => _engine?.SetSpeedMultiplier(multiplier); + + /// Pauses at a frame boundary and copies a linked battery save back to Android storage. + public async Task FlushBatterySaveAsync() { - var code = _core.GameCode; - if (!IsGen3Code(code)) return null; - return LiveGbaCompanion.Read(_core, MaxSpeciesGen3); + var engine = _engine; + if (engine is not null) + { + engine.SetPaused(true); + if (!engine.FlushSave(_batterySavePath)) + { + Services.AppLog.Warn("embedded", $"Could not flush the battery save for {GameTitle}."); + return false; + } + } + return await SyncLinkedSaveAsync(sessionClosed: false).ConfigureAwait(false); + } + + /// Saves a quick state atomically in PKForge's private data folder. + public bool SaveQuickState() + { + var temporaryPath = QuickStatePath + ".tmp"; + try + { + Directory.CreateDirectory(Path.GetDirectoryName(QuickStatePath)!); + if (_engine?.SaveState(temporaryPath) != true) + { + File.Delete(temporaryPath); + return false; + } + File.Move(temporaryPath, QuickStatePath, overwrite: true); + return true; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException) + { + Services.AppLog.Warn("embedded", $"Could not save a quick state for {GameTitle}: {error.Message}"); + try { File.Delete(temporaryPath); } catch (IOException) { } + return false; + } } - private static bool IsGen3Code(string code) => code is "BPRE" or "BPEE" or "BPEI" or "BPED" - or "BPSO" or "BPEO" or "AXVE" or "AXPE" or "AXVI" or "AXPI" or "AXVD" or "AXPD"; + /// Loads the last quick state for this ROM. + public bool LoadQuickState() => HasQuickState && _engine?.LoadState(QuickStatePath) == true; private const int MaxSpeciesGen3 = 386; // PKHeX Legal.MaxSpeciesID_3 - public void Dispose() + public Task CloseAsync() + { + lock (_disposeGate) + return _closeTask ??= CloseCoreAsync(); + } + + private async Task CloseCoreAsync() { - _engine?.Dispose(); + var gameTitle = GameTitle; + var engine = _engine; _engine = null; - _core.Dispose(); + var saveFlushed = true; + try + { + await Task.Run(() => + { + try + { + if (engine is not null) + { + engine.SetPaused(true); + saveFlushed = engine.FlushSave(_batterySavePath); + } + } + finally + { + engine?.Dispose(); + _core.Dispose(); + } + }).ConfigureAwait(false); + } + catch (Exception error) + { + Services.AppLog.Error("embedded", $"Could not stop {gameTitle}", error); + return false; + } + + if (!saveFlushed) + Services.AppLog.Warn("embedded", $"Could not flush the battery save for {gameTitle}."); + if (!saveFlushed) return false; + return await SyncLinkedSaveAsync(sessionClosed: true).ConfigureAwait(false); } + + private async Task SyncLinkedSaveAsync(bool sessionClosed) + { + if (_linkedSaveDocumentId is null || _saveFileAccess is null) + return true; + + await _saveSyncGate.WaitAsync().ConfigureAwait(false); + try + { + var bytes = await File.ReadAllBytesAsync(_batterySavePath).ConfigureAwait(false); + var linkedBytes = (await _saveFileAccess.ReadAsync(_linkedSaveDocumentId).ConfigureAwait(false)).ToArray(); + if (!bytes.AsSpan().SequenceEqual(linkedBytes)) + { + var marker = _linkedSaveSyncMarkerPath is null ? null : ReadSyncMarker(_linkedSaveSyncMarkerPath); + if (marker is null) + return SaveSyncConflict(); + + var localMatchesMarker = ContentHash(bytes).Equals(marker, StringComparison.Ordinal); + var linkedMatchesMarker = ContentHash(linkedBytes).Equals(marker, StringComparison.Ordinal); + if (localMatchesMarker && !linkedMatchesMarker) + { + if (!sessionClosed) return SaveSyncConflict(); + WriteFileAtomically(_batterySavePath, linkedBytes); + if (_linkedSaveSyncMarkerPath is not null) TryWriteSyncMarker(_linkedSaveSyncMarkerPath, linkedBytes); + HasSaveConflict = false; + return true; // The core is closed, so the external update can safely replace its stale copy. + } + if (!localMatchesMarker || !linkedMatchesMarker) + { + if (!linkedMatchesMarker) return SaveSyncConflict(); + } + } + await _saveFileAccess.WriteAtomicallyAsync(_linkedSaveDocumentId, bytes).ConfigureAwait(false); + if (_linkedSaveSyncMarkerPath is not null) TryWriteSyncMarker(_linkedSaveSyncMarkerPath, bytes); + HasSaveConflict = false; + return true; + } + catch (Exception error) + { + Services.AppLog.Error("embedded", $"Could not write the game save back to {_linkedSaveDocumentId}", error); + return false; + } + finally + { + _saveSyncGate.Release(); + } + } + + private bool SaveSyncConflict() + { + HasSaveConflict = true; + Services.AppLog.Warn("embedded", "The linked save changed during play; neither copy was overwritten."); + return false; + } + + public void Dispose() => CloseAsync().GetAwaiter().GetResult(); + + public ValueTask DisposeAsync() => new(CloseAsync()); } diff --git a/src/PKForge.App/Platforms/Android/IEmbeddedGameSession.cs b/src/PKForge.App/Platforms/Android/IEmbeddedGameSession.cs new file mode 100644 index 00000000..aca041fb --- /dev/null +++ b/src/PKForge.App/Platforms/Android/IEmbeddedGameSession.cs @@ -0,0 +1,32 @@ +using PKForge.Domain; +using SkiaSharp; + +namespace PKForge.App.Platforms.Android; + +/// The common controls exposed by the in-app GB/GBC/GBA and DS sessions. +public interface IEmbeddedGameSession : IAsyncDisposable +{ + event Action? FrameProduced; + (int Width, int Height) VideoSize { get; } + string GameTitle { get; } + string GameCode { get; } + int Generation { get; } + string QuickStatePath { get; } + bool HasQuickState { get; } + bool HasSaveConflict { get; } + bool SupportsTouchScreen { get; } + bool SupportsLiveCompanion { get; } + bool IsNintendoDs { get; } + void SetKeys(uint bitmask); + void SetSpeedMultiplier(int multiplier); + void SetTouchScreen(bool down, int x, int y); + void Draw(SKCanvas canvas, SKRect destination); + void DrawMainScreen(SKCanvas canvas, SKRect destination) => Draw(canvas, destination); + void DrawSecondaryScreen(SKCanvas canvas, SKRect destination) { } + LiveCompanionSnapshot? ReadLiveCompanion(); + void SetPaused(bool paused); + Task FlushBatterySaveAsync(); + bool SaveQuickState(); + bool LoadQuickState(); + Task CloseAsync(); +} diff --git a/src/PKForge.App/Platforms/Android/LiveDsSaveReader.cs b/src/PKForge.App/Platforms/Android/LiveDsSaveReader.cs new file mode 100644 index 00000000..d9e7a5ce --- /dev/null +++ b/src/PKForge.App/Platforms/Android/LiveDsSaveReader.cs @@ -0,0 +1,184 @@ +using PKForge.App.Services; +using PKForge.Domain; +using PKHeX.Core; + +namespace PKForge.App.Platforms.Android; + +/// Reads companion data from checksum-valid Generation 4 and 5 battery saves. +internal static class LiveDsSaveReader +{ + private const int MaximumPartySize = 6; + private const int MaximumGen4Species = 493; + private const int MaximumGen5Species = 649; + + public static LiveCompanionSnapshot? Read( + byte[] saveRam, + int expectedGeneration, + string gameTitle, + string gameCode) + { + ArgumentNullException.ThrowIfNull(saveRam); + if (expectedGeneration is not (4 or 5) || saveRam.Length != SaveUtil.SIZE_G4RAW) + return null; + + try + { + if (!SaveUtil.TryGetSaveFile(saveRam.AsMemory(), out var save) + || save is not (SAV4 or SAV5) + || save.Generation != expectedGeneration + || !save.ChecksumsValid + || save.PartyCount is < 0 or > MaximumPartySize) + return null; + + var maxSpecies = expectedGeneration == 4 ? MaximumGen4Species : MaximumGen5Species; + var language = DetectLanguage(save.Language, gameCode); + var party = ReadParty(save, maxSpecies, language); + var bag = ReadBag(save, language); + var caught = 0; + var seen = 0; + for (ushort species = 1; species <= maxSpecies; species++) + { + if (save.GetCaught(species)) caught++; + if (save.GetSeen(species)) seen++; + } + + return new LiveCompanionSnapshot( + gameTitle, + gameCode, + caught, + seen, + maxSpecies, + party.Count, + Math.Max(0, save.PlayedHours), + Math.Clamp(save.PlayedMinutes, 0, 59), + party, + bag); + } + catch (Exception error) when (error is ArgumentException or InvalidOperationException + or IndexOutOfRangeException or OverflowException or NotSupportedException or NullReferenceException) + { + // The live image may have been captured during a game save or contain damaged blocks. + return null; + } + } + + private static IReadOnlyList ReadParty( + SaveFile save, + int maxSpecies, + LanguageID saveLanguage) + { + var party = new List(save.PartyCount); + for (var index = 0; index < save.PartyCount; index++) + { + var pokemon = save.GetPartySlotAtIndex(index); + if (!pokemon.ChecksumValid + || pokemon.Species > maxSpecies + || (pokemon.Species == 0 && !pokemon.IsEgg)) + continue; + + var language = IsSupportedLanguage(pokemon.Language) + ? (LanguageID)pokemon.Language + : saveLanguage; + var speciesName = pokemon.IsEgg + ? AppStrings.CompanionEgg + : SpeciesName.GetSpeciesNameGeneration(pokemon.Species, (int)language, save.Generation); + var nickname = pokemon.IsEgg || string.IsNullOrWhiteSpace(pokemon.Nickname) + ? speciesName + : pokemon.Nickname; + + party.Add(new GameCompanionPartyMember( + pokemon.Species, + speciesName, + nickname, + pokemon.IsEgg ? 0 : pokemon.CurrentLevel, + Math.Max(0, pokemon.Stat_HPCurrent), + Math.Max(0, pokemon.Stat_HPMax), + StatusName(pokemon.Status_Condition), + pokemon.IsEgg, + pokemon.Form, + pokemon.IsShiny)); + } + + return party; + } + + private static IReadOnlyList ReadBag(SaveFile save, LanguageID language) + { + var itemNames = GameInfo.GetStrings(LanguageCode(language)).GetItemStrings(save.Context, save.Version); + var pockets = new List(); + foreach (var pouch in save.Inventory.Pouches) + { + var items = pouch.Items + .Where(item => item.Count > 0 && item.Index > 0 && item.Index < itemNames.Length) + .Select(item => new GameCompanionBagItem(item.Index, itemNames[item.Index], item.Count)) + .Where(item => !string.IsNullOrWhiteSpace(item.Name)) + .ToArray(); + if (items.Length == 0) continue; + + pockets.Add(new GameCompanionBagPocket( + pouch.Type.ToString(), + PocketName(pouch.Type), + items)); + } + + return pockets; + } + + private static LanguageID DetectLanguage(int saveLanguage, string gameCode) + { + if (IsSupportedLanguage(saveLanguage)) return (LanguageID)saveLanguage; + if (gameCode.Length > 0) + { + var codeLanguage = char.ToUpperInvariant(gameCode[^1]) switch + { + 'J' => LanguageID.Japanese, + 'E' => LanguageID.English, + 'F' => LanguageID.French, + 'D' => LanguageID.German, + 'I' => LanguageID.Italian, + 'S' => LanguageID.Spanish, + 'K' => LanguageID.Korean, + _ => (LanguageID)0, + }; + if ((int)codeLanguage != 0) return codeLanguage; + } + + return LanguageID.English; + } + + private static bool IsSupportedLanguage(int language) => language is 1 or 2 or 3 or 4 or 5 or 7 or 8; + + private static string LanguageCode(LanguageID language) => language switch + { + LanguageID.Japanese => "ja", + LanguageID.French => "fr", + LanguageID.German => "de", + LanguageID.Italian => "it", + LanguageID.Spanish => "es", + LanguageID.Korean => "ko", + _ => "en", + }; + + private static string PocketName(InventoryType type) => type switch + { + InventoryType.Items => AppStrings.CompanionPocketItems, + InventoryType.KeyItems => AppStrings.CompanionPocketKeyItems, + InventoryType.Medicine => AppStrings.CompanionPocketMedicine, + InventoryType.Balls => AppStrings.CompanionPocketBalls, + InventoryType.TMHMs => AppStrings.CompanionPocketMachines, + InventoryType.Berries => AppStrings.CompanionPocketBerries, + InventoryType.BattleItems => AppStrings.CompanionPocketBattleItems, + InventoryType.MailItems => AppStrings.CompanionPocketMail, + _ => type.ToString().ToUpperInvariant(), + }; + + private static string StatusName(int status) + { + if ((status & 0x80) != 0) return "TOX"; + if ((status & 0x40) != 0) return "PAR"; + if ((status & 0x20) != 0) return AppStrings.Fr ? "GEL" : "FRZ"; + if ((status & 0x10) != 0) return AppStrings.Fr ? "BRÛ" : "BRN"; + if ((status & 0x08) != 0) return "PSN"; + return (status & 0x07) != 0 ? "SLP" : string.Empty; + } +} diff --git a/src/PKForge.App/Platforms/Android/LiveGen12SaveReader.cs b/src/PKForge.App/Platforms/Android/LiveGen12SaveReader.cs new file mode 100644 index 00000000..3b7f69e2 --- /dev/null +++ b/src/PKForge.App/Platforms/Android/LiveGen12SaveReader.cs @@ -0,0 +1,177 @@ +using PKForge.App.Services; +using PKForge.Domain; +using PKHeX.Core; + +namespace PKForge.App.Platforms.Android; + +/// Reads read-only companion data from validated GB/GBC battery saves. +internal static class LiveGen12SaveReader +{ + private const int MaximumPartySize = 6; + + public static LiveCompanionSnapshot? Read( + byte[] saveRam, + int generation, + string gameTitle, + string gameCode, + string romFileName) + { + ArgumentNullException.ThrowIfNull(saveRam); + if (generation is not (1 or 2) || !HasSaveData(saveRam)) return null; + if (generation == 1 && saveRam.Length != SaveUtil.SIZE_G1RAW) return null; + if (generation == 2 && saveRam.Length is not (SaveUtil.SIZE_G2RAW_U or SaveUtil.SIZE_G2RAW_J)) return null; + + try + { + var language = DetectLanguage($"{gameTitle} {gameCode} {romFileName}"); + var version = DetectVersion(generation, $"{gameTitle} {romFileName}"); + SaveFile save = generation == 1 + ? new SAV1(saveRam, language, version) + : new SAV2(saveRam, language, version); + if (!save.ChecksumsValid || !save.IsVersionValid() || save.PartyCount is < 0 or > MaximumPartySize) + return null; + + var maxSpecies = generation == 1 ? 151 : 251; + var dexCaught = 0; + var dexSeen = 0; + for (ushort species = 1; species <= maxSpecies; species++) + { + if (save.GetCaught(species)) dexCaught++; + if (save.GetSeen(species)) dexSeen++; + } + + var languageCode = LanguageCode(language); + var party = ReadParty(save, maxSpecies, language); + var bag = ReadBag(save, languageCode); + return new LiveCompanionSnapshot( + gameTitle, gameCode, dexCaught, dexSeen, maxSpecies, + party.Count, Math.Max(0, save.PlayedHours), Math.Clamp(save.PlayedMinutes, 0, 59), + party, bag); + } + catch (Exception error) when (error is ArgumentException or IndexOutOfRangeException or OverflowException) + { + // A partially written or malformed battery image must never be shown as game data. + return null; + } + } + + private static IReadOnlyList ReadParty(SaveFile save, int maxSpecies, LanguageID language) + { + var party = new List(save.PartyCount); + for (var index = 0; index < save.PartyCount; index++) + { + var pokemon = save.GetPartySlotAtIndex(index); + if (!pokemon.ChecksumValid || (pokemon.Species == 0 && !pokemon.IsEgg) || pokemon.Species > maxSpecies) + continue; + + var speciesName = pokemon.IsEgg + ? AppStrings.CompanionEgg + : SpeciesName.GetSpeciesNameGeneration(pokemon.Species, (int)language, save.Generation); + var nickname = pokemon.IsEgg || string.IsNullOrWhiteSpace(pokemon.Nickname) + ? speciesName + : pokemon.Nickname; + party.Add(new GameCompanionPartyMember( + pokemon.Species, + speciesName, + nickname, + pokemon.IsEgg ? 0 : pokemon.CurrentLevel, + Math.Max(0, pokemon.Stat_HPCurrent), + Math.Max(0, pokemon.Stat_HPMax), + StatusName(pokemon.Status_Condition), + pokemon.IsEgg, + pokemon.Form, + pokemon.IsShiny)); + } + + return party; + } + + private static IReadOnlyList ReadBag(SaveFile save, string languageCode) + { + var itemNames = GameInfo.GetStrings(languageCode).GetItemStrings(save.Context, save.Version); + var pockets = new List(); + foreach (var pouch in save.Inventory.Pouches) + { + var items = pouch.Items + .Where(item => item.Count > 0 && item.Index > 0 && item.Index < itemNames.Length) + .Select(item => new GameCompanionBagItem(item.Index, itemNames[item.Index], item.Count)) + .Where(item => !string.IsNullOrWhiteSpace(item.Name)) + .ToArray(); + if (items.Length == 0) continue; + + pockets.Add(new GameCompanionBagPocket( + pouch.Type.ToString(), + PocketName(pouch.Type), + items)); + } + + return pockets; + } + + private static GameVersion DetectVersion(int generation, string identity) + { + if (generation == 1) + return identity.Contains("yellow", StringComparison.OrdinalIgnoreCase) + ? GameVersion.YW + : identity.Contains("red", StringComparison.OrdinalIgnoreCase) + || identity.Contains("blue", StringComparison.OrdinalIgnoreCase) + ? GameVersion.RB + : GameVersion.RBY; + + return identity.Contains("crystal", StringComparison.OrdinalIgnoreCase) + ? GameVersion.C + : GameVersion.GS; + } + + private static LanguageID DetectLanguage(string identity) + { + if (ContainsAny(identity, "japan", "japanese", "jpn", "japon")) return LanguageID.Japanese; + if (ContainsAny(identity, "korea", "korean", "kor")) return LanguageID.Korean; + if (ContainsAny(identity, "french", "france", "(fr)", "_fr", "-fr")) return LanguageID.French; + if (ContainsAny(identity, "german", "(de)", "_de", "-de")) return LanguageID.German; + if (ContainsAny(identity, "italian", "(it)", "_it", "-it")) return LanguageID.Italian; + if (ContainsAny(identity, "spanish", "(es)", "_es", "-es")) return LanguageID.Spanish; + return LanguageID.English; + } + + private static bool ContainsAny(string value, params string[] terms) => + terms.Any(term => value.Contains(term, StringComparison.OrdinalIgnoreCase)); + + private static string LanguageCode(LanguageID language) => language switch + { + LanguageID.French => "fr", + LanguageID.German => "de", + LanguageID.Italian => "it", + LanguageID.Spanish => "es", + LanguageID.Japanese => "ja", + LanguageID.Korean => "ko", + _ => "en", + }; + + private static bool HasSaveData(ReadOnlySpan saveRam) + { + foreach (var value in saveRam) + if (value is not (0 or 0xFF)) return true; + return false; + } + + private static string PocketName(InventoryType type) => type switch + { + InventoryType.Items => AppStrings.CompanionPocketItems, + InventoryType.KeyItems => AppStrings.CompanionPocketKeyItems, + InventoryType.Balls => AppStrings.CompanionPocketBalls, + InventoryType.TMHMs => AppStrings.CompanionPocketMachines, + InventoryType.Berries => AppStrings.CompanionPocketBerries, + _ => type.ToString().ToUpperInvariant(), + }; + + private static string StatusName(int status) + { + if ((status & 0x80) != 0) return "TOX"; + if ((status & 0x40) != 0) return "PAR"; + if ((status & 0x20) != 0) return AppStrings.Fr ? "GEL" : "FRZ"; + if ((status & 0x10) != 0) return AppStrings.Fr ? "BRÛ" : "BRN"; + if ((status & 0x08) != 0) return "PSN"; + return (status & 0x07) != 0 ? "SLP" : string.Empty; + } +} diff --git a/src/PKForge.App/Platforms/Android/LiveGen3SaveReader.cs b/src/PKForge.App/Platforms/Android/LiveGen3SaveReader.cs new file mode 100644 index 00000000..50850d81 --- /dev/null +++ b/src/PKForge.App/Platforms/Android/LiveGen3SaveReader.cs @@ -0,0 +1,163 @@ +using PKForge.App.Services; +using PKForge.Domain; +using PKHeX.Core; + +namespace PKForge.App.Platforms.Android; + +/// Reads read-only companion views from a validated Gen 3 battery save. +internal static class LiveGen3SaveReader +{ + private const int MaximumPartySize = 6; + private const int MaximumSpeciesId = 386; + + public static LiveGen3SaveData? Read(byte[] saveRam, string gameCode) + { + ArgumentNullException.ThrowIfNull(saveRam); + var save = OpenValidatedSave(saveRam, gameCode); + if (save is null) + return null; + + return new LiveGen3SaveData(ReadParty(save), ReadBag(save, gameCode)); + } + + private static SAV3? OpenValidatedSave(byte[] saveRam, string gameCode) + { + if (!SAV3.IsAllMainSectorsPresent(saveRam, 0, out _) + && !SAV3.IsAllMainSectorsPresent(saveRam, 1, out _)) + return null; + + var save = CreateSave(saveRam, gameCode); + return save is { ChecksumsValid: true } ? save : null; + } + + private static IReadOnlyList ReadParty(SAV3 save) + { + if (save.PartyCount is < 0 or > MaximumPartySize) + return []; + + var party = new List(save.PartyCount); + for (var index = 0; index < save.PartyCount; index++) + { + try + { + var pokemon = save.GetPartySlotAtIndex(index); + if (!pokemon.ChecksumValid || pokemon.Species > MaximumSpeciesId + || (pokemon.Species == 0 && !pokemon.IsEgg)) + continue; + + var language = pokemon.Language is >= 1 and <= 5 or 7 + ? pokemon.Language + : (int)LanguageID.English; + var speciesName = pokemon.IsEgg + ? AppStrings.CompanionEgg + : SpeciesName.GetSpeciesNameGeneration(pokemon.Species, language, generation: 3); + var nickname = pokemon.IsEgg || language != pokemon.Language + ? speciesName + : string.IsNullOrWhiteSpace(pokemon.Nickname) ? speciesName : pokemon.Nickname; + party.Add(new GameCompanionPartyMember( + pokemon.Species, + speciesName, + nickname, + pokemon.IsEgg ? 0 : pokemon.CurrentLevel, + Math.Max(0, pokemon.Stat_HPCurrent), + Math.Max(0, pokemon.Stat_HPMax), + StatusName(pokemon.Status_Condition), + pokemon.IsEgg, + pokemon.Form, + pokemon.IsShiny)); + } + catch (ArgumentOutOfRangeException) + { + // A save sector can be changing during the game's save operation. + return []; + } + } + + return party; + } + + private static IReadOnlyList ReadBag(SAV3 save, string gameCode) + { + var strings = GameInfo.GetStrings(GetLanguageCode(gameCode)); + var itemNames = strings.GetItemStrings(EntityContext.Gen3, save.Version); + var pockets = new List(); + + foreach (var pouch in save.Inventory.Pouches) + { + // PC storage is separate from the bag the player carries. + if (pouch.Type == InventoryType.PCItems) + continue; + + var items = pouch.Items + .Where(item => item.Count > 0 && item.Index > 0 && item.Index < itemNames.Length) + .Select(item => new GameCompanionBagItem(item.Index, itemNames[item.Index], item.Count)) + .Where(item => !string.IsNullOrWhiteSpace(item.Name)) + .ToArray(); + if (items.Length == 0) + continue; + + pockets.Add(new GameCompanionBagPocket( + pouch.Type.ToString(), + PocketName(pouch.Type), + items)); + } + + return pockets; + } + + private static SAV3? CreateSave(byte[] saveRam, string gameCode) + { + if (gameCode.StartsWith("BPE", StringComparison.Ordinal)) + return new SAV3E(saveRam); + + if (gameCode.StartsWith("BPR", StringComparison.Ordinal)) + return new SAV3FRLG(saveRam) { Version = GameVersion.FR }; + + if (gameCode.StartsWith("BPG", StringComparison.Ordinal)) + return new SAV3FRLG(saveRam) { Version = GameVersion.LG }; + + if (gameCode.StartsWith("AXV", StringComparison.Ordinal)) + return new SAV3RS(saveRam) { Version = GameVersion.R }; + + if (gameCode.StartsWith("AXP", StringComparison.Ordinal)) + return new SAV3RS(saveRam) { Version = GameVersion.S }; + + return null; + } + + private static string GetLanguageCode(string gameCode) => gameCode.Length >= 4 + ? char.ToUpperInvariant(gameCode[3]) switch + { + 'F' => "fr", + 'I' => "it", + 'D' => "de", + 'S' => "es", + 'J' => "ja", + _ => "en", + } + : "en"; + + private static string PocketName(InventoryType type) => type switch + { + InventoryType.Items => AppStrings.CompanionPocketItems, + InventoryType.KeyItems => AppStrings.CompanionPocketKeyItems, + InventoryType.Balls => AppStrings.CompanionPocketBalls, + InventoryType.TMHMs => AppStrings.CompanionPocketMachines, + InventoryType.Berries => AppStrings.CompanionPocketBerries, + _ => type.ToString().ToUpperInvariant(), + }; + + private static string StatusName(int status) + { + if ((status & 0x80) != 0) return "TOX"; + if ((status & 0x40) != 0) return "PAR"; + if ((status & 0x20) != 0) return AppStrings.Fr ? "GEL" : "FRZ"; + if ((status & 0x10) != 0) return AppStrings.Fr ? "BRÛ" : "BRN"; + if ((status & 0x08) != 0) return "PSN"; + return (status & 0x07) != 0 ? "SLP" : string.Empty; + } +} + +internal sealed record LiveGen3SaveData( + IReadOnlyList Party, + IReadOnlyList Bag); diff --git a/src/PKForge.App/Platforms/Android/MainActivity.cs b/src/PKForge.App/Platforms/Android/MainActivity.cs index 244d2eca..88271623 100644 --- a/src/PKForge.App/Platforms/Android/MainActivity.cs +++ b/src/PKForge.App/Platforms/Android/MainActivity.cs @@ -4,6 +4,7 @@ using Android.OS; using Android.Content; using Android.Views; +using PKForge.App.Platforms.Android; using PKForge.Domain; [assembly: UsesPermission(Android.Manifest.Permission.Vibrate)] @@ -89,9 +90,7 @@ protected override void OnPause() { // A Presentation owns a separate window, so Android does not reliably hide it // when the launcher backgrounds the main activity (notably on the AYN Thor). - StopHatRepeat(); - StopKeyRepeat(); - _hatDirection = null; + ReleaseNavigationInputs(); SecondaryDisplayHost()?.SuspendForActivityPause(); base.OnPause(); } @@ -112,9 +111,7 @@ protected override void OnResume() public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig) { base.OnConfigurationChanged(newConfig); - StopHatRepeat(); - StopKeyRepeat(); - _hatDirection = null; + ReleaseNavigationInputs(); } protected override void OnNewIntent(Intent? intent) @@ -257,8 +254,11 @@ public override bool OnGenericMotionEvent(MotionEvent? e) var direction = HatDirection(e); if (direction != _hatDirection) { + var previousDirection = _hatDirection; StopHatRepeat(); _hatDirection = direction; + if (previousDirection is { } released) + DispatchButtonRelease(released); if (direction is { } button) { DispatchHat(button, haptic: true); @@ -289,6 +289,26 @@ private void StopHatRepeat() _hatRepeatRunnable = null; } + /// + /// Axis hats report both deflection and return to neutral. The routed game input is + /// a held-button bitmask, so every hat transition must include the matching release. + /// + private static void DispatchButtonRelease(Services.PadButton button) => + IPlatformApplication.Current?.Services.GetService()?.DispatchRelease(button); + + /// Clear held navigation buttons when focus or the connected controller changes. + private void ReleaseNavigationInputs() + { + var hatDirection = _hatDirection; + var keyDirection = _keyRepeatButton; + StopHatRepeat(); + StopKeyRepeat(); + _hatDirection = null; + + if (hatDirection is { } hat) DispatchButtonRelease(hat); + if (keyDirection is { } key && key != hatDirection) DispatchButtonRelease(key); + } + private static void DispatchHat(Services.PadButton button, bool haptic) { var router = IPlatformApplication.Current?.Services.GetService(); @@ -361,14 +381,16 @@ private static void Haptic() /// The AYN Thor does NOT tag its bottom screen as a presentation-category display, /// so detection falls back to GetDisplays()[1] when the category query is empty. /// -public sealed class AndroidSecondaryDisplayHost(IServiceProvider services) : ISecondaryDisplayHost +public sealed class AndroidSecondaryDisplayHost(IServiceProvider services) : ISecondaryDisplayHost, Services.IDualScreenGameDisplayHost { private readonly object _showGate = new(); private PagePresentation? _presentation; private ContentPage? _page; + private IEmbeddedGameSession? _activeDsSession; private bool _resumeAfterActivityPause; public bool IsAvailable => Services.SecondScreenMode.Allowed && ResolveDisplay() is not null; + public event Action? DisplayContentChanged; /// True on a dual-screen handheld when PKForge runs on a panel other than the main one. internal static bool LaunchedOnLowerScreen(Activity activity) => @@ -379,33 +401,95 @@ internal static bool LaunchedOnLowerScreen(Activity activity) => public ValueTask ShowAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var display = ResolveDisplay() ?? throw new InvalidOperationException("No secondary display is available."); - var activity = Platform.CurrentActivity ?? throw new InvalidOperationException("No foreground Android activity is available."); + ShowCurrentPage(allowMissingDisplay: _activeDsSession is not null); + return ValueTask.CompletedTask; + } + + public Task ShowNintendoDsBottomScreenAsync( + IEmbeddedGameSession session, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(session); + cancellationToken.ThrowIfCancellationRequested(); + if (!session.IsNintendoDs) return Task.FromResult(false); + + lock (_showGate) _activeDsSession = session; + var shown = ShowCurrentPage(allowMissingDisplay: true); + return Task.FromResult(shown && IsShowingNintendoDsBottomScreen(session)); + } + public bool IsShowingNintendoDsBottomScreen(IEmbeddedGameSession session) + { + lock (_showGate) + return ReferenceEquals(_activeDsSession, session) + && _page is Views.NintendoDsSecondaryScreenPage gamePage + && ReferenceEquals(gamePage.Session, session) + && _presentation is { IsShowing: true }; + } + + public ValueTask RestoreDefaultScreenAsync( + IEmbeddedGameSession session, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(session); + cancellationToken.ThrowIfCancellationRequested(); lock (_showGate) { - if (_presentation is { IsShowing: true }) + if (!ReferenceEquals(_activeDsSession, session)) return ValueTask.CompletedTask; + _activeDsSession = null; + if (_page is Views.NintendoDsSecondaryScreenPage) + DismissPresentationLocked(); + } + + DisplayContentChanged?.Invoke(); + if (IsAvailable) return ShowAsync(cancellationToken); + return ValueTask.CompletedTask; + } + + /// Creates or replaces the presentation for its current owner. DS output + /// deliberately ignores the app's companion visibility preference: it is the console's + /// second framebuffer, not optional companion content. + private bool ShowCurrentPage(bool allowMissingDisplay) + { + var display = ResolveDisplay(); + if (display is null) + { + lock (_showGate) { - if (_page is Views.PokeparkJournalPage journalPage) - _ = journalPage.RefreshAsync(cancellationToken); - return ValueTask.CompletedTask; + if (_activeDsSession is not null && _presentation is not null) + DismissPresentationLocked(); + } + DisplayContentChanged?.Invoke(); + if (!allowMissingDisplay) throw new InvalidOperationException("No secondary display is available."); + return false; + } + + var activity = Platform.CurrentActivity + ?? throw new InvalidOperationException("No foreground Android activity is available."); + var shown = false; + lock (_showGate) + { + var gameSession = _activeDsSession; + var isCurrentPage = gameSession is null + ? _page is not Views.NintendoDsSecondaryScreenPage + : _page is Views.NintendoDsSecondaryScreenPage gamePage + && ReferenceEquals(gamePage.Session, gameSession); + if (_presentation is { IsShowing: true } && isCurrentPage) + { + if (gameSession is null && _page is Views.PokeparkJournalPage journalPage) + _ = journalPage.RefreshAsync(); + return true; } // A dismissed presentation (SAF picker, sleep) cannot be reshown; - // rebuild the page and presentation as one serialized operation. - _presentation?.Dismiss(); - if (_page is Views.SecondScreenBoxPage boxPage) - boxPage.Cleanup(); - else if (_page is Views.PokeparkJournalPage journalPage) - journalPage.Cleanup(); - _presentation = null; - _page = null; - if (!Services.SecondScreenMode.Allowed) return ValueTask.CompletedTask; - - // Built and shown as locals: a display Android refuses (a virtual or removed one - // raises BadToken/InvalidDisplay) leaves nothing half-built, and PKForge carries - // on with one screen instead of crashing. - var page = services.GetRequiredService(); + // rebuild its page and presentation as one serialized operation. + DismissPresentationLocked(); + if (gameSession is null && !Services.SecondScreenMode.Allowed) + return false; + + ContentPage page = gameSession is null + ? services.GetRequiredService() + : new Views.NintendoDsSecondaryScreenPage(gameSession); var presentation = new PagePresentation(activity, display, page, services); try { @@ -413,15 +497,23 @@ public ValueTask ShowAsync(CancellationToken cancellationToken = default) } catch (Exception error) when (error is WindowManagerBadTokenException or WindowManagerInvalidDisplayException or Java.Lang.Exception) { - page.Cleanup(); - Services.SecondScreenMode.DisableForSession($"display {display.DisplayId} ({display.Name}) refused the lower screen", error); - return ValueTask.CompletedTask; + CleanupPage(page); + if (gameSession is null) + Services.SecondScreenMode.DisableForSession($"display {display.DisplayId} ({display.Name}) refused the lower screen", error); + else + Services.AppLog.Warn("second", $"DS bottom screen could not be shown on display {display.DisplayId} ({display.Name}); keeping both screens on the main display: {error.Message}"); + DisplayContentChanged?.Invoke(); + return false; } _page = page; _presentation = presentation; - Services.AppLog.Info("second", $"Lower screen on display {display.DisplayId} ({display.Name}, flags 0x{(int)display.Flags:X})"); + shown = true; + Services.AppLog.Info("second", gameSession is null + ? $"Companion screen on display {display.DisplayId} ({display.Name}, flags 0x{(int)display.Flags:X})" + : $"Nintendo DS bottom screen on display {display.DisplayId} ({display.Name}, flags 0x{(int)display.Flags:X})"); } - return ValueTask.CompletedTask; + if (shown) DisplayContentChanged?.Invoke(); + return shown; } public ValueTask ShowPokeparkJournalAsync(CancellationToken cancellationToken = default) @@ -458,7 +550,12 @@ public ValueTask RefreshPokeparkJournalAsync(CancellationToken cancellationToken public ValueTask DismissAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - Dismiss(); + lock (_showGate) + { + _activeDsSession = null; + DismissPresentationLocked(); + } + DisplayContentChanged?.Invoke(); _resumeAfterActivityPause = false; StopWaitingForDisplay(); return ValueTask.CompletedTask; @@ -519,14 +616,33 @@ public void OnDisplayRemoved(int displayId) { } private void Dismiss() { lock (_showGate) + DismissPresentationLocked(); + DisplayContentChanged?.Invoke(); + } + + /// Called while holding _showGate. The active DS session intentionally + /// survives activity pause so Android can recreate its bottom-screen surface on wake. + private void DismissPresentationLocked() + { + _presentation?.Dismiss(); + _presentation = null; + if (_page is not null) CleanupPage(_page); + _page = null; + } + + private static void CleanupPage(ContentPage page) + { + switch (page) { - _presentation?.Dismiss(); - _presentation = null; - if (_page is Views.SecondScreenBoxPage boxPage) + case Views.SecondScreenBoxPage boxPage: boxPage.Cleanup(); - else if (_page is Views.PokeparkJournalPage journalPage) + break; + case Views.PokeparkJournalPage journalPage: journalPage.Cleanup(); - _page = null; + break; + case Views.NintendoDsSecondaryScreenPage gamePage: + gamePage.Cleanup(); + break; } } diff --git a/src/PKForge.App/Platforms/Android/MelonDsCore.cs b/src/PKForge.App/Platforms/Android/MelonDsCore.cs new file mode 100644 index 00000000..e3cca98a --- /dev/null +++ b/src/PKForge.App/Platforms/Android/MelonDsCore.cs @@ -0,0 +1,130 @@ +using System.Text; +using System.Runtime.InteropServices; + +namespace PKForge.App.Platforms.Android; + +/// One melonDS cart instance. The engine serializes all native access. +internal sealed class MelonDsCore : IDisposable +{ + private nint _core; + + public bool IsRunning => _core != nint.Zero && MelonDsNative.IsRunning(_core) != 0; + public string? RomPath { get; private set; } + public string? LoadError { get; private set; } + public string GameTitle { get; private set; } = string.Empty; + public string GameCode { get; private set; } = string.Empty; + public (int Width, int Height) VideoSize => IsRunning ? (256, 384) : (0, 0); + + public bool Load(string romPath, string savePath) + { + LoadError = null; + if (_core != nint.Zero) + { + LoadError = "Une ROM est déjà chargée dans melonDS."; + return false; + } + + _core = MelonDsNative.Create(romPath, savePath); + if (_core == nint.Zero) + { + LoadError = MarshalError(); + return false; + } + + try + { + Span title = stackalloc byte[13]; + Span code = stackalloc byte[5]; + MelonDsNative.GameTitle(_core, title, (nuint)title.Length); + MelonDsNative.GameCode(_core, code, (nuint)code.Length); + GameTitle = DecodeHeader(title); + GameCode = DecodeHeader(code); + if (!IsRunning) + { + LoadError = "melonDS a chargé la ROM, mais la console ne tourne pas."; + Dispose(); + return false; + } + RomPath = romPath; + return true; + } + catch + { + Dispose(); + throw; + } + } + + private static string DecodeHeader(ReadOnlySpan bytes) + { + var zero = bytes.IndexOf((byte)0); + return Encoding.ASCII.GetString(zero < 0 ? bytes : bytes[..zero]).Trim(); + } + + private static string MarshalError() + { + var error = Marshal.PtrToStringUTF8(MelonDsNative.LastError()); + return string.IsNullOrWhiteSpace(error) ? "melonDS n'a pas pu démarrer cette ROM DS." : error; + } + + public void RunFrame(uint keys, bool touchDown, int touchX, int touchY) + { + ThrowWhenNotRunning(); + MelonDsNative.RunFrame(_core, keys, touchDown ? 1 : 0, touchX, touchY); + } + + public void CopyFrame(Span buffer) + { + ThrowWhenNotRunning(); + const int pixelCount = 256 * 384; + if (buffer.Length < pixelCount) + throw new ArgumentException($"The buffer holds {buffer.Length} pixels; the DS frame needs {pixelCount}."); + if (MelonDsNative.CopyFrame(_core, buffer, (nuint)buffer.Length) == 0) + throw new InvalidOperationException("melonDS could not copy the current dual-screen frame."); + } + + public int ReadAudio(Span destination, int frameCapacity) + { + if (!IsRunning || frameCapacity <= 0) return 0; + return MelonDsNative.ReadAudio(_core, destination, frameCapacity); + } + + public bool FlushSave() => !IsRunning || MelonDsNative.FlushSave(_core) != 0; + + public int BatterySaveSize + { + get + { + ThrowWhenNotRunning(); + const nuint maximumSaveSize = 16 * 1024 * 1024; + var size = MelonDsNative.SaveSize(_core); + return size == 0 || size > maximumSaveSize ? 0 : (int)size; + } + } + + public bool CopyBatterySave(Span destination) + { + ThrowWhenNotRunning(); + var size = BatterySaveSize; + if (size == 0 || destination.Length < size) return false; + return MelonDsNative.CopySave(_core, destination, (nuint)size) == (nuint)size; + } + + public bool SaveState(string path) => IsRunning && MelonDsNative.SaveState(_core, path) != 0; + public bool LoadState(string path) => IsRunning && MelonDsNative.LoadState(_core, path) != 0; + + private void ThrowWhenNotRunning() + { + if (!IsRunning) throw new InvalidOperationException("No Nintendo DS ROM is loaded."); + } + + public void Dispose() + { + if (_core == nint.Zero) return; + var core = _core; + _core = nint.Zero; + RomPath = null; + try { MelonDsNative.Destroy(core); } + catch (DllNotFoundException) { } + } +} diff --git a/src/PKForge.App/Platforms/Android/MelonDsEngine.cs b/src/PKForge.App/Platforms/Android/MelonDsEngine.cs new file mode 100644 index 00000000..8e6b11e0 --- /dev/null +++ b/src/PKForge.App/Platforms/Android/MelonDsEngine.cs @@ -0,0 +1,343 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using Android.Media; +using PKForge.Domain; +using SkiaSharp; + +namespace PKForge.App.Platforms.Android; + +/// Drives one melonDS instance, audio stream and dual-screen frame. +internal sealed class MelonDsEngine : IDisposable +{ + private const double FramesPerSecond = 59.8261; + private const int AudioRate = 32768; + private const int AudioFramesPerDrain = 1024; + private const int SaveFlushIntervalFrames = 300; + + private readonly MelonDsCore _core; + private readonly Thread _thread; + private readonly CancellationTokenSource _cancel = new(); + private readonly ManualResetEventSlim _resume = new(initialState: true); + private readonly object _coreGate = new(); + private readonly object _lifecycleGate = new(); + private readonly object _audioGate = new(); + private readonly object _frameGate = new(); + private readonly object _inputGate = new(); + private readonly short[] _audioScratch = new short[AudioFramesPerDrain * 2]; + private readonly uint[] _frameScratch = new uint[256 * 384]; + private readonly Java.Nio.ByteBuffer _audioBuffer; + private readonly AudioTrack? _track; + private SKBitmap? _frame; + private SKImage? _frameImage; + private uint _keysPending; + private int _speedMultiplier = 1; + private byte[]? _companionSaveBuffer; + private byte[]? _lastCompanionSave; + private LiveCompanionSnapshot? _lastCompanionSnapshot; + private bool _touchDown; + private int _touchX; + private int _touchY; + private volatile bool _audioEnabled = true; + private volatile bool _disposed; + + public event Action? FrameProduced; + public bool IsRunning => _thread.IsAlive; + + public MelonDsEngine(MelonDsCore core) + { + _core = core ?? throw new ArgumentNullException(nameof(core)); + if (!core.IsRunning) throw new ArgumentException("The DS core has no running ROM.", nameof(core)); + _thread = new Thread(RunLoop) { IsBackground = true, Name = "PKForge melonDS" }; + _audioBuffer = Java.Nio.ByteBuffer.AllocateDirect(_audioScratch.Length * sizeof(short)); + _audioBuffer.Order(Java.Nio.ByteOrder.LittleEndian!); + try + { +#pragma warning disable CA1416 // AudioTrack.Builder is available on Android 23+ devices. + var attributesBuilder = new AudioAttributes.Builder(); + attributesBuilder.SetUsage(AudioUsageKind.Game); + attributesBuilder.SetContentType(AudioContentType.Music); + var attributes = attributesBuilder.Build()!; + + var formatBuilder = new AudioFormat.Builder(); + formatBuilder.SetEncoding(Encoding.Pcm16bit); + formatBuilder.SetSampleRate(AudioRate); + formatBuilder.SetChannelMask(ChannelOut.Stereo); + var format = formatBuilder.Build()!; + + var trackBuilder = new AudioTrack.Builder(); + trackBuilder.SetAudioAttributes(attributes); + trackBuilder.SetAudioFormat(format); + trackBuilder.SetBufferSizeInBytes(3840 * 4); + trackBuilder.SetTransferMode(AudioTrackMode.Stream); + _track = trackBuilder.Build(); +#pragma warning restore CA1416 + _track.Play(); + } + catch (Exception error) + { + try { _track?.Stop(); } catch (Exception) { } + try { _track?.Release(); } catch (Exception) { } + _track = null; + Services.AppLog.Warn("embedded", $"DS audio is unavailable; the game will run silently: {error.Message}"); + } + } + + public void Start() => _thread.Start(); + + public void SetKeys(uint bitmask) + { + lock (_inputGate) _keysPending = bitmask & 0xFFFu; + } + + public void SetSpeedMultiplier(int multiplier) + { + if (multiplier is < 1 or > 4) + throw new ArgumentOutOfRangeException(nameof(multiplier), "The emulation speed must be between ×1 and ×4."); + + var previous = Interlocked.Exchange(ref _speedMultiplier, multiplier); + if (previous == multiplier || _track is null) return; + + lock (_audioGate) + { + try + { + if (multiplier > 1) + { + _track.Pause(); + _track.Flush(); + } + else if (_resume.IsSet) + { + _track.Play(); + } + } + catch (Exception error) + { + Services.AppLog.Warn("embedded", $"Could not update DS audio for emulation speed ×{multiplier}: {error.Message}"); + } + } + } + + public LiveCompanionSnapshot? ReadLiveCompanion(int generation) + { + lock (_coreGate) + { + if (_disposed || !_core.IsRunning) return null; + var saveSize = _core.BatterySaveSize; + if (saveSize == 0) return null; + if (_companionSaveBuffer is null || _companionSaveBuffer.Length != saveSize) + _companionSaveBuffer = new byte[saveSize]; + if (!_core.CopyBatterySave(_companionSaveBuffer)) return null; + if (_lastCompanionSave is not null && _companionSaveBuffer.AsSpan().SequenceEqual(_lastCompanionSave)) + return _lastCompanionSnapshot; + + _lastCompanionSave = _companionSaveBuffer.ToArray(); + _lastCompanionSnapshot = LiveDsSaveReader.Read(_companionSaveBuffer, generation, _core.GameTitle, _core.GameCode); + return _lastCompanionSnapshot; + } + } + + public void SetTouchScreen(bool down, int x, int y) + { + lock (_inputGate) + { + _touchDown = down; + _touchX = Math.Clamp(x, 0, 255); + _touchY = Math.Clamp(y, 0, 191); + } + } + + public void SetPaused(bool paused) + { + lock (_lifecycleGate) + { + if (_disposed) return; + if (paused) + { + _resume.Reset(); + lock (_audioGate) + try { _track?.Pause(); } catch (Exception) { } + lock (_coreGate) { } + } + else + { + _resume.Set(); + if (Volatile.Read(ref _speedMultiplier) == 1) + lock (_audioGate) + try { _track?.Play(); } catch (Exception) { } + } + } + } + + public bool FlushSave() + { + lock (_coreGate) return !_disposed && _core.FlushSave(); + } + + public bool SaveState(string path) + { + lock (_coreGate) return !_disposed && _core.IsRunning && _core.SaveState(path); + } + + public bool LoadState(string path) + { + lock (_coreGate) return !_disposed && _core.IsRunning && _core.LoadState(path); + } + + public void Draw(SKCanvas canvas, SKRect destination) + { + lock (_frameGate) + { + if (_frameImage is null) return; + var sampling = new SKSamplingOptions(SKFilterMode.Nearest, SKMipmapMode.None); + canvas.DrawImage(_frameImage, destination, sampling); + } + } + + public void DrawMainScreen(SKCanvas canvas, SKRect destination) => DrawScreen(canvas, destination, top: true); + + public void DrawSecondaryScreen(SKCanvas canvas, SKRect destination) => DrawScreen(canvas, destination, top: false); + + private void DrawScreen(SKCanvas canvas, SKRect destination, bool top) + { + lock (_frameGate) + { + if (_frameImage is null) return; + var source = top + ? new SKRect(0, 0, 256, 192) + : new SKRect(0, 192, 256, 384); + var sampling = new SKSamplingOptions(SKFilterMode.Nearest, SKMipmapMode.None); + canvas.DrawImage(_frameImage, source, destination, sampling); + } + } + + private void RunLoop() + { + var frame = new SKBitmap(256, 384, SKColorType.Rgba8888, SKAlphaType.Opaque); + lock (_frameGate) _frame = frame; + var baseFramePeriod = Stopwatch.Frequency / FramesPerSecond; + double deadline = Stopwatch.GetTimestamp(); + var frameCount = 0; + var renderedFrameCount = 0; + try + { + while (!_cancel.IsCancellationRequested) + { + if (!_resume.IsSet) + { + _resume.Wait(TimeSpan.FromMilliseconds(50)); + deadline = Stopwatch.GetTimestamp(); + continue; + } + + var speedMultiplier = Volatile.Read(ref _speedMultiplier); + var framePeriod = baseFramePeriod / speedMultiplier; + var publishFrame = ++renderedFrameCount % speedMultiplier == 0; + + int audioFrames; + lock (_coreGate) + { + if (_cancel.IsCancellationRequested) break; + if (!_resume.IsSet) continue; + + uint keys; + bool touchDown; + int touchX; + int touchY; + lock (_inputGate) + { + keys = _keysPending; + touchDown = _touchDown; + touchX = _touchX; + touchY = _touchY; + } + _core.RunFrame(keys, touchDown, touchX, touchY); + if (publishFrame) + { + _core.CopyFrame(_frameScratch); + MemoryMarshal.AsBytes(_frameScratch.AsSpan()).CopyTo(frame.GetPixelSpan()); + } + audioFrames = _core.ReadAudio(_audioScratch, AudioFramesPerDrain); + if (++frameCount % SaveFlushIntervalFrames == 0 && !_core.FlushSave()) + Services.AppLog.Warn("embedded", "Could not flush the DS battery save after a periodic checkpoint."); + } + + if (publishFrame) + { + lock (_frameGate) + { + _frameImage?.Dispose(); + _frameImage = SKImage.FromBitmap(frame); + } + try { FrameProduced?.Invoke(); } + catch (Exception error) { Services.AppLog.Warn("embedded", $"A DS frame listener failed: {error.Message}"); } + } + + if (audioFrames > 0 && _track is not null && _audioEnabled && speedMultiplier == 1) + { + lock (_audioGate) + { + if (Volatile.Read(ref _speedMultiplier) == 1) + { + try + { + _audioBuffer.Rewind(); + _audioBuffer.AsShortBuffer().Put(_audioScratch, 0, audioFrames * 2); + _audioBuffer.Rewind(); + if (_track.Write(_audioBuffer, audioFrames * 4, WriteMode.Blocking) < 0) + { + _audioEnabled = false; + Services.AppLog.Warn("embedded", "DS audio stopped after an AudioTrack write error."); + } + } + catch (Exception error) + { + _audioEnabled = false; + Services.AppLog.Warn("embedded", $"DS audio stopped: {error.Message}"); + } + } + } + } + + deadline += framePeriod; + var remaining = TimeSpan.FromSeconds((deadline - Stopwatch.GetTimestamp()) / Stopwatch.Frequency); + if (remaining > TimeSpan.Zero) + { + var coarseSleep = remaining - TimeSpan.FromMilliseconds(1); + if (coarseSleep > TimeSpan.Zero) Thread.Sleep(coarseSleep); + while (!_cancel.IsCancellationRequested && Stopwatch.GetTimestamp() < deadline) + Thread.SpinWait(32); + } + else if (remaining < TimeSpan.FromMilliseconds(-100)) + deadline = Stopwatch.GetTimestamp(); // recover from a long pause without runaway catch-up + } + } + catch (Exception error) + { + Services.AppLog.Error("embedded", "The melonDS emulation loop stopped unexpectedly.", error); + } + } + + public void Dispose() + { + lock (_lifecycleGate) + { + if (_disposed) return; + _disposed = true; + _cancel.Cancel(); + _resume.Set(); + } + if (_thread.IsAlive && _thread != Thread.CurrentThread) _thread.Join(); + lock (_frameGate) + { + _frameImage?.Dispose(); + _frameImage = null; + _frame?.Dispose(); + _frame = null; + } + try { _track?.Stop(); } catch (Exception) { } + try { _track?.Release(); } catch (Exception) { } + _resume.Dispose(); + _cancel.Dispose(); + } +} diff --git a/src/PKForge.App/Platforms/Android/MelonDsNative.cs b/src/PKForge.App/Platforms/Android/MelonDsNative.cs new file mode 100644 index 00000000..50d2e6bd --- /dev/null +++ b/src/PKForge.App/Platforms/Android/MelonDsNative.cs @@ -0,0 +1,54 @@ +using System.Runtime.InteropServices; + +namespace PKForge.App.Platforms.Android; + +/// Flat UTF-8 C ABI over melonDS 1.1, built as libpkforge_melonds.so. +internal static partial class MelonDsNative +{ + private const string Library = "pkforge_melonds"; + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_available")] + internal static partial int Available(); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_last_error")] + internal static partial nint LastError(); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_create", StringMarshalling = StringMarshalling.Utf8)] + internal static partial nint Create(string romPath, string savePath); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_destroy")] + internal static partial void Destroy(nint core); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_is_running")] + internal static partial int IsRunning(nint core); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_game_title")] + internal static partial void GameTitle(nint core, Span output, nuint capacity); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_game_code")] + internal static partial void GameCode(nint core, Span output, nuint capacity); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_run_frame")] + internal static partial void RunFrame(nint core, uint keys, int touchDown, int touchX, int touchY); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_copy_frame")] + internal static partial int CopyFrame(nint core, Span output, nuint pixelCapacity); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_read_audio")] + internal static partial int ReadAudio(nint core, Span output, int frameCapacity); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_flush_save")] + internal static partial int FlushSave(nint core); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_save_size")] + internal static partial nuint SaveSize(nint core); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_copy_save")] + internal static partial nuint CopySave(nint core, Span output, nuint capacity); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_save_state", StringMarshalling = StringMarshalling.Utf8)] + internal static partial int SaveState(nint core, string path); + + [LibraryImport(Library, EntryPoint = "pkforge_melonds_load_state", StringMarshalling = StringMarshalling.Utf8)] + internal static partial int LoadState(nint core, string path); +} diff --git a/src/PKForge.App/Platforms/Android/MgbaCore.cs b/src/PKForge.App/Platforms/Android/MgbaCore.cs index 554b8886..0bca3f28 100644 --- a/src/PKForge.App/Platforms/Android/MgbaCore.cs +++ b/src/PKForge.App/Platforms/Android/MgbaCore.cs @@ -13,33 +13,71 @@ namespace PKForge.App.Platforms.Android; internal sealed class MgbaCore : Domain.IEmbeddedCore { private nint _core; + private (int Width, int Height) _videoSize; + private string _gameTitle = string.Empty; + private string _gameCode = string.Empty; public bool IsRunning { get; private set; } public string? RomPath { get; private set; } + public string? LoadError { get; private set; } public bool Load(string romPath, string? savePath = null) { - if (IsRunning) return false; + LoadError = null; + if (IsRunning) + { + LoadError = "Une ROM est déjà chargée dans ce cœur."; + return false; + } + var core = MgbaNative.CoreCreate(romPath); - if (core == nint.Zero) return false; + if (core == nint.Zero) + { + LoadError = "mGBA ne reconnaît pas ce fichier comme une ROM GB, GBC ou GBA valide."; + return false; + } + + var initialized = false; try { if (MgbaNative.CoreLoad(core, romPath, savePath) == 0) { - MgbaNative.CoreDestroy(core); + LoadError = "mGBA a reconnu la ROM, mais n'a pas pu charger son contenu ou sa sauvegarde. Vérifie le fichier et ses droits d'accès."; + return false; + } + + var videoSize = ReadVideoSize(core); + if (videoSize.Width <= 0 || videoSize.Height <= 0) + { + LoadError = "mGBA n'a pas fourni de dimensions vidéo valides pour cette ROM."; return false; } + + var gameTitle = ReadGameTitle(core); + var gameCode = ReadGameCode(core); _core = core; + _videoSize = videoSize; + _gameTitle = gameTitle; + _gameCode = gameCode; RomPath = romPath; IsRunning = true; + initialized = true; return true; } - catch (Exception) + catch (Exception error) { - try { MgbaNative.CoreDestroy(core); } catch (DllNotFoundException) { } + LoadError = $"Erreur pendant le chargement natif : {error.Message}"; return false; } + finally + { + if (!initialized) + { + try { MgbaNative.CoreDestroy(core); } + catch (Exception error) { Services.AppLog.Warn("embedded", $"Could not release a failed mGBA core: {error.Message}"); } + } + } } private void ThrowWhenNotRunning() @@ -55,36 +93,39 @@ public void RunFrame() public string GameTitle { - get - { - if (!IsRunning) return string.Empty; - Span title = stackalloc byte[17]; - MgbaNative.CoreGameTitle(_core, title); - var length = title.IndexOf((byte)0); - return length < 0 ? Encoding.ASCII.GetString(title) : Encoding.ASCII.GetString(title[..length]); - } + get => IsRunning ? _gameTitle : string.Empty; } public string GameCode { - get - { - if (!IsRunning) return string.Empty; - Span code = stackalloc byte[5]; - MgbaNative.CoreGameCode(_core, code); - var length = code.IndexOf((byte)0); - return length < 0 ? Encoding.ASCII.GetString(code) : Encoding.ASCII.GetString(code[..length]); - } + get => IsRunning ? _gameCode : string.Empty; } public (int Width, int Height) VideoSize { - get - { - if (!IsRunning) return (0, 0); - MgbaNative.CoreVideoSize(_core, out var width, out var height); - return ((int)width, (int)height); - } + get => IsRunning ? _videoSize : (0, 0); + } + + private static string ReadGameTitle(nint core) + { + Span title = stackalloc byte[17]; + MgbaNative.CoreGameTitle(core, title); + var length = title.IndexOf((byte)0); + return length < 0 ? Encoding.ASCII.GetString(title) : Encoding.ASCII.GetString(title[..length]); + } + + private static string ReadGameCode(nint core) + { + Span code = stackalloc byte[5]; + MgbaNative.CoreGameCode(core, code); + var length = code.IndexOf((byte)0); + return length < 0 ? Encoding.ASCII.GetString(code) : Encoding.ASCII.GetString(code[..length]); + } + + private static (int Width, int Height) ReadVideoSize(nint core) + { + MgbaNative.CoreVideoSize(core, out var width, out var height); + return ((int)width, (int)height); } public void CopyFrame(Span buffer) @@ -110,6 +151,14 @@ public bool ReadBytes(uint address, Span destination) return MgbaNative.CoreReadBytes(_core, address, destination, (UIntPtr)destination.Length) != 0; } + /// Copies mGBA's raw battery data without relying on the cartridge bus window. + public int CopySavedata(Span destination) + { + if (!IsRunning || destination.IsEmpty) return 0; + var copied = MgbaNative.CoreCopySavedata(_core, destination, (UIntPtr)destination.Length).ToUInt64(); + return copied <= (ulong)destination.Length ? (int)copied : 0; + } + public uint? Read32(uint address) { Span four = stackalloc byte[4]; @@ -139,6 +188,12 @@ public bool LoadState(string path) return MgbaNative.CoreLoadState(_core, path) != 0; } + public bool FlushSave(string path) + { + ThrowWhenNotRunning(); + return MgbaNative.CoreFlushSave(_core, path) != 0; + } + public void Dispose() { if (!IsRunning) return; diff --git a/src/PKForge.App/Platforms/Android/MgbaNative.cs b/src/PKForge.App/Platforms/Android/MgbaNative.cs index 9fa49c79..882d10cb 100644 --- a/src/PKForge.App/Platforms/Android/MgbaNative.cs +++ b/src/PKForge.App/Platforms/Android/MgbaNative.cs @@ -5,9 +5,10 @@ namespace PKForge.App.Platforms.Android; /// /// P/Invoke over PKForge's libmgba shim (tools/build-mgba/jni_bridge.c), built as /// libpkforge_mgba.so for arm64-v8a. The shim is flat C over mGBA's mCore API -/// (0.10.5, signature-for-signature from mgba/core/core.h): every function -/// returns int (1 = success, 0 = failure) and every string is UTF-8 — no C bool -/// marshalling, no struct layouts on the managed side. +/// (0.10.5, signature-for-signature from mgba/core/core.h): status functions +/// return int (1 = success, 0 = failure), core handles use native pointer size, +/// and every string is UTF-8 — no C bool marshalling or struct layouts on the +/// managed side. /// internal static partial class MgbaNative { @@ -15,6 +16,9 @@ internal static partial class MgbaNative // ---- Lifecycle ---- + [LibraryImport(Library, EntryPoint = "pkforg_core_available")] + internal static partial int CoreAvailable(); + /// mCoreFind + init + loadConfig; returns the core handle, 0 on failure. [LibraryImport(Library, EntryPoint = "pkforg_core_create", StringMarshalling = StringMarshalling.Utf8)] internal static partial nint CoreCreate(string romPath); @@ -26,6 +30,14 @@ internal static partial class MgbaNative [LibraryImport(Library, EntryPoint = "pkforg_core_load", StringMarshalling = StringMarshalling.Utf8)] internal static partial int CoreLoad(nint core, string romPath, string? savePath); + /// Writes the core's current battery RAM to its save file and syncs it to storage. + [LibraryImport(Library, EntryPoint = "pkforg_core_flush_save", StringMarshalling = StringMarshalling.Utf8)] + internal static partial int CoreFlushSave(nint core, string savePath); + + /// Copies the mGBA savedata clone; returns 0 when it does not fit. + [LibraryImport(Library, EntryPoint = "pkforg_core_copy_savedata")] + internal static partial UIntPtr CoreCopySavedata(nint core, Span destination, UIntPtr capacity); + // ---- Run ---- [LibraryImport(Library, EntryPoint = "pkforg_core_run_frame")] diff --git a/src/PKForge.App/Platforms/Android/NintendoDsGameSession.cs b/src/PKForge.App/Platforms/Android/NintendoDsGameSession.cs new file mode 100644 index 00000000..e563bac6 --- /dev/null +++ b/src/PKForge.App/Platforms/Android/NintendoDsGameSession.cs @@ -0,0 +1,312 @@ +using System.Security.Cryptography; +using System.Text; +using PKForge.Domain; +using SkiaSharp; + +namespace PKForge.App.Platforms.Android; + +/// melonDS session and the DS battery-save synchronization boundary. +internal sealed class NintendoDsGameSession : IEmbeddedGameSession +{ + private readonly string _batterySavePath; + private readonly string? _linkedSaveSyncMarkerPath; + private readonly string? _linkedSaveDocumentId; + private readonly ISaveFileAccess? _saveFileAccess; + private readonly SemaphoreSlim _saveSyncGate = new(1, 1); + private readonly object _disposeGate = new(); + private MelonDsCore? _core; + private MelonDsEngine? _engine; + private Task? _closeTask; + + public event Action? FrameProduced + { + add { if (_engine is not null) _engine.FrameProduced += value; } + remove { if (_engine is not null) _engine.FrameProduced -= value; } + } + + public (int Width, int Height) VideoSize => _core?.VideoSize ?? (0, 0); + public string GameTitle => _core?.GameTitle ?? string.Empty; + public string GameCode => _core?.GameCode ?? string.Empty; + public int Generation { get; } + public string QuickStatePath { get; } + public bool HasQuickState => File.Exists(QuickStatePath); + public bool HasSaveConflict { get; private set; } + public bool SupportsTouchScreen => true; + public bool SupportsLiveCompanion => true; + public bool IsNintendoDs => true; + + private NintendoDsGameSession( + MelonDsCore core, + MelonDsEngine engine, + string romPath, + string? romFileName, + string batterySavePath, + int generation, + string? linkedSaveDocumentId, + ISaveFileAccess? saveFileAccess, + bool hasSaveConflict) + { + _core = core; + _engine = engine; + _batterySavePath = batterySavePath; + _linkedSaveSyncMarkerPath = linkedSaveDocumentId is null ? null : batterySavePath + ".synced"; + _linkedSaveDocumentId = linkedSaveDocumentId; + _saveFileAccess = saveFileAccess; + Generation = generation; + var fileName = Path.GetFileNameWithoutExtension(romFileName ?? romPath); + QuickStatePath = EmbeddedGameSession.PrivateFilePath("ds-states", romPath, ".ss0", fileName); + HasSaveConflict = hasSaveConflict; + } + + public static bool IsAvailable + { + get + { + try + { + var available = MelonDsNative.Available() != 0; + EmulatorCatalog.EmbeddedDsCoreAvailable = available; + return available; + } + catch (DllNotFoundException) { } + catch (EntryPointNotFoundException) { } + catch (BadImageFormatException) { } + EmulatorCatalog.EmbeddedDsCoreAvailable = false; + return false; + } + } + + public static EmbeddedGameStartResult TryStart( + string romPath, + int generation, + string? romFileName, + string? linkedSaveDocumentId, + ISaveFileAccess? saveFileAccess) + { + MelonDsCore? core = null; + MelonDsEngine? engine = null; + try + { + var extension = Path.GetExtension(romFileName ?? romPath); + if (!extension.Equals(".nds", StringComparison.OrdinalIgnoreCase) + && !extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) + return new EmbeddedGameStartResult(null, "Le cœur DS intégré accepte les fichiers .nds et les archives .zip contenant une seule ROM .nds."); + + var localRomPath = EmbeddedGameSession.MaterializeNintendoDsRom(romPath, romFileName); + var savePath = EmbeddedGameSession.SavePathForRom(romPath, linkedSaveDocumentId); + Directory.CreateDirectory(Path.GetDirectoryName(savePath)!); + var hasSaveConflict = false; + if (linkedSaveDocumentId is not null) + { + if (saveFileAccess is null) + throw new InvalidOperationException("Le service de sauvegarde liée n'est pas disponible."); + var linkedBytes = saveFileAccess.ReadAsync(linkedSaveDocumentId).AsTask().GetAwaiter().GetResult().ToArray(); + hasSaveConflict = EmbeddedGameSession.ReconcileLinkedSave(savePath, savePath + ".synced", linkedBytes); + } + + core = new MelonDsCore(); + if (!core.Load(localRomPath, savePath)) + { + var reason = core.LoadError ?? "melonDS n'a pas pu charger cette ROM DS."; + Services.AppLog.Error("embedded", $"Could not load {Path.GetFileName(romPath)}: {reason}", new InvalidOperationException(reason)); + core.Dispose(); + return new EmbeddedGameStartResult(null, reason); + } + + engine = new MelonDsEngine(core); + var session = new NintendoDsGameSession(core, engine, romPath, romFileName, savePath, + generation, linkedSaveDocumentId, saveFileAccess, hasSaveConflict); + engine.Start(); + return new EmbeddedGameStartResult(session, null); + } + catch (DllNotFoundException error) + { + const string reason = "Android n'a pas pu charger le cœur melonDS intégré à cette APK."; + Services.AppLog.Error("embedded", reason, error); + engine?.Dispose(); + core?.Dispose(); + return new EmbeddedGameStartResult(null, $"{reason} {error.Message}"); + } + catch (EntryPointNotFoundException error) + { + const string reason = "Le cœur melonDS de l'APK est incomplet ou trop ancien pour PKForge."; + Services.AppLog.Error("embedded", reason, error); + engine?.Dispose(); + core?.Dispose(); + return new EmbeddedGameStartResult(null, reason); + } + catch (BadImageFormatException error) + { + const string reason = "L'architecture du cœur melonDS ne correspond pas à cet appareil."; + Services.AppLog.Error("embedded", reason, error); + engine?.Dispose(); + core?.Dispose(); + return new EmbeddedGameStartResult(null, reason); + } + catch (InvalidDataException error) + { + const string reason = "Archive DS invalide."; + Services.AppLog.Warn("embedded", $"Could not open DS archive {Path.GetFileName(romPath)}: {error.Message}"); + engine?.Dispose(); + core?.Dispose(); + return new EmbeddedGameStartResult(null, $"{reason} {error.Message}"); + } + catch (Exception error) + { + Services.AppLog.Error("embedded", $"Could not start DS ROM {Path.GetFileName(romPath)}", error); + engine?.Dispose(); + core?.Dispose(); + return new EmbeddedGameStartResult(null, $"{error.GetType().Name}: {error.Message}"); + } + } + + public void SetKeys(uint bitmask) => _engine?.SetKeys(bitmask); + public void SetTouchScreen(bool down, int x, int y) => _engine?.SetTouchScreen(down, x, y); + public void Draw(SKCanvas canvas, SKRect destination) => _engine?.Draw(canvas, destination); + public void DrawMainScreen(SKCanvas canvas, SKRect destination) => _engine?.DrawMainScreen(canvas, destination); + public void DrawSecondaryScreen(SKCanvas canvas, SKRect destination) => _engine?.DrawSecondaryScreen(canvas, destination); + public LiveCompanionSnapshot? ReadLiveCompanion() => _engine?.ReadLiveCompanion(Generation); + public void SetPaused(bool paused) => _engine?.SetPaused(paused); + public void SetSpeedMultiplier(int multiplier) => _engine?.SetSpeedMultiplier(multiplier); + + public async Task FlushBatterySaveAsync() + { + var engine = _engine; + if (engine is not null) + { + engine.SetPaused(true); + if (!engine.FlushSave()) + { + Services.AppLog.Warn("embedded", $"Could not flush the DS battery save for {GameTitle}."); + return false; + } + } + return await SyncLinkedSaveAsync(sessionClosed: false).ConfigureAwait(false); + } + + public bool SaveQuickState() + { + var temporaryPath = QuickStatePath + ".tmp"; + try + { + Directory.CreateDirectory(Path.GetDirectoryName(QuickStatePath)!); + if (_engine?.SaveState(temporaryPath) != true) + { + File.Delete(temporaryPath); + return false; + } + File.Move(temporaryPath, QuickStatePath, overwrite: true); + return true; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException) + { + Services.AppLog.Warn("embedded", $"Could not save a DS quick state for {GameTitle}: {error.Message}"); + try { File.Delete(temporaryPath); } catch (IOException) { } + return false; + } + } + + public bool LoadQuickState() => HasQuickState && _engine?.LoadState(QuickStatePath) == true; + + public Task CloseAsync() + { + lock (_disposeGate) return _closeTask ??= CloseCoreAsync(); + } + + private async Task CloseCoreAsync() + { + var gameTitle = GameTitle; + var engine = _engine; + var core = _core; + _engine = null; + _core = null; + var saveFlushed = true; + try + { + await Task.Run(() => + { + try + { + if (engine is not null) + { + engine.SetPaused(true); + saveFlushed = engine.FlushSave(); + } + } + finally + { + engine?.Dispose(); + core?.Dispose(); + } + }).ConfigureAwait(false); + } + catch (Exception error) + { + Services.AppLog.Error("embedded", $"Could not stop DS game {gameTitle}", error); + return false; + } + + if (!saveFlushed) + { + Services.AppLog.Warn("embedded", $"Could not flush the DS battery save for {gameTitle}."); + return false; + } + return await SyncLinkedSaveAsync(sessionClosed: true).ConfigureAwait(false); + } + + private async Task SyncLinkedSaveAsync(bool sessionClosed) + { + if (_linkedSaveDocumentId is null || _saveFileAccess is null) return true; + await _saveSyncGate.WaitAsync().ConfigureAwait(false); + try + { + var bytes = await File.ReadAllBytesAsync(_batterySavePath).ConfigureAwait(false); + var linkedBytes = (await _saveFileAccess.ReadAsync(_linkedSaveDocumentId).ConfigureAwait(false)).ToArray(); + if (!bytes.AsSpan().SequenceEqual(linkedBytes)) + { + var marker = _linkedSaveSyncMarkerPath is null + ? null + : EmbeddedGameSession.ReadSyncMarker(_linkedSaveSyncMarkerPath); + if (marker is null) return SaveSyncConflict(); + var localMatchesMarker = EmbeddedGameSession.ContentHash(bytes).Equals(marker, StringComparison.Ordinal); + var linkedMatchesMarker = EmbeddedGameSession.ContentHash(linkedBytes).Equals(marker, StringComparison.Ordinal); + if (localMatchesMarker && !linkedMatchesMarker) + { + if (!sessionClosed) return SaveSyncConflict(); + EmbeddedGameSession.WriteFileAtomically(_batterySavePath, linkedBytes); + if (_linkedSaveSyncMarkerPath is not null) + EmbeddedGameSession.TryWriteSyncMarker(_linkedSaveSyncMarkerPath, linkedBytes); + HasSaveConflict = false; + return true; + } + if (!localMatchesMarker || !linkedMatchesMarker) + { + if (!linkedMatchesMarker) return SaveSyncConflict(); + } + } + await _saveFileAccess.WriteAtomicallyAsync(_linkedSaveDocumentId, bytes).ConfigureAwait(false); + if (_linkedSaveSyncMarkerPath is not null) + EmbeddedGameSession.TryWriteSyncMarker(_linkedSaveSyncMarkerPath, bytes); + HasSaveConflict = false; + return true; + } + catch (Exception error) + { + Services.AppLog.Error("embedded", $"Could not sync the linked DS save {_linkedSaveDocumentId}", error); + return false; + } + finally + { + _saveSyncGate.Release(); + } + } + + private bool SaveSyncConflict() + { + HasSaveConflict = true; + Services.AppLog.Warn("embedded", "The linked DS save changed during play; neither copy was overwritten."); + return false; + } + + public ValueTask DisposeAsync() => new(CloseAsync()); +} diff --git a/src/PKForge.App/Services/AppStrings.cs b/src/PKForge.App/Services/AppStrings.cs index 0683bf79..180d43e8 100644 --- a/src/PKForge.App/Services/AppStrings.cs +++ b/src/PKForge.App/Services/AppStrings.cs @@ -48,11 +48,25 @@ public static void Set(AppLanguage language) // ---- Library ---- public static string LibraryTitle => Fr ? "Bibliothèque" : "Library"; public static string ScanRoms => Fr ? "Scanner les ROMs" : "Scan ROMs"; + public static string LibrarySearch => Fr ? "Rechercher un jeu" : "Search games"; + public static string LibrarySearchPlaceholder => Fr ? "Jeu ou nom du fichier ROM…" : "Game or ROM filename…"; + public static string LibraryClearSearch => Fr ? "Effacer la recherche" : "Clear search"; + public static string LibraryScanHint => Fr + ? "Appuyez sur Scanner pour chercher vos ROMs dans /storage/emulated/0/ROMs." + : "Tap Scan to look for your ROMs in /storage/emulated/0/ROMs."; + public static string LibraryReady => Fr + ? "Touchez une ROM pour la lancer, ou sélectionnez-la puis appuyez sur A." + : "Tap a ROM to launch it, or select it and press A."; + public static string LibraryNoResults(string query) => Fr + ? $"Aucun jeu ne correspond à « {query} »." + : $"No games match “{query}”."; + public static string LibraryResults(int count, int roms) => Fr + ? $"{count} résultat(s) · {roms} ROM(s)" + : $"{count} result(s) · {roms} ROM(s)"; public static string NoRomRoot => Fr ? "Dossier ROMs introuvable. Accordez l'accès à tous les fichiers dans les réglages Android, puis rescannez." : "No ROMs folder found. Grant All files access in Android settings, then scan again."; public static string Scanning => Fr ? "Scan en cours…" : "Scanning…"; - public static string RomCount(int count) => Fr ? $"{count} ROM(s) Pokémon trouvée(s)." : $"{count} Pokémon ROM(s) found."; public static string Play => Fr ? "Jouer" : "Play"; // ---- Cartridge menu ---- @@ -60,6 +74,114 @@ public static void Set(AppLanguage language) public static string UnlinkRom => Fr ? "Délier la ROM" : "Unlink ROM"; public static string PickFromLibrary => Fr ? "Choisir dans la bibliothèque" : "Pick from library"; public static string RomMissing => Fr ? "Émulateur manquant" : "Emulator missing"; + public static string GamePause => Fr ? "Pause" : "Pause"; + public static string GameResume => Fr ? "Reprendre" : "Resume"; + public static string GameOptions => Fr ? "Options" : "Options"; + public static string GameOptionsSpeed(int multiplier) => $"Options · ×{multiplier}"; + public static string GameSpeed => Fr ? "Vitesse du jeu" : "Game speed"; + public static string GameSpeedMenuLabel(int multiplier) => Fr + ? $"Vitesse du jeu · ×{multiplier}" + : $"Game speed · ×{multiplier}"; + public static string GameSpeedHelp => Fr + ? "Choisis une accélération. Le son est coupé au-dessus de ×1 et revient à vitesse normale." + : "Choose a fast-forward speed. Audio is muted above ×1 and returns at normal speed."; + public static string GameSpeedChoice(int multiplier) => multiplier == 1 + ? Fr ? "×1 · normale" : "×1 · normal" + : $"×{multiplier}"; + public static string GameDisplay => Fr ? "Taille du jeu" : "Game size"; + public static string GameDisplayHelp => Fr + ? "Choisis la taille de l'image. Le rapport du jeu reste toujours respecté." + : "Choose the game image size. The game's aspect ratio is always preserved."; + public static string GameScaleFit => Fr ? "Maximum · adapter à l'écran" : "Maximum · fit screen"; + public static string GameScale90 => Fr ? "90 % de la taille maximale" : "90% of maximum size"; + public static string GameScale75 => Fr ? "75 % de la taille maximale" : "75% of maximum size"; + public static string GameScalePixelPerfect => Fr ? "Pixels entiers · pixel perfect" : "Whole pixels · pixel perfect"; + public static string GameEnterFullScreen => Fr ? "Plein écran" : "Full screen"; + public static string GameExitFullScreen => Fr ? "Afficher l'interface" : "Show interface"; + public static string GameToggleTouchControls => Fr ? "Afficher les commandes tactiles" : "Toggle touch controls"; + public static string GameHideTouchControls => Fr ? "Masquer les commandes" : "Hide controls"; + public static string GameShowTouchControls => Fr ? "Afficher les commandes" : "Show controls"; + public static string GameSaveState => Fr ? "Sauvegarder l'état" : "Save state"; + public static string GameLoadState => Fr ? "Charger l'état" : "Load state"; + public static string GameExit => Fr ? "Quitter le jeu" : "Exit game"; + public static string GameSavingState => Fr ? "Sauvegarde de l'état…" : "Saving state…"; + public static string GameLoadingState => Fr ? "Chargement de l'état…" : "Loading state…"; + public static string GamePaused => Fr ? "Jeu en pause." : "Game paused."; + public static string GameStateSaved => Fr ? "État sauvegardé." : "State saved."; + public static string GameStateLoaded => Fr ? "État chargé." : "State loaded."; + public static string GameStateSaveFailed => Fr ? "Impossible de sauvegarder l'état." : "Could not save the state."; + public static string GameStateLoadFailed => Fr ? "Impossible de charger l'état." : "Could not load the state."; + public static string CompanionParty => Fr ? "ÉQUIPE" : "PARTY"; + public static string CompanionBag => Fr ? "SAC" : "BAG"; + public static string CompanionPokedex => Fr ? "POKÉDEX" : "POKÉDEX"; + public static string CompanionSession => Fr ? "SESSION" : "SESSION"; + public static string CompanionRestorePoints => Fr ? "REPRISES" : "RESTORES"; + public static string CompanionSettings => Fr ? "OPTIONS" : "SETTINGS"; + public static string CompanionSettingsTitle => Fr ? "Options du compagnon" : "Companion settings"; + public static string CompanionSettingsHelp => Fr + ? "Choisis les pages visibles et celle qui s'ouvre en premier." + : "Choose which pages are visible and which one opens first."; + public static string CompanionShowTab => Fr ? "Afficher" : "Show"; + public static string CompanionHideTab => Fr ? "Masquer" : "Hide"; + public static string CompanionMakeHome => Fr ? "Ouvrir au démarrage" : "Open on launch"; + public static string CompanionCurrentHome => Fr ? "Page d'accueil" : "Home page"; + public static string CompanionNoParty => Fr + ? "Aucune équipe n'est enregistrée dans cette sauvegarde valide." + : "No party is recorded in this valid save."; + public static string CompanionNoSavedData => Fr + ? "Aucune sauvegarde valide n'est disponible pour ce jeu." + : "No valid save is available for this game."; + public static string CompanionSavedDataNotice => Fr + ? "Données de la dernière sauvegarde valide" + : "Data from the latest valid game save"; + public static string CompanionBagEmpty => Fr ? "Le sac est vide." : "The bag is empty."; + public static string CompanionEgg => Fr ? "ŒUF" : "EGG"; + public static string CompanionPocketAll => Fr ? "TOUT" : "ALL"; + public static string CompanionPocketItems => Fr ? "OBJETS" : "ITEMS"; + public static string CompanionPocketKeyItems => Fr ? "OBJETS RARES" : "KEY ITEMS"; + public static string CompanionPocketMedicine => Fr ? "MÉDICAMENTS" : "MEDICINE"; + public static string CompanionPocketBalls => Fr ? "POKÉ BALLS" : "POKÉ BALLS"; + public static string CompanionPocketMachines => Fr ? "CT / CS" : "TMs / HMs"; + public static string CompanionPocketBerries => Fr ? "BAIES" : "BERRIES"; + public static string CompanionPocketBattleItems => Fr ? "OBJETS DE COMBAT" : "BATTLE ITEMS"; + public static string CompanionPocketMail => Fr ? "COURRIER" : "MAIL"; + public static string CompanionPartyMember(int index, string nickname, string species, int level, bool isEgg = false) => + isEgg + ? $"{index}. {nickname} · {species}" + : Fr + ? $"{index}. {nickname} · {species} · N. {level}" + : $"{index}. {nickname} · {species} · Lv. {level}"; + public static string CompanionHp(int current, int maximum) => Fr ? $"{current}/{maximum} PV" : $"{current}/{maximum} HP"; + public static string CompanionDex(int caught, int seen, int total) => Fr + ? $"Capturés {caught} · vus {seen} · total {total}" + : $"Caught {caught} · seen {seen} · total {total}"; + public static string CompanionPlaytime(int hours, int minutes) => Fr + ? $"Temps de jeu · {hours} h {minutes:D2}" + : $"Play time · {hours} h {minutes:D2}"; + public static string CompanionPartyLabel(int count) => Fr ? $"Équipe · {count}/6" : $"Party · {count}/6"; + public static string CompanionNoRestorePoints => Fr ? "Aucun point de restauration disponible." : "No restore points are available."; + public static string GameBatterySaveFailed => Fr + ? "PKForge n'a pas pu confirmer l'enregistrement de la sauvegarde de jeu. Vérifiez l'espace disponible et l'accès au fichier." + : "PKForge could not confirm the game save. Check available storage and file access."; + public static string GameBatterySaveFailedTitle => Fr ? "Sauvegarde de jeu non synchronisée" : "Game save not synchronized"; + public static string GameSaveConflict => Fr + ? "Le fichier lié et la sauvegarde locale ont changé séparément. Aucune copie n'a été écrasée." + : "The linked file and private game save changed separately. Neither copy was overwritten."; + public static string GameLaunchFailedTitle => Fr ? "Jeu impossible à lancer" : "Could not launch"; + public static string GameLaunchFailed(string name, string? reason = null, int generation = 0) + { + var core = generation is 4 or 5 ? "melonDS" : "mGBA"; + var message = Fr + ? $"{name} n'a pas pu démarrer dans PKForge. Vérifie la ROM, le cœur {core} intégré et l'accès à la sauvegarde." + : $"{name} could not start in PKForge. Check the ROM, the integrated {core} core, and save-file access."; + return string.IsNullOrWhiteSpace(reason) ? message : $"{message}\n\n{reason}"; + } + public static string EmbeddedCoreMissing(int generation) => Fr + ? $"Le cœur PKForge pour la génération {generation} n'est pas présent ou chargeable dans cette APK. La ROM ne sera pas envoyée à un émulateur externe." + : $"PKForge's integrated core for generation {generation} is missing or could not be loaded from this APK. The ROM will not be handed to an external emulator."; + public static string EmbeddedRomFormatUnsupported(int generation, string fileName) => Fr + ? $"PKForge ne prend pas encore en charge ce format pour la génération {generation} : {fileName}. Les archives et formats DSi ne sont pas encore intégrés." + : $"PKForge does not support this format for generation {generation} yet: {fileName}. Archives and DSi formats are not integrated yet."; // ---- External companion: play stats ---- public static string SessionTime => Fr ? "Session" : "Session"; @@ -68,20 +190,31 @@ public static void Set(AppLanguage language) public static string DexProgressLabel => Fr ? "Dex" : "Dex"; public static string PlaytimeHours(int hours, int minutes) => Fr ? $"{hours} h {minutes:00} min" : $"{hours}h {minutes:00}m"; - // ---- External companion: restore points ---- - // (RestorePointsTitle / Restore / RestoreThisPoint already exist in the "Restore points" section below.) - public static string NoRestorePoints => Fr ? "Aucun point pour ce jeu." : "No restore point for this game."; - public static string CreateRestorePoint => Fr ? "Créer un point de restauration" : "Create a restore point"; - public static string RestorePointCreated => Fr ? "Point de restauration créé." : "Restore point created."; - public static string RestorePointCreateFailed => Fr ? "Impossible de créer le point (sauvegarde illisible ?)." : "Could not create the point (save unreadable?)."; - public static string RestorePointConfirm => Fr - ? "La sauvegarde du jeu sera remplacée par ce point. Une sauvegarde de sécurité est faite d'abord." - : "The game's save will be replaced by this point. A safety backup is made first."; - public static string RestoreDone => Fr ? "Point restauré. Relancez le jeu pour le charger." : "Point restored. Relaunch the game to load it."; - public static string RestoreFailed => Fr ? "La restauration a échoué (point illisible ?)." : "Restore failed (point unreadable?)."; - // ---- Trophies ---- public static string TrophiesTitle => Fr ? "Trophées" : "Trophies"; + public static string MuseumTitle => Fr ? "Musée" : "Museum"; + public static string MuseumScan => Fr ? "Actualiser" : "Refresh"; + public static string MuseumPrevious => Fr ? "Précédent" : "Previous"; + public static string MuseumNext => Fr ? "Suivant" : "Next"; + public static string MuseumReading => Fr ? "Lecture des Pokédex liés…" : "Reading linked Pokédexes…"; + public static string MuseumReadOnly => Fr + ? "Lecture seule · progression lue dans la dernière sauvegarde de chaque jeu." + : "Read only · progress is read from each game's latest save."; + public static string MuseumNoSaves => Fr + ? "Aucune sauvegarde liée. Liez un jeu depuis l'écran d'accueil pour remplir le Musée." + : "No linked saves. Link a game from Home to fill the Museum."; + public static string MuseumReadError(string error) => Fr + ? $"Sauvegarde illisible : {error}" + : $"Save could not be read: {error}"; + public static string MuseumProgress(int seen, int caught, int total, int shiny) => Fr + ? $"{seen}/{total} vus · {caught}/{total} capturés · {shiny} chromatiques" + : $"{seen}/{total} seen · {caught}/{total} caught · {shiny} shiny"; + public static string MuseumNoDex => Fr + ? "Aucune entrée Pokédex lisible pour cette sauvegarde." + : "No readable Pokédex entries in this save."; + public static string MuseumSpeciesState(bool seen, bool caught, bool shiny) => Fr + ? $"{(caught ? "Capturé" : seen ? "Vu" : "Non découvert")}{(shiny ? " · chromatique dans la sauvegarde" : "")}" + : $"{(caught ? "Caught" : seen ? "Seen" : "Unseen")}{(shiny ? " · shiny in this save" : "")}"; public static string ScanSaves => Fr ? "Analyser les sauv." : "Scan saves"; public static string Unlocked => Fr ? "Débloqué" : "Unlocked"; diff --git a/src/PKForge.App/Services/EmbeddedGameDisplayPreferences.cs b/src/PKForge.App/Services/EmbeddedGameDisplayPreferences.cs new file mode 100644 index 00000000..6a2e53c1 --- /dev/null +++ b/src/PKForge.App/Services/EmbeddedGameDisplayPreferences.cs @@ -0,0 +1,49 @@ +namespace PKForge.App.Services; + +public enum EmbeddedGameScaleMode +{ + Fit, + NinetyPercent, + SeventyFivePercent, + PixelPerfect, +} + +/// Display preferences for the in-app emulator. Image proportions are always preserved. +public static class EmbeddedGameDisplayPreferences +{ + private const string FullScreenKey = "embedded_game_full_screen"; + private const string ScaleModeKey = "embedded_game_scale_mode"; + private const string TouchControlsKey = "embedded_game_touch_controls"; + + public static bool FullScreen + { + get => Preferences.Default.Get(FullScreenKey, true); + set => Preferences.Default.Set(FullScreenKey, value); + } + + public static EmbeddedGameScaleMode ScaleMode + { + get + { + var stored = Preferences.Default.Get(ScaleModeKey, nameof(EmbeddedGameScaleMode.Fit)); + return Enum.TryParse(stored, out var mode) + ? mode + : EmbeddedGameScaleMode.Fit; + } + set => Preferences.Default.Set(ScaleModeKey, value.ToString()); + } + + public static bool TouchControlsVisible + { + get => Preferences.Default.Get(TouchControlsKey, true); + set => Preferences.Default.Set(TouchControlsKey, value); + } + + public static float ScaleFor(EmbeddedGameScaleMode mode, float maximumScale) => mode switch + { + EmbeddedGameScaleMode.NinetyPercent => maximumScale * 0.90f, + EmbeddedGameScaleMode.SeventyFivePercent => maximumScale * 0.75f, + EmbeddedGameScaleMode.PixelPerfect when maximumScale >= 1f => MathF.Floor(maximumScale), + _ => maximumScale, + }; +} diff --git a/src/PKForge.App/Services/EmbeddedGamePreferences.cs b/src/PKForge.App/Services/EmbeddedGamePreferences.cs new file mode 100644 index 00000000..e18883af --- /dev/null +++ b/src/PKForge.App/Services/EmbeddedGamePreferences.cs @@ -0,0 +1,22 @@ +namespace PKForge.App.Services; + +/// Preferences shared by PKForge's in-app game sessions. +public static class EmbeddedGamePreferences +{ + private const string SpeedMultiplierKey = "embedded_game_speed_multiplier"; + + public static int SpeedMultiplier + { + get + { + var stored = Preferences.Default.Get(SpeedMultiplierKey, 1); + return stored is >= 1 and <= 4 ? stored : 1; + } + set + { + if (value is < 1 or > 4) + throw new ArgumentOutOfRangeException(nameof(value), "The embedded game speed must be between ×1 and ×4."); + Preferences.Default.Set(SpeedMultiplierKey, value); + } + } +} diff --git a/src/PKForge.App/Services/ExternalRestorePointService.cs b/src/PKForge.App/Services/ExternalRestorePointService.cs deleted file mode 100644 index d5f45cf2..00000000 --- a/src/PKForge.App/Services/ExternalRestorePointService.cs +++ /dev/null @@ -1,91 +0,0 @@ -using PKForge.App.Views; -using PKForge.Domain; - -namespace PKForge.App.Services; - -/// -/// Restore points of the save an external emulator is playing (US-005), on top of the -/// existing atomic backup pipeline (): listing is newest-first -/// via , creating a point is a named, timestamped backup of -/// the current save bytes (never an in-place write), and restoring is a destructive action -/// that always asks first (PadMenu.ConfirmAsync) and always takes a safety backup of the -/// live save before overwriting it — atomically (temp file + move), like every store here. -/// -public sealed class ExternalRestorePointService(IBackupService backups, ISaveEngine engine) -{ - /// The restore points of this save file, newest first. Empty when the save does not parse. - public async Task> ListForAsync(string savePath, CancellationToken cancellationToken = default) - { - var open = await OpenSnapshotAsync(savePath, cancellationToken).ConfigureAwait(false); - var all = await backups.ListAsync(cancellationToken).ConfigureAwait(false); - return RestorePointRules.ForGame(all, savePath, open); - } - - /// - /// Creates a named, timestamped restore point of the save's current bytes through the - /// atomic backup pipeline. Returns the receipt, or null when the save cannot be read/parsed. - /// - public async Task CreatePointAsync(string savePath, CancellationToken cancellationToken = default) - { - var snapshot = await OpenSnapshotAsync(savePath, cancellationToken).ConfigureAwait(false); - if (snapshot is null) return null; - var name = RestorePointRules.NameFor(RestorePointKind.Manual, DateTimeOffset.UtcNow, AppStrings.Fr); - return await backups.CreateAsync(snapshot, name, savePath, cancellationToken).ConfigureAwait(false); - } - - /// - /// Restores a point into the save file: asks for confirmation (destructive), takes a - /// safety backup of the live save first, then writes the point's bytes atomically. - /// Returns false when the user cancels, the save is unreadable, or the point is corrupt. - /// - public async Task RestoreAsync(Grid host, string savePath, string backupId, CancellationToken cancellationToken = default) - { - var confirmed = await PadMenu.ConfirmAsync(host, - AppStrings.RestoreThisPoint, AppStrings.RestorePointConfirm, AppStrings.Restore).ConfigureAwait(false); - if (!confirmed) return false; - - try - { - // Safety backup of the live save before anything destructive — never in-place. - var live = await OpenSnapshotAsync(savePath, cancellationToken).ConfigureAwait(false); - if (live is not null) - { - var safetyName = RestorePointRules.NameFor(RestorePointKind.SafetyBeforeRestore, DateTimeOffset.UtcNow, AppStrings.Fr); - await backups.CreateAsync(live, safetyName, savePath, cancellationToken).ConfigureAwait(false); - } - - var bytes = await backups.ReadAsync(backupId, cancellationToken).ConfigureAwait(false); // hash-checked - WriteAtomically(savePath, bytes.Span); - return true; - } - catch (Exception error) - { - AppLog.Error("companion", $"Restore of {backupId} into {savePath} failed", error); - return false; - } - } - - /// Opens the save file as a snapshot for backup matching; null when unreadable/unrecognized. - private async Task OpenSnapshotAsync(string savePath, CancellationToken cancellationToken) - { - try - { - var bytes = await Task.Run(() => File.ReadAllBytes(savePath), cancellationToken).ConfigureAwait(false); - if (!engine.Validate(bytes)) return null; - return engine.Open(bytes, Path.GetFileName(savePath)); - } - catch (Exception error) - { - AppLog.Info("companion", $"Reading {savePath} for a restore point failed: {error.Message}"); - return null; - } - } - - /// Temp file + move: the live save is never written in-place mid-flush. - private static void WriteAtomically(string path, ReadOnlySpan bytes) - { - var temp = path + ".restore-tmp"; - File.WriteAllBytes(temp, bytes.ToArray()); - File.Move(temp, path, overwrite: true); - } -} diff --git a/src/PKForge.App/Services/GameCompanionPreferences.cs b/src/PKForge.App/Services/GameCompanionPreferences.cs new file mode 100644 index 00000000..0e77b63c --- /dev/null +++ b/src/PKForge.App/Services/GameCompanionPreferences.cs @@ -0,0 +1,59 @@ +namespace PKForge.App.Services; + +public enum GameCompanionTab +{ + Party, + Bag, + Pokedex, + Session, + RestorePoints, +} + +/// Persists the lower-screen companion's visible tabs and opening tab. +public static class GameCompanionPreferences +{ + private const string TabsKey = "game_companion_tabs"; + private const string HomeTabKey = "game_companion_home_tab"; + private static readonly GameCompanionTab[] DefaultTabs = + [GameCompanionTab.Party, GameCompanionTab.Bag, GameCompanionTab.Pokedex, GameCompanionTab.Session]; + + public static IReadOnlyList VisibleTabs + { + get + { + var raw = Preferences.Default.Get(TabsKey, string.Join(',', DefaultTabs)); + var tabs = raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(value => Enum.TryParse(value, out var tab) ? tab : (GameCompanionTab?)null) + .Where(tab => tab.HasValue) + .Select(tab => tab!.Value) + .Distinct() + .ToArray(); + return tabs.Length == 0 ? DefaultTabs : tabs; + } + } + + public static GameCompanionTab HomeTab + { + get + { + var raw = Preferences.Default.Get(HomeTabKey, nameof(GameCompanionTab.Party)); + return Enum.TryParse(raw, out var tab) && VisibleTabs.Contains(tab) + ? tab + : VisibleTabs[0]; + } + } + + public static void ToggleTab(GameCompanionTab tab) + { + var tabs = VisibleTabs.ToList(); + if (!tabs.Remove(tab)) tabs.Add(tab); + if (tabs.Count == 0) return; + Preferences.Default.Set(TabsKey, string.Join(',', tabs)); + if (!tabs.Contains(HomeTab)) SetHomeTab(tabs[0]); + } + + public static void SetHomeTab(GameCompanionTab tab) + { + if (VisibleTabs.Contains(tab)) Preferences.Default.Set(HomeTabKey, tab.ToString()); + } +} diff --git a/src/PKForge.App/Services/GameCompanionStore.cs b/src/PKForge.App/Services/GameCompanionStore.cs index 0c0cd319..c6ce79f8 100644 --- a/src/PKForge.App/Services/GameCompanionStore.cs +++ b/src/PKForge.App/Services/GameCompanionStore.cs @@ -17,10 +17,54 @@ public sealed partial class GameCompanionStore : ObservableObject, IGameCompanio [ObservableProperty] private ExternalCompanionSnapshot? _external; - public void Start(GameCompanion companion) => Current = companion; + [ObservableProperty] private bool _speedControlAvailable; + + [ObservableProperty] private int _speedMultiplier = 1; + + private Action? _applySpeedMultiplier; + + public void Start(GameCompanion companion) + { + ClearSpeedControl(); + Live = null; + External = null; + Current = companion; + } public void UpdateLive(LiveCompanionSnapshot snapshot) => Live = snapshot; + public void BindSpeedControl(int multiplier, Action apply) + { + ArgumentNullException.ThrowIfNull(apply); + if (multiplier is < 1 or > 4) + throw new ArgumentOutOfRangeException(nameof(multiplier)); + + _applySpeedMultiplier = apply; + SpeedMultiplier = multiplier; + SpeedControlAvailable = true; + } + + public void RequestSpeedMultiplier(int multiplier) + { + if (multiplier is < 1 or > 4) + throw new ArgumentOutOfRangeException(nameof(multiplier)); + if (SpeedControlAvailable) + _applySpeedMultiplier?.Invoke(multiplier); + } + + public void UpdateSpeedMultiplier(int multiplier) + { + if (multiplier is < 1 or > 4) + throw new ArgumentOutOfRangeException(nameof(multiplier)); + SpeedMultiplier = multiplier; + } + + public void ClearSpeedControl() + { + _applySpeedMultiplier = null; + SpeedControlAvailable = false; + } + public void ClearLive() => Live = null; public void UpdateExternal(ExternalCompanionSnapshot snapshot) => External = snapshot; @@ -29,6 +73,7 @@ public sealed partial class GameCompanionStore : ObservableObject, IGameCompanio public void Stop() { + ClearSpeedControl(); Current = null; Live = null; External = null; @@ -47,11 +92,19 @@ public async Task StartForGameAsync(RomLink link) var points = new List(); try { - if (services?.GetService() is { } backups) + // Only show points when they can be tied to this exact linked save. + // Library-only links and external emulator saves have no safe match here. + if (link.Emulator == EmulatorKind.Embedded + && !string.IsNullOrWhiteSpace(link.SaveDocumentId) + && !string.Equals(link.SaveDocumentId, "library", StringComparison.OrdinalIgnoreCase) + && services?.GetService() is { } backups) { - foreach (var info in await backups.ListAsync()) - points.Add(new CompanionRestorePoint(info.BackupId, info.CreatedUtc, info.Sha256)); - points.Reverse(); // newest first + var linkedPoints = (await backups.ListAsync()) + .Where(info => string.Equals(info.DocumentId, link.SaveDocumentId, StringComparison.Ordinal)) + .OrderByDescending(info => info.CreatedUtc) + .Take(8); + points.AddRange(linkedPoints.Select(info => + new CompanionRestorePoint(info.BackupId, info.CreatedUtc, info.Sha256))); } } catch (Exception error) diff --git a/src/PKForge.App/Services/IDualScreenGameDisplayHost.cs b/src/PKForge.App/Services/IDualScreenGameDisplayHost.cs new file mode 100644 index 00000000..b432d7c1 --- /dev/null +++ b/src/PKForge.App/Services/IDualScreenGameDisplayHost.cs @@ -0,0 +1,19 @@ +using PKForge.App.Platforms.Android; + +namespace PKForge.App.Services; + +/// Routes a dual-screen console's second framebuffer to Android's secondary display. +public interface IDualScreenGameDisplayHost +{ + event Action? DisplayContentChanged; + + bool IsShowingNintendoDsBottomScreen(IEmbeddedGameSession session); + + Task ShowNintendoDsBottomScreenAsync( + IEmbeddedGameSession session, + CancellationToken cancellationToken = default); + + ValueTask RestoreDefaultScreenAsync( + IEmbeddedGameSession session, + CancellationToken cancellationToken = default); +} diff --git a/src/PKForge.App/Services/TransferService.cs b/src/PKForge.App/Services/TransferService.cs index f512dbc7..08125b16 100644 --- a/src/PKForge.App/Services/TransferService.cs +++ b/src/PKForge.App/Services/TransferService.cs @@ -4,7 +4,12 @@ namespace PKForge.App.Services; /// Outcome of a bank-to-game or game-to-game transfer. -public sealed record TransferOutcome(bool Success, string Message, int Box = -1, int Slot = -1, string? BackupId = null); +public sealed record TransferOutcome(bool Success, string Message, int Box = -1, int Slot = -1, + string? BackupId = null, TransferLanding? Landing = null); + +/// The destination slot and exact exported bytes written there. The receipt lets a +/// failed move undo only the Pokémon that this transfer placed, never a later replacement. +public sealed record TransferLanding(string DocumentId, SlotRef Slot, byte[] Data); /// /// Pre-flight answer for a transfer: what the conversion will change and a legality @@ -71,8 +76,11 @@ public async Task SendToGameAsync( ? Refusal(entityBytes, nickname, snapshot, target.GameLabel, format) : $"{nickname} cannot go to {target.GameLabel}. {refusal}"); + var landed = session.ExportSlot(landing.Box, landing.Slot); var receipt = await WriteTargetAsync(target, snapshot, session, $"{nickname} arrived from a transfer", cancellationToken).ConfigureAwait(false); - return new TransferOutcome(true, $"{nickname} joined {target.GameLabel} (box {landing.Box + 1}).", landing.Box, landing.Slot, receipt.BackupId); + return new TransferOutcome(true, $"{nickname} joined {target.GameLabel} (box {landing.Box + 1}).", + landing.Box, landing.Slot, receipt.BackupId, + new TransferLanding(target.DocumentId, landing, landed.Data.ToArray())); } /// @@ -102,10 +110,10 @@ public static bool TryImport(ISaveEngineSession session, int box, int slot, byte /// /// Places a whole batch in the target save's free slots (from ) in - /// one write, or writes nothing and says which Pokémon could not enter and why. Returns the - /// slots the batch took, for to undo it. + /// one write, or writes nothing and says which Pokémon could not enter and why. Returns an + /// exact receipt for each slot, so a later undo cannot release a Pokémon that replaced it. /// - public async Task<(string? Refusal, IReadOnlyList Landed)> SendManyToGameAsync( + public async Task<(string? Refusal, IReadOnlyList Landed)> SendManyToGameAsync( IReadOnlyList items, DetectedSave target, string changeDescription, CancellationToken cancellationToken = default, SlotRef? startAt = null) { @@ -122,21 +130,47 @@ public static bool TryImport(ISaveEngineSession session, int box, int slot, byte ? Refusal(item.Data, item.Nickname, snapshot, target.GameLabel, item.Format) : $"{item.Nickname} cannot go to {target.GameLabel}. {refusal}", []); } + var landed = rooms.Select(room => + { + var export = session.ExportSlot(room.Box, room.Slot); + return new TransferLanding(target.DocumentId, room, export.Data.ToArray()); + }).ToArray(); await WriteTargetAsync(target, snapshot, session, changeDescription, cancellationToken).ConfigureAwait(false); - return (null, rooms); + return (null, landed); } - /// Empties of the target save in one write: the undo of - /// a batch that reached it but could not leave its source. - public async Task ReleaseFromGameAsync(DetectedSave target, IReadOnlyList slots, string changeDescription, + /// Undo of an import whose source could not release its Pokémon. Every destination + /// slot is re-read and compared before any mutation; if one changed, nothing is removed. + public async Task UndoTransferAsync(DetectedSave target, IReadOnlyList landed, + string changeDescription, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(landed); + if (landed.Count == 0) return "The destination receipt is empty."; + using var session = await OpenTargetAsync(target, cancellationToken).ConfigureAwait(false); var snapshot = session.Snapshot; - foreach (var slot in slots) - session.ReleaseSlot(slot.Box, slot.Slot); + + var seen = new HashSet(); + foreach (var transfer in landed) + { + if (!string.Equals(transfer.DocumentId, target.DocumentId, StringComparison.Ordinal)) + return "The destination receipt belongs to a different save."; + if (!seen.Add(transfer.Slot)) + return $"The destination receipt repeats box {transfer.Slot.Box + 1}, slot {transfer.Slot.Slot + 1}."; + if (!snapshot.Slots.Any(slot => slot.Box == transfer.Slot.Box && slot.Slot == transfer.Slot.Slot)) + return $"Box {transfer.Slot.Box + 1}, slot {transfer.Slot.Slot + 1} no longer exists in {target.GameLabel}."; + + var current = session.ExportSlot(transfer.Slot.Box, transfer.Slot.Slot); + if (!current.Data.AsSpan().SequenceEqual(transfer.Data)) + return $"Box {transfer.Slot.Box + 1}, slot {transfer.Slot.Slot + 1} changed after the transfer; it was left untouched."; + } + + foreach (var transfer in landed) + session.ReleaseSlot(transfer.Slot.Box, transfer.Slot.Slot); await WriteTargetAsync(target, snapshot, session, changeDescription, cancellationToken).ConfigureAwait(false); + return null; } /// Writes a throwaway target session back through the safe path (validate, backup, atomic write). diff --git a/src/PKForge.App/Views/BankPage.cs b/src/PKForge.App/Views/BankPage.cs index 5703e145..0e84e0b7 100644 --- a/src/PKForge.App/Views/BankPage.cs +++ b/src/PKForge.App/Views/BankPage.cs @@ -1065,18 +1065,14 @@ private async Task SendSelectionToGameAsync(List selection) var preview = await transfer.PreviewAsync(items[0].Data, items[0].Nickname, target, format: items[0].Format); if (!await Services.TransferPreviewPrompt.ConfirmAsync(_hostGrid, preview, subject, target.GameLabel)) return; - IReadOnlyList landed = []; + IReadOnlyList landed = []; outcome = await PKForge.Engine.BankTransfers.WithdrawAsync(_bank, ids, target.GameLabel, async () => { (var refusal, landed) = await transfer.SendManyToGameAsync(items, target, $"{subject} arrived from the bank"); return refusal; }, - async () => - { - await transfer.ReleaseFromGameAsync(target, landed, $"{subject} went back to the bank"); - return null; - }); + async () => await transfer.UndoTransferAsync(target, landed, $"{subject} went back to the bank")); } if (outcome.Success || outcome.Duplicated) FinishOrganizer(outcome.Message); @@ -1560,6 +1556,7 @@ private async Task SendToGamePickerAsync(BankEntry entry, bool keepOriginal = fa var bytes = _bank.GetData(entry.Id); var nickname = entry.Info.Nickname; var format = entry.Info.Format; + var sourceRemoved = false; if (destination.Other is null) { @@ -1584,12 +1581,36 @@ private async Task SendToGamePickerAsync(BankEntry entry, bool keepOriginal = fa var target = destination.Other; var preview = await transfer.PreviewAsync(bytes, nickname, target, format: format); if (!await Services.TransferPreviewPrompt.ConfirmAsync(_hostGrid, preview, nickname, target.GameLabel)) return; - var outcome = await transfer.SendToGameAsync(bytes, nickname, target, format: format); - _boxViewModel.Status = outcome.Message; - if (!outcome.Success) return; + if (keepOriginal) + { + var copied = await transfer.SendToGameAsync(bytes, nickname, target, format: format); + _boxViewModel.Status = copied.Message; + if (!copied.Success) return; + } + else + { + Services.TransferLanding? landed = null; + var outcome = await PKForge.Engine.BankTransfers.WithdrawAsync(_bank, [entry.Id], target.GameLabel, + async () => + { + var sent = await transfer.SendToGameAsync(bytes, nickname, target, format: format); + landed = sent.Landing; + return sent.Success ? null : sent.Message; + }, + async () => landed is null + ? "The destination did not return a slot receipt." + : await transfer.UndoTransferAsync(target, [landed], $"{nickname} returned to the Bank: the transfer was undone")); + _boxViewModel.Status = outcome.Message; + if (!outcome.Success) + { + if (outcome.Duplicated) { RefreshBoxEntries(); UpdatePreview(); } + return; + } + sourceRemoved = true; + } } - if (!keepOriginal) + if (!keepOriginal && !sourceRemoved) { _bank.Remove(entry.Id); RefreshBoxEntries(); @@ -1939,9 +1960,6 @@ private static void PaintDexEntry(SKCanvas canvas, SKRect area, List lin SummaryInk.Draw(canvas, $"Pokémon {version}", area.Right, y - SummaryInk.Leading(size), size, EditorPaint.Cyan, align: SKTextAlign.Right); } - private static SKColor ToSk(Color color) => - new((byte)(color.Red * 255), (byte)(color.Green * 255), (byte)(color.Blue * 255)); - /// A new Pokédex entry every little while, like flipping through the dex. private void StartFactRotation() { diff --git a/src/PKForge.App/Views/BoxBrowserPage.cs b/src/PKForge.App/Views/BoxBrowserPage.cs index af909868..b5a0c4c6 100644 --- a/src/PKForge.App/Views/BoxBrowserPage.cs +++ b/src/PKForge.App/Views/BoxBrowserPage.cs @@ -1334,7 +1334,7 @@ private async Task SendSelectionToGameAsync(bool copy) // these slots in one write, and a failed release takes the batch back out of that game. var items = marked.Select(m => session.ExportSlot(m.Box, m.Slot)) .Select(export => new PKForge.Engine.TransferItem(export.Data, export.Format, export.FileName)).ToArray(); - IReadOnlyList landed = []; + IReadOnlyList landed = []; var outcome = await PKForge.Engine.BankTransfers.MoveAsync(items.Length, target.GameLabel, async () => { @@ -1342,12 +1342,27 @@ private async Task SendSelectionToGameAsync(bool copy) $"{items.Length} Pokémon arrived from a transfer", startAt: startAt); return refusal; }, - copy ? null : async () => await _viewModel.BulkReleaseAsync(marked) ? null : _viewModel.Status, - async () => + copy ? null : async () => { - await transfer.ReleaseFromGameAsync(target, landed, $"{items.Length} Pokémon sent back: the transfer was undone"); - return null; - }); + var released = await _viewModel.RunMutationAsync(s => + { + for (var i = 0; i < marked.Length; i++) + { + var current = s.ExportSlot(marked[i].Box, marked[i].Slot); + if (!current.Data.AsSpan().SequenceEqual(items[i].Data)) + return new GenerationOutcome(false, + $"{BoxBrowserViewModel.SlotLabel(marked[i].Box, marked[i].Slot)} changed during transfer; all source Pokémon were left untouched."); + } + foreach (var (box, slot) in marked) + s.ReleaseSlot(box, slot); + return new GenerationOutcome(true, $"Moved {items.Length} Pokémon to {target.GameLabel}."); + }, Math.Max(0, _viewModel.SelectedSlot), refreshSlot: false, action: SaveAction.Move); + _viewModel.RefreshAllSlots(); + if (released) _viewModel.ClearMarksQuietly(); + return released ? null : _viewModel.Status; + }, + async () => await transfer.UndoTransferAsync(target, landed, + $"{items.Length} Pokémon sent back: the transfer was undone")); if (outcome.Success && copy) _viewModel.ClearMarksQuietly(); _viewModel.Status = outcome.Message; } @@ -4161,8 +4176,8 @@ private async Task ShowRandomTeamAsync() } /// - /// Game-to-game: pick any other detected save, the transfer service converts and - /// writes there, then the mon leaves this box (a real move, not a copy). + /// Game-to-game: preview, write the destination, release the source, and undo the + /// destination if the source write fails. The destination undo verifies its receipt. /// private async Task SendSlotToAnotherGameAsync(int slot, string nickname, bool copyInsteadOfMove = false) { @@ -4196,17 +4211,28 @@ private async Task SendSlotToAnotherGameAsync(int slot, string nickname, bool co var export = session.ExportSlot(_viewModel.BoxIndex, slot); // Cross-generation conversions change things; the diff preview is the trust // step before the write. Same-generation sends show an empty diff. - var preview = await transfer.PreviewAsync(export.Data, nickname, target); + var preview = await transfer.PreviewAsync(export.Data, nickname, target, format: export.Format); if (!await Services.TransferPreviewPrompt.ConfirmAsync(_hostGrid, preview, nickname, target.GameLabel)) return; - var outcome = await transfer.SendToGameAsync(export.Data, nickname, target); + Services.TransferLanding? landed = null; + var outcome = await PKForge.Engine.BankTransfers.MoveAsync(1, target.GameLabel, + async () => + { + var sent = await transfer.SendToGameAsync(export.Data, nickname, target, format: export.Format); + landed = sent.Landing; + return sent.Success ? null : sent.Message; + }, + copyInsteadOfMove ? null : async () => await _viewModel.RunMutationAsync(s => + { + var current = s.ExportSlot(_viewModel.BoxIndex, slot); + if (!current.Data.AsSpan().SequenceEqual(export.Data)) + return new GenerationOutcome(false, $"{nickname} changed in this save during transfer; the source was left untouched."); + s.ReleaseSlot(_viewModel.BoxIndex, slot); + return new GenerationOutcome(true, $"{nickname} moved to {target.GameLabel}."); + }, slot, action: SaveAction.Move) ? null : _viewModel.Status, + async () => landed is null + ? "The destination did not return a slot receipt." + : await transfer.UndoTransferAsync(target, [landed], $"{nickname} returned: the transfer was undone")); _viewModel.Status = outcome.Message; - if (!outcome.Success || copyInsteadOfMove) return; - - await _viewModel.RunMutationAsync(s => - { - s.ReleaseSlot(_viewModel.BoxIndex, slot); - return new GenerationOutcome(true, $"{nickname} moved to {target.GameLabel}."); - }, slot, action: SaveAction.Move); } /// Writes the decrypted .pk* file and hands it to Android's share sheet. diff --git a/src/PKForge.App/Views/CollectionDexPage.cs b/src/PKForge.App/Views/CollectionDexPage.cs index 5cd6b000..b06c836e 100644 --- a/src/PKForge.App/Views/CollectionDexPage.cs +++ b/src/PKForge.App/Views/CollectionDexPage.cs @@ -12,10 +12,10 @@ namespace PKForge.App.Views; /// /// The living-dex tracker, HOME-style: every species of the national dex as a sprite -/// cell, colored by what your collection actually contains (bank plus open save), not -/// by dex flags. Normal living dex and shiny living dex each get their own view; -/// per-generation scopes show how far each era is, and the "this game" scope matches -/// the open save. A missing species can jump straight into "How to get" to plan the +/// cell, colored by what your collection actually contains (bank plus every linked save), +/// not by dex flags. Normal living dex and shiny living dex each get their own view; +/// per-generation scopes show how far each era is, and "this game" reads only the open +/// save. A missing species can jump straight into "How to get" to plan the /// catch. The forms view lists every collectible form (Unown letters, Vivillon patterns, /// regional forms...) of the species that have several, missing ones as silhouettes. /// Read-only: nothing here writes a save or the bank. @@ -35,6 +35,10 @@ public sealed class CollectionDexPage : IPadPagingHandler private readonly HashSet _shiny = []; private readonly HashSet _ownedForms = []; private readonly HashSet _shinyForms = []; + private readonly HashSet _gameOwned = []; + private readonly HashSet _gameShiny = []; + private readonly HashSet _gameOwnedForms = []; + private readonly HashSet _gameShinyForms = []; private readonly List _allIds = []; private readonly List _formIds = []; private readonly List _viewIds = []; @@ -140,6 +144,7 @@ private CollectionDexPage(Grid host, BoxBrowserViewModel viewModel, ISaveEngineS _ = Task.Run(async () => { var collection = await CollectAsync(_session); + var thisGame = CurrentGameCollection(); var catalog = LivingDexCatalogBuilder.Build(); var storable = _session is null ? null : LivingDexCatalogBuilder.StorableIn(_session); @@ -147,7 +152,7 @@ private CollectionDexPage(Grid host, BoxBrowserViewModel viewModel, ISaveEngineS // counts all nine; "this game" is only a view filter (RefreshView). MainThread.BeginInvokeOnMainThread(() => { - Apply(collection); + Apply(collection, thisGame); _allIds.AddRange(Enumerable.Range(1, Math.Min(CollectionDex.MaxSpecies, _data.SpeciesNames.Count - 1)) .Where(id => _data.SpeciesNames[id].Length > 0)); _formIds.AddRange(_allIds.Where(id => catalog.Forms.ContainsKey(id)) @@ -204,13 +209,18 @@ private CollectionDexPage(Grid host, BoxBrowserViewModel viewModel, ISaveEngineS return collection; } - private void Apply(List<(int Species, int Form, bool Shiny)> collection) + private void Apply(List<(int Species, int Form, bool Shiny)> collection, + IReadOnlyList<(int Species, int Form, bool Shiny)> thisGame) { _progressData = CollectionDex.Compute(collection.Select(c => (c.Species, c.Shiny)), CollectionDex.MaxSpecies, _data.SpeciesNames); _owned.Clear(); _shiny.Clear(); _ownedForms.Clear(); _shinyForms.Clear(); + _gameOwned.Clear(); + _gameShiny.Clear(); + _gameOwnedForms.Clear(); + _gameShinyForms.Clear(); foreach (var (species, form, shiny) in collection) { if (species < 1 || species >= _data.SpeciesNames.Count || _data.SpeciesNames[species].Length == 0) continue; @@ -222,8 +232,26 @@ private void Apply(List<(int Species, int Form, bool Shiny)> collection) _shinyForms.Add(Key(species, form)); } } + foreach (var (species, form, shiny) in thisGame) + { + if (species < 1 || species >= _data.SpeciesNames.Count || _data.SpeciesNames[species].Length == 0) continue; + _gameOwned.Add(species); + _gameOwnedForms.Add(Key(species, form)); + if (shiny) + { + _gameShiny.Add(species); + _gameShinyForms.Add(Key(species, form)); + } + } } + private IReadOnlyList<(int Species, int Form, bool Shiny)> CurrentGameCollection() => + _session?.Snapshot.Slots + .Where(slot => slot.Species is > 0 && !slot.IsEgg) + .Select(slot => (slot.Species!.Value, slot.Form, slot.IsShiny)) + .ToArray() + ?? Array.Empty<(int Species, int Form, bool Shiny)>(); + private static int Key(int species, int form) => species | (form << 16); private static int SpeciesOf(int key) => key & 0xFFFF; private static int FormOf(int key) => key >> 16; @@ -232,7 +260,7 @@ private void Apply(List<(int Species, int Form, bool Shiny)> collection) private (int Owned, int Total) Tally(int? scope) { var cells = InScope(_formsDex ? _formIds : _allIds, scope).ToList(); - return (cells.Count(IsOwned), cells.Count); + return (cells.Count(IsOwnedInView), cells.Count); } private IEnumerable InScope(IEnumerable cells, int? scope) @@ -287,7 +315,7 @@ private void RefreshChrome() { var cap = _session?.MaxSpeciesId ?? CollectionDex.MaxSpecies; var ids = _allIds.Where(id => id <= cap).ToList(); - return (ids.Count(IsOwned), ids.Count); + return (ids.Count(IsOwnedInView), ids.Count); } var segment = _progressData.Segments.FirstOrDefault(s => s.Generation == _genScope); return segment is null ? (0, 0) : (_shinyDex ? segment.Shiny : segment.Owned, segment.Total); @@ -340,16 +368,25 @@ private Grid TitleRow() return row; } - private bool IsOwned(int key) => _formsDex - ? (_shinyDex ? _shinyForms : _ownedForms).Contains(key) - : (_shinyDex ? _shiny : _owned).Contains(SpeciesOf(key)); + private bool IsOwnedInView(int key) + { + if (_genScope == 0) + { + if (_formsDex) return (_shinyDex ? _gameShinyForms : _gameOwnedForms).Contains(key); + return (_shinyDex ? _gameShiny : _gameOwned).Contains(SpeciesOf(key)); + } + if (_formsDex) return (_shinyDex ? _shinyForms : _ownedForms).Contains(key); + return (_shinyDex ? _shiny : _owned).Contains(SpeciesOf(key)); + } - private bool IsShinyOwned(int key) => _formsDex ? _shinyForms.Contains(key) : _shiny.Contains(SpeciesOf(key)); + private bool IsShinyOwnedInView(int key) => _formsDex + ? (_genScope == 0 ? _gameShinyForms : _shinyForms).Contains(key) + : (_genScope == 0 ? _gameShiny : _shiny).Contains(SpeciesOf(key)); private void RefreshView() { var view = InScope(_formsDex ? _formIds : _allIds, _genScope); - if (_missingOnly) view = view.Where(id => !IsOwned(id)); + if (_missingOnly) view = view.Where(id => !IsOwnedInView(id)); _viewIds.Clear(); _viewIds.AddRange(view); _grid.Show(_viewIds, LookOf, identify: key => (SpeciesOf(key), FormOf(key))); @@ -360,8 +397,8 @@ private void RefreshView() /// Owned entries in colour with their ball, missing ones as silhouettes, shinies starred. private DexGridView.Look LookOf(int key) { - var owned = IsOwned(key); - return new DexGridView.Look(Seen: owned, Caught: owned, Shiny: _shinyDex && owned, ShinyMark: IsShinyOwned(key)); + var owned = IsOwnedInView(key); + return new DexGridView.Look(Seen: owned, Caught: owned, Shiny: _shinyDex && owned, ShinyMark: IsShinyOwnedInView(key)); } private void RefreshCursorInfo() @@ -373,9 +410,9 @@ private void RefreshCursorInfo() } var key = _viewIds[Math.Min(_grid.Cursor, Count - 1)]; var id = SpeciesOf(key); - var state = IsShinyOwned(key) + var state = IsShinyOwnedInView(key) ? (_shinyDex ? "Shiny owned" : "Owned + shiny") - : (_formsDex ? _ownedForms.Contains(key) : _owned.Contains(id)) ? "Owned" : "Missing"; + : IsOwnedInView(key) ? "Owned" : "Missing"; _cursorInfo.Text = $"#{id:000} {CellName(key)} · {state}"; } @@ -446,7 +483,7 @@ private async Task ShowActionsAsync() // A catch may have added a species; recount before returning. National scope, // same as the initial count: a catch must never shrink the header to game scope. - Apply(await CollectAsync(_session)); + Apply(await CollectAsync(_session), CurrentGameCollection()); RefreshView(); } } @@ -464,7 +501,7 @@ private async Task OpenAutopilotAsync() { _router?.Push(this); } - Apply(await CollectAsync(_session)); + Apply(await CollectAsync(_session), CurrentGameCollection()); RefreshView(); } diff --git a/src/PKForge.App/Views/EmbeddedGamePage.cs b/src/PKForge.App/Views/EmbeddedGamePage.cs index 5cd2d31b..8206bd71 100644 --- a/src/PKForge.App/Views/EmbeddedGamePage.cs +++ b/src/PKForge.App/Views/EmbeddedGamePage.cs @@ -1,5 +1,6 @@ using PKForge.App.Platforms.Android; using PKForge.App.Services; +using PKForge.App.Theme; using SkiaSharp; using SkiaSharp.Views.Maui; using SkiaSharp.Views.Maui.Controls; @@ -7,30 +8,495 @@ namespace PKForge.App.Views; /// -/// The embedded game screen (option A): the mGBA core renders the game in-process -/// and this page blits it. Pixel-crisp: integer scaling only (a fractional scale -/// would smear the GBA's 240×160), letterboxed when the screen's ratio isn't 3:2. +/// The embedded game screen: mGBA or melonDS renders in-process and this page +/// scales the framebuffer to the available screen while preserving its aspect ratio. /// public sealed class EmbeddedGamePage : ContentPage, IPadHandler, IPadReleaseHandler { private readonly SKCanvasView _canvas = new() { IgnorePixelScaling = true }; - private readonly EmbeddedGameSession _session; + private readonly IEmbeddedGameSession _session; + private readonly IDualScreenGameDisplayHost? _dualScreenHost; private readonly Dictionary _held = []; + private readonly HashSet _touchHeld = []; private readonly object _heldGate = new(); + private readonly Button _pauseButton; + private readonly Button _optionsButton; + private readonly Button _floatingOptionsButton; + private readonly Button _loadStateButton; + private readonly Grid _header; + private readonly VerticalStackLayout _footer; + private Grid _touchControls = null!; + private Grid _hostGrid = null!; + private bool _exitStarted; + private volatile bool _pageVisible; + private bool _usingSeparateDsDisplays; + private Domain.GameCompanion? _companionOwner; + private GameCompanionStore? _companionStore; + private readonly Label _status = new() + { + FontFamily = "PixelUI", + FontSize = 10, + TextColor = Colors.LightGray, + HorizontalTextAlignment = TextAlignment.Center, + }; + private bool _userPaused; + private Task? _suspendSaveTask; + private SKRect _gameRect; + private long _stylusPointerId = -1; - public EmbeddedGamePage(EmbeddedGameSession session) + public EmbeddedGamePage(IEmbeddedGameSession session) { _session = session ?? throw new ArgumentNullException(nameof(session)); + _dualScreenHost = IPlatformApplication.Current?.Services.GetService(); BackgroundColor = Colors.Black; - Content = _canvas; + _session.SetSpeedMultiplier(EmbeddedGamePreferences.SpeedMultiplier); + + _pauseButton = ActionButton(AppStrings.GamePause); + _optionsButton = ActionButton(AppStrings.GameOptions); + _floatingOptionsButton = new Button + { + Text = "⚙", + FontSize = 18, + TextColor = Colors.White, + BackgroundColor = Color.FromArgb("#AA17141F"), + BorderColor = Color.FromArgb("#B0FFFFFF"), + BorderWidth = 1, + CornerRadius = 20, + Padding = new Thickness(6, 0), + WidthRequest = 72, + HeightRequest = 42, + HorizontalOptions = LayoutOptions.End, + VerticalOptions = LayoutOptions.Start, + Margin = new Thickness(10), + }; + _loadStateButton = ActionButton(AppStrings.GameLoadState); + _pauseButton.Clicked += (_, _) => TogglePause(); + _optionsButton.Clicked += async (_, _) => await ShowOptionsAsync(); + _floatingOptionsButton.Clicked += async (_, _) => await ShowOptionsAsync(); + _loadStateButton.Clicked += async (_, _) => await LoadStateAsync(); + UpdateSpeedIndicators(); + + var saveStateButton = ActionButton(AppStrings.GameSaveState); + saveStateButton.Clicked += async (_, _) => await SaveStateAsync(); + var exitButton = ActionButton(AppStrings.GameExit); + exitButton.Clicked += async (_, _) => await ExitGameAsync(); + + _header = new Grid + { + Padding = new Thickness(12, 6), + ColumnDefinitions = [new(GridLength.Star), new(GridLength.Auto), new(GridLength.Auto), new(GridLength.Auto)], + ColumnSpacing = 8, + BackgroundColor = Color.FromArgb("#17141F"), + Children = + { + new Label + { + Text = string.IsNullOrWhiteSpace(_session.GameTitle) ? "PKForge" : _session.GameTitle, + FontFamily = "PixelUI", + FontSize = 13, + TextColor = Colors.White, + VerticalTextAlignment = TextAlignment.Center, + LineBreakMode = LineBreakMode.TailTruncation, + }, + _pauseButton, + _optionsButton, + exitButton, + }, + }; + Grid.SetColumn(_pauseButton, 1); + Grid.SetColumn(_optionsButton, 2); + Grid.SetColumn(exitButton, 3); + + var actions = new HorizontalStackLayout + { + Spacing = 8, + HorizontalOptions = LayoutOptions.Center, + Children = { saveStateButton, _loadStateButton }, + }; + _footer = new VerticalStackLayout + { + Spacing = 4, + Padding = new Thickness(8, 6), + BackgroundColor = Color.FromArgb("#17141F"), + Children = { actions }, + }; + + _touchControls = BuildTouchControls(); + _status.HorizontalOptions = LayoutOptions.Center; + _status.VerticalOptions = LayoutOptions.Start; + _status.Margin = new Thickness(48, 12, 48, 0); + _status.Padding = new Thickness(8, 4); + _status.BackgroundColor = Color.FromArgb("#AA17141F"); + _status.IsVisible = false; + var playfield = new Grid { Children = { _canvas, _touchControls, _status, _floatingOptionsButton } }; + var layout = new Grid + { + RowDefinitions = [new(GridLength.Auto), new(GridLength.Star), new(GridLength.Auto)], + Children = { _header, playfield, _footer }, + }; + _hostGrid = layout; + Grid.SetRow(playfield, 1); + Grid.SetRow(_footer, 2); + Content = layout; + + _touchControls.IsVisible = EmbeddedGameDisplayPreferences.TouchControlsVisible; + _floatingOptionsButton.IsVisible = EmbeddedGameDisplayPreferences.FullScreen; + _header.IsVisible = !EmbeddedGameDisplayPreferences.FullScreen; + _footer.IsVisible = !EmbeddedGameDisplayPreferences.FullScreen; + NavigationPage.SetHasNavigationBar(this, !EmbeddedGameDisplayPreferences.FullScreen); + _canvas.PaintSurface += OnPaint; + _canvas.EnableTouchEvents = session.SupportsTouchScreen; + if (session.SupportsTouchScreen) _canvas.Touch += OnCanvasTouch; _session.FrameProduced += Invalidate; + UpdateStateActions(); + } + + private static Button ActionButton(string text) => new() + { + Text = text, + FontFamily = "PixelUI", + FontSize = 10, + TextColor = Colors.White, + BackgroundColor = Color.FromArgb("#342F43"), + CornerRadius = 6, + Padding = new Thickness(10, 5), + MinimumHeightRequest = 36, + }; + + private Grid BuildTouchControls() + { + var directions = new Grid + { + WidthRequest = 156, + HeightRequest = 156, + RowDefinitions = [new(48), new(48), new(48)], + ColumnDefinitions = [new(48), new(48), new(48)], + RowSpacing = 4, + ColumnSpacing = 4, + HorizontalOptions = LayoutOptions.Start, + VerticalOptions = LayoutOptions.End, + }; + AddTouchButton(directions, PadButton.Up, "↑", 0, 1, 48); + AddTouchButton(directions, PadButton.Left, "←", 1, 0, 48); + AddTouchButton(directions, PadButton.Right, "→", 1, 2, 48); + AddTouchButton(directions, PadButton.Down, "↓", 2, 1, 48); + + var actions = new Grid + { + WidthRequest = 128, + HeightRequest = 128, + RowDefinitions = [new(60), new(60)], + ColumnDefinitions = [new(60), new(60)], + RowSpacing = 8, + ColumnSpacing = 8, + HorizontalOptions = LayoutOptions.End, + VerticalOptions = LayoutOptions.End, + }; + AddTouchButton(actions, PadButton.B, "B", 1, 0, 60); + AddTouchButton(actions, PadButton.A, "A", 0, 1, 60); + if (_session.IsNintendoDs) + { + AddTouchButton(actions, PadButton.X, "X", 0, 0, 60); + AddTouchButton(actions, PadButton.Y, "Y", 1, 1, 60); + } + + var systemButtons = new HorizontalStackLayout + { + Spacing = 8, + HorizontalOptions = LayoutOptions.Center, + VerticalOptions = LayoutOptions.End, + Children = + { + TouchButton(PadButton.Select, "Select", 72, 38, 8), + TouchButton(PadButton.Start, "Start", 72, 38, 8), + }, + }; + + var overlay = new Grid + { + Padding = new Thickness(12), + ColumnDefinitions = [new(GridLength.Star), new(GridLength.Auto), new(GridLength.Star)], + Children = { directions, systemButtons, actions }, + }; + Grid.SetColumn(systemButtons, 1); + Grid.SetColumn(actions, 2); + return overlay; + } + + private void AddTouchButton(Grid grid, PadButton button, string label, int row, int column, double size) + { + var view = TouchButton(button, label, size, size, (int)(size / 2)); + grid.Children.Add(view); + Grid.SetRow(view, row); + Grid.SetColumn(view, column); + } + + private Button TouchButton(PadButton button, string label, double width, double height, int cornerRadius) + { + var view = new Button + { + Text = label, + FontFamily = "PixelUI", + FontSize = 11, + TextColor = Colors.White, + BackgroundColor = Color.FromArgb("#AA342F43"), + BorderColor = Color.FromArgb("#B0FFFFFF"), + BorderWidth = 1, + CornerRadius = cornerRadius, + Padding = 0, + WidthRequest = width, + HeightRequest = height, + MinimumWidthRequest = width, + MinimumHeightRequest = height, + }; + view.Pressed += (_, _) => SetTouchButton(button, true); + view.Released += (_, _) => SetTouchButton(button, false); + return view; + } + + private void ToggleTouchControls() + { + _touchControls.IsVisible = !_touchControls.IsVisible; + EmbeddedGameDisplayPreferences.TouchControlsVisible = _touchControls.IsVisible; + if (!_touchControls.IsVisible) ReleaseTouchButtons(); + } + + private void ToggleFullScreen() + { + EmbeddedGameDisplayPreferences.FullScreen = !EmbeddedGameDisplayPreferences.FullScreen; + var fullScreen = EmbeddedGameDisplayPreferences.FullScreen; + _header.IsVisible = !fullScreen; + _footer.IsVisible = !fullScreen; + _floatingOptionsButton.IsVisible = fullScreen; + NavigationPage.SetHasNavigationBar(this, !fullScreen); + } + + private async Task ShowOptionsAsync() + { + var options = new List + { + _userPaused ? AppStrings.GameResume : AppStrings.GamePause, + AppStrings.GameSpeedMenuLabel(EmbeddedGamePreferences.SpeedMultiplier), + AppStrings.GameDisplay, + EmbeddedGameDisplayPreferences.FullScreen ? AppStrings.GameExitFullScreen : AppStrings.GameEnterFullScreen, + _touchControls.IsVisible ? AppStrings.GameHideTouchControls : AppStrings.GameShowTouchControls, + AppStrings.GameSaveState, + }; + if (_session.HasQuickState) options.Add(AppStrings.GameLoadState); + options.Add(AppStrings.GameExit); + + var choice = await PadMenu.ShowAsync(_hostGrid, AppStrings.GameOptions, null, [.. options]); + switch (choice) + { + case var value when value == (_userPaused ? AppStrings.GameResume : AppStrings.GamePause): + TogglePause(); + break; + case var value when value == AppStrings.GameSpeedMenuLabel(EmbeddedGamePreferences.SpeedMultiplier): + await ShowSpeedSettingsAsync(); + break; + case var value when value == AppStrings.GameDisplay: + await ShowDisplaySettingsAsync(); + break; + case var value when value == (EmbeddedGameDisplayPreferences.FullScreen ? AppStrings.GameExitFullScreen : AppStrings.GameEnterFullScreen): + ToggleFullScreen(); + break; + case var value when value == (_touchControls.IsVisible ? AppStrings.GameHideTouchControls : AppStrings.GameShowTouchControls): + ToggleTouchControls(); + break; + case var value when value == AppStrings.GameSaveState: + await SaveStateAsync(); + break; + case var value when value == AppStrings.GameLoadState: + await LoadStateAsync(); + break; + case var value when value == AppStrings.GameExit: + await ExitGameAsync(); + break; + } + } + + private async Task ShowSpeedSettingsAsync() + { + var current = EmbeddedGamePreferences.SpeedMultiplier; + var options = Enumerable.Range(1, 4) + .Select(multiplier => new PadOption( + AppStrings.GameSpeedChoice(multiplier), + multiplier == current ? "✓" : null, + multiplier == current ? UiTokens.Cyan : null)) + .ToArray(); + var selected = await PadMenu.ShowAtAsync( + _hostGrid, AppStrings.GameSpeed, AppStrings.GameSpeedHelp, current - 1, options); + if (selected is null) return; + + var selectedIndex = Array.FindIndex(options, option => option.Label == selected); + if ((uint)selectedIndex >= (uint)options.Length) return; + var multiplier = selectedIndex + 1; + ApplySpeedMultiplier(multiplier); + } + + private void ApplySpeedMultiplier(int multiplier) + { + EmbeddedGamePreferences.SpeedMultiplier = multiplier; + _session.SetSpeedMultiplier(multiplier); + _companionStore?.UpdateSpeedMultiplier(multiplier); + UpdateSpeedIndicators(); + } + + private void UpdateSpeedIndicators() + { + var multiplier = EmbeddedGamePreferences.SpeedMultiplier; + _optionsButton.Text = AppStrings.GameOptionsSpeed(multiplier); + _floatingOptionsButton.Text = $"⚙ ×{multiplier}"; + } + + private async Task ShowDisplaySettingsAsync() + { + var modes = new (EmbeddedGameScaleMode Mode, string Label)[] + { + (EmbeddedGameScaleMode.Fit, AppStrings.GameScaleFit), + (EmbeddedGameScaleMode.NinetyPercent, AppStrings.GameScale90), + (EmbeddedGameScaleMode.SeventyFivePercent, AppStrings.GameScale75), + (EmbeddedGameScaleMode.PixelPerfect, AppStrings.GameScalePixelPerfect), + }; + var currentIndex = Array.FindIndex(modes, item => item.Mode == EmbeddedGameDisplayPreferences.ScaleMode); + var options = modes.Select((item, index) => + new PadOption(item.Label, index == currentIndex ? "✓" : null, index == currentIndex ? UiTokens.Cyan : null)).ToArray(); + var selected = await PadMenu.ShowAtAsync(_hostGrid, AppStrings.GameDisplay, AppStrings.GameDisplayHelp, + Math.Max(0, currentIndex), options); + if (selected is null) return; + EmbeddedGameDisplayPreferences.ScaleMode = selected switch + { + var value when value == AppStrings.GameScale90 => EmbeddedGameScaleMode.NinetyPercent, + var value when value == AppStrings.GameScale75 => EmbeddedGameScaleMode.SeventyFivePercent, + var value when value == AppStrings.GameScalePixelPerfect => EmbeddedGameScaleMode.PixelPerfect, + _ => EmbeddedGameScaleMode.Fit, + }; + _canvas.InvalidateSurface(); + } + + private void SetTouchButton(PadButton button, bool pressed) + { + lock (_heldGate) + { + if (pressed) _touchHeld.Add(button); + else _touchHeld.Remove(button); + UpdateKeysLocked(); + } + } + + private void ReleaseTouchButtons() + { + lock (_heldGate) + { + _touchHeld.Clear(); + UpdateKeysLocked(); + } + } + + private void ReleaseAllButtons() + { + lock (_heldGate) + { + _held.Clear(); + _touchHeld.Clear(); + UpdateKeysLocked(); + } + } + + private void UpdateKeysLocked() + { + var keys = _held.Values.Aggregate(0u, (mask, value) => mask | value); + foreach (var button in _touchHeld) keys |= BitOf(button); + _session.SetKeys(keys); + } + + private void TogglePause() + { + _userPaused = !_userPaused; + _session.SetPaused(_userPaused); + _pauseButton.Text = _userPaused ? AppStrings.GameResume : AppStrings.GamePause; + SetStatus(_userPaused ? AppStrings.GamePaused : string.Empty); + } + + private async Task SaveStateAsync() + { + SetStatus(AppStrings.GameSavingState); + var saved = await Task.Run(_session.SaveQuickState); + SetStatus(saved ? AppStrings.GameStateSaved : AppStrings.GameStateSaveFailed); + UpdateStateActions(); + } + + private async Task LoadStateAsync() + { + SetStatus(AppStrings.GameLoadingState); + var loaded = await Task.Run(_session.LoadQuickState); + SetStatus(loaded ? AppStrings.GameStateLoaded : AppStrings.GameStateLoadFailed); + UpdateStateActions(); + } + + private void UpdateStateActions() => _loadStateButton.IsEnabled = _session.HasQuickState; + + private void SetStatus(string text) + { + _status.Text = text; + _status.IsVisible = !string.IsNullOrWhiteSpace(text); + } + + private async Task ExitGameAsync() + { + if (_exitStarted) return; + _exitStarted = true; + _pauseButton.IsEnabled = false; + if (!await _session.CloseAsync()) + await PadMenu.ShowAsync(_hostGrid, AppStrings.GameBatterySaveFailedTitle, + _session.HasSaveConflict ? AppStrings.GameSaveConflict : AppStrings.GameBatterySaveFailed, + AppStrings.Ok); + await Navigation.PopAsync(); + } + + protected override bool OnBackButtonPressed() + { + _ = ExitGameAsync(); + return true; + } + + private void OnAppSuspended() + { + ReleaseAllButtons(); + _session.SetTouchScreen(false, 0, 0); + _stylusPointerId = -1; + _suspendSaveTask = _session.FlushBatterySaveAsync(); + } + + private async void OnAppResumed() + { + var syncTask = _suspendSaveTask; + _suspendSaveTask = null; + if (syncTask is not null && !await syncTask) + SetStatus(_session.HasSaveConflict ? AppStrings.GameSaveConflict : AppStrings.GameBatterySaveFailed); + if (!_userPaused) _session.SetPaused(false); } private void Invalidate() => MainThread.InvokeOnMainThreadAsync(_canvas.InvalidateSurface); - /// The pad's button → GBA bit mapping (mGBA's own bit order). - private static uint BitOf(PadButton button) => button switch + /// Maps the shared pad into each console's hardware key bits. + private uint BitOf(PadButton button) => _session.IsNintendoDs ? button switch + { + PadButton.A => Domain.NdsKeys.A, + PadButton.B => Domain.NdsKeys.B, + PadButton.Start => Domain.NdsKeys.Start, + PadButton.Select => Domain.NdsKeys.Select, + PadButton.L => Domain.NdsKeys.L, + PadButton.R => Domain.NdsKeys.R, + PadButton.X => Domain.NdsKeys.X, + PadButton.Y => Domain.NdsKeys.Y, + PadButton.Up => Domain.NdsKeys.Up, + PadButton.Down => Domain.NdsKeys.Down, + PadButton.Left => Domain.NdsKeys.Left, + PadButton.Right => Domain.NdsKeys.Right, + _ => 0, + } : button switch { PadButton.A => Domain.GbaKeys.A, PadButton.B => Domain.GbaKeys.B, @@ -55,7 +521,7 @@ public bool OnPadButton(PadButton button) lock (_heldGate) { _held[button] = bit; - _session.SetKeys(_held.Values.Aggregate(0u, (mask, value) => mask | value)); + UpdateKeysLocked(); } return true; // the game screen consumes every button } @@ -66,7 +532,7 @@ public void OnPadReleased(PadButton button) lock (_heldGate) { _held.Remove(button); - _session.SetKeys(_held.Values.Aggregate(0u, (mask, value) => mask | value)); + UpdateKeysLocked(); } } @@ -74,20 +540,99 @@ private void OnPaint(object? sender, SKPaintSurfaceEventArgs args) { var canvas = args.Surface.Canvas; canvas.Clear(SKColors.Black); - var (width, height) = _session.VideoSize; + var splitDsScreens = _session.IsNintendoDs && _usingSeparateDsDisplays; + var (width, height) = splitDsScreens ? (256, 192) : _session.VideoSize; if (width == 0 || height == 0) return; - // Integer scale, centered: the GBA's pixels stay square and unsmeared. - var scale = Math.Min( - (float)Math.Floor((double)args.Info.Width / width), - (float)Math.Floor((double)args.Info.Height / height)); - if (scale < 1) scale = Math.Min((float)args.Info.Width / width, (float)args.Info.Height / height); + var maximumScale = Math.Min((float)args.Info.Width / width, (float)args.Info.Height / height); + var scale = EmbeddedGameDisplayPreferences.ScaleFor(EmbeddedGameDisplayPreferences.ScaleMode, maximumScale); var drawWidth = width * scale; var drawHeight = height * scale; var left = (args.Info.Width - drawWidth) / 2f; var top = (args.Info.Height - drawHeight) / 2f; - _session.Draw(canvas, new SKRect(left, top, left + drawWidth, top + drawHeight)); + _gameRect = new SKRect(left, top, left + drawWidth, top + drawHeight); + if (splitDsScreens) _session.DrawMainScreen(canvas, _gameRect); + else _session.Draw(canvas, _gameRect); + } + + private void OnCanvasTouch(object? sender, SKTouchEventArgs args) + { + if (!_session.SupportsTouchScreen || _usingSeparateDsDisplays) return; + switch (args.ActionType) + { + case SKTouchAction.Pressed: + _stylusPointerId = args.Id; + UpdateStylus(args.Location); + args.Handled = true; + break; + case SKTouchAction.Moved when args.Id == _stylusPointerId: + UpdateStylus(args.Location); + args.Handled = true; + break; + case SKTouchAction.Released or SKTouchAction.Cancelled when args.Id == _stylusPointerId: + _stylusPointerId = -1; + _session.SetTouchScreen(false, 0, 0); + args.Handled = true; + break; + } + } + + private void UpdateStylus(SKPoint location) + { + var (width, height) = _session.VideoSize; + if (!_gameRect.Contains(location.X, location.Y) || width != 256 || height != 384) + { + _session.SetTouchScreen(false, 0, 0); + return; + } + + var lowerScreenTop = _gameRect.Top + _gameRect.Height / 2f; + if (location.Y < lowerScreenTop) + { + _session.SetTouchScreen(false, 0, 0); + return; + } + + var x = (int)((location.X - _gameRect.Left) * 256f / _gameRect.Width); + var y = (int)((location.Y - lowerScreenTop) * 192f / (_gameRect.Height / 2f)); + _session.SetTouchScreen(true, Math.Clamp(x, 0, 255), Math.Clamp(y, 0, 191)); + } + + private async Task ShowDsBottomScreenAsync() + { + if (_dualScreenHost is null || !_pageVisible) return; + try + { + await _dualScreenHost.ShowNintendoDsBottomScreenAsync(_session); + OnSecondaryDisplayContentChanged(); + } + catch (Exception error) + { + Services.AppLog.Warn("second", $"Could not route the DS lower screen to the second display; keeping both screens on the main display: {error.Message}"); + SetSeparateDsDisplays(false); + } + } + + private void OnSecondaryDisplayContentChanged() + { + if (!_pageVisible || _dualScreenHost is null || !_session.IsNintendoDs) return; + SetSeparateDsDisplays(_dualScreenHost.IsShowingNintendoDsBottomScreen(_session)); + } + + private void SetSeparateDsDisplays(bool enabled) + { + MainThread.BeginInvokeOnMainThread(() => + { + if (_usingSeparateDsDisplays == enabled) return; + _usingSeparateDsDisplays = enabled; + if (enabled && _stylusPointerId != -1) + { + _stylusPointerId = -1; + _session.SetTouchScreen(false, 0, 0); + } + _canvas.InvalidateSurface(); + }); } private Timer? _liveTimer; @@ -95,33 +640,66 @@ private void OnPaint(object? sender, SKPaintSurfaceEventArgs args) protected override void OnAppearing() { base.OnAppearing(); + _pageVisible = true; + App.Suspended += OnAppSuspended; + App.Resumed += OnAppResumed; + _session.SetPaused(_userPaused); + if (_session.HasSaveConflict) SetStatus(AppStrings.GameSaveConflict); IPlatformApplication.Current?.Services.GetService()?.Push(this); - // PokéDaisy: while the game runs in-app, publish a live companion snapshot - // (dex/party/playtime read from the core's save RAM) every second. + if (_session.IsNintendoDs && _dualScreenHost is not null) + { + _dualScreenHost.DisplayContentChanged += OnSecondaryDisplayContentChanged; + _ = ShowDsBottomScreenAsync(); + } + // Refresh companion values from mGBA's battery-save image. Until we read the + // game's emulated RAM directly, these values reflect the last in-game save. var store = IPlatformApplication.Current?.Services.GetService(); - if (store is not null) + if (store is not null && _session.SupportsLiveCompanion) { - store.Start(new Domain.GameCompanion(_session.GameTitle, 3, 0, 0, 0, [])); + var owner = new Domain.GameCompanion(_session.GameTitle, _session.Generation, 0, 0, 0, []); + _companionOwner = owner; + _companionStore = store; + store.Start(owner); + store.BindSpeedControl(EmbeddedGamePreferences.SpeedMultiplier, ApplySpeedMultiplier); _liveTimer = new Timer(_ => { + if (!_pageVisible || !ReferenceEquals(store.Current, owner)) return; var snapshot = _session.ReadLiveCompanion(); if (snapshot is null) return; - MainThread.BeginInvokeOnMainThread(() => store.UpdateLive(new Domain.LiveCompanionSnapshot( - snapshot.GameTitle, snapshot.GameCode, - snapshot.DexCaught, snapshot.DexSeen, snapshot.DexTotal, - snapshot.PartyCount, snapshot.PlaytimeHours, snapshot.PlaytimeMinutes))); - }, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); + MainThread.BeginInvokeOnMainThread(() => + { + if (!_pageVisible || !ReferenceEquals(store.Current, owner)) return; + store.UpdateLive(snapshot); + }); + }, null, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } } protected override void OnDisappearing() { base.OnDisappearing(); + _pageVisible = false; + App.Suspended -= OnAppSuspended; + App.Resumed -= OnAppResumed; + if (_dualScreenHost is not null) + { + _dualScreenHost.DisplayContentChanged -= OnSecondaryDisplayContentChanged; + _ = _dualScreenHost.RestoreDefaultScreenAsync(_session); + } _session.FrameProduced -= Invalidate; + ReleaseAllButtons(); + _session.SetTouchScreen(false, 0, 0); IPlatformApplication.Current?.Services.GetService()?.Remove(this); _liveTimer?.Dispose(); _liveTimer = null; - IPlatformApplication.Current?.Services.GetService()?.ClearLive(); - _session.Dispose(); + var companionStore = IPlatformApplication.Current?.Services.GetService(); + if (companionStore is not null && ReferenceEquals(companionStore.Current, _companionOwner)) + { + companionStore.ClearSpeedControl(); + companionStore.ClearLive(); + } + _companionStore = null; + _companionOwner = null; + _ = _session.CloseAsync(); } } diff --git a/src/PKForge.App/Views/EmulatorsPage.cs b/src/PKForge.App/Views/EmulatorsPage.cs index e48ed21c..a27793c6 100644 --- a/src/PKForge.App/Views/EmulatorsPage.cs +++ b/src/PKForge.App/Views/EmulatorsPage.cs @@ -184,17 +184,24 @@ private View BuildConsoleRow(ConsoleRow row) return Kit.Well(line, padding: 10); } - /// The Cocoon flow: the console's installed emulators, one tap binds. - /// Consoles PKForge runs in-app (GB/GBC/GBA) never reach here: no row, no binding. + /// The console's emulator choice. Pokémon games for integrated consoles + /// always stay in PKForge; external apps remain listed for save-file discovery. private async Task ChooseConsoleEmulatorAsync(ConsoleRow row) { if (ConsoleRules.RunsInApp(row.Console)) { - _viewModel.Status = $"{row.Name}: plays in PKForge itself."; + var available = row.Console == GameConsole.NintendoDs + ? EmulatorCatalog.EmbeddedDsCoreAvailable + : EmulatorCatalog.EmbeddedCoreAvailable; + _viewModel.Status = available + ? $"{row.Name}: plays in PKForge itself." + : $"{row.Name}: the PKForge core is missing from this APK."; return; } var candidates = ConsoleRules.EmulatorsFor(row.Console) - .Where(kind => kind != EmulatorKind.Embedded && EmulatorCatalog.IsInstalled(kind, _launcher.IsInstalled)) + .Where(kind => kind == EmulatorKind.Embedded + ? row.Console == GameConsole.NintendoDs && EmulatorCatalog.EmbeddedDsCoreAvailable + : EmulatorCatalog.IsInstalled(kind, _launcher.IsInstalled)) .ToList(); if (candidates.Count == 0) { @@ -308,7 +315,7 @@ public void RefreshChips() var consoles = Enum.GetValues(); foreach (var console in consoles) { - // Consoles PKForge runs in-app (GB/GBC/GBA): no external binding row, ever. + // Integrated Pokémon consoles have no external launch binding. if (ConsoleRules.RunsInApp(console)) continue; var bound = _consoleEmulators.Find(console); diff --git a/src/PKForge.App/Views/GameCompanionView.cs b/src/PKForge.App/Views/GameCompanionView.cs index 2632ff78..7c21a27c 100644 --- a/src/PKForge.App/Views/GameCompanionView.cs +++ b/src/PKForge.App/Views/GameCompanionView.cs @@ -1,100 +1,92 @@ using PKForge.App.Services; using PKForge.App.Theme; using PKForge.Domain; +using SkiaSharp; +using SkiaSharp.Views.Maui; +using SkiaSharp.Views.Maui.Controls; namespace PKForge.App.Views; -/// -/// The in-game companion on the lower screen: the running game's name and dex -/// progress, plus its restore points. Shown while an emulator owns the -/// foreground; every surface is read-only (the companion never edits a save the -/// emulator holds open). -/// +/// The configurable lower-screen companion for embedded and external games. public sealed class GameCompanionView : VerticalStackLayout { private readonly Label _title = new() { - FontFamily = DsChrome.PixelFont, FontSize = 16, TextColor = UiTokens.Ink0, + FontFamily = DsChrome.PixelFont, + FontSize = 15, + TextColor = UiTokens.Ink0, HorizontalTextAlignment = TextAlignment.Center, + LineBreakMode = LineBreakMode.TailTruncation, }; - private readonly Label _dex = new() + private readonly Grid _navigation = new() { ColumnSpacing = 4 }; + private readonly VerticalStackLayout _content = new() { Spacing = 8 }; + private readonly ScrollView _contentScroll; + private readonly Label _externalSummary = new() { - FontFamily = DsChrome.PixelFont, FontSize = 13, TextColor = UiTokens.Cyan, - HorizontalTextAlignment = TextAlignment.Center, - }; - private readonly Label _live = new() - { - FontFamily = DsChrome.PixelFont, FontSize = 11, TextColor = UiTokens.Green, - HorizontalTextAlignment = TextAlignment.Center, - IsVisible = false, - }; - private readonly Label _external = new() - { - FontFamily = DsChrome.PixelFont, FontSize = 11, TextColor = UiTokens.Cyan, + FontFamily = DsChrome.PixelFont, + FontSize = 10, + TextColor = UiTokens.Cyan, HorizontalTextAlignment = TextAlignment.Center, IsVisible = false, }; - private readonly VerticalStackLayout _points = new() { Spacing = 3 }; + private GameCompanion? _companion; + private LiveCompanionSnapshot? _live; + private GameCompanionTab _selectedTab; + private string? _selectedBagPocketId; + private bool _showSettings; + private bool _hasShown; public GameCompanionView() { - Spacing = 10; - Margin = new Thickness(14, 12); - Padding = new Thickness(10); - HorizontalOptions = LayoutOptions.Center; - VerticalOptions = LayoutOptions.Center; + Spacing = 8; + Margin = new Thickness(10, 8); + Padding = new Thickness(8); + HorizontalOptions = LayoutOptions.Fill; + VerticalOptions = LayoutOptions.Fill; + _contentScroll = new ScrollView { Content = _content, VerticalOptions = LayoutOptions.Fill }; Children.Add(_title); - Children.Add(_dex); - Children.Add(_live); - Children.Add(_external); - Children.Add(new Label - { - Text = AppStrings.Fr ? "Points de restauration" : "Restore points", - FontFamily = DsChrome.PixelFont, FontSize = 11, TextColor = UiTokens.Ink1, - }); - Children.Add(_points); + Children.Add(_externalSummary); + Children.Add(_navigation); + Children.Add(_contentScroll); IsVisible = false; } - /// Replaces the companion wholesale: one immutable record per launch. public void Show(GameCompanion companion) { + var newGame = !ReferenceEquals(_companion, companion); + _companion = companion; _title.Text = companion.GameLabel; - _dex.Text = AppStrings.Fr - ? $"Pokédex : {companion.DexCaught}/{companion.DexTotal} capturés · {companion.DexPercent}%" - : $"Pokédex: {companion.DexCaught}/{companion.DexTotal} caught · {companion.DexPercent}%"; - _points.Children.Clear(); - _live.IsVisible = false; - _external.IsVisible = false; - if (companion.RestorePoints.Count == 0) - { - _points.Children.Add(new Label - { - Text = AppStrings.Fr ? "Aucun point pour cette sauvegarde." : "No points for this save yet.", - FontFamily = DsChrome.PixelFont, FontSize = 10, TextColor = UiTokens.InkSoft, - }); + _externalSummary.IsVisible = false; + _externalSummary.Text = string.Empty; + if (!newGame && _hasShown) + { + if (_showSettings) Render(); + IsVisible = true; + return; } - else + if (newGame || !_hasShown) { - foreach (var point in companion.RestorePoints.Take(5)) - { - _points.Children.Add(new Label - { - Text = $"· {point.CreatedUtc:yyyy-MM-dd HH:mm} UTC", - FontFamily = DsChrome.PixelFont, FontSize = 10, TextColor = UiTokens.InkSoft, - }); - } + if (newGame) _live = null; + _selectedTab = GameCompanionPreferences.HomeTab; + _selectedBagPocketId = null; + _showSettings = false; + _hasShown = true; } + else if (!GameCompanionPreferences.VisibleTabs.Contains(_selectedTab)) + _selectedTab = GameCompanionPreferences.HomeTab; + Render(); IsVisible = true; } - /// Overlays a live read from the running embedded game (PokéDaisy). public void ShowLive(LiveCompanionSnapshot live) { - _live.Text = AppStrings.Fr - ? $"En direct : dex {live.DexCaught}/{live.DexTotal} · équipe {live.PartyCount}/6 · {live.PlaytimeHours}h{live.PlaytimeMinutes:D2}" - : $"Live: dex {live.DexCaught}/{live.DexTotal} · party {live.PartyCount}/6 · {live.PlaytimeHours}h{live.PlaytimeMinutes:D2}"; - _live.IsVisible = true; + if (_live is { } current && HaveSameSnapshot(current, live)) + return; + + _live = live; + if (!_showSettings && _selectedTab is GameCompanionTab.Party or GameCompanionTab.Bag + or GameCompanionTab.Pokedex or GameCompanionTab.Session) + Render(); } /// @@ -104,23 +96,514 @@ public void ShowLive(LiveCompanionSnapshot live) /// public void ShowExternal(ExternalCompanionSnapshot external, PlaySessionStats? session) { - var dex = AppStrings.Fr - ? $"{AppStrings.DexProgressLabel} {external.DexCaught}/{external.DexTotal} · {external.DexPercent}%" - : $"{AppStrings.DexProgressLabel} {external.DexCaught}/{external.DexTotal} · {external.DexPercent}%"; var save = AppStrings.PlaytimeHours(external.PlaytimeHours, external.PlaytimeMinutes); - var line = AppStrings.Fr - ? $"{dex} · équipe {external.PartyCount}/6 · {AppStrings.SavePlaytime} {save}" - : $"{dex} · party {external.PartyCount}/6 · {AppStrings.SavePlaytime} {save}"; + var party = AppStrings.Fr ? "équipe" : "party"; + var line = $"{AppStrings.DexProgressLabel} {external.DexCaught}/{external.DexTotal} · " + + $"{external.DexPercent}% · {party} {external.PartyCount}/6 · {AppStrings.SavePlaytime} {save}"; if (session is not null) { var now = DateTimeOffset.UtcNow; var sessionLine = PlaySessionStats.FormatDuration(session.SessionElapsed(now)); var totalLine = PlaySessionStats.FormatDuration(session.GrandTotal(now)); - line += AppStrings.Fr - ? $" · {AppStrings.SessionTime} {sessionLine} · {AppStrings.TotalPlaytime} {totalLine}" - : $" · {AppStrings.SessionTime} {sessionLine} · {AppStrings.TotalPlaytime} {totalLine}"; + line += $" · {AppStrings.SessionTime} {sessionLine} · {AppStrings.TotalPlaytime} {totalLine}"; + } + _externalSummary.Text = line; + _externalSummary.IsVisible = true; + } + + private static bool HaveSameSnapshot(LiveCompanionSnapshot left, LiveCompanionSnapshot right) => + left.GameLabel == right.GameLabel + && left.GameCode == right.GameCode + && left.DexCaught == right.DexCaught + && left.DexSeen == right.DexSeen + && left.DexTotal == right.DexTotal + && left.PartyCount == right.PartyCount + && left.PlaytimeHours == right.PlaytimeHours + && left.PlaytimeMinutes == right.PlaytimeMinutes + && left.PartyMembers.SequenceEqual(right.PartyMembers) + && left.BagPockets.Count == right.BagPockets.Count + && left.BagPockets.Zip(right.BagPockets).All(pair => + pair.First.Id == pair.Second.Id + && pair.First.Name == pair.Second.Name + && pair.First.Items.SequenceEqual(pair.Second.Items)); + + private void Render() + { + RenderNavigation(); + _content.Children.Clear(); + if (_showSettings) + { + RenderSettings(); + return; + } + + switch (_selectedTab) + { + case GameCompanionTab.Party: + RenderParty(); + break; + case GameCompanionTab.Bag: + RenderBag(); + break; + case GameCompanionTab.Pokedex: + RenderPokedex(); + break; + case GameCompanionTab.Session: + RenderSession(); + break; + case GameCompanionTab.RestorePoints: + RenderRestorePoints(); + break; + } + } + + private void RenderNavigation() + { + _navigation.Children.Clear(); + _navigation.ColumnDefinitions.Clear(); + var tabs = GameCompanionPreferences.VisibleTabs; + for (var index = 0; index < tabs.Count + 1; index++) + _navigation.ColumnDefinitions.Add(new ColumnDefinition(index == tabs.Count ? GridLength.Auto : GridLength.Star)); + + for (var index = 0; index < tabs.Count; index++) + { + var tab = tabs[index]; + var button = NavigationButton(LabelFor(tab), !_showSettings && _selectedTab == tab); + button.Clicked += (_, _) => + { + _selectedTab = tab; + _showSettings = false; + Render(); + }; + _navigation.Add(button, index, 0); + } + + var settings = NavigationButton("⚙", _showSettings); + settings.WidthRequest = 40; + settings.Clicked += (_, _) => + { + _showSettings = !_showSettings; + Render(); + }; + _navigation.Add(settings, tabs.Count, 0); + } + + private void RenderParty() + { + if (_live is not { } live) + { + AddNote(AppStrings.CompanionNoSavedData); + return; + } + + var party = live.PartyMembers; + if (party.Count == 0) + { + AddNote(AppStrings.CompanionSavedDataNotice); + AddNote(AppStrings.CompanionNoParty); + return; + } + + AddNote(AppStrings.CompanionSavedDataNotice); + + foreach (var (member, index) in party.Select((member, index) => (member, index))) + { + var sprites = IPlatformApplication.Current?.Services.GetService(); + var sprite = new SKCanvasView + { + WidthRequest = 44, + HeightRequest = 44, + IgnorePixelScaling = true, + InputTransparent = true, + }; + sprite.PaintSurface += (_, args) => + { + var canvas = args.Surface.Canvas; + canvas.Clear(SKColors.Transparent); + var bitmap = member.Species > 0 + ? sprites?.GetSprite(member.Species, member.Form, member.IsShiny) + : null; + if (bitmap is null) + { + if (member.Species > 0) + sprites?.Warm(member.Species, member.Form, member.IsShiny, + () => MainThread.BeginInvokeOnMainThread(sprite.InvalidateSurface)); + return; + } + + var scale = Math.Min(args.Info.Width / (float)bitmap.Width, args.Info.Height / (float)bitmap.Height); + var width = bitmap.Width * scale; + var height = bitmap.Height * scale; + var destination = new SKRect( + (args.Info.Width - width) / 2f, + (args.Info.Height - height) / 2f, + (args.Info.Width + width) / 2f, + (args.Info.Height + height) / 2f); + canvas.DrawBitmap(bitmap, destination); + }; + var heading = new Label + { + Text = AppStrings.CompanionPartyMember( + index + 1, member.Nickname, member.SpeciesName, member.Level, member.IsEgg), + FontFamily = DsChrome.PixelFont, + FontSize = 10, + TextColor = UiTokens.Ink0, + LineBreakMode = LineBreakMode.TailTruncation, + }; + var hp = new Label + { + Text = AppStrings.CompanionHp(member.CurrentHp, member.MaxHp) + + (string.IsNullOrEmpty(member.Status) ? string.Empty : $" · {member.Status}"), + FontFamily = DsChrome.PixelFont, + FontSize = 9, + TextColor = member.Status.Length == 0 ? UiTokens.InkSoft : UiTokens.RedOrange, + VerticalTextAlignment = TextAlignment.Center, + }; + var ratio = member.MaxHp <= 0 ? 0 : Math.Clamp((double)member.CurrentHp / member.MaxHp, 0, 1); + var health = new ProgressBar + { + Progress = ratio, + ProgressColor = ratio > 0.5 ? UiTokens.Green : ratio > 0.2 ? UiTokens.Yellow : UiTokens.RedOrange, + BackgroundColor = UiTokens.ShellEdge, + HeightRequest = 5, + VerticalOptions = LayoutOptions.Center, + }; + var row = new Grid + { + ColumnDefinitions = [new(GridLength.Auto), new(GridLength.Star), new(GridLength.Auto)], + RowDefinitions = [new(GridLength.Auto), new(GridLength.Auto)], + ColumnSpacing = 8, + RowSpacing = 3, + Children = { sprite, heading, hp, health }, + }; + Grid.SetRowSpan(sprite, 2); + Grid.SetColumn(heading, 1); + Grid.SetColumn(hp, 2); + Grid.SetRow(health, 1); + Grid.SetColumn(health, 1); + Grid.SetColumnSpan(health, 2); + var rowBorder = new Border + { + Padding = new Thickness(8, 5), + BackgroundColor = UiTokens.Paper, + Stroke = UiTokens.ShellEdge, + StrokeThickness = 1, + StrokeShape = new Microsoft.Maui.Controls.Shapes.RoundRectangle { CornerRadius = 5 }, + Content = row, + }; + _content.Children.Add(rowBorder); + } + } + + private void RenderPokedex() + { + if (_live is not { } live) + { + AddNote(AppStrings.CompanionNoSavedData); + return; + } + + AddNote(AppStrings.CompanionSavedDataNotice); + + _content.Children.Add(new Label + { + Text = AppStrings.CompanionDex(live.DexCaught, live.DexSeen, live.DexTotal), + FontFamily = DsChrome.PixelFont, + FontSize = 11, + TextColor = UiTokens.Cyan, + HorizontalTextAlignment = TextAlignment.Center, + }); + _content.Children.Add(new ProgressBar + { + Progress = Math.Clamp(live.DexPercent / 100d, 0, 1), + ProgressColor = UiTokens.Cyan, + BackgroundColor = UiTokens.ShellEdge, + }); + _content.Children.Add(new Label + { + Text = $"{live.DexPercent}%", + FontFamily = DsChrome.PixelFont, + FontSize = 22, + TextColor = UiTokens.Ink0, + HorizontalTextAlignment = TextAlignment.Center, + }); + } + + private void RenderBag() + { + if (_live is not { } live) + { + AddNote(AppStrings.CompanionNoSavedData); + return; + } + + AddNote(AppStrings.CompanionSavedDataNotice); + var pockets = live.BagPockets; + if (pockets.Count == 0) + { + AddNote(AppStrings.CompanionBagEmpty); + return; } - _external.Text = line; - _external.IsVisible = true; + + var pocketButtons = new HorizontalStackLayout { Spacing = 4 }; + var allButton = NavigationButton(AppStrings.CompanionPocketAll, _selectedBagPocketId is null); + allButton.Clicked += (_, _) => + { + _selectedBagPocketId = null; + Render(); + }; + pocketButtons.Children.Add(allButton); + + foreach (var pocket in pockets) + { + var button = NavigationButton(pocket.Name, _selectedBagPocketId == pocket.Id); + button.Clicked += (_, _) => + { + _selectedBagPocketId = pocket.Id; + Render(); + }; + pocketButtons.Children.Add(button); + } + + _content.Children.Add(new ScrollView + { + Orientation = ScrollOrientation.Horizontal, + HorizontalOptions = LayoutOptions.Fill, + Content = pocketButtons, + }); + + IEnumerable visiblePockets = _selectedBagPocketId is null + ? pockets + : pockets.Where(pocket => pocket.Id == _selectedBagPocketId).ToArray(); + foreach (var pocket in visiblePockets) + { + if (_selectedBagPocketId is null) + { + _content.Children.Add(new Label + { + Text = pocket.Name, + FontFamily = DsChrome.PixelFont, + FontSize = 10, + TextColor = UiTokens.Cyan, + }); + } + + foreach (var item in pocket.Items) + { + var name = new Label + { + Text = item.Name, + FontFamily = DsChrome.PixelFont, + FontSize = 10, + TextColor = UiTokens.Ink0, + LineBreakMode = LineBreakMode.TailTruncation, + VerticalTextAlignment = TextAlignment.Center, + }; + var count = new Label + { + Text = item.Count.ToString(), + FontFamily = DsChrome.PixelFont, + FontSize = 10, + TextColor = UiTokens.Cyan, + VerticalTextAlignment = TextAlignment.Center, + }; + var row = new Grid + { + ColumnDefinitions = [new(GridLength.Star), new(GridLength.Auto)], + ColumnSpacing = 8, + Children = { name, count }, + }; + Grid.SetColumn(count, 1); + _content.Children.Add(new Border + { + Padding = new Thickness(8, 5), + BackgroundColor = UiTokens.Paper, + Stroke = UiTokens.ShellEdge, + StrokeThickness = 1, + StrokeShape = new Microsoft.Maui.Controls.Shapes.RoundRectangle { CornerRadius = 5 }, + Content = row, + }); + } + } + } + + private void RenderSession() + { + if (_live is not { } live) + { + AddNote(AppStrings.CompanionNoSavedData); + return; + } + + AddNote(AppStrings.CompanionSavedDataNotice); + + AddValue(AppStrings.CompanionPartyLabel(live.PartyCount)); + AddValue(AppStrings.CompanionPlaytime(live.PlaytimeHours, live.PlaytimeMinutes)); + AddValue(string.IsNullOrWhiteSpace(live.GameCode) ? live.GameLabel : $"{live.GameLabel} · {live.GameCode}"); + } + + private void RenderRestorePoints() + { + var points = _companion?.RestorePoints ?? []; + if (points.Count == 0) + { + AddNote(AppStrings.CompanionNoRestorePoints); + return; + } + + foreach (var point in points.Take(8)) + AddValue($"· {point.CreatedUtc.ToLocalTime():yyyy-MM-dd HH:mm}"); + } + + private void RenderSettings() + { + _content.Children.Add(new Label + { + Text = AppStrings.CompanionSettingsTitle, + FontFamily = DsChrome.PixelFont, + FontSize = 12, + TextColor = UiTokens.Cyan, + HorizontalTextAlignment = TextAlignment.Center, + }); + _content.Children.Add(new Label + { + Text = AppStrings.CompanionSettingsHelp, + FontFamily = DsChrome.PixelFont, + FontSize = 9, + TextColor = UiTokens.InkSoft, + }); + + if (IPlatformApplication.Current?.Services.GetService() is { SpeedControlAvailable: true } speedStore) + { + _content.Children.Add(new Label + { + Text = AppStrings.GameSpeed, + FontFamily = DsChrome.PixelFont, + FontSize = 10, + TextColor = UiTokens.Ink0, + }); + var speedRow = new Grid + { + ColumnDefinitions = [new(GridLength.Star), new(GridLength.Star), new(GridLength.Star), new(GridLength.Star)], + ColumnSpacing = 4, + }; + for (var multiplier = 1; multiplier <= 4; multiplier++) + { + var selectedMultiplier = multiplier; + var selected = multiplier == speedStore.SpeedMultiplier; + var button = SmallButton(AppStrings.GameSpeedChoice(multiplier)); + button.TextColor = selected ? UiTokens.Cyan : UiTokens.Ink0; + button.BackgroundColor = selected ? UiTokens.SelectFill : UiTokens.Paper; + button.Clicked += (_, _) => speedStore.RequestSpeedMultiplier(selectedMultiplier); + speedRow.Add(button, multiplier - 1, 0); + } + _content.Children.Add(speedRow); + AddNote(AppStrings.GameSpeedHelp); + } + + var visible = GameCompanionPreferences.VisibleTabs; + foreach (var tab in Enum.GetValues()) + { + var row = new Grid + { + ColumnDefinitions = [new(GridLength.Star), new(GridLength.Auto), new(GridLength.Auto)], + ColumnSpacing = 4, + Children = + { + new Label + { + Text = LabelFor(tab), + FontFamily = DsChrome.PixelFont, + FontSize = 10, + TextColor = UiTokens.Ink0, + VerticalTextAlignment = TextAlignment.Center, + }, + }, + }; + var toggle = SmallButton(visible.Contains(tab) ? AppStrings.CompanionHideTab : AppStrings.CompanionShowTab); + toggle.IsEnabled = !visible.Contains(tab) || visible.Count > 1; + toggle.Clicked += (_, _) => + { + GameCompanionPreferences.ToggleTab(tab); + if (!GameCompanionPreferences.VisibleTabs.Contains(_selectedTab)) + _selectedTab = GameCompanionPreferences.HomeTab; + Render(); + }; + var home = SmallButton(GameCompanionPreferences.HomeTab == tab ? "✓" : "⌂"); + home.IsEnabled = visible.Contains(tab); + home.Clicked += (_, _) => + { + GameCompanionPreferences.SetHomeTab(tab); + _selectedTab = tab; + _showSettings = false; + Render(); + }; + row.Add(toggle, 1, 0); + row.Add(home, 2, 0); + _content.Children.Add(row); + } + _content.Children.Add(new Label + { + Text = $"{AppStrings.CompanionCurrentHome} · {LabelFor(GameCompanionPreferences.HomeTab)}", + FontFamily = DsChrome.PixelFont, + FontSize = 9, + TextColor = UiTokens.Cyan, + }); } + + private void AddNote(string text) => _content.Children.Add(new Label + { + Text = text, + FontFamily = DsChrome.PixelFont, + FontSize = 10, + TextColor = UiTokens.InkSoft, + HorizontalTextAlignment = TextAlignment.Center, + }); + + private void AddValue(string text) => _content.Children.Add(new Label + { + Text = text, + FontFamily = DsChrome.PixelFont, + FontSize = 10, + TextColor = UiTokens.Ink1, + HorizontalTextAlignment = TextAlignment.Center, + }); + + private static string LabelFor(GameCompanionTab tab) => tab switch + { + GameCompanionTab.Party => AppStrings.CompanionParty, + GameCompanionTab.Bag => AppStrings.CompanionBag, + GameCompanionTab.Pokedex => AppStrings.CompanionPokedex, + GameCompanionTab.Session => AppStrings.CompanionSession, + GameCompanionTab.RestorePoints => AppStrings.CompanionRestorePoints, + _ => tab.ToString().ToUpperInvariant(), + }; + + private static Button NavigationButton(string text, bool selected) => new() + { + Text = text, + FontFamily = DsChrome.PixelFont, + FontSize = 9, + TextColor = selected ? UiTokens.Cyan : UiTokens.InkSoft, + BackgroundColor = selected ? UiTokens.Paper : Colors.Transparent, + BorderColor = UiTokens.ShellEdge, + BorderWidth = 1, + CornerRadius = 4, + Padding = new Thickness(4, 3), + MinimumHeightRequest = 34, + }; + + private static Button SmallButton(string text) => new() + { + Text = text, + FontFamily = DsChrome.PixelFont, + FontSize = 8, + TextColor = UiTokens.Ink0, + BackgroundColor = UiTokens.Paper, + BorderColor = UiTokens.ShellEdge, + BorderWidth = 1, + CornerRadius = 4, + Padding = new Thickness(6, 3), + MinimumHeightRequest = 30, + }; } diff --git a/src/PKForge.App/Views/HomePage.cs b/src/PKForge.App/Views/HomePage.cs index 845b5c5b..3c118955 100644 --- a/src/PKForge.App/Views/HomePage.cs +++ b/src/PKForge.App/Views/HomePage.cs @@ -82,32 +82,41 @@ public HomePage(SavePickerViewModel viewModel) Grid.SetRow(_shelf, 1); BlockNativeFocus(_shelf); - // The three destinations as PKSM tiles with bundled pixel icons. + // Home destinations as DS-style tiles with bundled pixel icons. var bank = new DsCard("bank", AppStrings.Bank) { Tapped = () => _ = PushAsync() }; var autopilot = new DsCard("pokedex", AppStrings.DexAutopilot) { Tapped = () => _ = OpenAutopilotAsync() }; var park = new DsCard("park", AppStrings.Pokepark) { Tapped = () => _ = PushParkAsync() }; var events = new DsCard("events", AppStrings.Events) { Tapped = () => _ = ShowEventsMenuAsync() }; var emulators = new DsCard("retroarch", AppStrings.EmulatorsTitle) { Tapped = () => _ = PushAsync() }; var library = new DsCard("platform-gba", "Library") { Tapped = () => _ = PushAsync() }; + var museum = new DsCard("pokedex", AppStrings.MuseumTitle) { Tapped = () => _ = PushAsync() }; var trophies = new DsCard("ribbons", "Trophies") { Tapped = () => _ = PushAsync() }; var awards = new DsCard("credits", "Awards") { Tapped = () => _ = PushAsync() }; var settings = new DsCard("settings", AppStrings.Settings) { Tapped = () => _ = ShowSettingsAsync() }; - _cards = [bank, autopilot, park, events, emulators, library, trophies, awards, settings]; + _cards = [bank, autopilot, park, events, museum, emulators, library, trophies, awards, settings]; foreach (var card in _cards) BlockNativeFocus(card); var cards = new Grid { ColumnSpacing = 10, - ColumnDefinitions = [new(GridLength.Star), new(GridLength.Star), new(GridLength.Star), new(GridLength.Star), new(GridLength.Star), new(GridLength.Star), new(GridLength.Star), new(GridLength.Star), new(GridLength.Star)], - Children = { bank, autopilot, park, events, emulators, library, trophies, awards, settings }, + RowSpacing = 4, + ColumnDefinitions = [new(GridLength.Star), new(GridLength.Star), new(GridLength.Star), new(GridLength.Star), new(GridLength.Star)], + RowDefinitions = [new(GridLength.Auto), new(GridLength.Auto)], + Children = { bank, autopilot, park, events, museum, emulators, library, trophies, awards, settings }, }; Grid.SetColumn(autopilot, 1); Grid.SetColumn(park, 2); Grid.SetColumn(events, 3); - Grid.SetColumn(emulators, 4); - Grid.SetColumn(library, 5); - Grid.SetColumn(trophies, 6); - Grid.SetColumn(awards, 7); - Grid.SetColumn(settings, 8); + Grid.SetColumn(museum, 4); + Grid.SetColumn(emulators, 0); + Grid.SetRow(emulators, 1); + Grid.SetColumn(library, 1); + Grid.SetRow(library, 1); + Grid.SetColumn(trophies, 2); + Grid.SetRow(trophies, 1); + Grid.SetColumn(awards, 3); + Grid.SetRow(awards, 1); + Grid.SetColumn(settings, 4); + Grid.SetRow(settings, 1); var body = new Grid { @@ -396,9 +405,14 @@ public bool OnPadButton(PadButton button) switch (button) { case PadButton.Down when _zone == 0: _zone = 1; return FocusCard(0); - case PadButton.Up when _zone == 1: _zone = 0; ClearCardFocus(); return true; - case PadButton.Left: return _zone == 0 ? MoveShelf(-1) : FocusCard(_cardIndex - 1); - case PadButton.Right: return _zone == 0 ? MoveShelf(1) : FocusCard(_cardIndex + 1); + case PadButton.Up when _zone == 1: + if (_cardIndex >= 5) return FocusCard(_cardIndex - 5); + _zone = 0; + ClearCardFocus(); + return true; + case PadButton.Down when _zone == 1: return FocusCard(_cardIndex + 5); + case PadButton.Left: return _zone == 0 ? MoveShelf(-1) : MoveCard(-1); + case PadButton.Right: return _zone == 0 ? MoveShelf(1) : MoveCard(1); case PadButton.A: if (_zone == 1) { _cards[_cardIndex].Tapped?.Invoke(); return true; } return OpenShelfSelection(); @@ -415,7 +429,7 @@ public bool OnPadButton(PadButton button) } } - /// Move the cursor among the Bank/Events/Settings cards (the second focus zone). + /// Move the cursor among the Home destination cards (the second focus zone). private bool FocusCard(int index) { if (_cards.Length == 0) return false; @@ -424,6 +438,14 @@ private bool FocusCard(int index) return true; } + private bool MoveCard(int delta) + { + if (_cards.Length == 0) return false; + var rowStart = _cardIndex / 5 * 5; + var rowEnd = Math.Min(rowStart + 4, _cards.Length - 1); + return FocusCard(Math.Clamp(_cardIndex + delta, rowStart, rowEnd)); + } + private void ClearCardFocus() { foreach (var card in _cards) card.Selected = false; diff --git a/src/PKForge.App/Views/InfoKit.cs b/src/PKForge.App/Views/InfoKit.cs index 92395ceb..10c6ac5c 100644 --- a/src/PKForge.App/Views/InfoKit.cs +++ b/src/PKForge.App/Views/InfoKit.cs @@ -22,8 +22,6 @@ public static class InfoKit public static Color TypeColor(int type) => type == TypeFacts.Stellar ? StellarColor : TypePalette.ForType(type); - private static Color TypeInk(int type) => type == TypeFacts.Stellar ? Colors.White : TypePalette.ForegroundForType(type); - /// A fixed-width type plate ("FIRE", see ) so badge columns line up down a list. public static Border TypeBadge(int? type = null, double width = 60) { diff --git a/src/PKForge.App/Views/MuseumPage.cs b/src/PKForge.App/Views/MuseumPage.cs new file mode 100644 index 00000000..231014fc --- /dev/null +++ b/src/PKForge.App/Views/MuseumPage.cs @@ -0,0 +1,420 @@ +using PKForge.App.Services; +using PKForge.App.Theme; +using PKForge.App.ViewModels; +using PKForge.Chrome; +using PKForge.Domain; + +namespace PKForge.App.Views; + +/// Read-only Pokédex archive, one entry per linked save. The game flags come from +/// that save; shiny marks come from Pokémon currently stored in its boxes or party. +public sealed class MuseumPage : ContentPage, IPadHandler +{ + private sealed record MuseumGame( + DetectedSave Save, + IReadOnlyList Species, + IReadOnlyDictionary Entries, + IReadOnlySet ShinySpecies, + int Seen, + int Caught, + string? Error) + { + public int Total => Species.Count; + public bool CanOpen => Error is null && Total > 0; + public int ShinyCount => ShinySpecies.Count; + } + + private readonly SavePickerViewModel _saves; + private readonly ISaveFileAccess _files; + private readonly ISaveEngine _engine; + private readonly IGameDataService _data; + private readonly ISpriteService _sprites; + private readonly GamepadRouter _router; + private readonly SecondScreenState _secondScreen; + private readonly List _games = []; + private readonly List _gameRows = []; + private readonly Label _readout; + private readonly VerticalStackLayout _rows; + private readonly ScrollView _scroll; + private readonly Button _refresh; + private readonly Grid _hostGrid; + private SecondScreenClaim? _pageClaim; + private SecondScreenClaim? _dexClaim; + private DexGridView? _dexGrid; + private Grid? _dexOverlay; + private Label? _dexProgress; + private Label? _dexCursorInfo; + private CancellationTokenSource? _scanCancellation; + private int _selectedRow; + private bool _scanInProgress; + + public MuseumPage(SavePickerViewModel saves, ISaveFileAccess files, ISaveEngine engine, + IGameDataService data, ISpriteService sprites, GamepadRouter router, SecondScreenState secondScreen) + { + _saves = saves; + _files = files; + _engine = engine; + _data = data; + _sprites = sprites; + _router = router; + _secondScreen = secondScreen; + + Title = AppStrings.MuseumTitle; + BackgroundColor = UiTokens.Housing; + NavigationPage.SetHasNavigationBar(this, false); + + var back = Kit.MiniCapsule(AppStrings.Back, UiTokens.Ink0); + back.WidthRequest = 72; + back.Clicked += async (_, _) => await Navigation.PopAsync(); + var header = Kit.HeaderBar(AppStrings.MuseumTitle); + header.VerticalOptions = LayoutOptions.Center; + _refresh = Kit.Capsule(AppStrings.MuseumScan, UiTokens.Cyan); + _refresh.Clicked += (_, _) => _ = ScanAsync(); + + var titleRow = new Grid + { + ColumnSpacing = 10, + ColumnDefinitions = [new(GridLength.Auto), new(GridLength.Star), new(GridLength.Auto)], + Children = { back, header, _refresh }, + }; + Grid.SetColumn(header, 1); + Grid.SetColumn(_refresh, 2); + + _readout = new Label + { + Text = AppStrings.MuseumReadOnly, + TextColor = UiTokens.InkSoft, + FontFamily = DsChrome.PixelFont, + FontSize = UiTokens.TextBody, + LineBreakMode = LineBreakMode.WordWrap, + }; + _rows = new VerticalStackLayout { Spacing = 3 }; + _scroll = new ScrollView + { + Orientation = ScrollOrientation.Vertical, + VerticalScrollBarVisibility = ScrollBarVisibility.Never, + Content = _rows, + }; + + var hints = Kit.WindowHints( + ("A", AppStrings.Open, () => OpenSelectedDex()), + ("B", AppStrings.Back, () => _ = Navigation.PopAsync()), + ("X", AppStrings.MuseumScan, () => _ = ScanAsync())); + var body = new Grid + { + RowSpacing = 8, + RowDefinitions = [new(GridLength.Auto), new(GridLength.Star), new(GridLength.Auto)], + Children = { Kit.Well(_readout, padding: 8), _scroll, hints }, + }; + Grid.SetRow(_scroll, 1); + Grid.SetRow(hints, 2); + + var panel = Kit.DevicePanel(body); + var root = new Grid + { + Padding = new Thickness(14, 10), + RowSpacing = 10, + RowDefinitions = [new(GridLength.Auto), new(GridLength.Star)], + Children = { titleRow, panel }, + }; + Grid.SetRow(panel, 1); + _hostGrid = new Grid { Children = { DsChrome.GridBackground(), root } }; + Content = _hostGrid; + } + + protected override void OnAppearing() + { + base.OnAppearing(); + _secondScreen.PreviewSpecies = null; + _pageClaim ??= _secondScreen.Routes.CreateClaim(SecondScreenOwner.Pokedex); + _pageClaim.Activate(); + _router.Push(this); + if (_games.Count == 0) _ = ScanAsync(); + } + + protected override void OnDisappearing() + { + base.OnDisappearing(); + _scanCancellation?.Cancel(); + CloseDexOverlay(); + _pageClaim?.Release(); + _router.Remove(this); + } + + private async Task ScanAsync() + { + if (_scanInProgress) return; + _scanInProgress = true; + _refresh.IsEnabled = false; + _readout.Text = AppStrings.MuseumReading; + var cancellation = new CancellationTokenSource(); + _scanCancellation = cancellation; + var token = cancellation.Token; + try + { + var saves = _saves.Saves.Where(save => save.Identity?.IsHidden != true).ToArray(); + var measured = new List(saves.Length); + foreach (var save in saves) + { + token.ThrowIfCancellationRequested(); + try + { + var bytes = await _files.ReadAsync(save.DocumentId, token).ConfigureAwait(false); + measured.Add(await Task.Run(() => Measure(save, bytes), token).ConfigureAwait(false)); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + throw; + } + catch (Exception error) + { + AppLog.Error("museum", $"Reading {save.GameLabel} ({save.FileName}) failed", error); + measured.Add(Failed(save, error)); + } + } + + await MainThread.InvokeOnMainThreadAsync(() => + { + if (token.IsCancellationRequested) return; + _games.Clear(); + _games.AddRange(measured); + RebuildRows(); + _readout.Text = saves.Length == 0 + ? AppStrings.MuseumNoSaves + : AppStrings.MuseumReadOnly; + }); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + // Leaving the page cancels the scan; the next visit starts a fresh read. + } + finally + { + cancellation.Dispose(); + if (ReferenceEquals(_scanCancellation, cancellation)) _scanCancellation = null; + _scanInProgress = false; + await MainThread.InvokeOnMainThreadAsync(() => _refresh.IsEnabled = true); + } + } + + private MuseumGame Measure(DetectedSave save, ReadOnlyMemory bytes) + { + using var session = _engine.OpenSession(bytes, save.EngineHint, save.Format); + var maxSpecies = Math.Min(session.MaxSpeciesId, _data.SpeciesNames.Count - 1); + var species = new List(Math.Max(0, maxSpecies)); + var entries = new Dictionary(); + for (var id = 1; id <= maxSpecies; id++) + { + if (_data.SpeciesNames[id].Length == 0 || !session.IsDexSpecies(id)) continue; + species.Add(id); + entries[id] = session.GetDexEntry(id); + } + + var shiny = session.Snapshot.Slots + .Where(slot => slot.Species is > 0 && !slot.IsEgg && slot.IsShiny) + .Select(slot => slot.Species!.Value) + .Where(entries.ContainsKey) + .ToHashSet(); + return new MuseumGame(save, species, entries, shiny, + entries.Values.Count(entry => entry.Seen), + entries.Values.Count(entry => entry.Caught), + Error: species.Count == 0 ? AppStrings.MuseumNoDex : null); + } + + private static MuseumGame Failed(DetectedSave save, Exception error) => + new(save, [], new Dictionary(), new HashSet(), 0, 0, + AppStrings.MuseumReadError(error.Message)); + + private void RebuildRows() + { + _rows.Children.Clear(); + _gameRows.Clear(); + _selectedRow = Math.Clamp(_selectedRow, 0, Math.Max(0, _games.Count - 1)); + if (_games.Count == 0) + { + _rows.Children.Add(Kit.BodyText(AppStrings.MuseumNoSaves, UiTokens.InkSoft)); + return; + } + + for (var i = 0; i < _games.Count; i++) + { + var game = _games[i]; + var titleText = game.Save.Identity?.DisplayName is { Length: > 0 } customName + ? customName + : game.Save.EngineHint; + var title = new Label + { + Text = titleText, + TextColor = UiTokens.Ink0, + FontFamily = DsChrome.PixelFont, + FontSize = 14, + VerticalOptions = LayoutOptions.Center, + LineBreakMode = LineBreakMode.TailTruncation, + }; + var detail = new Label + { + Text = game.Error ?? AppStrings.MuseumProgress(game.Seen, game.Caught, game.Total, game.ShinyCount), + TextColor = game.Error is null ? UiTokens.InkSoft : UiTokens.Gold, + FontFamily = DsChrome.PixelFont, + FontSize = UiTokens.TextSmall, + LineBreakMode = LineBreakMode.TailTruncation, + }; + var filename = Kit.Caption(game.Save.FileName); + var text = new VerticalStackLayout { Spacing = 2, Children = { title, detail, filename } }; + var row = Kit.Row(text, shaded: i % 2 != 0, padding: new Thickness(10, 7)); + var tap = new TapGestureRecognizer(); + var index = i; + tap.Tapped += (_, _) => + { + SelectRow(index); + OpenSelectedDex(); + }; + row.GestureRecognizers.Add(tap); + _rows.Children.Add(row); + _gameRows.Add(row); + } + SelectRow(_selectedRow, scrollIntoView: false); + } + + private void SelectRow(int index, bool scrollIntoView = true) + { + if (_gameRows.Count == 0) return; + _selectedRow = Math.Clamp(index, 0, _gameRows.Count - 1); + for (var i = 0; i < _gameRows.Count; i++) + Kit.SetRowFocus(_gameRows[i], i == _selectedRow, shaded: i % 2 != 0); + if (scrollIntoView) _ = _scroll.ScrollToAsync(_gameRows[_selectedRow], ScrollToPosition.MakeVisible, true); + } + + private void OpenSelectedDex() + { + if (_dexOverlay is not null || (uint)_selectedRow >= (uint)_games.Count) return; + var game = _games[_selectedRow]; + if (!game.CanOpen) + { + _readout.Text = game.Error ?? AppStrings.MuseumNoDex; + return; + } + + var ids = game.Species; + var grid = new DexGridView(_sprites) { VerticalOptions = LayoutOptions.Fill }; + _dexGrid = grid; + _dexProgress = new Label + { + TextColor = UiTokens.Ink1, + FontFamily = DsChrome.PixelFont, + FontSize = UiTokens.TextBody, + HorizontalTextAlignment = TextAlignment.End, + HorizontalOptions = LayoutOptions.End, + }; + _dexCursorInfo = new Label + { + TextColor = UiTokens.Ink1, + FontFamily = DsChrome.PixelFont, + FontSize = UiTokens.TextBody, + }; + var title = new Label + { + Text = game.Save.Identity?.DisplayName is { Length: > 0 } customName ? customName : game.Save.EngineHint, + TextColor = UiTokens.Ink0, + FontFamily = DsChrome.PixelFont, + FontSize = 15, + LineBreakMode = LineBreakMode.TailTruncation, + VerticalOptions = LayoutOptions.Center, + }; + var titleRow = new Grid + { + ColumnSpacing = 12, + ColumnDefinitions = [new(GridLength.Star), new(GridLength.Auto)], + Children = { title, _dexProgress }, + }; + Grid.SetColumn(_dexProgress, 1); + var hints = Kit.WindowHints( + ("B", AppStrings.Back, CloseDexOverlay), + ("L", AppStrings.MuseumPrevious, () => grid.JumpSection(-1)), + ("R", AppStrings.MuseumNext, () => grid.JumpSection(1))); + var content = new Grid + { + RowSpacing = 6, + RowDefinitions = [new(GridLength.Auto), new(GridLength.Star), new(GridLength.Auto), new(GridLength.Auto)], + Children = { titleRow, grid, _dexCursorInfo, hints }, + }; + Grid.SetRow(grid, 1); + Grid.SetRow(_dexCursorInfo, 2); + Grid.SetRow(hints, 3); + + grid.Show(ids, id => + { + var state = game.Entries[id]; + return new DexGridView.Look(state.Seen, state.Caught, ShinyMark: game.ShinySpecies.Contains(id)); + }); + grid.CursorChanged += index => UpdateDexCursor(game, ids, index); + grid.Tapped += index => grid.SetCursor(index); + + var window = Kit.DevicePanel(content, padding: 10); + window.Margin = new Thickness(24, 12); + var scrim = new BoxView { Color = UiTokens.Scrim }; + var scrimTap = new TapGestureRecognizer(); + scrimTap.Tapped += (_, _) => CloseDexOverlay(); + scrim.GestureRecognizers.Add(scrimTap); + _dexOverlay = new Grid { Children = { scrim, window } }; + _hostGrid.Add(_dexOverlay); + Grid.SetRowSpan(_dexOverlay, Math.Max(1, _hostGrid.RowDefinitions.Count)); + Grid.SetColumnSpan(_dexOverlay, Math.Max(1, _hostGrid.ColumnDefinitions.Count)); + _dexClaim = _secondScreen.Routes.OpenOverlay(SecondScreenOwner.Pokedex); + Kit.AnimateIn(window); + grid.SetCursor(0); + } + + private void UpdateDexCursor(MuseumGame game, IReadOnlyList ids, int index) + { + if ((uint)index >= (uint)ids.Count) return; + var species = ids[index]; + var state = game.Entries[species]; + var shiny = game.ShinySpecies.Contains(species); + if (_dexProgress is not null) + _dexProgress.Text = AppStrings.MuseumProgress(game.Seen, game.Caught, game.Total, game.ShinyCount); + if (_dexCursorInfo is not null) + _dexCursorInfo.Text = $"#{species:000} {_data.SpeciesNames[species]} · {AppStrings.MuseumSpeciesState(state.Seen, state.Caught, shiny)}"; + _secondScreen.PreviewSpecies = species; + } + + private void CloseDexOverlay() + { + _dexClaim?.Release(); + _dexClaim = null; + _secondScreen.PreviewSpecies = null; + if (_dexOverlay is not null) _hostGrid.Remove(_dexOverlay); + _dexOverlay = null; + _dexGrid = null; + _dexProgress = null; + _dexCursorInfo = null; + } + + public bool OnPadButton(PadButton button) + { + if (_dexGrid is { } grid) + { + switch (button) + { + case PadButton.Left: grid.Move(-1, 0); return true; + case PadButton.Right: grid.Move(1, 0); return true; + case PadButton.Up: grid.Move(0, -1); return true; + case PadButton.Down: grid.Move(0, 1); return true; + case PadButton.L: grid.JumpSection(-1); return true; + case PadButton.R: grid.JumpSection(1); return true; + case PadButton.B: CloseDexOverlay(); return true; + default: return true; + } + } + + switch (button) + { + case PadButton.Up: SelectRow(_selectedRow - 1); return true; + case PadButton.Down: SelectRow(_selectedRow + 1); return true; + case PadButton.A: OpenSelectedDex(); return true; + case PadButton.B: _ = Navigation.PopAsync(); return true; + case PadButton.X: _ = ScanAsync(); return true; + default: return true; + } + } +} diff --git a/src/PKForge.App/Views/NintendoDsSecondaryScreenPage.cs b/src/PKForge.App/Views/NintendoDsSecondaryScreenPage.cs new file mode 100644 index 00000000..b4a2e9ca --- /dev/null +++ b/src/PKForge.App/Views/NintendoDsSecondaryScreenPage.cs @@ -0,0 +1,100 @@ +using PKForge.App.Platforms.Android; +using SkiaSharp; +using SkiaSharp.Views.Maui; +using SkiaSharp.Views.Maui.Controls; + +namespace PKForge.App.Views; + +/// Displays the Nintendo DS lower framebuffer on Android's secondary display. +public sealed class NintendoDsSecondaryScreenPage : ContentPage +{ + private readonly IEmbeddedGameSession _session; + private readonly SKCanvasView _canvas = new() { IgnorePixelScaling = true, EnableTouchEvents = true }; + private SKRect _screenRect; + private long _touchPointerId = -1; + private bool _cleanedUp; + + public IEmbeddedGameSession Session => _session; + + public NintendoDsSecondaryScreenPage(IEmbeddedGameSession session) + { + _session = session ?? throw new ArgumentNullException(nameof(session)); + BackgroundColor = Colors.Black; + Content = _canvas; + _canvas.PaintSurface += OnPaint; + _canvas.Touch += OnTouch; + _session.FrameProduced += Invalidate; + } + + private void OnPaint(object? sender, SKPaintSurfaceEventArgs args) + { + var canvas = args.Surface.Canvas; + canvas.Clear(SKColors.Black); + var scale = Math.Min(args.Info.Width / 256f, args.Info.Height / 192f); + if (scale <= 0) return; + + var width = 256 * scale; + var height = 192 * scale; + var left = (args.Info.Width - width) / 2f; + var top = (args.Info.Height - height) / 2f; + _screenRect = new SKRect(left, top, left + width, top + height); + _session.DrawSecondaryScreen(canvas, _screenRect); + } + + private void OnTouch(object? sender, SKTouchEventArgs args) + { + switch (args.ActionType) + { + case SKTouchAction.Pressed when _touchPointerId == -1: + _touchPointerId = args.Id; + UpdateTouch(args.Location); + args.Handled = true; + break; + case SKTouchAction.Moved when args.Id == _touchPointerId: + UpdateTouch(args.Location); + args.Handled = true; + break; + case SKTouchAction.Released or SKTouchAction.Cancelled when args.Id == _touchPointerId: + ReleaseTouch(); + args.Handled = true; + break; + } + } + + private void UpdateTouch(SKPoint location) + { + if (!_screenRect.Contains(location.X, location.Y) || _screenRect.Width <= 0 || _screenRect.Height <= 0) + { + _session.SetTouchScreen(false, 0, 0); + return; + } + + var x = (int)((location.X - _screenRect.Left) * 256f / _screenRect.Width); + var y = (int)((location.Y - _screenRect.Top) * 192f / _screenRect.Height); + _session.SetTouchScreen(true, Math.Clamp(x, 0, 255), Math.Clamp(y, 0, 191)); + } + + private void ReleaseTouch() + { + _touchPointerId = -1; + _session.SetTouchScreen(false, 0, 0); + } + + private void Invalidate() => MainThread.InvokeOnMainThreadAsync(_canvas.InvalidateSurface); + + public void Cleanup() + { + if (_cleanedUp) return; + _cleanedUp = true; + ReleaseTouch(); + _session.FrameProduced -= Invalidate; + _canvas.PaintSurface -= OnPaint; + _canvas.Touch -= OnTouch; + } + + protected override void OnDisappearing() + { + base.OnDisappearing(); + Cleanup(); + } +} diff --git a/src/PKForge.App/Views/PokeparkPage.cs b/src/PKForge.App/Views/PokeparkPage.cs index 58f1ac0f..3a67e07f 100644 --- a/src/PKForge.App/Views/PokeparkPage.cs +++ b/src/PKForge.App/Views/PokeparkPage.cs @@ -1102,17 +1102,6 @@ private static (string Trait, string Likes, string Story, string Greeting) Perso }; } - private static ParkEnvironmentId HomeHabitat(ParkPokemon mon) - { - var types = HabitatCatalog.TypesFor(mon.Species, mon.Form); - if (types.Contains(ParkType.Water)) return ParkEnvironmentId.WaterfallLake; - if (types.Contains(ParkType.Fire) || types.Contains(ParkType.Ground)) - return ParkEnvironmentId.EmberGrove; - if (types.Contains(ParkType.Flying) || types.Contains(ParkType.Ice) || types.Contains(ParkType.Rock)) - return ParkEnvironmentId.SkySummit; - return ParkEnvironmentId.Commons; - } - private async Task ShowJournalAsync() { var offline = _offlineJournal.Load().Journal.Select(e => (At: e.Timestamp, e.Text)); diff --git a/src/PKForge.App/Views/RomLibraryPage.cs b/src/PKForge.App/Views/RomLibraryPage.cs index aa1c0a96..42ff0679 100644 --- a/src/PKForge.App/Views/RomLibraryPage.cs +++ b/src/PKForge.App/Views/RomLibraryPage.cs @@ -9,30 +9,39 @@ namespace PKForge.App.Views; /// /// The game library, PlayHub-style: one card per discovered Pokémon ROM with its /// artwork (cartridge mark as fallback), the generation · emulator subtitle, and a -/// colored status line — green when a save was found, amber when the ROM is linked, -/// muted otherwise. Tapping a playable row launches it in the console's bound -/// emulator. The emulator chips above link in one tap through the standard save -/// folders, never a folder picker. +/// ROM filename. Tapping a playable row launches it in the console's bound +/// emulator. Search filters by game, ROM filename, or console; the same list can +/// be navigated with a controller. /// public sealed class RomLibraryPage : ContentPage, IPadHandler { + private sealed record LibraryCard(string GameName, int Generation, LibraryRom? Rom); + private sealed record LibraryRow(LibraryCard Card, View View); + private readonly IRomScanner _scanner; private readonly IRomLibraryStore _library; private readonly IConsoleEmulatorStore _consoleEmulators; private readonly IEmulatorLauncher _launcher; - private readonly DirectSaveScanner? _saveScanner; private VerticalStackLayout _rows = null!; + private ScrollView _scroll = null!; + private Entry _search = null!; + private Button _scanButton = null!; private Grid _hostGrid = null!; private Label _readout = null!; private Label _countLabel = null!; - - public RomLibraryPage(IRomScanner scanner, IRomLibraryStore library, IConsoleEmulatorStore consoleEmulators, IEmulatorLauncher launcher, ISaveEngine? engine = null) + private readonly List _catalogRows = []; + private readonly List _visibleRows = []; + private readonly List _visiblePlayableRows = []; + private IReadOnlyList _allRoms = []; + private int _selectedRomIndex = -1; + private bool _scanInProgress; + + public RomLibraryPage(IRomScanner scanner, IRomLibraryStore library, IConsoleEmulatorStore consoleEmulators, IEmulatorLauncher launcher) { _scanner = scanner; _library = library; _consoleEmulators = consoleEmulators; _launcher = launcher; - _saveScanner = engine is not null ? new DirectSaveScanner(engine) : null; Title = AppStrings.LibraryTitle; BackgroundColor = UiTokens.Housing; NavigationPage.SetHasNavigationBar(this, false); @@ -52,18 +61,18 @@ public RomLibraryPage(IRomScanner scanner, IRomLibraryStore library, IConsoleEmu VerticalOptions = LayoutOptions.Center, }; - var scan = Kit.Capsule(AppStrings.ScanRoms, UiTokens.Cyan); - scan.Clicked += (_, _) => _ = ScanAsync(); + _scanButton = Kit.Capsule(AppStrings.ScanRoms, UiTokens.Cyan); + _scanButton.Clicked += (_, _) => _ = ScanAsync(); var titleRow = new Grid { ColumnSpacing = 10, ColumnDefinitions = [new(GridLength.Auto), new(GridLength.Star), new(GridLength.Auto), new(GridLength.Auto)], - Children = { back, header, _countLabel, scan }, + Children = { back, header, _countLabel, _scanButton }, }; Grid.SetColumn(header, 1); Grid.SetColumn(_countLabel, 2); - Grid.SetColumn(scan, 3); + Grid.SetColumn(_scanButton, 3); _readout = new Label { @@ -73,21 +82,45 @@ public RomLibraryPage(IRomScanner scanner, IRomLibraryStore library, IConsoleEmu LineBreakMode = LineBreakMode.WordWrap, }; + _search = new Entry + { + Placeholder = AppStrings.LibrarySearchPlaceholder, + ClearButtonVisibility = ClearButtonVisibility.WhileEditing, + ReturnType = ReturnType.Search, + IsSpellCheckEnabled = false, + IsTextPredictionEnabled = false, + FontSize = 14, + TextColor = UiTokens.Ink0, + PlaceholderColor = UiTokens.Ink1, + BackgroundColor = UiTokens.ShellPress, + HeightRequest = 40, + }; + _search.TextChanged += (_, _) => ApplySearch(); + _search.Completed += (_, _) => _search.Unfocus(); + _rows = new VerticalStackLayout { Spacing = 6 }; - var scrollable = new ScrollView + _scroll = new ScrollView { Orientation = ScrollOrientation.Vertical, VerticalScrollBarVisibility = ScrollBarVisibility.Never, Content = _rows, }; + var hints = Kit.WindowHints( + ("A", AppStrings.Play, LaunchSelected), + ("B", AppStrings.Back, () => _ = Navigation.PopAsync()), + ("Y", AppStrings.LibrarySearch, () => _search.Focus()), + ("X", AppStrings.LibraryClearSearch, () => _search.Text = string.Empty), + ("+", AppStrings.ScanRoms, () => _ = ScanAsync())); var body = new Grid { RowSpacing = 10, - RowDefinitions = [new(GridLength.Auto), new(GridLength.Star)], - Children = { Kit.Well(_readout, padding: 8), scrollable }, + RowDefinitions = [new(GridLength.Auto), new(GridLength.Auto), new(GridLength.Star), new(GridLength.Auto)], + Children = { Kit.Well(_readout, padding: 8), _search, _scroll, hints }, }; - Grid.SetRow(scrollable, 1); + Grid.SetRow(_search, 1); + Grid.SetRow(_scroll, 2); + Grid.SetRow(hints, 3); var panel = Kit.DevicePanel(body); var root = new Grid @@ -112,29 +145,119 @@ protected override void OnAppearing() protected override void OnDisappearing() { base.OnDisappearing(); + _search.Unfocus(); IPlatformApplication.Current?.Services.GetService()?.Remove(this); } private void Rebuild(IReadOnlyList roms) { _rows.Children.Clear(); - // The whole catalog shows: owned games first (with their ROM), the rest after, - // each with a colored owned/missing label. - var byName = roms.GroupBy(r => r.GameName, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); - // Catalog order (Gen 1 → 9, release order within a generation): owned games - // show their ROM, the rest show the colored missing label. - var ordered = TrophyCatalog.Games - .Select(game => (Game: game, Rom: byName.GetValueOrDefault(Normalise(game.Label)))) - .ToList(); - foreach (var (game, rom) in ordered) - _rows.Children.Add(rom is not null ? BuildRomCard(rom) : BuildMissingCard(game.Label, game.Generation)); - _countLabel.Text = AppStrings.RomCount(roms.Count); - _readout.Text = roms.Count > 0 - ? AppStrings.RomCount(roms.Count) - : _scanner.RomRoot is null ? AppStrings.NoRomRoot : AppStrings.Fr - ? "Appuyez sur Scanner pour chercher vos ROMs dans /storage/emulated/0/ROMs." - : "Tap Scan to look for your ROMs in /storage/emulated/0/ROMs."; + _catalogRows.Clear(); + _allRoms = roms; + + // Keep every ROM for an edition; selecting only the first dump hid alternate + // copies and formats from both touch and controller users. + var byName = roms.GroupBy(rom => Normalise(rom.GameName), StringComparer.OrdinalIgnoreCase) + .ToDictionary(group => group.Key, + group => group.OrderBy(rom => rom.FileName, StringComparer.OrdinalIgnoreCase).ToArray(), + StringComparer.OrdinalIgnoreCase); + foreach (var (label, generation, _) in TrophyCatalog.Games) + { + if (byName.TryGetValue(Normalise(label), out var matches)) + { + foreach (var rom in matches) + AddCatalogRow(new LibraryCard(label, generation, rom), BuildRomCard(rom)); + } + else + { + AddCatalogRow(new LibraryCard(label, generation, null), BuildMissingCard(label, generation)); + } + } + ApplySearch(); + } + + private void AddCatalogRow(LibraryCard card, View view) + { + var row = new LibraryRow(card, view); + _catalogRows.Add(row); + _rows.Children.Add(view); + } + + private void ApplySearch() + { + var selectedPath = SelectedRom()?.FilePath; + var query = _search.Text?.Trim() ?? string.Empty; + _visibleRows.Clear(); + _visiblePlayableRows.Clear(); + + foreach (var row in _catalogRows) + { + var visible = Matches(row.Card, query); + row.View.IsVisible = visible; + if (!visible) continue; + _visibleRows.Add(row); + if (row.Card.Rom is not null) _visiblePlayableRows.Add(row); + } + + _countLabel.Text = AppStrings.LibraryResults( + _visibleRows.Count, _visibleRows.Count(row => row.Card.Rom is not null)); + _readout.Text = query.Length > 0 && _visibleRows.Count == 0 + ? AppStrings.LibraryNoResults(query) + : _allRoms.Count > 0 + ? AppStrings.LibraryReady + : _scanner.RomRoot is null ? AppStrings.NoRomRoot : AppStrings.LibraryScanHint; + + _selectedRomIndex = selectedPath is null + ? -1 + : _visiblePlayableRows.FindIndex(row => row.Card.Rom?.FilePath == selectedPath); + if (_selectedRomIndex < 0 && _visiblePlayableRows.Count > 0) _selectedRomIndex = 0; + UpdateRomSelection(scrollIntoView: false); + } + + private static bool Matches(LibraryCard card, string query) + { + if (query.Length == 0 || card.GameName.Contains(query, StringComparison.OrdinalIgnoreCase)) return true; + if (card.Rom is not { } rom) return false; + return rom.FileName.Contains(query, StringComparison.OrdinalIgnoreCase) + || ConsoleNameConverter.ConsoleLabel(rom.Console).Contains(query, StringComparison.OrdinalIgnoreCase); + } + + private LibraryRom? SelectedRom() => + (uint)_selectedRomIndex < (uint)_visiblePlayableRows.Count + ? _visiblePlayableRows[_selectedRomIndex].Card.Rom + : null; + + private void SelectRom(int index, bool scrollIntoView = true) + { + if (_visiblePlayableRows.Count == 0) + { + _selectedRomIndex = -1; + return; + } + _selectedRomIndex = Math.Clamp(index, 0, _visiblePlayableRows.Count - 1); + UpdateRomSelection(scrollIntoView); + } + + private void UpdateRomSelection(bool scrollIntoView) + { + var selectedRow = (uint)_selectedRomIndex < (uint)_visiblePlayableRows.Count + ? _visiblePlayableRows[_selectedRomIndex] + : null; + foreach (var row in _catalogRows) + { + if (row.Card.Rom is null || row.View is not Border border) continue; + var selected = ReferenceEquals(row, selectedRow); + border.BackgroundColor = selected ? UiTokens.SelectFill : UiTokens.Paper; + border.Stroke = selected ? UiTokens.Rim : UiTokens.ShellEdge; + border.StrokeThickness = selected ? UiTokens.PanelEdge : 1; + } + if (scrollIntoView && selectedRow is not null) + _ = _scroll.ScrollToAsync(selectedRow.View, ScrollToPosition.MakeVisible, true); + } + + private void LaunchSelected() + { + if (SelectedRom() is { } rom) _ = LaunchAsync(rom); } private static string Normalise(string label) => @@ -201,8 +324,7 @@ private View BuildMissingCard(string label, int generation) return card; } - /// One game card: artwork (cartridge mark as fallback), title, generation· - /// emulator subtitle, and the colored status line. + /// One playable ROM card, including its source filename and console. private View BuildRomCard(LibraryRom rom) { // The artwork loads asynchronously at build time: the cartridge mark shows @@ -272,7 +394,13 @@ private View BuildRomCard(LibraryRom rom) // Every binding in the card reads from the row's own context. row.BindingContext = rom; var tap = new TapGestureRecognizer(); - tap.Tapped += (_, _) => _ = LaunchAsync(rom); + tap.Tapped += (_, _) => + { + var index = _visiblePlayableRows.FindIndex(candidate => + string.Equals(candidate.Card.Rom?.FilePath, rom.FilePath, StringComparison.Ordinal)); + if (index >= 0) SelectRom(index, scrollIntoView: false); + _ = LaunchAsync(rom); + }; row.GestureRecognizers.Add(tap); return row; } @@ -287,35 +415,47 @@ private static async Task LoadArtAsync(Image art, GameCartridgeMark mark, string mark.IsVisible = false; } - /// A tap launches the game. GB/GBC/GBA always play in PKForge itself - /// (the embedded core); the other consoles go to their bound external emulator. + /// Launches ROMs with an integrated core in PKForge; otherwise uses the + /// selected console emulator. Pokémon ROMs never follow a stale external DS binding. private async Task LaunchAsync(LibraryRom rom) { - // Consoles PKForge runs in-app (GB/GBC/GBA): embedded first and only — - // a stale binding or an installed external emulator is never consulted. + var bound = _consoleEmulators.Find(rom.Console); + var generation = RomNameRules.GenerationOf(rom.GameName); if (ConsoleRules.RunsInApp(rom.Console)) { - var save = Platforms.Android.EmbeddedGameSession.SavePathForRom(rom.FilePath); - var session = await Task.Run(() => Platforms.Android.EmbeddedGameSession.TryStart(rom.FilePath, save)); - if (session is not null) + var services = IPlatformApplication.Current?.Services; + var romLinks = services?.GetService(); + var linkedSave = romLinks?.GetAll() + .FirstOrDefault(link => string.Equals(link.RomUri, rom.FilePath, StringComparison.Ordinal)); + if (linkedSave is not null && RomLinkRules.UsesIntegratedCore(generation) + && linkedSave.Emulator != EmulatorKind.Embedded) + { + romLinks?.Set(linkedSave with { Emulator = EmulatorKind.Embedded, Generation = generation }); + } + var saveFiles = linkedSave is null ? null : services?.GetService(); + var start = await Task.Run(() => Platforms.Android.EmbeddedGameSession.TryStart( + rom.FilePath, generation, rom.FileName, linkedSave?.SaveDocumentId, saveFiles)); + if (start.Session is { } session) { await MainThread.InvokeOnMainThreadAsync(() => Navigation.PushAsync(new EmbeddedGamePage(session))); return; } - await PadMenu.ShowAsync(_hostGrid, AppStrings.RomMissing, - $"{rom.GameName}: the embedded core is not packed in this build.", AppStrings.Ok); + await PadMenu.ShowAsync(_hostGrid, AppStrings.GameLaunchFailedTitle, + AppStrings.GameLaunchFailed(rom.GameName, start.Error, generation), AppStrings.Ok); return; } - var bound = _consoleEmulators.Find(rom.Console); var fallback = ConsoleRules.EmulatorsFor(rom.Console) - .FirstOrDefault(kind => EmulatorCatalog.IsInstalled(kind, _launcher.IsInstalled)); - if (bound is null && fallback == default) + .Where(kind => kind != EmulatorKind.Embedded) + .Where(kind => EmulatorCatalog.IsInstalled(kind, _launcher.IsInstalled)) + .Select(kind => (EmulatorKind?)kind) + .FirstOrDefault(); + if (bound is null && fallback is null) { await PadMenu.ShowAsync(_hostGrid, AppStrings.RomMissing, $"{rom.GameName}: {AppStrings.NotInstalled}.", AppStrings.Ok); return; } - var kind = bound ?? fallback; + var kind = bound ?? fallback!.Value; var link = new RomLink("library", rom.FilePath, rom.FileName, kind, RomNameRules.GenerationOf(rom.GameName), $"Pokémon {rom.GameName}"); if (await _launcher.LaunchAsync(link)) @@ -332,6 +472,9 @@ await PadMenu.ShowAsync(_hostGrid, AppStrings.RomMissing, /// One pass over every console's ES-DE folder; the library is replaced wholesale. private async Task ScanAsync() { + if (_scanInProgress) return; + _scanInProgress = true; + _scanButton.IsEnabled = false; _readout.Text = AppStrings.Scanning; try { @@ -349,14 +492,24 @@ private async Task ScanAsync() { _readout.Text = error.Message; } + finally + { + _scanInProgress = false; + _scanButton.IsEnabled = true; + } } public bool OnPadButton(PadButton button) { switch (button) { - case PadButton.A: _ = ScanAsync(); return true; + case PadButton.Up: SelectRom(_selectedRomIndex - 1); return true; + case PadButton.Down: SelectRom(_selectedRomIndex + 1); return true; + case PadButton.A: LaunchSelected(); return true; case PadButton.B: _ = Navigation.PopAsync(); return true; + case PadButton.X: _search.Text = string.Empty; return true; + case PadButton.Y: _search.Focus(); return true; + case PadButton.Start: _ = ScanAsync(); return true; default: return true; // own the pad while this page is up } } diff --git a/src/PKForge.App/Views/SaveIdentitySheet.cs b/src/PKForge.App/Views/SaveIdentitySheet.cs index 8103b89e..a7bc7817 100644 --- a/src/PKForge.App/Views/SaveIdentitySheet.cs +++ b/src/PKForge.App/Views/SaveIdentitySheet.cs @@ -38,7 +38,7 @@ public static async Task ShowAsync(Grid host, SavePickerViewModel picker, if (offerOpen) options.Add(new PadOption(OpenOption, IconPath: "play")); if (romLink is { } linked) { - var where = linked.Generation is >= 1 and <= 3 + var where = RomLinkRules.MustRunInApp(linked.Generation, linked.RomFileName) ? (AppStrings.Fr ? "dans PKForge" : "in PKForge") : $"in {SaveDescriptions.EmulatorName(linked.Emulator)}"; options.Add(new PadOption(PlayOption, IconPath: "play", @@ -47,7 +47,7 @@ public static async Task ShowAsync(Grid host, SavePickerViewModel picker, } options.Add(new PadOption(LinkRomOption, IconPath: "file", Detail: romLink is null - ? (AppStrings.Fr ? "Choisissez la ROM de ce jeu une fois ; Jouer la lancera dans PKForge (GB/GBA) ou son émulateur." : "Pick this game's ROM once; Play then launches it in PKForge (GB/GBA) or its emulator.") + ? (AppStrings.Fr ? "Choisissez la ROM de ce jeu une fois ; Jouer la lancera dans PKForge (GB/GBC/GBA/DS .nds) ou via un émulateur externe tant que le cœur de sa console manque." : "Pick this game's ROM once; Play launches it in PKForge (GB/GBC/GBA/DS .nds), or an external emulator while that console's core is still missing.") : (AppStrings.Fr ? $"Remplacer {romLink.RomFileName}." : $"Replace {romLink.RomFileName}."))); options.Add(new PadOption(RenameOption, IconPath: "rename")); options.Add(new PadOption(ColorOption, Glyph: "●", Accent: SaveColors.For(resolved?.ColorKey, save.Generation), @@ -115,13 +115,17 @@ public static async Task ShowAsync(Grid host, SavePickerViewModel picker, private static IDocumentPicker? FilePicker => IPlatformApplication.Current?.Services.GetService(); - /// Launches a linked ROM: GB/GBC/GBA (Gen 1-3) play in PKForge itself via the - /// embedded core; anything else is handed to its external emulator. + /// Launches supported Gen 1-5 Pokémon ROMs in PKForge. Older saved DS links + /// are migrated on first play so a stale third-party selection cannot take over. private static async Task LaunchAsync(Grid host, RomLink link) { - if (link.Generation is >= 1 and <= 3) + if (RomLinkRules.MustRunInApp(link.Generation, link.RomFileName)) { - await LaunchEmbeddedAsync(host, link); + var generation = RomLinkRules.ResolveIntegratedGeneration(link.Generation, link.RomFileName); + var integratedLink = link with { Emulator = EmulatorKind.Embedded, Generation = generation }; + if (link.Emulator != EmulatorKind.Embedded || link.Generation != generation) + RomLinks?.Set(integratedLink); + await LaunchEmbeddedAsync(host, integratedLink); return; } var launcher = Launcher; @@ -140,12 +144,13 @@ await PadMenu.ShowAsync(host, "Could not launch", /// Opens the linked GB/GBC/GBA ROM in the embedded game screen. private static async Task LaunchEmbeddedAsync(Grid host, RomLink link) { - var save = Platforms.Android.EmbeddedGameSession.SavePathForRom(link.RomUri); - var session = await Task.Run(() => Platforms.Android.EmbeddedGameSession.TryStart(link.RomUri, save)); - if (session is null) + var saveFiles = IPlatformApplication.Current?.Services.GetService(); + var start = await Task.Run(() => Platforms.Android.EmbeddedGameSession.TryStart( + link.RomUri, link.Generation, link.RomFileName, link.SaveDocumentId, saveFiles)); + if (start.Session is not { } session) { - await PadMenu.ShowAsync(host, "Could not launch", - $"{link.RomFileName}: the embedded core is not packed in this build.", "OK"); + await PadMenu.ShowAsync(host, AppStrings.GameLaunchFailedTitle, + AppStrings.GameLaunchFailed(link.RomFileName, start.Error, link.Generation), AppStrings.Ok); return; } await MainThread.InvokeOnMainThreadAsync(async () => @@ -178,20 +183,46 @@ private static async Task LinkRomAsync(Grid host, DetectedSave save) if (candidates.FirstOrDefault(r => r.FileName == choice) is { } fromLibrary) { - // Gen 1-3 (GB/GBC/GBA) always launch embedded in PKForge; the console binding - // only matters for the consoles that still need an external emulator. - var kind = ConsoleRules.RunsInApp(fromLibrary.Console) - ? EmulatorKind.Embedded - : IPlatformApplication.Current?.Services.GetService()?.Find(fromLibrary.Console) - ?? ConsoleRules.EmulatorsFor(fromLibrary.Console) - .FirstOrDefault(k => k != EmulatorKind.Embedded && EmulatorCatalog.IsInstalled(k, Launcher is { } l ? l.IsInstalled : _ => false)); - if (kind == default && !ConsoleRules.RunsInApp(fromLibrary.Console)) + var generation = fromLibrary.Generation > 0 ? fromLibrary.Generation : save.Generation; + if (RomLinkRules.UsesIntegratedCore(generation)) + { + if (!RomLinkRules.IsSupportedEmbeddedFormat(generation, fromLibrary.FileName)) + { + await PadMenu.ShowAsync(host, "ROM non prise en charge", + AppStrings.EmbeddedRomFormatUnsupported(generation, fromLibrary.FileName), AppStrings.Ok); + return; + } + + var coreAvailable = generation is >= 1 and <= 3 + ? EmulatorCatalog.EmbeddedCoreAvailable + : EmulatorCatalog.EmbeddedDsCoreAvailable; + if (!coreAvailable) + { + await PadMenu.ShowAsync(host, AppStrings.GameLaunchFailedTitle, + AppStrings.EmbeddedCoreMissing(generation), AppStrings.Ok); + return; + } + + links.Set(new RomLink(save.DocumentId, fromLibrary.FilePath, fromLibrary.FileName, + EmulatorKind.Embedded, generation, save.EngineHint)); + return; + } + + var consoleEmulators = IPlatformApplication.Current?.Services.GetService(); + var bound = consoleEmulators?.Find(fromLibrary.Console); + EmulatorKind? kind = bound is null or EmulatorKind.Embedded ? null : bound; + kind ??= ConsoleRules.EmulatorsFor(fromLibrary.Console) + .Where(k => k != EmulatorKind.Embedded) + .Where(k => EmulatorCatalog.IsInstalled(k, Launcher is { } l ? l.IsInstalled : _ => false)) + .Select(k => (EmulatorKind?)k) + .FirstOrDefault(); + if (kind is null) { await PadMenu.ShowAsync(host, AppStrings.RomMissing, $"Bind an emulator for the {fromLibrary.Console} in the Emulators tab, or install one.", "OK"); return; } - links.Set(new RomLink(save.DocumentId, fromLibrary.FilePath, fromLibrary.FileName, kind, save.Generation, save.EngineHint)); + links.Set(new RomLink(save.DocumentId, fromLibrary.FilePath, fromLibrary.FileName, kind.Value, generation, save.EngineHint)); return; } @@ -205,11 +236,21 @@ await PadMenu.ShowAsync(host, AppStrings.RomMissing, var emulators = RomLinkRules.EmulatorsForRom(save.Generation, name); if (emulators.Count == 0) { + if (RomLinkRules.UsesIntegratedCore(save.Generation) + && RomLinkRules.IsSupportedEmbeddedFormat(save.Generation, name)) + { + await PadMenu.ShowAsync(host, AppStrings.GameLaunchFailedTitle, + AppStrings.EmbeddedCoreMissing(save.Generation), AppStrings.Ok); + return; + } await PadMenu.ShowAsync(host, "ROM not linked", - $"PKForge cannot launch a Gen {save.Generation} game from {name}. Link a ROM for a Game Boy, GBA or Nintendo DS Pokémon game instead.", "OK"); + $"PKForge cannot launch a Gen {save.Generation} game from {name}. Link a ROM for a Game Boy, Game Boy Color, GBA or Nintendo DS Pokémon game instead.", "OK"); return; } - var installed = emulators.Where(kind => EmulatorCatalog.IsInstalled(kind, Launcher is { } l ? l.IsInstalled : _ => false)).ToArray(); + // RomLinkRules includes the embedded core only after checking the precise + // generation's library; its presence is not a generic package query. + var installed = emulators.Where(kind => kind == EmulatorKind.Embedded + || EmulatorCatalog.IsInstalled(kind, Launcher is { } l ? l.IsInstalled : _ => false)).ToArray(); if (installed.Length == 0) { await PadMenu.ShowAsync(host, AppStrings.RomMissing, diff --git a/src/PKForge.App/Views/SecondScreenBoxPage.cs b/src/PKForge.App/Views/SecondScreenBoxPage.cs index 85f9d93e..a58bfcae 100644 --- a/src/PKForge.App/Views/SecondScreenBoxPage.cs +++ b/src/PKForge.App/Views/SecondScreenBoxPage.cs @@ -254,7 +254,11 @@ void QueueSwap() { _companionHandler = (_, args) => { - if (args.PropertyName is nameof(Services.GameCompanionStore.Live) or nameof(Services.GameCompanionStore.Current) or nameof(Services.GameCompanionStore.External)) + if (args.PropertyName is nameof(Services.GameCompanionStore.Live) + or nameof(Services.GameCompanionStore.Current) + or nameof(Services.GameCompanionStore.External) + or nameof(Services.GameCompanionStore.SpeedControlAvailable) + or nameof(Services.GameCompanionStore.SpeedMultiplier)) QueueSwap(); }; companionStore.PropertyChanged += _companionHandler; diff --git a/src/PKForge.Domain/EmbeddedCore.cs b/src/PKForge.Domain/EmbeddedCore.cs index 76dc9958..aeb120c6 100644 --- a/src/PKForge.Domain/EmbeddedCore.cs +++ b/src/PKForge.Domain/EmbeddedCore.cs @@ -2,9 +2,9 @@ namespace PKForge.Domain; /// /// The embedded emulator core's contract: PKForge runs the game itself (the -/// PokeDaisy model — the core in-process, the companion reads its memory live) -/// instead of handing the ROM to an external emulator. The GBA/GB core (mGBA) -/// comes first; the same shape extends to DS (melonDS) later. +/// PokeDaisy model — the core runs in-process and the companion reads its data) +/// instead of handing the ROM to an external emulator. This contract covers mGBA; +/// DS sessions use a separate page contract for two screens and stylus input. /// public interface IEmbeddedCore : IDisposable { @@ -73,3 +73,20 @@ public static class GbaKeys public const uint R = 1 << 8; public const uint L = 1 << 9; } + +/// The Nintendo DS active-high key bits consumed by melonDS. +public static class NdsKeys +{ + public const uint A = 1 << 0; + public const uint B = 1 << 1; + public const uint Select = 1 << 2; + public const uint Start = 1 << 3; + public const uint Right = 1 << 4; + public const uint Left = 1 << 5; + public const uint Up = 1 << 6; + public const uint Down = 1 << 7; + public const uint R = 1 << 8; + public const uint L = 1 << 9; + public const uint X = 1 << 10; + public const uint Y = 1 << 11; +} diff --git a/src/PKForge.Domain/EmulatorCatalog.cs b/src/PKForge.Domain/EmulatorCatalog.cs index cd52b193..724da351 100644 --- a/src/PKForge.Domain/EmulatorCatalog.cs +++ b/src/PKForge.Domain/EmulatorCatalog.cs @@ -102,11 +102,14 @@ public static EmulatorApp App(EmulatorKind kind) => /// True when any of the emulator's packages is installed. /// The embedded core has no package: it is installed when the shim is packed in the APK. public static bool IsInstalled(EmulatorKind kind, Func isPackageInstalled) => - kind == EmulatorKind.Embedded ? EmbeddedCoreAvailable : App(kind).PackageIds.Any(isPackageInstalled); + kind == EmulatorKind.Embedded ? EmbeddedCoreAvailable || EmbeddedDsCoreAvailable : App(kind).PackageIds.Any(isPackageInstalled); /// Set by the app at startup: true when libpkforge_mgba.so is packed (the embedded core runs). public static bool EmbeddedCoreAvailable { get; set; } + /// Set at startup when libpkforge_melonds.so is packed and loadable. + public static bool EmbeddedDsCoreAvailable { get; set; } + /// The RetroArch core file name (without directories) for a core. public static string CoreFileName(RetroArchCore core) => core switch { @@ -139,7 +142,13 @@ public static bool IsInstalled(EmulatorKind kind, Func isPackageIn /// The systems whose ROMs this emulator runs, for the launcher's expectations. public static string SystemsOf(EmulatorKind kind) => kind switch { - EmulatorKind.Embedded => "GB, GBC, GBA", + EmulatorKind.Embedded => (EmbeddedCoreAvailable, EmbeddedDsCoreAvailable) switch + { + (true, true) => "GB, GBC, GBA, Nintendo DS", + (true, false) => "GB, GBC, GBA", + (false, true) => "Nintendo DS", + _ => "No embedded core", + }, EmulatorKind.RetroArch => "DS", EmulatorKind.MelonDS => "Nintendo DS", EmulatorKind.Azahar or EmulatorKind.CitraMmj => "Nintendo 3DS", diff --git a/src/PKForge.Domain/GameCompanion.cs b/src/PKForge.Domain/GameCompanion.cs index 8466ea84..2990ae13 100644 --- a/src/PKForge.Domain/GameCompanion.cs +++ b/src/PKForge.Domain/GameCompanion.cs @@ -23,8 +23,8 @@ public sealed record GameCompanion( public sealed record CompanionRestorePoint(string BackupId, DateTimeOffset CreatedUtc, string? Sha256 = null); /// -/// A live read from the running embedded game's memory (the PokéDaisy model): what -/// the second screen refreshes while the game plays natively in-app. +/// Companion data read from the latest valid battery-save image exposed by the +/// embedded core. Unsaved changes in emulated RAM are not included yet. /// public sealed record LiveCompanionSnapshot( string GameLabel, @@ -34,11 +34,37 @@ public sealed record LiveCompanionSnapshot( int DexTotal, int PartyCount, int PlaytimeHours, - int PlaytimeMinutes) + int PlaytimeMinutes, + IReadOnlyList? Party = null, + IReadOnlyList? Bag = null) { public int DexPercent => DexTotal == 0 ? 0 : (int)Math.Round(DexCaught * 100.0 / DexTotal); + public IReadOnlyList PartyMembers => Party ?? []; + public IReadOnlyList BagPockets => Bag ?? []; } +/// A read-only party entry decoded from a GB, GBC, or GBA battery save. +public sealed record GameCompanionPartyMember( + int Species, + string SpeciesName, + string Nickname, + int Level, + int CurrentHp, + int MaxHp, + string Status, + bool IsEgg, + int Form = 0, + bool IsShiny = false); + +/// A named pocket from the game's saved bag. +public sealed record GameCompanionBagPocket( + string Id, + string Name, + IReadOnlyList Items); + +/// An item and quantity shown in a companion bag pocket. +public sealed record GameCompanionBagItem(int Id, string Name, int Count); + /// /// Tracks the companion: set when Play launches a game, cleared when the player /// returns to PKForge's own screens. The second screen's swap reads it. @@ -47,7 +73,7 @@ public interface IGameCompanionStore { GameCompanion? Current { get; } - /// A live snapshot from the running embedded game, when one is playing. + /// The latest valid battery-save snapshot from an embedded game, when available. LiveCompanionSnapshot? Live { get; } /// The latest snapshot polled from an external emulator's save file (US-003). @@ -56,7 +82,7 @@ public interface IGameCompanionStore /// Shows this game's companion on the lower screen for the whole emulation. void Start(GameCompanion companion); - /// Publishes a live snapshot (embedded game running in-app). + /// Publishes a validated save snapshot from the embedded game session. void UpdateLive(LiveCompanionSnapshot snapshot); /// Clears the live snapshot (the embedded game stopped). diff --git a/src/PKForge.Domain/LiveGbaCompanion.cs b/src/PKForge.Domain/LiveGbaCompanion.cs index debfb103..f8339d8b 100644 --- a/src/PKForge.Domain/LiveGbaCompanion.cs +++ b/src/PKForge.Domain/LiveGbaCompanion.cs @@ -1,17 +1,13 @@ namespace PKForge.Domain; /// -/// The live, in-emulator companion (the PokéDaisy model): the GBA's save RAM is read -/// straight out of the running core, so the second screen tracks the game as it -/// plays — dex progress, party count, playtime — without waiting for a save flush. -/// All offsets are relative to the SRAM/Flash bus base 0x0E000000, in the sector -/// layout PKHeX's SAV3 parses (4 KiB sectors, sector ID at 0xFF4, active slot first). +/// Builds companion snapshots from a captured Generation 3 battery-save image. +/// This reports the last persisted save state; it does not expose unsaved changes +/// held in the game's emulated RAM. Offsets use the sector layout parsed by SAV3 +/// (4 KiB sectors, sector ID at 0xFF4, active slot first). /// public static class LiveGbaCompanion { - /// The GBA cartridge save region (SRAM 64 KiB, Flash 128 KiB, mirrored at 0x0F000000). - public const uint SaveBase = 0x0E000000; - private const int SectorSize = 0x1000; private const int MainSectors = 14; private const int MainSize = MainSectors * SectorSize; @@ -22,32 +18,11 @@ public static class LiveGbaCompanion private const int CaughtOffset = 0x18 + 0x10; private const int SeenOffset = 0x18 + 0x44; - /// One live snapshot of the running game's companion data. - public sealed record LiveCompanionSnapshot( - string GameTitle, - string GameCode, - int DexCaught, - int DexSeen, - int DexTotal, - int PartyCount, - int PlaytimeHours, - int PlaytimeMinutes) + /// Reads lightweight counters from a captured pair of save slots. + public static LiveCompanionSnapshot? Read(string gameTitle, string gameCode, byte[] both, int maxSpeciesId) { - public int DexPercent => DexTotal == 0 ? 0 : (int)Math.Round(DexCaught * 100.0 / DexTotal); - } - - /// - /// Reads the active save slot out of the core's memory and measures it. - /// Returns null when the memory is unreadable or no small sector is found. - /// - public static LiveCompanionSnapshot? Read(IEmbeddedCore core, int maxSpeciesId) - { - ArgumentNullException.ThrowIfNull(core); - if (!core.IsRunning || maxSpeciesId <= 0) return null; - - // Read both 128 KiB slots when the cart has them; slot 0 always exists. - var both = new byte[MainSize * 2]; - if (!core.ReadBytes(SaveBase, both)) return null; + ArgumentNullException.ThrowIfNull(both); + if (maxSpeciesId <= 0 || both.Length < MainSize * 2) return null; var active = ActiveSlot(both); var baseOffset = active * MainSize; @@ -72,7 +47,7 @@ public sealed record LiveCompanionSnapshot( var minutes = small.Length > 0x0D ? small[0x0D] : (byte)0; return new LiveCompanionSnapshot( - core.GameTitle, core.GameCode, caught, seen, maxSpeciesId, + gameTitle, gameCode, caught, seen, maxSpeciesId, partyCount, hours, minutes); } diff --git a/src/PKForge.Domain/RomLibrary.cs b/src/PKForge.Domain/RomLibrary.cs index e4cdb80f..dbf5d9c6 100644 --- a/src/PKForge.Domain/RomLibrary.cs +++ b/src/PKForge.Domain/RomLibrary.cs @@ -13,8 +13,8 @@ public enum GameConsole } /// -/// The player's emulator of choice per console (the Cocoon-style binding): which app -/// launches the console's ROMs, so a ROM never asks again once its console is bound. +/// The player's external emulator choice for consoles still awaiting an integrated +/// PKForge core. Integrated consoles ignore stale external bindings. /// public sealed record ConsoleEmulatorLink(GameConsole Console, EmulatorKind Emulator); @@ -68,19 +68,20 @@ public static class ConsoleRules _ => [], }; - /// True when PKForge runs this console's games itself (the embedded core), - /// so no external emulator may be bound or chosen for it. + /// Pokémon consoles with an in-process core. Unsupported ROM formats fail + /// with an in-app explanation instead of being handed to a third-party emulator. public static bool RunsInApp(GameConsole console) => - console is GameConsole.GameBoy or GameConsole.GameBoyColor or GameConsole.GameBoyAdvance; + console is GameConsole.GameBoy or GameConsole.GameBoyColor or GameConsole.GameBoyAdvance + or GameConsole.NintendoDs; /// The emulators that can run a console's ROMs, best first — the Cocoon choice list. - /// GB/GBC/GBA run in PKForge itself (the embedded core); no external emulator is offered. + /// GB/GBC/GBA/DS Pokémon ROMs use PKForge's in-process cores. public static IReadOnlyList EmulatorsFor(GameConsole console) => console switch { GameConsole.GameBoy or GameConsole.GameBoyColor or GameConsole.GameBoyAdvance => [EmulatorKind.Embedded], - GameConsole.NintendoDs => - [EmulatorKind.MelonDS, EmulatorKind.RetroArch, EmulatorKind.DraStic], + GameConsole.NintendoDs when EmulatorCatalog.EmbeddedDsCoreAvailable => [EmulatorKind.Embedded], + GameConsole.NintendoDs => [], GameConsole.Nintendo3Ds => [EmulatorKind.Azahar, EmulatorKind.CitraMmj], GameConsole.GameCube => [EmulatorKind.Dolphin], @@ -91,7 +92,9 @@ public static bool RunsInApp(GameConsole console) => /// True when one of the emulators that run this console is installed. /// The embedded core counts as installed when the shim is packed (EmulatorCatalog.IsInstalled). public static bool AnyInstalled(GameConsole console, Func isPackageInstalled) => - EmulatorsFor(console).Any(kind => EmulatorCatalog.IsInstalled(kind, isPackageInstalled)); + EmulatorsFor(console).Any(kind => kind == EmulatorKind.Embedded + ? console == GameConsole.NintendoDs ? EmulatorCatalog.EmbeddedDsCoreAvailable : EmulatorCatalog.EmbeddedCoreAvailable + : EmulatorCatalog.IsInstalled(kind, isPackageInstalled)); } /// diff --git a/src/PKForge.Domain/RomLinks.cs b/src/PKForge.Domain/RomLinks.cs index 0ac84371..3267467b 100644 --- a/src/PKForge.Domain/RomLinks.cs +++ b/src/PKForge.Domain/RomLinks.cs @@ -35,25 +35,54 @@ public interface IRomLinkStore /// Which emulator a linked ROM should launch with, and whether PKForge can hand it over directly. public static class RomLinkRules { + /// Generations with an in-process PKForge core. A stale saved emulator + /// selection must never send one of these Pokémon ROMs to another app. + public static bool UsesIntegratedCore(int generation) => generation is >= 1 and <= 5; + + /// Whether this Pokémon ROM belongs to an integrated generation or carries + /// a DS cartridge extension that must never be handed to an external emulator. + public static bool MustRunInApp(int generation, string romFileName) => + UsesIntegratedCore(generation) || ExtensionOf(romFileName) is ".nds" or ".dsi"; + + /// Uses the generation stored on a save link, then the recognized Pokémon + /// edition in its ROM filename. Unknown editions remain unresolved. + public static int ResolveIntegratedGeneration(int generation, string romFileName) + { + if (UsesIntegratedCore(generation)) return generation; + var inferred = RomNameRules.GenerationOf(RomNameRules.GameName(romFileName)); + return UsesIntegratedCore(inferred) ? inferred : 0; + } + + /// Formats that the currently integrated cores can load or safely materialize. + public static bool IsSupportedEmbeddedFormat(int generation, string romFileName) + { + ArgumentNullException.ThrowIfNull(romFileName); + var extension = ExtensionOf(romFileName); + return generation switch + { + 1 or 2 => extension is ".gb" or ".gbc", + 3 => extension == ".gba", + 4 or 5 => extension is ".nds" or ".zip", + _ => false, + }; + } + /// - /// The emulators that can run this ROM, best first, inferred from the generation and the - /// file extension. The player's linked choice always wins over this preference order. + /// The currently supported core for this ROM, inferred from generation, extension and + /// the matching embedded library. Integrated Pokémon generations have no external fallback. /// public static IReadOnlyList EmulatorsForRom(int generation, string romFileName) { if (!GenerationKnows(generation)) return []; - var extension = ExtensionOf(romFileName); - if (generation <= 2 && extension is not (".gb" or ".gbc" or ".zip" or ".7z")) - return []; - if (generation == 3 && extension is not (".gba" or ".zip" or ".7z")) - return []; - if (generation is 4 or 5 && extension is not (".nds" or ".dsi" or ".zip" or ".7z")) + if (!IsSupportedEmbeddedFormat(generation, romFileName)) return []; return generation switch { - 1 or 2 or 3 => [EmulatorKind.Embedded], - 4 or 5 => [EmulatorKind.MelonDS, EmulatorKind.RetroArch, EmulatorKind.DraStic], + 1 or 2 or 3 when EmulatorCatalog.EmbeddedCoreAvailable => [EmulatorKind.Embedded], + 1 or 2 or 3 => [], + 4 or 5 when EmulatorCatalog.EmbeddedDsCoreAvailable => [EmulatorKind.Embedded], + 4 or 5 => [], _ => [], }; } diff --git a/src/PKForge.Engine/ShowdownTeamService.cs b/src/PKForge.Engine/ShowdownTeamService.cs index d4f3cf8b..2e428cf2 100644 --- a/src/PKForge.Engine/ShowdownTeamService.cs +++ b/src/PKForge.Engine/ShowdownTeamService.cs @@ -19,7 +19,7 @@ public static class ShowdownTeamService ArgumentNullException.ThrowIfNull(paste); var lines = paste.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n') .Where(line => !line.TrimStart().StartsWith("===", StringComparison.Ordinal)); - var text = string.Join('\n', lines); + var text = string.Join('\n', lines).TrimStart(); var result = new List<(string, ShowdownSet)>(); var start = 0; while (start < text.Length) diff --git a/tests/PKForge.Domain.Tests/EmulatorCatalogTestState.cs b/tests/PKForge.Domain.Tests/EmulatorCatalogTestState.cs new file mode 100644 index 00000000..faedeb1c --- /dev/null +++ b/tests/PKForge.Domain.Tests/EmulatorCatalogTestState.cs @@ -0,0 +1,30 @@ +using PKForge.Domain; +using Xunit; + +namespace PKForge.Domain.Tests; + +[CollectionDefinition(EmulatorCatalogCollection.Name)] +public sealed class EmulatorCatalogCollection +{ + public const string Name = "Emulator catalog state"; +} + +internal sealed class EmbeddedCoreAvailabilityScope : IDisposable +{ + private readonly bool _previousMgba; + private readonly bool _previousMelonDs; + + public EmbeddedCoreAvailabilityScope(bool mgba, bool melonDs) + { + _previousMgba = EmulatorCatalog.EmbeddedCoreAvailable; + _previousMelonDs = EmulatorCatalog.EmbeddedDsCoreAvailable; + EmulatorCatalog.EmbeddedCoreAvailable = mgba; + EmulatorCatalog.EmbeddedDsCoreAvailable = melonDs; + } + + public void Dispose() + { + EmulatorCatalog.EmbeddedCoreAvailable = _previousMgba; + EmulatorCatalog.EmbeddedDsCoreAvailable = _previousMelonDs; + } +} diff --git a/tests/PKForge.Domain.Tests/LiveGbaCompanionTests.cs b/tests/PKForge.Domain.Tests/LiveGbaCompanionTests.cs index 579be84c..97a5283d 100644 --- a/tests/PKForge.Domain.Tests/LiveGbaCompanionTests.cs +++ b/tests/PKForge.Domain.Tests/LiveGbaCompanionTests.cs @@ -5,36 +5,10 @@ namespace PKForge.Domain.Tests; public sealed class LiveGbaCompanionTests { - /// Minimal in-memory IEmbeddedCore holding a synthetic GBA save image. - private sealed class FakeCore(byte[] sram, string title = "POKEMON EMER", string code = "BPEE") : IEmbeddedCore - { - public bool IsRunning => true; - public string? RomPath => "/roms/emerald.gba"; - public string GameTitle => title; - public string GameCode => code; - public (int Width, int Height) VideoSize => (240, 160); - - public bool Load(string romPath, string? savePath = null) => true; - public void RunFrame() { } - public void CopyFrame(Span buffer) { } - public void SetKeys(uint bitmask) { } - public bool ReadBytes(uint address, Span destination) - { - if (address != LiveGbaCompanion.SaveBase) return false; - if (destination.Length > sram.Length) return false; - sram.AsSpan(0, destination.Length).CopyTo(destination); - return true; - } - public uint? Read32(uint address) => 0; - public bool SaveState(string path) => true; - public bool LoadState(string path) => true; - public void Dispose() { } - } - private const int Sector = 0x1000; private const int Main = 14 * Sector; - /// Builds a 128 KiB SRAM image: sector 0 of slot 0 holds the dex flags + trainer block. + /// Builds two 14-sector save slots; slot 0 holds the dex flags and trainer data. private static byte[] SramWithDex(int caughtBits, int seenBits, byte partyCount = 3, byte hours = 12, byte minutes = 34) { var sram = new byte[Main * 2]; @@ -62,9 +36,7 @@ private static byte[] SramWithDex(int caughtBits, int seenBits, byte partyCount public void ReadsDexCaughtSeenPartyAndPlaytimeFromTheActiveSlot() { var sram = SramWithDex(caughtBits: 0b0000_0111, seenBits: 0b0000_1111, partyCount: 4, hours: 7, minutes: 55); - var core = new FakeCore(sram); - - var snapshot = LiveGbaCompanion.Read(core, maxSpeciesId: 386); + var snapshot = LiveGbaCompanion.Read("POKEMON EMER", "BPEE", sram, maxSpeciesId: 386); Assert.NotNull(snapshot); Assert.Equal(3, snapshot.DexCaught); // bits 0,1,2 set @@ -73,7 +45,7 @@ public void ReadsDexCaughtSeenPartyAndPlaytimeFromTheActiveSlot() Assert.Equal(4, snapshot.PartyCount); Assert.Equal(7, snapshot.PlaytimeHours); Assert.Equal(55, snapshot.PlaytimeMinutes); - Assert.Equal("POKEMON EMER", snapshot.GameTitle); + Assert.Equal("POKEMON EMER", snapshot.GameLabel); Assert.Equal("BPEE", snapshot.GameCode); } @@ -81,65 +53,28 @@ public void ReadsDexCaughtSeenPartyAndPlaytimeFromTheActiveSlot() public void PartyCountIsCappedAtSix() { var sram = SramWithDex(0, 0, partyCount: 200); - var snapshot = LiveGbaCompanion.Read(new FakeCore(sram), 386); + var snapshot = LiveGbaCompanion.Read("POKEMON EMER", "BPEE", sram, 386); Assert.Equal(6, snapshot!.PartyCount); } [Fact] public void ReturnsNullWhenTheSaveRegionIsUnreadable() { - // The bus read fails: nothing is copied, no snapshot. - Assert.Null(LiveGbaCompanion.Read(new UnreadableCore(), 386)); - } - - private sealed class UnreadableCore : IEmbeddedCore - { - public bool IsRunning => true; - public string? RomPath => null; - public string GameTitle => ""; - public string GameCode => "BPEE"; - public (int Width, int Height) VideoSize => (240, 160); - public bool Load(string romPath, string? savePath = null) => false; - public void RunFrame() { } - public void CopyFrame(Span buffer) { } - public void SetKeys(uint bitmask) { } - public bool ReadBytes(uint address, Span destination) => false; - public uint? Read32(uint address) => null; - public bool SaveState(string path) => false; - public bool LoadState(string path) => false; - public void Dispose() { } + Assert.Null(LiveGbaCompanion.Read("POKEMON EMER", "BPEE", new byte[Main * 2 - 1], 386)); } [Fact] public void DexPercentIsCaughtOverTotal() { var sram = SramWithDex(caughtBits: 0xFF, seenBits: 0xFF); - var snapshot = LiveGbaCompanion.Read(new FakeCore(sram), 386); + var snapshot = LiveGbaCompanion.Read("POKEMON EMER", "BPEE", sram, 386); Assert.Equal(8, snapshot!.DexCaught); Assert.True(snapshot.DexPercent >= 2 && snapshot.DexPercent <= 3); // 8/386 ≈ 2.07% } [Fact] - public void ReturnsNullWhenNotRunning() - { - Assert.Null(LiveGbaCompanion.Read(new StoppedCore(), 386)); - } - - private sealed class StoppedCore : IEmbeddedCore + public void ReturnsNullWhenSpeciesCountIsInvalid() { - public bool IsRunning => false; - public string? RomPath => null; - public string GameTitle => ""; - public string GameCode => "BPEE"; - public (int Width, int Height) VideoSize => (0, 0); - public bool Load(string romPath, string? savePath = null) => false; - public void RunFrame() { } - public void CopyFrame(Span buffer) { } - public void SetKeys(uint bitmask) { } - public bool ReadBytes(uint address, Span destination) => false; - public uint? Read32(uint address) => null; - public bool SaveState(string path) => false; - public bool LoadState(string path) => false; - public void Dispose() { } + Assert.Null(LiveGbaCompanion.Read("POKEMON EMER", "BPEE", SramWithDex(0, 0), 0)); } } diff --git a/tests/PKForge.Domain.Tests/RomLinkTests.cs b/tests/PKForge.Domain.Tests/RomLinkTests.cs index 3b2a188d..7d03e54d 100644 --- a/tests/PKForge.Domain.Tests/RomLinkTests.cs +++ b/tests/PKForge.Domain.Tests/RomLinkTests.cs @@ -3,17 +3,19 @@ namespace PKForge.Domain.Tests; +[Collection(EmulatorCatalogCollection.Name)] public sealed class RomLinkRulesTests { [Theory] [InlineData(1, "Pokemon - Red Version.gb", EmulatorKind.Embedded)] [InlineData(2, "Pokemon - Crystal Version.gbc", EmulatorKind.Embedded)] - [InlineData(2, "Pokemon - Crystal Version.zip", EmulatorKind.Embedded)] [InlineData(3, "Pokemon - Emerald Version.gba", EmulatorKind.Embedded)] - [InlineData(4, "Pokemon - Diamond Version.nds", EmulatorKind.MelonDS)] - [InlineData(5, "Pokemon - Black Version 2.nds", EmulatorKind.MelonDS)] + [InlineData(4, "Pokemon - Diamond Version.nds", EmulatorKind.Embedded)] + [InlineData(4, "Pokemon - Diamond Version.zip", EmulatorKind.Embedded)] + [InlineData(5, "Pokemon - Black Version 2.nds", EmulatorKind.Embedded)] public void PrefersTheEmulatorThatRunsTheGeneration(int generation, string rom, EmulatorKind first) { + using var cores = new EmbeddedCoreAvailabilityScope(mgba: true, melonDs: true); var emulators = RomLinkRules.EmulatorsForRom(generation, rom); Assert.NotEmpty(emulators); Assert.Equal(first, emulators[0]); @@ -25,13 +27,28 @@ public void PrefersTheEmulatorThatRunsTheGeneration(int generation, string rom, [InlineData(3, "Pokemon - Emerald Version.gba")] public void GenOneToThreeRomsHaveEmbeddedAsTheirOnlyRoute(int generation, string rom) { + using var cores = new EmbeddedCoreAvailabilityScope(mgba: true, melonDs: true); // Gen 1-3 ROMs can never be handed to an external emulator. Assert.Equal([EmulatorKind.Embedded], RomLinkRules.EmulatorsForRom(generation, rom)); } + [Fact] + public void IntegratedRomsNeedTheirNativeCoreToBePackaged() + { + using var cores = new EmbeddedCoreAvailabilityScope(mgba: false, melonDs: false); + + Assert.Empty(RomLinkRules.EmulatorsForRom(3, "Pokemon - Emerald Version.gba")); + Assert.Empty(RomLinkRules.EmulatorsForRom(4, "Pokemon - Diamond Version.nds")); + EmulatorCatalog.EmbeddedCoreAvailable = true; + Assert.Equal([EmulatorKind.Embedded], RomLinkRules.EmulatorsForRom(3, "Pokemon - Emerald Version.gba")); + EmulatorCatalog.EmbeddedDsCoreAvailable = true; + Assert.Equal([EmulatorKind.Embedded], RomLinkRules.EmulatorsForRom(4, "Pokemon - Diamond Version.nds")); + } + [Theory] [InlineData(3, "Pokemon - Emerald Version.nds")] // a GBA game on a DS file [InlineData(4, "Pokemon - Diamond Version.gba")] // a DS game on a GBA file + [InlineData(2, "Pokemon - Crystal Version.zip")] // GB/GBC archives are not loaded by the core [InlineData(1, "Pokemon - Red Version.3ds")] // nothing runnable [InlineData(6, "Pokemon - X.3ds")] // Gen 6 has no launch route yet [InlineData(0, "Whatever.gb")] // unknown generation diff --git a/tests/PKForge.Domain.Tests/TrophyTests.cs b/tests/PKForge.Domain.Tests/TrophyTests.cs index bfada293..76c85900 100644 --- a/tests/PKForge.Domain.Tests/TrophyTests.cs +++ b/tests/PKForge.Domain.Tests/TrophyTests.cs @@ -256,6 +256,7 @@ public void MapsEditionsToGenerations(string gameName, int expected) => Assert.Equal(expected, RomNameRules.GenerationOf(gameName)); } +[Collection(EmulatorCatalogCollection.Name)] public sealed class ConsoleRulesTests { [Fact] @@ -271,11 +272,12 @@ public void GenerationsMapToTheirConsoles() [Fact] public void EachConsoleNamesItsEmulatorsInPreferenceOrder() { + using var cores = new EmbeddedCoreAvailabilityScope(mgba: true, melonDs: true); // GB/GBC/GBA play in PKForge itself — the embedded core, no external emulator. Assert.Equal([EmulatorKind.Embedded], ConsoleRules.EmulatorsFor(GameConsole.GameBoy)); Assert.Equal([EmulatorKind.Embedded], ConsoleRules.EmulatorsFor(GameConsole.GameBoyColor)); Assert.Equal([EmulatorKind.Embedded], ConsoleRules.EmulatorsFor(GameConsole.GameBoyAdvance)); - Assert.Equal(EmulatorKind.MelonDS, ConsoleRules.EmulatorsFor(GameConsole.NintendoDs)[0]); + Assert.Equal([EmulatorKind.Embedded], ConsoleRules.EmulatorsFor(GameConsole.NintendoDs)); Assert.Equal(EmulatorKind.Azahar, ConsoleRules.EmulatorsFor(GameConsole.Nintendo3Ds)[0]); Assert.Equal(EmulatorKind.Eden, ConsoleRules.EmulatorsFor(GameConsole.NintendoSwitch)[0]); } @@ -284,8 +286,10 @@ public void EachConsoleNamesItsEmulatorsInPreferenceOrder() [InlineData(GameConsole.GameBoy)] [InlineData(GameConsole.GameBoyColor)] [InlineData(GameConsole.GameBoyAdvance)] + [InlineData(GameConsole.NintendoDs)] public void InAppConsolesNeverOfferAnExternalEmulator(GameConsole console) { + using var cores = new EmbeddedCoreAvailabilityScope(mgba: true, melonDs: true); // The single source of truth for "this console runs in PKForge": every candidate // list for it is exactly [Embedded] — no RetroArch/Linkboy/PizzaBoy can leak in. Assert.True(ConsoleRules.RunsInApp(console)); @@ -295,7 +299,6 @@ public void InAppConsolesNeverOfferAnExternalEmulator(GameConsole console) } [Theory] - [InlineData(GameConsole.NintendoDs)] [InlineData(GameConsole.Nintendo3Ds)] [InlineData(GameConsole.GameCube)] [InlineData(GameConsole.NintendoSwitch)] @@ -308,22 +311,13 @@ public void ExternalConsolesAreNotMarkedInApp(GameConsole console) [Fact] public void InstallChecksFollowThePreferenceList() { - // The embedded core needs no package: GB counts as covered exactly when the - // shim is packed (EmbeddedCoreAvailable, probed at app startup). - var previous = EmulatorCatalog.EmbeddedCoreAvailable; - try - { - EmulatorCatalog.EmbeddedCoreAvailable = true; - Assert.True(ConsoleRules.AnyInstalled(GameConsole.GameBoy, _ => false)); - EmulatorCatalog.EmbeddedCoreAvailable = false; - Assert.False(ConsoleRules.AnyInstalled(GameConsole.GameBoy, _ => false)); - Assert.True(ConsoleRules.AnyInstalled(GameConsole.NintendoDs, id => id == "io.github.melonds")); - Assert.False(ConsoleRules.AnyInstalled(GameConsole.Nintendo3Ds, id => id == "com.retroarch")); - } - finally - { - EmulatorCatalog.EmbeddedCoreAvailable = previous; - } + using var cores = new EmbeddedCoreAvailabilityScope(mgba: true, melonDs: false); + Assert.True(ConsoleRules.AnyInstalled(GameConsole.GameBoy, _ => false)); + Assert.Empty(ConsoleRules.EmulatorsFor(GameConsole.NintendoDs)); + Assert.False(ConsoleRules.AnyInstalled(GameConsole.NintendoDs, _ => true)); + EmulatorCatalog.EmbeddedDsCoreAvailable = true; + Assert.True(ConsoleRules.AnyInstalled(GameConsole.NintendoDs, _ => false)); + Assert.False(ConsoleRules.AnyInstalled(GameConsole.Nintendo3Ds, id => id == "com.retroarch")); } } diff --git a/tests/PKForge.Engine.Tests/ShowdownTeamAndBulkTests.cs b/tests/PKForge.Engine.Tests/ShowdownTeamAndBulkTests.cs index fdd80d41..1a8d304e 100644 --- a/tests/PKForge.Engine.Tests/ShowdownTeamAndBulkTests.cs +++ b/tests/PKForge.Engine.Tests/ShowdownTeamAndBulkTests.cs @@ -34,7 +34,7 @@ Nonsense line that is not a set field [Fact] public void SplitCutsSetsWhereShowdownDoesAndDropsTeamHeaders() { - var sets = ShowdownTeamService.Split(Team.Replace("\n", "\r\n")); + var sets = ShowdownTeamService.Split(Team.ReplaceLineEndings("\r\n")); Assert.Equal(3, sets.Count); Assert.Equal([(ushort)Species.Pikachu, (ushort)Species.Garchomp, (ushort)Species.Bulbasaur], sets.Select(s => s.Set.Species)); Assert.StartsWith("Pikachu @ Light Ball", sets[0].Text, StringComparison.Ordinal); diff --git a/tools/build-azahar/build.ps1 b/tools/build-azahar/build.ps1 new file mode 100644 index 00000000..38a11716 --- /dev/null +++ b/tools/build-azahar/build.ps1 @@ -0,0 +1,97 @@ +param( + [string]$NdkPath = $env:ANDROID_NDK_ROOT, + [string]$CMakePath +) + +$ErrorActionPreference = "Stop" +$scriptDirectory = $PSScriptRoot +$repositoryRoot = (Resolve-Path (Join-Path $scriptDirectory "../..")).Path +$azaharDirectory = Join-Path $repositoryRoot "external/azahar" +$sdkRoot = $env:ANDROID_SDK_ROOT + +if (-not $NdkPath -and $sdkRoot) { + $ndkRoot = Join-Path $sdkRoot "ndk" + if (Test-Path $ndkRoot) { + $NdkPath = (Get-ChildItem -LiteralPath $ndkRoot -Directory | + Sort-Object Name -Descending | Select-Object -First 1).FullName + } +} +if (-not $NdkPath -and $env:LOCALAPPDATA) { + $ndkRoot = Join-Path $env:LOCALAPPDATA "Android/Sdk/ndk" + if (Test-Path $ndkRoot) { + $NdkPath = (Get-ChildItem -LiteralPath $ndkRoot -Directory | + Sort-Object Name -Descending | Select-Object -First 1).FullName + } +} +if (-not $NdkPath -or -not (Test-Path (Join-Path $NdkPath "build/cmake/android.toolchain.cmake"))) { + throw "Set ANDROID_NDK_ROOT or pass -NdkPath with an installed Android NDK." +} +$ndkProperties = Join-Path $NdkPath "source.properties" +if (-not (Test-Path $ndkProperties)) { throw "NDK metadata is missing at $ndkProperties." } +$ndkRevision = Select-String -Path $ndkProperties -Pattern 'Pkg.Revision\s*=\s*(\d+)\.' | Select-Object -First 1 +if (-not $ndkRevision -or [int]$ndkRevision.Matches[0].Groups[1].Value -lt 29) { + throw "Azahar's Android core requires NDK r29 or newer. Install a supported NDK and pass its path with -NdkPath." +} +if (-not (Test-Path (Join-Path $azaharDirectory "CMakeLists.txt"))) { + throw "The Azahar source pin is missing. Run: git submodule update --init external/azahar" +} + +if (-not $CMakePath -and $sdkRoot) { + $sdkCMake = Join-Path $sdkRoot "cmake/3.30.3/bin/cmake.exe" + if (Test-Path $sdkCMake) { $CMakePath = $sdkCMake } +} +if (-not $CMakePath) { + $CMakePath = (Get-Command cmake -ErrorAction Stop).Source +} +$cmakeVersionText = (& $CMakePath --version | Select-Object -First 1) +if ($LASTEXITCODE -ne 0 -or $cmakeVersionText -notmatch 'cmake version (\d+)\.(\d+)') { + throw "Could not read the CMake version from $CMakePath." +} +if ([int]$Matches[1] -lt 3 -or ([int]$Matches[1] -eq 3 -and [int]$Matches[2] -lt 25)) { + throw "Azahar requires CMake 3.25 or newer; found $cmakeVersionText." +} + +$git = Get-Command git -ErrorAction Stop +& $git.Source -C $azaharDirectory submodule update --init --recursive +if ($LASTEXITCODE -ne 0) { throw "Could not initialize Azahar's pinned dependencies." } + +$buildDirectory = Join-Path $scriptDirectory "out/android-arm64" +$toolchain = Join-Path $NdkPath "build/cmake/android.toolchain.cmake" +$configureArgs = @( + "-S", $azaharDirectory, + "-B", $buildDirectory, + "-G", "Ninja", + "-DCMAKE_BUILD_TYPE=Release", + "-DCMAKE_TOOLCHAIN_FILE=$toolchain", + "-DANDROID_ABI=arm64-v8a", + "-DANDROID_PLATFORM=android-21", + "-DANDROID_STL=c++_static", + "-DENABLE_LIBRETRO=ON", + "-DENABLE_TESTS=OFF", + "-DENABLE_OPENGL=ON", + "-DENABLE_VULKAN=ON", + "-DENABLE_LTO=OFF" +) +& $CMakePath @configureArgs +if ($LASTEXITCODE -ne 0) { throw "Azahar Android arm64 CMake configure failed with exit code $LASTEXITCODE." } + +& $CMakePath --build $buildDirectory --target azahar_libretro --config Release --parallel +if ($LASTEXITCODE -ne 0) { throw "Azahar Android arm64 core build failed with exit code $LASTEXITCODE." } + +$hostTag = "windows-x86_64" +$strip = Join-Path $NdkPath "toolchains/llvm/prebuilt/$hostTag/bin/llvm-strip.exe" +if (-not (Test-Path $strip)) { throw "NDK llvm-strip was not found at $strip." } +$sourceLibrary = Join-Path $buildDirectory "bin/Release/azahar_libretro.so" +if (-not (Test-Path $sourceLibrary)) { throw "Azahar did not produce the expected libretro library: $sourceLibrary." } + +$destination = Join-Path $repositoryRoot "src/PKForge.App/Libraries/arm64-v8a/libpkforge_azahar.so" +New-Item -ItemType Directory -Force -Path (Split-Path $destination -Parent) | Out-Null +$stagedLibrary = "$destination.tmp" +Copy-Item -LiteralPath $sourceLibrary -Destination $stagedLibrary -Force +& $strip --strip-unneeded $stagedLibrary +if ($LASTEXITCODE -ne 0) { + Remove-Item -LiteralPath $stagedLibrary -Force -ErrorAction SilentlyContinue + throw "Could not strip Azahar symbols (exit code $LASTEXITCODE)." +} +Move-Item -LiteralPath $stagedLibrary -Destination $destination -Force +Write-Output "Built the Azahar arm64 libretro core: $destination" diff --git a/tools/build-melonds/CMakeLists.txt b/tools/build-melonds/CMakeLists.txt new file mode 100644 index 00000000..238600dd --- /dev/null +++ b/tools/build-melonds/CMakeLists.txt @@ -0,0 +1,31 @@ +cmake_minimum_required(VERSION 3.22.1) +project(pkforge_melonds LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +get_filename_component(MELONDS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../external/melonDS" ABSOLUTE) +if(NOT EXISTS "${MELONDS_DIR}/src/NDS.h") + message(FATAL_ERROR "melonDS submodule is missing. Run: git submodule update --init external/melonDS") +endif() + +set(BUILD_QT_SDL OFF CACHE BOOL "" FORCE) +set(ENABLE_OGLRENDERER OFF CACHE BOOL "" FORCE) +set(ENABLE_GDBSTUB OFF CACHE BOOL "" FORCE) +set(ENABLE_LTO_RELEASE OFF CACHE BOOL "" FORCE) +set(ENABLE_LTO OFF CACHE BOOL "" FORCE) +set(ENABLE_JIT ON CACHE BOOL "" FORCE) + +add_subdirectory("${MELONDS_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/melonds" EXCLUDE_FROM_ALL) + +add_library(pkforge_melonds SHARED + melonds_platform.cpp + pkforge_melonds.cpp) +target_include_directories(pkforge_melonds PRIVATE "${MELONDS_DIR}/src") +target_link_libraries(pkforge_melonds PRIVATE core android log) +target_link_options(pkforge_melonds PRIVATE + "-Wl,--no-undefined" + "-Wl,-z,max-page-size=16384" + "-Wl,-z,common-page-size=16384") +set_target_properties(pkforge_melonds PROPERTIES OUTPUT_NAME "pkforge_melonds") diff --git a/tools/build-melonds/build.ps1 b/tools/build-melonds/build.ps1 new file mode 100644 index 00000000..87a55560 --- /dev/null +++ b/tools/build-melonds/build.ps1 @@ -0,0 +1,58 @@ +param( + [string]$NdkPath = $env:ANDROID_NDK_ROOT +) + +$ErrorActionPreference = "Stop" +$scriptDirectory = $PSScriptRoot +$repositoryRoot = (Resolve-Path (Join-Path $scriptDirectory "../..")).Path +$sdkRoot = $env:ANDROID_SDK_ROOT + +if (-not $NdkPath -and $sdkRoot) { + $ndkRoot = Join-Path $sdkRoot "ndk" + if (Test-Path $ndkRoot) { + $NdkPath = (Get-ChildItem -LiteralPath $ndkRoot -Directory | Sort-Object Name -Descending | Select-Object -First 1).FullName + } +} +if (-not $NdkPath -and $env:LOCALAPPDATA) { + $ndkRoot = Join-Path $env:LOCALAPPDATA "Android/Sdk/ndk" + if (Test-Path $ndkRoot) { + $NdkPath = (Get-ChildItem -LiteralPath $ndkRoot -Directory | Sort-Object Name -Descending | Select-Object -First 1).FullName + } +} +if (-not $NdkPath -or -not (Test-Path (Join-Path $NdkPath "build/cmake/android.toolchain.cmake"))) { + throw "Set ANDROID_NDK_ROOT or pass -NdkPath with an installed Android NDK." +} + +$buildDirectory = Join-Path $scriptDirectory "out/android-arm64" +$toolchain = Join-Path $NdkPath "build/cmake/android.toolchain.cmake" +$configureArgs = @( + "-S", $scriptDirectory, + "-B", $buildDirectory, + "-G", "Ninja", + "-DCMAKE_BUILD_TYPE=Release", + "-DCMAKE_TOOLCHAIN_FILE=$toolchain", + "-DANDROID_ABI=arm64-v8a", + "-DANDROID_PLATFORM=android-26", + "-DANDROID_STL=c++_static" +) +& cmake @configureArgs +if ($LASTEXITCODE -ne 0) { throw "melonDS CMake configure failed with exit code $LASTEXITCODE." } + +& cmake --build $buildDirectory --target pkforge_melonds --parallel +if ($LASTEXITCODE -ne 0) { throw "melonDS native build failed with exit code $LASTEXITCODE." } + +$hostTag = "windows-x86_64" +$strip = Join-Path $NdkPath "toolchains/llvm/prebuilt/$hostTag/bin/llvm-strip.exe" +if (-not (Test-Path $strip)) { throw "NDK llvm-strip was not found at $strip." } +$sourceLibrary = Join-Path $buildDirectory "libpkforge_melonds.so" +$destination = Join-Path $repositoryRoot "src/PKForge.App/Libraries/arm64-v8a/libpkforge_melonds.so" +New-Item -ItemType Directory -Force -Path (Split-Path $destination -Parent) | Out-Null +$stagedLibrary = "$destination.tmp" +Copy-Item -LiteralPath $sourceLibrary -Destination $stagedLibrary -Force +& $strip --strip-unneeded $stagedLibrary +if ($LASTEXITCODE -ne 0) { + Remove-Item -LiteralPath $stagedLibrary -Force -ErrorAction SilentlyContinue + throw "Could not strip melonDS symbols (exit code $LASTEXITCODE)." +} +Move-Item -LiteralPath $stagedLibrary -Destination $destination -Force +Write-Output "Built arm64 melonDS core: $destination" diff --git a/tools/build-melonds/melonds_platform.cpp b/tools/build-melonds/melonds_platform.cpp new file mode 100644 index 00000000..d60826e1 --- /dev/null +++ b/tools/build-melonds/melonds_platform.cpp @@ -0,0 +1,260 @@ +// Android platform services required by melonDS' core library. +// The app owns ROMs, battery saves, audio, input and rendering; this layer only +// supplies the small OS boundary used by the upstream core. +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +extern "C" void pkforge_melonds_mark_save_dirty(void* userdata); + +namespace melonDS::Platform +{ + +void SignalStop(StopReason, void*) {} + +struct FileHandle { FILE* file; }; + +static const char* FileModeString(FileMode mode) +{ + const bool text = (mode & FileMode::Text) != 0; + if (mode & FileMode::Append) return text ? "a+" : "a+b"; + if ((mode & FileMode::Read) && (mode & FileMode::Write)) + return (mode & FileMode::Preserve) ? (text ? "r+" : "r+b") : (text ? "w+" : "w+b"); + if (mode & FileMode::Write) + return (mode & FileMode::Preserve) ? (text ? "r+" : "r+b") : (text ? "w" : "wb"); + return text ? "r" : "rb"; +} + +FileHandle* OpenFile(const std::string& path, FileMode mode) +{ + struct stat info {}; + const bool exists = stat(path.c_str(), &info) == 0; + if ((mode & FileMode::NoCreate) && !exists) return nullptr; + + FILE* file = fopen(path.c_str(), FileModeString(mode)); + if (!file && !exists && (mode & FileMode::Write) && (mode & FileMode::Preserve) + && !(mode & FileMode::NoCreate)) + { + const bool text = (mode & FileMode::Text) != 0; + file = fopen(path.c_str(), text ? "w+" : "w+b"); + } + return file ? new FileHandle{file} : nullptr; +} + +FileHandle* OpenLocalFile(const std::string& path, FileMode mode) { return OpenFile(path, mode); } +std::string GetLocalFilePath(const std::string& filename) { return filename; } +bool FileExists(const std::string& name) { return access(name.c_str(), F_OK) == 0; } +bool LocalFileExists(const std::string& name) { return FileExists(name); } +bool CheckFileWritable(const std::string& path) +{ + return access(path.c_str(), F_OK) != 0 || access(path.c_str(), W_OK) == 0; +} +bool CheckLocalFileWritable(const std::string& path) { return CheckFileWritable(path); } + +bool CloseFile(FileHandle* file) +{ + if (!file) return false; + const bool success = fclose(file->file) == 0; + delete file; + return success; +} + +bool IsEndOfFile(FileHandle* file) { return !file || feof(file->file) != 0; } +bool FileReadLine(char* text, int count, FileHandle* file) +{ + return file && fgets(text, count, file->file) != nullptr; +} +u64 FilePosition(FileHandle* file) +{ + if (!file) return 0; + const auto position = ftello(file->file); + return position < 0 ? 0 : static_cast(position); +} +bool FileSeek(FileHandle* file, s64 offset, FileSeekOrigin origin) +{ + if (!file) return false; + const int whence = origin == FileSeekOrigin::Start ? SEEK_SET + : origin == FileSeekOrigin::Current ? SEEK_CUR : SEEK_END; + return fseeko(file->file, static_cast(offset), whence) == 0; +} +void FileRewind(FileHandle* file) { if (file) rewind(file->file); } +u64 FileRead(void* data, u64 size, u64 count, FileHandle* file) +{ + return file ? static_cast(fread(data, static_cast(size), static_cast(count), file->file)) : 0; +} +bool FileFlush(FileHandle* file) { return file && fflush(file->file) == 0; } +u64 FileWrite(const void* data, u64 size, u64 count, FileHandle* file) +{ + return file ? static_cast(fwrite(data, static_cast(size), static_cast(count), file->file)) : 0; +} +u64 FileWriteFormatted(FileHandle* file, const char* format, ...) +{ + if (!file) return 0; + va_list args; + va_start(args, format); + const int result = vfprintf(file->file, format, args); + va_end(args); + return result < 0 ? 0 : static_cast(result); +} +u64 FileLength(FileHandle* file) +{ + if (!file) return 0; + const auto current = ftello(file->file); + if (current < 0 || fseeko(file->file, 0, SEEK_END) != 0) return 0; + const auto length = ftello(file->file); + (void)fseeko(file->file, current, SEEK_SET); + return length < 0 ? 0 : static_cast(length); +} + +void Log(LogLevel level, const char* format, ...) +{ + int priority = ANDROID_LOG_DEBUG; + if (level == LogLevel::Info) priority = ANDROID_LOG_INFO; + else if (level == LogLevel::Warn) priority = ANDROID_LOG_WARN; + else if (level == LogLevel::Error) priority = ANDROID_LOG_ERROR; + va_list args; + va_start(args, format); + __android_log_vprint(priority, "PKForge-melonDS", format, args); + va_end(args); +} + +struct Thread { std::thread thread; }; +Thread* Thread_Create(std::function function) { return new Thread{std::thread(std::move(function))}; } +void Thread_Free(Thread* thread) +{ + if (!thread) return; + if (thread->thread.joinable()) + { + if (thread->thread.get_id() == std::this_thread::get_id()) thread->thread.detach(); + else thread->thread.join(); + } + delete thread; +} +void Thread_Wait(Thread* thread) +{ + if (thread && thread->thread.joinable()) thread->thread.join(); +} + +struct Semaphore +{ + std::mutex mutex; + std::condition_variable condition; + int count = 0; +}; +Semaphore* Semaphore_Create() { return new Semaphore(); } +void Semaphore_Free(Semaphore* semaphore) { delete semaphore; } +void Semaphore_Reset(Semaphore* semaphore) +{ + std::lock_guard lock(semaphore->mutex); + semaphore->count = 0; +} +void Semaphore_Wait(Semaphore* semaphore) +{ + std::unique_lock lock(semaphore->mutex); + semaphore->condition.wait(lock, [semaphore] { return semaphore->count > 0; }); + --semaphore->count; +} +bool Semaphore_TryWait(Semaphore* semaphore, int timeoutMs) +{ + std::unique_lock lock(semaphore->mutex); + if (timeoutMs == 0) + { + if (semaphore->count == 0) return false; + } + else if (!semaphore->condition.wait_for(lock, std::chrono::milliseconds(timeoutMs), + [semaphore] { return semaphore->count > 0; })) return false; + --semaphore->count; + return true; +} +void Semaphore_Post(Semaphore* semaphore, int count) +{ + { + std::lock_guard lock(semaphore->mutex); + semaphore->count += count; + } + semaphore->condition.notify_all(); +} + +struct Mutex { std::mutex mutex; }; +Mutex* Mutex_Create() { return new Mutex(); } +void Mutex_Free(Mutex* mutex) { delete mutex; } +void Mutex_Lock(Mutex* mutex) { mutex->mutex.lock(); } +void Mutex_Unlock(Mutex* mutex) { mutex->mutex.unlock(); } +bool Mutex_TryLock(Mutex* mutex) { return mutex->mutex.try_lock(); } + +void Sleep(u64 usecs) { std::this_thread::sleep_for(std::chrono::microseconds(usecs)); } +u64 GetMSCount() +{ + using namespace std::chrono; + return static_cast(duration_cast(steady_clock::now().time_since_epoch()).count()); +} +u64 GetUSCount() +{ + using namespace std::chrono; + return static_cast(duration_cast(steady_clock::now().time_since_epoch()).count()); +} + +void WriteNDSSave(const u8*, u32, u32, u32, void* userdata) { pkforge_melonds_mark_save_dirty(userdata); } +void WriteGBASave(const u8*, u32, u32, u32, void*) {} +void WriteFirmware(const Firmware&, u32, u32, void*) {} +void WriteDateTime(int, int, int, int, int, int, void*) {} + +void MP_Begin(void*) {} +void MP_End(void*) {} +int MP_SendPacket(u8*, int, u64, void*) { return 0; } +int MP_RecvPacket(u8*, u64*, void*) { return 0; } +int MP_SendCmd(u8*, int, u64, void*) { return 0; } +int MP_SendReply(u8*, int, u64, u16, void*) { return 0; } +int MP_SendAck(u8*, int, u64, void*) { return 0; } +int MP_RecvHostPacket(u8*, u64*, void*) { return 0; } +u16 MP_RecvReplies(u8*, u64, u16, void*) { return 0; } +int Net_SendPacket(u8*, int, void*) { return 0; } +int Net_RecvPacket(u8*, void*) { return 0; } +void Camera_Start(int, void*) {} +void Camera_Stop(int, void*) {} +void Camera_CaptureFrame(int, u32*, int, int, bool, void*) {} +void Mic_Start(void*) {} +void Mic_Stop(void*) {} +int Mic_ReadInput(s16*, int, void*) { return 0; } +AACDecoder* AAC_Init() { return nullptr; } +void AAC_DeInit(AACDecoder*) {} +bool AAC_Configure(AACDecoder*, int, int) { return false; } +bool AAC_DecodeFrame(AACDecoder*, const void*, int, void*, int) { return false; } +bool Addon_KeyDown(KeyType, void*) { return false; } +void Addon_RumbleStart(u32, void*) {} +void Addon_RumbleStop(void*) {} +float Addon_MotionQuery(MotionQueryType type, void*) +{ + return type == MotionAccelerationZ ? 1.0f : 0.0f; +} + +struct DynamicLibrary { void* handle; }; +DynamicLibrary* DynamicLibrary_Load(const char* library) +{ + void* handle = dlopen(library, RTLD_NOW | RTLD_LOCAL); + return handle ? new DynamicLibrary{handle} : nullptr; +} +void DynamicLibrary_Unload(DynamicLibrary* library) +{ + if (!library) return; + if (library->handle) dlclose(library->handle); + delete library; +} +void* DynamicLibrary_LoadFunction(DynamicLibrary* library, const char* name) +{ + return library && library->handle ? dlsym(library->handle, name) : nullptr; +} + +} // namespace melonDS::Platform diff --git a/tools/build-melonds/pkforge_melonds.cpp b/tools/build-melonds/pkforge_melonds.cpp new file mode 100644 index 00000000..fdef5c31 --- /dev/null +++ b/tools/build-melonds/pkforge_melonds.cpp @@ -0,0 +1,287 @@ +// Minimal PKForge C ABI over melonDS 1.1. The .NET engine owns timing and all +// calls into a handle are serialized on its emulation thread. +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace +{ +constexpr size_t kScreenWidth = 256; +constexpr size_t kScreenHeight = 192; +constexpr size_t kCombinedFramePixels = kScreenWidth * kScreenHeight * 2; +constexpr uint64_t kMaximumRomBytes = 512ull * 1024 * 1024; +constexpr uint64_t kMaximumSaveBytes = 16ull * 1024 * 1024; +constexpr uint64_t kMaximumStateBytes = 128ull * 1024 * 1024; + +thread_local std::string gLastError; + +struct Core +{ + std::unique_ptr nds; + std::string savePath; + std::string title; + std::string code; + std::vector frame = std::vector(kCombinedFramePixels); + bool saveDirty = false; +}; + +bool ReadFile(const std::string& path, uint64_t maximumBytes, std::vector& output, bool allowEmpty = false) +{ + std::ifstream input(path, std::ios::binary | std::ios::ate); + if (!input) return false; + const auto end = input.tellg(); + if (end < 0 || (!allowEmpty && end == 0) || static_cast(end) > maximumBytes) return false; + output.resize(static_cast(end)); + input.seekg(0, std::ios::beg); + return end == 0 || static_cast(input.read(reinterpret_cast(output.data()), end)); +} + +bool WriteFileAtomically(const std::string& path, const uint8_t* data, size_t length) +{ + const std::string temporaryPath = path + ".tmp"; + FILE* file = fopen(temporaryPath.c_str(), "wb"); + if (!file) return false; + bool success = length == 0 || fwrite(data, 1, length, file) == length; + if (success) success = fflush(file) == 0; + if (success) success = fsync(fileno(file)) == 0; + if (fclose(file) != 0) success = false; + if (success && rename(temporaryPath.c_str(), path.c_str()) != 0) success = false; + if (!success) unlink(temporaryPath.c_str()); + return success; +} + +void SetError(const char* error) { gLastError = error; } + +bool FlushSave(Core& core) +{ + if (!core.nds || !core.saveDirty) return true; + const auto* save = core.nds->GetNDSSave(); + const uint32_t length = core.nds->GetNDSSaveLength(); + if (!save || length == 0) + { + core.saveDirty = false; + return true; + } + if (!WriteFileAtomically(core.savePath, save, length)) return false; + core.saveDirty = false; + return true; +} + +void CopyScreen(const uint32_t* source, uint32_t* destination) +{ + for (size_t i = 0; i < kScreenWidth * kScreenHeight; ++i) + { + const uint32_t pixel = source[i]; // melonDS: 0xAARRGGBB + destination[i] = 0xFF000000u | ((pixel & 0xFFu) << 16) + | (pixel & 0x0000FF00u) | ((pixel >> 16) & 0xFFu); // RGBA byte order + } +} +} + +extern "C" void pkforge_melonds_mark_save_dirty(void* userdata) +{ + if (auto* core = static_cast(userdata)) core->saveDirty = true; +} + +extern "C" int pkforge_melonds_available() { return 1; } +extern "C" const char* pkforge_melonds_last_error() { return gLastError.c_str(); } + +extern "C" void* pkforge_melonds_create(const char* romPath, const char* savePath) +{ + gLastError.clear(); + if (!romPath || !savePath) + { + SetError("Le chemin de ROM ou de sauvegarde est vide."); + return nullptr; + } + + std::vector romBytes; + if (!ReadFile(romPath, kMaximumRomBytes, romBytes) || romBytes.size() < 0x200) + { + SetError("La ROM DS est illisible, trop petite ou dépasse la limite de 512 Mio."); + return nullptr; + } + + auto core = std::make_unique(); + core->savePath = savePath; + std::vector saveBytes; + if (access(savePath, F_OK) == 0 && !ReadFile(savePath, kMaximumSaveBytes, saveBytes, true)) + { + SetError("La sauvegarde DS existante est illisible ou dépasse la limite de 16 Mio."); + return nullptr; + } + + melonDS::NDSArgs args; + args.OutputSampleRate = 32768.0; + args.Interpolation = melonDS::AudioInterpolation::None; + // Keep the arm64 JIT, but use guarded memory to avoid installing the JIT's + // optional fault handler alongside Android's and PKForge's handlers. + args.JIT = melonDS::JITArgs{32, true, true, false}; + core->nds = std::make_unique(std::move(args), core.get()); + core->nds->Reset(); + + melonDS::NDSCart::NDSCartArgs cartArgs; + if (!saveBytes.empty()) + { + cartArgs.SRAM = std::make_unique(saveBytes.size()); + std::memcpy(cartArgs.SRAM.get(), saveBytes.data(), saveBytes.size()); + cartArgs.SRAMLength = static_cast(saveBytes.size()); + } + auto rom = std::make_unique(romBytes.size()); + std::memcpy(rom.get(), romBytes.data(), romBytes.size()); + auto cart = melonDS::NDSCart::ParseROM(std::move(rom), static_cast(romBytes.size()), + core.get(), std::move(cartArgs)); + if (!cart) + { + SetError("melonDS ne reconnaît pas cette ROM comme une cartouche DS valide."); + return nullptr; + } + + const auto& header = cart->GetHeader(); + core->title.assign(header.GameTitle, strnlen(header.GameTitle, sizeof(header.GameTitle))); + core->code.assign(header.GameCode, strnlen(header.GameCode, sizeof(header.GameCode))); + core->nds->SetNDSCart(std::move(cart)); + core->nds->Reset(); + core->nds->SetupDirectBoot("rom.nds"); + core->nds->Start(); + if (!core->nds->IsRunning()) + { + SetError("melonDS n'a pas démarré la cartouche DS."); + return nullptr; + } + return core.release(); +} + +extern "C" void pkforge_melonds_destroy(void* handle) +{ + auto* core = static_cast(handle); + if (!core) return; + (void)FlushSave(*core); + if (core->nds) core->nds->Stop(); + delete core; +} + +extern "C" int pkforge_melonds_is_running(void* handle) +{ + const auto* core = static_cast(handle); + return core && core->nds && core->nds->IsRunning() ? 1 : 0; +} + +extern "C" void pkforge_melonds_game_title(void* handle, char* output, size_t capacity) +{ + if (!output || capacity == 0) return; + output[0] = '\0'; + const auto* core = static_cast(handle); + if (!core) return; + const size_t length = std::min(capacity - 1, core->title.size()); + std::memcpy(output, core->title.data(), length); + output[length] = '\0'; +} + +extern "C" void pkforge_melonds_game_code(void* handle, char* output, size_t capacity) +{ + if (!output || capacity == 0) return; + output[0] = '\0'; + const auto* core = static_cast(handle); + if (!core) return; + const size_t length = std::min(capacity - 1, core->code.size()); + std::memcpy(output, core->code.data(), length); + output[length] = '\0'; +} + +extern "C" void pkforge_melonds_run_frame(void* handle, uint32_t keys, int touchDown, int touchX, int touchY) +{ + auto* core = static_cast(handle); + if (!core || !core->nds || !core->nds->IsRunning()) return; + core->nds->SetKeyMask(~keys & 0xFFFu); + if (touchDown) + { + const auto x = static_cast(std::clamp(touchX, 0, 255)); + const auto y = static_cast(std::clamp(touchY, 0, 191)); + core->nds->TouchScreen(x, y); + } + else core->nds->ReleaseScreen(); + core->nds->RunFrame(); + + const int front = core->nds->GPU.FrontBuffer; + auto* top = core->nds->GPU.Framebuffer[front][0].get(); + auto* bottom = core->nds->GPU.Framebuffer[front][1].get(); + if (top && bottom) + { + CopyScreen(top, core->frame.data()); + CopyScreen(bottom, core->frame.data() + kScreenWidth * kScreenHeight); + } +} + +extern "C" int pkforge_melonds_copy_frame(void* handle, uint32_t* output, size_t pixelCapacity) +{ + const auto* core = static_cast(handle); + if (!core || !output || pixelCapacity < kCombinedFramePixels) return 0; + std::memcpy(output, core->frame.data(), kCombinedFramePixels * sizeof(uint32_t)); + return 1; +} + +extern "C" int pkforge_melonds_read_audio(void* handle, int16_t* output, int frameCapacity) +{ + auto* core = static_cast(handle); + if (!core || !core->nds || !output || frameCapacity <= 0) return 0; + return core->nds->SPU.ReadOutput(output, frameCapacity); +} + +extern "C" int pkforge_melonds_flush_save(void* handle) +{ + auto* core = static_cast(handle); + return core && FlushSave(*core) ? 1 : 0; +} + +extern "C" size_t pkforge_melonds_save_size(void* handle) +{ + const auto* core = static_cast(handle); + return core && core->nds ? core->nds->GetNDSSaveLength() : 0; +} + +extern "C" size_t pkforge_melonds_copy_save(void* handle, uint8_t* output, size_t capacity) +{ + const auto* core = static_cast(handle); + if (!core || !core->nds || !output) return 0; + const auto length = core->nds->GetNDSSaveLength(); + const auto* save = core->nds->GetNDSSave(); + if (!save || length == 0 || capacity < length) return 0; + std::memcpy(output, save, length); + return length; +} + +extern "C" int pkforge_melonds_save_state(void* handle, const char* path) +{ + auto* core = static_cast(handle); + if (!core || !core->nds || !path) return 0; + melonDS::Savestate state; + if (state.Error || !core->nds->DoSavestate(&state) || state.Error) return 0; + state.Finish(); + return WriteFileAtomically(path, static_cast(state.Buffer()), state.Length()) ? 1 : 0; +} + +extern "C" int pkforge_melonds_load_state(void* handle, const char* path) +{ + auto* core = static_cast(handle); + if (!core || !core->nds || !path) return 0; + std::vector bytes; + if (!ReadFile(path, kMaximumStateBytes, bytes) || bytes.size() < 16) return 0; + melonDS::Savestate state(bytes.data(), static_cast(bytes.size()), false); + if (state.Error || !core->nds->DoSavestate(&state) || state.Error) return 0; + return 1; +} diff --git a/tools/build-mgba/build.sh b/tools/build-mgba/build.sh index 9256d2e9..b78dd141 100755 --- a/tools/build-mgba/build.sh +++ b/tools/build-mgba/build.sh @@ -18,6 +18,7 @@ OUT="${HERE}/../../src/PKForge.App/Libraries/arm64-v8a" API=26 TRIPLE="aarch64-linux-android" +BUILD_DIR="build-android-ninja" mkdir -p "${WORK}" "${OUT}" cd "${WORK}" @@ -28,33 +29,42 @@ if [ ! -d "mgba-${MGBA_VERSION}" ]; then fi cd "mgba-${MGBA_VERSION}" -# 2. libmgba static for arm64 — the flags PokeDaisy uses (no frontends, no extras). -cmake -B build-android \ +# 2. libmgba static for arm64: GB/GBA cores, ZIP/7z ROM support, no frontend. +cmake -B "${BUILD_DIR}" -G Ninja \ + -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \ -DCMAKE_TOOLCHAIN_FILE="${NDK_HOME}/build/cmake/android.toolchain.cmake" \ -DANDROID_ABI=arm64-v8a \ -DANDROID_PLATFORM=android-${API} \ -DBUILD_QT=OFF -DBUILD_SDL=OFF -DBUILD_LIBRETRO=OFF \ -DBUILD_STATIC=ON -DBUILD_SHARED=OFF \ + -DM_CORE_GB=ON -DM_CORE_GBA=ON \ -DUSE_FFMPEG=OFF -DUSE_DISCORD_RPC=OFF -DUSE_GDB_STUB=OFF \ - -DUSE_SQLITE3=OFF -DUSE_MINIZIP=OFF -DUSE_PNG=OFF -DUSE_LIBZIP=OFF + -DUSE_SQLITE3=OFF -DUSE_MINIZIP=OFF -DUSE_PNG=OFF -DUSE_LIBZIP=OFF \ + -DUSE_ZLIB=ON -DUSE_LZMA=ON # BUILD_STATIC=ON produces libmgba.a (the standard add_library output name). -cmake --build build-android -j"$(nproc)" +cmake --build "${BUILD_DIR}" --parallel # 3. The shim links against the static lib. -HOST_TAG="$(uname | tr '[:upper:]' '[:lower:]')-x86_64" -if [ "${HOST_TAG}" = "darwin-x86_64" ]; then HOST_TAG="darwin-x86_64"; fi +case "$(uname -s)" in + Darwin*) HOST_TAG="darwin-x86_64" ;; + MINGW*|MSYS*|CYGWIN*) HOST_TAG="windows-x86_64" ;; + *) HOST_TAG="linux-x86_64" ;; +esac CLANG="${NDK_HOME}/toolchains/llvm/prebuilt/${HOST_TAG}/bin/clang" +if [ ! -x "${CLANG}" ] && [ -x "${CLANG}.exe" ]; then CLANG="${CLANG}.exe"; fi if [ ! -x "${CLANG}" ]; then - # Some NDK releases name it aarch64-linux-...; fall back to any prebuilt dir. - CLANG="$(find "${NDK_HOME}/toolchains/llvm/prebuilt" -name clang -type f | head -1)" + echo "Could not find the NDK clang compiler for ${HOST_TAG}." >&2 + exit 1 fi "${CLANG}" \ --target="${TRIPLE}${API}" \ -shared -fPIC -O2 \ + -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=16384 \ + -Wl,--no-undefined \ -I"${WORK}/mgba-${MGBA_VERSION}/include" \ "${HERE}/jni_bridge.c" \ - "${WORK}/mgba-${MGBA_VERSION}/build-android/libmgba.a" \ + "${WORK}/mgba-${MGBA_VERSION}/${BUILD_DIR}/libmgba.a" \ -o "${OUT}/libpkforge_mgba.so" \ - -llog -landroid + -llog -landroid -lGLESv3 -lz -lm echo "Built ${OUT}/libpkforge_mgba.so" diff --git a/tools/build-mgba/jni_bridge.c b/tools/build-mgba/jni_bridge.c index 6c552fa2..4e741bbe 100644 --- a/tools/build-mgba/jni_bridge.c +++ b/tools/build-mgba/jni_bridge.c @@ -1,7 +1,7 @@ /* PKForge's flat C shim over libmgba 0.10.5 (mgba/core/core.h), the layer - * MgbaNative.cs P/Invokes. Every function returns int (1 = success, 0 = failure) - * and every string is UTF-8: no C bools to marshal, no struct layouts on the - * managed side. One core handle per ROM; the caller owns the threading. + * MgbaNative.cs P/Invokes. Status functions return int (1 = success, 0 = failure), + * handles use intptr_t, and strings are UTF-8: no C bools to marshal and no struct + * layouts on the managed side. One core handle per ROM; the caller owns threading. * * Built by tools/build-mgba/build.sh (NDK, arm64-v8a) into libpkforge_mgba.so, * linking libmgba static — the same flags PokeDaisy uses: @@ -12,6 +12,8 @@ #include #include #include +#include +#include #include #include #include @@ -26,7 +28,11 @@ struct PkforgeCore { uint32_t* frame; }; -int pkforg_core_create(const char* romPath) { +int pkforg_core_available(void) { + return 1; +} + +intptr_t pkforg_core_create(const char* romPath) { struct mCore* core = mCoreFind(romPath); if (!core) { return 0; @@ -38,6 +44,7 @@ int pkforg_core_create(const char* romPath) { /* The port name picks mGBA's config section; NULL keeps the default ("None"), * which is fine: PKForge sets no per-port options through mCoreConfig. */ mCoreInitConfig(core, NULL); + mCoreLoadConfig(core); struct PkforgeCore* handle = malloc(sizeof(struct PkforgeCore)); if (!handle) { core->deinit(core); @@ -45,7 +52,7 @@ int pkforg_core_create(const char* romPath) { } handle->core = core; handle->frame = NULL; - return (int)(intptr_t)handle; + return (intptr_t)handle; } void pkforg_core_destroy(intptr_t coreHandle) { @@ -74,18 +81,13 @@ int pkforg_core_load(intptr_t coreHandle, const char* romPath, const char* saveP if (!core || !romPath) { return 0; } - struct VFile* rom = VFileOpen(romPath, O_RDONLY); - if (!rom) { - return 0; - } - if (!core->loadROM(core, rom)) { - rom->close(rom); + if (!mCoreLoadFile(core, romPath)) { return 0; } if (savePath) { struct VFile* save = VFileOpen(savePath, O_RDWR | O_CREAT); - if (save) { - core->loadSave(core, save); + if (!save || !core->loadSave(core, save)) { + return 0; } } /* The video buffer is allocated and pinned once, at load: the core renders into @@ -94,18 +96,90 @@ int pkforg_core_load(intptr_t coreHandle, const char* romPath, const char* saveP unsigned width = 0; unsigned height = 0; core->desiredVideoDimensions(core, &width, &height); + if (width == 0 || height == 0) { + return 0; + } + if ((size_t)width > SIZE_MAX / height) { + return 0; + } size_t pixels = (size_t)width * height; - uint32_t* frame = malloc(pixels * sizeof(uint32_t)); - if (frame) { - core->setVideoBuffer(core, frame, width); + if (pixels > SIZE_MAX / sizeof(uint32_t)) { + return 0; } - if (handle) { - handle->frame = frame; + uint32_t* frame = malloc(pixels * sizeof(uint32_t)); + if (!frame) { + return 0; } + core->setVideoBuffer(core, frame, width); + handle->frame = frame; core->reset(core); return 1; } +int pkforg_core_flush_save(intptr_t coreHandle, const char* savePath) { + struct mCore* core = asCore(coreHandle); + if (!core || !savePath || !core->savedataClone) { + return 0; + } + + void* savedata = NULL; + size_t savedataSize = core->savedataClone(core, &savedata); + if (savedataSize && !savedata) { + return 0; + } + struct VFile* vf = VFileOpen(savePath, O_RDWR | O_CREAT); + if (!vf) { + free(savedata); + return 0; + } + + ssize_t fileSize = vf->size(vf); + if (fileSize < 0) { + vf->close(vf); + free(savedata); + return 0; + } + size_t trailerSize = (size_t)fileSize > savedataSize ? (size_t)fileSize - savedataSize : 0; + uint8_t* trailer = trailerSize ? malloc(trailerSize) : NULL; + if (trailerSize && (!trailer + || vf->seek(vf, (off_t)savedataSize, SEEK_SET) < 0 + || vf->read(vf, trailer, trailerSize) != (ssize_t)trailerSize)) { + vf->close(vf); + free(trailer); + free(savedata); + return 0; + } + + bool ok = vf->seek(vf, 0, SEEK_SET) >= 0 + && (!savedataSize || vf->write(vf, savedata, savedataSize) == (ssize_t)savedataSize) + && (!trailerSize || vf->write(vf, trailer, trailerSize) == (ssize_t)trailerSize); + if (ok) { + vf->truncate(vf, savedataSize + trailerSize); + ok = vf->sync(vf, NULL, 0); + } + vf->close(vf); + free(trailer); + free(savedata); + return ok ? 1 : 0; +} + +size_t pkforg_core_copy_savedata(intptr_t coreHandle, uint8_t* destination, size_t capacity) { + struct mCore* core = asCore(coreHandle); + if (!core || !core->savedataClone || !destination || capacity == 0) { + return 0; + } + + void* savedata = NULL; + size_t size = core->savedataClone(core, &savedata); + if (!size || !savedata || size > capacity) { + free(savedata); + return 0; + } + memcpy(destination, savedata, size); + free(savedata); + return size; +} + void pkforg_core_run_frame(intptr_t coreHandle) { struct mCore* core = asCore(coreHandle); if (core) { @@ -165,25 +239,27 @@ int pkforg_core_read_bytes(intptr_t coreHandle, uint32_t address, uint8_t* desti return 0; } /* mCoreGetMemoryBlockInfo resolves the block that owns the address (mirrors - * included); the read is a single memcpy when the range fits the block, - * per-word bus reads otherwise (unmapped or straddling ranges). + * included); copy mapped ranges directly and use byte bus reads when the block + * cannot be exposed as a contiguous memory buffer. */ + if (length - 1 > UINT32_MAX - address) { + return 0; + } const struct mCoreMemoryBlock* info = mCoreGetMemoryBlockInfo(core, address); - if (!info || info->size == 0 || address < info->start - || length > (size_t)(info->end - address) || address < info->start) { - for (size_t i = 0; i < length; i += 4) { - uint32_t word = core->busRead32(core, address + (uint32_t)i); - size_t chunk = length - i < 4 ? length - i : 4; - memcpy(destination + i, &word, chunk); - } - return 1; + if (!info || info->size == 0 || address < info->start || address >= info->end + || length > (size_t)(info->end - address)) { + return 0; } size_t blockSize = 0; void* block = mCoreGetMemoryBlock(core, info->start, &blockSize); - if (!block || blockSize < info->size) { - return 0; + size_t offset = address - info->start; + if (block && offset <= blockSize && length <= blockSize - offset) { + memcpy(destination, (uint8_t*)block + offset, length); + return 1; + } + for (size_t i = 0; i < length; ++i) { + destination[i] = (uint8_t)core->busRead8(core, address + (uint32_t)i); } - memcpy(destination, (uint8_t*)block + (address - info->start), length); return 1; }