diff --git a/src/PKForge.App/Platforms/Android/AndroidEmulatorLauncher.cs b/src/PKForge.App/Platforms/Android/AndroidEmulatorLauncher.cs index 99b7c0de..b58d135a 100644 --- a/src/PKForge.App/Platforms/Android/AndroidEmulatorLauncher.cs +++ b/src/PKForge.App/Platforms/Android/AndroidEmulatorLauncher.cs @@ -2,6 +2,7 @@ using Android.Content; using Android.Content.PM; using Android.Net; +using PKForge.App.ViewModels; using PKForge.Domain; namespace PKForge.App; @@ -70,7 +71,7 @@ public Task OpenAppAsync(EmulatorKind kind, CancellationToken cancellation break; } catch (ActivityNotFoundException) { } - catch (SecurityException) { } + catch (Java.Lang.SecurityException) { } } if (!opened) Services.AppLog.Info("launch", $"Could not open {SaveDescriptions.EmulatorName(kind)} ({package}): no launchable activity."); @@ -143,7 +144,7 @@ private static Task StartActivityAsync(Activity activity, Intent intent, R { started = false; } - catch (SecurityException) + catch (Java.Lang.SecurityException) { started = false; } diff --git a/src/PKForge.App/Services/HttpRetroAchievementsClient.cs b/src/PKForge.App/Services/HttpRetroAchievementsClient.cs index 7f9262e4..55d49d86 100644 --- a/src/PKForge.App/Services/HttpRetroAchievementsClient.cs +++ b/src/PKForge.App/Services/HttpRetroAchievementsClient.cs @@ -38,8 +38,7 @@ public async Task VerifyCredentialsAsync(CancellationToken cancellationTok await using var stream = await response.Content.ReadAsStreamAsync(timeout.Token).ConfigureAwait(false); using var document = await JsonDocument.ParseAsync(stream, cancellationToken: timeout.Token).ConfigureAwait(false); // An unknown user comes back as an error object, a valid one as a profile with an ID. - return document.RootElement.ValueKind == JsonValueKind.Object - && document.RootElement.TryGetProperty("ID", out _); + return RetroAchievementsJson.LooksLikeProfile(document.RootElement); } public async Task GetGameProgressAsync(int gameId, CancellationToken cancellationToken = default) @@ -55,46 +54,13 @@ public async Task GetGameProgressAsync(int gameId, Cancellati await using var stream = await response.Content.ReadAsStreamAsync(timeout.Token).ConfigureAwait(false); using var document = await JsonDocument.ParseAsync(stream, cancellationToken: timeout.Token).ConfigureAwait(false); var root = document.RootElement; - if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("ID", out _)) + if (!RetroAchievementsJson.LooksLikeGame(root)) throw new InvalidOperationException("RetroAchievements did not recognise that game."); - var title = root.TryGetProperty("Title", out var titleElement) ? titleElement.GetString() ?? string.Empty : string.Empty; - var achievements = new List(); - if (root.TryGetProperty("Achievements", out var set) && set.ValueKind == JsonValueKind.Object) - { - foreach (var entry in set.EnumerateObject()) - { - var a = entry.Value; - var id = a.TryGetProperty("ID", out var idElement) && idElement.TryGetInt32(out var parsedId) ? parsedId : 0; - var earned = a.TryGetProperty("DateEarned", out var dateEarned) && dateEarned.ValueKind == JsonValueKind.String; - var earnedHardcore = a.TryGetProperty("DateEarnedHardcore", out var dateHardcore) && dateHardcore.ValueKind == JsonValueKind.String; - achievements.Add(new RetroAchievement( - id, - a.TryGetProperty("Title", out var name) ? name.GetString() ?? string.Empty : string.Empty, - a.TryGetProperty("Description", out var description) ? description.GetString() ?? string.Empty : string.Empty, - a.TryGetProperty("Points", out var points) && points.TryGetInt32(out var pointValue) ? pointValue : 0, - a.TryGetProperty("BadgeName", out var badge) ? badge.GetString() ?? string.Empty : string.Empty, - earned, - earned && ParseTimestamp(a, "DateEarned"), - earnedHardcore)); - } - } - - var progress = new RetroGameProgress(gameId, title, [.. achievements.OrderBy(a => a.Id)]); + var progress = RetroAchievementsJson.ParseGameProgress(root, gameId); cache.Store(progress); return progress; } - - /// RA's "YYYY-MM-DD HH:mm:ss" timestamps, treated as UTC (the site's own clock). - private static DateTimeOffset? ParseTimestamp(JsonElement achievement, string property) - { - if (!achievement.TryGetProperty(property, out var value) || value.ValueKind != JsonValueKind.String) return null; - return DateTimeOffset.TryParse( - value.GetString(), - System.Globalization.CultureInfo.InvariantCulture, - System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, - out var parsed) ? parsed : null; - } } /// diff --git a/src/PKForge.App/Services/TrophyScanService.cs b/src/PKForge.App/Services/TrophyScanService.cs index 0818ca47..2ca3b7e3 100644 --- a/src/PKForge.App/Services/TrophyScanService.cs +++ b/src/PKForge.App/Services/TrophyScanService.cs @@ -58,7 +58,12 @@ public async Task> ScanAllAsync(IReadOnlyList 0 || stats.PlayTimeMinutes > 0) + ? stats.PlayTimeHours + : TryParsePlaytime(save.PlayTime); return new SaveScanFacts( save.DocumentId, save.EngineHint, diff --git a/src/PKForge.App/ViewModels/SavePickerViewModel.cs b/src/PKForge.App/ViewModels/SavePickerViewModel.cs index dac5260b..ec4e37cc 100644 --- a/src/PKForge.App/ViewModels/SavePickerViewModel.cs +++ b/src/PKForge.App/ViewModels/SavePickerViewModel.cs @@ -98,15 +98,7 @@ public static string GroupDetail(IReadOnlyList saves) return string.Join(" · ", parts); } - public static string EmulatorName(EmulatorKind kind) => kind switch - { - EmulatorKind.MelonDS => "melonDS", - EmulatorKind.DraStic => "DraStic", - EmulatorKind.PizzaBoyGba => "Pizza Boy GBA", - EmulatorKind.PizzaBoyGbc => "Pizza Boy GBC", - EmulatorKind.CitraMmj => "Citra MMJ", - _ => kind.ToString(), - }; + public static string EmulatorName(EmulatorKind kind) => EmulatorCatalog.Name(kind); } public partial class SavePickerViewModel : ObservableObject diff --git a/src/PKForge.App/Views/EmulatorsPage.cs b/src/PKForge.App/Views/EmulatorsPage.cs index a67ea7c2..bfad93e5 100644 --- a/src/PKForge.App/Views/EmulatorsPage.cs +++ b/src/PKForge.App/Views/EmulatorsPage.cs @@ -1,4 +1,5 @@ using CommunityToolkit.Mvvm.Input; +using PKForge.App.Services; using PKForge.App.Theme; using PKForge.App.ViewModels; using PKForge.Domain; @@ -262,11 +263,11 @@ private bool MoveCursor(int delta) if (_chips.Count == 0) return true; var previous = _index >= 0 && _index < _rows.Children.Count ? _rows.Children[_index] as VisualElement : null; _index = Math.Clamp(_index < 0 ? 0 : _index + delta, 0, _chips.Count - 1); - _ = previous?.ScaleTo(1.0, 80); + if (previous is not null) _ = previous.ScaleToAsync(1.0, 80); if (_rows.Children[_index] is VisualElement current) { - _ = current.ScaleTo(1.03, 90); - _ = current.ScaleTo(1.0, 80); + _ = current.ScaleToAsync(1.03, 90); + _ = current.ScaleToAsync(1.0, 80); } return true; } diff --git a/src/PKForge.App/Views/SaveIdentitySheet.cs b/src/PKForge.App/Views/SaveIdentitySheet.cs index 68d20845..fa2045d3 100644 --- a/src/PKForge.App/Views/SaveIdentitySheet.cs +++ b/src/PKForge.App/Views/SaveIdentitySheet.cs @@ -36,10 +36,10 @@ public static async Task ShowAsync(Grid host, SavePickerViewModel picker, var options = new List(); var romLink = RomLinks?.FindBySave(save.DocumentId); if (offerOpen) options.Add(new PadOption(OpenOption, IconPath: "play")); - if (romLink is { } link) + if (romLink is { } linked) { options.Add(new PadOption(PlayOption, IconPath: "play", - Detail: $"Launch {link.RomFileName} in {SaveDescriptions.EmulatorName(link.Emulator)}")); + Detail: $"Launch {linked.RomFileName} in {SaveDescriptions.EmulatorName(linked.Emulator)}")); options.Add(new PadOption(UnlinkRomOption, IconPath: "unlink", Detail: "Forget this save's ROM. The save file stays.")); } options.Add(new PadOption(LinkRomOption, IconPath: "file", diff --git a/src/PKForge.App/Views/TrophiesPage.cs b/src/PKForge.App/Views/TrophiesPage.cs index d1514320..35a97a37 100644 --- a/src/PKForge.App/Views/TrophiesPage.cs +++ b/src/PKForge.App/Views/TrophiesPage.cs @@ -21,7 +21,6 @@ public sealed class TrophiesPage : ContentPage, IPadHandler private VerticalStackLayout _rows = null!; private Grid _hostGrid = null!; private Label _readout = null!; - private GameTrophyCard? _open; public TrophiesPage(SavePickerViewModel saves, TrophyScanService scanner, ITrophyStore trophies) { diff --git a/src/PKForge.Domain/AppUpdate.cs b/src/PKForge.Domain/AppUpdate.cs index 7d3942ff..1809fc1a 100644 --- a/src/PKForge.Domain/AppUpdate.cs +++ b/src/PKForge.Domain/AppUpdate.cs @@ -31,9 +31,12 @@ public static bool IsNewerVersion(string installed, string candidate) var core = next.Core.CompareTo(current.Core); if (core != 0) return core > 0; + // SemVer: a release outranks any prerelease of the same version; among two + // prereleases, the one with the more dot-separated identifiers wins when all + // shared identifiers tie (1.4.0-beta.2 > 1.4.0-beta.1 > 1.4.0-beta). if (next.Prerelease.Length == 0 || current.Prerelease.Length == 0) return next.Prerelease.Length == 0 && current.Prerelease.Length != 0; - return string.CompareOrdinal(next.Prerelease, current.Prerelease) > 0; + return ComparePrerelease(next.Prerelease, current.Prerelease) > 0; } /// Don't-remind-me applies to one release. A newer release always asks again. @@ -66,5 +69,29 @@ private static bool TryParse(string value, out ReleaseVersion version) return true; } + /// SemVer prerelease ordering: numeric identifiers compare numerically and + /// rank below alphanumeric ones; more identifiers win when the shared prefix ties. + private static int ComparePrerelease(string left, string right) + { + var a = left.Split('.'); + var b = right.Split('.'); + for (var i = 0; i < Math.Min(a.Length, b.Length); i++) + { + var aNumeric = int.TryParse(a[i], out var an); + var bNumeric = int.TryParse(b[i], out var bn); + int order; + if (aNumeric && bNumeric) + order = an.CompareTo(bn); + else if (aNumeric) + order = -1; // numeric identifiers rank lower than alphanumeric ones + else if (bNumeric) + order = 1; + else + order = string.CompareOrdinal(a[i], b[i]); + if (order != 0) return order; + } + return a.Length.CompareTo(b.Length); + } + private readonly record struct ReleaseVersion(Version Core, string Prerelease); } diff --git a/src/PKForge.Domain/EmulatorCatalog.cs b/src/PKForge.Domain/EmulatorCatalog.cs index 6f0a860f..c0bf9b6d 100644 --- a/src/PKForge.Domain/EmulatorCatalog.cs +++ b/src/PKForge.Domain/EmulatorCatalog.cs @@ -85,6 +85,17 @@ public static EmulatorApp App(EmulatorKind kind) => All.FirstOrDefault(app => app.Kind == kind) ?? new EmulatorApp(kind, [kind.ToString().ToLowerInvariant()], RomLaunchStyle.OpenAppOnly); + /// The display name of an emulator ("melonDS", "Pizza Boy GBA", ...). + public static string Name(EmulatorKind kind) => kind switch + { + EmulatorKind.MelonDS => "melonDS", + EmulatorKind.DraStic => "DraStic", + EmulatorKind.PizzaBoyGba => "Pizza Boy GBA", + EmulatorKind.PizzaBoyGbc => "Pizza Boy GBC", + EmulatorKind.CitraMmj => "Citra MMJ", + _ => kind.ToString(), + }; + /// True when any of the emulator's packages is installed. public static bool IsInstalled(EmulatorKind kind, Func isPackageInstalled) => App(kind).PackageIds.Any(isPackageInstalled); diff --git a/src/PKForge.Domain/RetroAchievements.cs b/src/PKForge.Domain/RetroAchievements.cs index 9f38e4c5..7b32602e 100644 --- a/src/PKForge.Domain/RetroAchievements.cs +++ b/src/PKForge.Domain/RetroAchievements.cs @@ -1,3 +1,5 @@ +using System.Text.Json; + namespace PKForge.Domain; /// The player's RetroAchievements credentials. The API key is a secret: it is @@ -13,6 +15,63 @@ public interface IRetroCredentialStore void Save(RetroCredentials? credentials); } +/// +/// Parses the RetroAchievements web API's JSON, in isolation from HTTP so the mapping +/// is unit tested. Follows API_GetGameInfoAndUserProgress: an achievement carries +/// DateEarned/DateEarnedHardcore only once unlocked, but older API responses returned +/// an empty string for a locked one - presence alone is never proof of an unlock. +/// +public static class RetroAchievementsJson +{ + public static bool LooksLikeGame(JsonElement root) => + root.ValueKind == JsonValueKind.Object && root.TryGetProperty("ID", out _); + + public static bool LooksLikeProfile(JsonElement root) => + root.ValueKind == JsonValueKind.Object && root.TryGetProperty("ID", out _); + + public static RetroGameProgress ParseGameProgress(JsonElement root, int requestedGameId) + { + var title = root.TryGetProperty("Title", out var titleElement) ? titleElement.GetString() ?? string.Empty : string.Empty; + var achievements = new List(); + if (root.TryGetProperty("Achievements", out var set) && set.ValueKind == JsonValueKind.Object) + { + foreach (var entry in set.EnumerateObject()) + { + var a = entry.Value; + var id = a.TryGetProperty("ID", out var idElement) && idElement.TryGetInt32(out var parsedId) ? parsedId : 0; + var earned = IsEarned(a, "DateEarned"); + var earnedHardcore = IsEarned(a, "DateEarnedHardcore"); + achievements.Add(new RetroAchievement( + id, + a.TryGetProperty("Title", out var name) ? name.GetString() ?? string.Empty : string.Empty, + a.TryGetProperty("Description", out var description) ? description.GetString() ?? string.Empty : string.Empty, + a.TryGetProperty("Points", out var points) && points.TryGetInt32(out var pointValue) ? pointValue : 0, + a.TryGetProperty("BadgeName", out var badge) ? badge.GetString() ?? string.Empty : string.Empty, + earned, + earned ? ParseTimestamp(a, "DateEarned") : null, + earnedHardcore)); + } + } + return new RetroGameProgress(requestedGameId, title, [.. achievements.OrderBy(a => a.Id)]); + } + + private static bool IsEarned(JsonElement achievement, string property) => + achievement.TryGetProperty(property, out var value) + && value.ValueKind == JsonValueKind.String + && !string.IsNullOrWhiteSpace(value.GetString()); + + /// RA's "YYYY-MM-DD HH:mm:ss" timestamps, treated as UTC (the site's own clock). + private static DateTimeOffset? ParseTimestamp(JsonElement achievement, string property) + { + if (!achievement.TryGetProperty(property, out var value) || value.ValueKind != JsonValueKind.String) return null; + return DateTimeOffset.TryParse( + value.GetString(), + System.Globalization.CultureInfo.InvariantCulture, + System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, + out var parsed) ? parsed : null; + } +} + /// One official RetroAchievements achievement, as PKForge shows it. public sealed record RetroAchievement( int Id, diff --git a/src/PKForge.Domain/RomLinks.cs b/src/PKForge.Domain/RomLinks.cs index e405505f..4ee0b0bc 100644 --- a/src/PKForge.Domain/RomLinks.cs +++ b/src/PKForge.Domain/RomLinks.cs @@ -64,7 +64,7 @@ public static IReadOnlyList EmulatorsForRom(int generation, string /// The subtitle the Emulators tab and the identity menu show for a link. public static string Describe(RomLink link) => - $"{link.RomFileName} · {SaveDescriptions.EmulatorName(link.Emulator)}"; + $"{link.RomFileName} · {EmulatorCatalog.Name(link.Emulator)}"; private static string ExtensionOf(string fileName) { diff --git a/src/PKForge.Engine/LegalizerService.cs b/src/PKForge.Engine/LegalizerService.cs index 772b9dfd..0e7dd0ec 100644 --- a/src/PKForge.Engine/LegalizerService.cs +++ b/src/PKForge.Engine/LegalizerService.cs @@ -252,7 +252,7 @@ internal static PKM LegalizeKeepingOrigin(SaveFile save, PKM current, Shiny shin made = TryKeep(made, pk => pk.Ball = current.Ball); if (current.CurrentLevel > made.CurrentLevel) made = TryKeep(made, pk => { pk.CurrentLevel = current.CurrentLevel; pk.ResetPartyStats(); }); if (moves.Length > 0) made = TryKeep(made, pk => { pk.SetMoves(moves); pk.HealPP(); }); - if (current.IsNicknamed) made = TryKeep(made, pk => pk.SetNickname(current.Nickname)); + if (current.IsNicknamed) made = TryKeep(made, pk => pk.SetNickname(SaveEngineSession.TrimToNicknameLimit(current.Nickname, pk))); return made; } return null; diff --git a/src/PKForge.Engine/SaveEngine.cs b/src/PKForge.Engine/SaveEngine.cs index a4a21920..d7ee890b 100644 --- a/src/PKForge.Engine/SaveEngine.cs +++ b/src/PKForge.Engine/SaveEngine.cs @@ -279,13 +279,4 @@ public ISaveEngineSession OpenBlankSession(int generation, string? displayName = }; return save.Generation <= 3 && tag != "JA" ? null : tag; } - - /// - /// Unbound relocates the PC and extends FireRed's species table, so editing it with - /// the stock FireRed engine would corrupt the save. It is recognized (and labeled) - /// everywhere, but stays closed until the dedicated Unbound engine ships. - /// - private static InvalidOperationException UnboundNotEditable() => new( - "Pokémon Unbound is recognized, but its CFRU save layout needs the Unbound editor " + - "(coming soon). The save file was not touched."); } diff --git a/src/PKForge.Engine/SaveEngineSession.cs b/src/PKForge.Engine/SaveEngineSession.cs index 40e57f69..6687ae2a 100644 --- a/src/PKForge.Engine/SaveEngineSession.cs +++ b/src/PKForge.Engine/SaveEngineSession.cs @@ -165,7 +165,7 @@ public void ApplyEdit(int box, int slot, EntityEdit edit) } if (edit.Nickname is { } nickname && !string.Equals(entity.Nickname, nickname, StringComparison.Ordinal)) { - entity.SetNickname(nickname); + entity.SetNickname(TrimToNicknameLimit(nickname, entity)); changed = true; } if (edit.Level is { } level && entity.CurrentLevel != Math.Clamp(level, 1, 100)) @@ -268,7 +268,7 @@ public void ApplyEdit(int box, int slot, EntityEdit edit) } if (edit.OriginalTrainer is { } ot && !string.Equals(entity.OriginalTrainerName, ot, StringComparison.Ordinal)) { - SetOriginalTrainerName(entity, ot, _save); + SetOriginalTrainerName(entity, TrimToTrainerNameLimit(ot, entity), _save); changed = true; } if (edit.Gender is { } gender && entity.Gender != Math.Clamp(gender, 0, 2)) @@ -897,11 +897,11 @@ internal static bool ApplyInstructions(PKM entity, IReadOnlyList instruc break; } case "nickname": - entity.SetNickname(value); + entity.SetNickname(TrimToNicknameLimit(value, entity)); changed = true; break; case "ot" or "trainer": - SetOriginalTrainerName(entity, value); + SetOriginalTrainerName(entity, TrimToTrainerNameLimit(value, entity)); changed = true; break; } @@ -1639,7 +1639,16 @@ internal bool MakeOwned(PKM entity, TrainerProfile? profile, out string? failure /// (Japanese: 5 characters and a terminator, the alignment bytes stay zero). A plain /// overwrite keeps the old name's tail after the new terminator, which PKHeX rightly flags /// as "Final terminator missing". Other formats have no such buffer rule. + /// + /// Cuts a nickname to what the mon's format stores (PKHeX's own per-format buffer size: + /// 10 in Gen 1-5, 12 from Gen 6 on, 5 for Japanese Gen 1/2). A longer name would + /// overflow the buffer when the string is encoded into the save. + /// + internal static string TrimToNicknameLimit(string nickname, PKM entity) => + nickname.Length <= entity.MaxStringLengthNickname ? nickname : nickname[..entity.MaxStringLengthNickname]; + internal static void SetOriginalTrainerName(PKM entity, string name, SaveFile? owner = null) + { if (entity is PK3 pk3) { @@ -1651,9 +1660,13 @@ internal static void SetOriginalTrainerName(PKM entity, string name, SaveFile? o } PrefillTrainerName3(trash, pk3.Japanese); } - entity.OriginalTrainerName = name; + entity.OriginalTrainerName = TrimToTrainerNameLimit(name, entity); } + /// Cuts an OT name to the mon's trainer-name buffer (PKHeX's own per-format size). + internal static string TrimToTrainerNameLimit(string name, PKM entity) => + name.Length <= entity.MaxStringLengthTrainer ? name : name[..entity.MaxStringLengthTrainer]; + /// The Gen 3 naming screen's buffer before a name is written: terminators for /// every character the language allows plus one, zero beyond. private static void PrefillTrainerName3(Span buffer, bool japanese) diff --git a/tests/PKForge.Domain.Tests/AppUpdateRulesTests.cs b/tests/PKForge.Domain.Tests/AppUpdateRulesTests.cs index beb32ac3..2c8b85cd 100644 --- a/tests/PKForge.Domain.Tests/AppUpdateRulesTests.cs +++ b/tests/PKForge.Domain.Tests/AppUpdateRulesTests.cs @@ -13,6 +13,14 @@ public sealed class AppUpdateRulesTests [InlineData("3.0.3", "v3.1.0", true)] // the 3.1 release, as a 3.0.3 install sees it [InlineData("3.1.0", "v3.0.3", false)] [InlineData("1.4.0", "v1.4.0-beta+build.1", false)] + [InlineData("1.4.0-beta", "v1.4.0", true)] // a release outranks its own prerelease + [InlineData("1.4.0", "v1.4.0-rc.1", false)] + [InlineData("1.4.0-beta.1", "v1.4.0-beta.2", true)] // numeric identifiers compare numerically + [InlineData("1.4.0-beta.2", "v1.4.0-beta.10", true)] // 10 > 2, not an ordinal "1" < "2" read + [InlineData("1.4.0-beta", "v1.4.0-beta.1", true)] // more identifiers win a shared-prefix tie + [InlineData("1.4.0-beta.1", "v1.4.0-beta", false)] + [InlineData("1.4.0-alpha", "v1.4.0-beta", true)] // ordinal among alphanumeric identifiers + [InlineData("1.4.0-beta.1", "v1.4.0-2", false)] // numeric ranks below alphanumeric [InlineData("garbage", "v1.4.0", false)] public void ComparesStableReleaseTags(string installed, string candidate, bool expected) => Assert.Equal(expected, AppUpdateRules.IsNewerVersion(installed, candidate)); diff --git a/tests/PKForge.Domain.Tests/RetroAchievementsJsonTests.cs b/tests/PKForge.Domain.Tests/RetroAchievementsJsonTests.cs new file mode 100644 index 00000000..aa2a4d59 --- /dev/null +++ b/tests/PKForge.Domain.Tests/RetroAchievementsJsonTests.cs @@ -0,0 +1,149 @@ +using System.Text.Json; +using PKForge.Domain; +using Xunit; + +namespace PKForge.Domain.Tests; + +/// +/// The RA web API adds DateEarned/DateEarnedHardcore to an achievement only once the +/// player unlocked it, but older responses returned an empty string for a locked one: +/// the property's presence alone must never count as an unlock. +/// +public sealed class RetroAchievementsJsonTests +{ + private static JsonElement Parse(string json) + { + using var document = JsonDocument.Parse(json); + return document.RootElement.Clone(); + } + + [Fact] + public void EarnedAchievementKeepsItsTimestamp() + { + var root = Parse(""" + { + "ID": 1, "Title": "Sonic the Hedgehog", "NumAchievements": 1, + "Achievements": { + "9": { "ID": 9, "Title": "That Was Easy", "Description": "Complete act 1", + "Points": 3, "BadgeName": "250336", + "DateEarned": "2016-03-12 17:47:29", "DateEarnedHardcore": "2016-03-12 17:47:29" } + } + } + """); + var progress = RetroAchievementsJson.ParseGameProgress(root, 1); + var achievement = Assert.Single(progress.Achievements); + Assert.True(achievement.Earned); + Assert.True(achievement.EarnedHardcore); + Assert.Equal(new DateTimeOffset(2016, 3, 12, 17, 47, 29, TimeSpan.Zero), achievement.DateEarned); + Assert.Equal(1, progress.Unlocked); + Assert.Equal(3, progress.PointsEarned); + } + + [Fact] + public void AchievementWithoutEarnedFieldsIsLocked() + { + var root = Parse(""" + { + "ID": 1, "Title": "Sonic the Hedgehog", + "Achievements": { + "9": { "ID": 9, "Title": "That Was Easy", "Description": "Complete act 1", + "Points": 3, "BadgeName": "250336" } + } + } + """); + var achievement = Assert.Single(RetroAchievementsJson.ParseGameProgress(root, 1).Achievements); + Assert.False(achievement.Earned); + Assert.False(achievement.EarnedHardcore); + Assert.Null(achievement.DateEarned); + } + + [Theory] + [InlineData("\"DateEarned\": \"\"")] + [InlineData("\"DateEarned\": \" \"")] + [InlineData("\"DateEarned\": null")] + public void EmptyStringDateEarnedIsNotAnUnlock(string dateField) + { + var root = Parse($$""" + { + "ID": 1, "Title": "Sonic the Hedgehog", + "Achievements": { + "9": { "ID": 9, "Title": "That Was Easy", "Description": "Complete act 1", + "Points": 3, "BadgeName": "250336", {{dateField}} } + } + } + """); + var achievement = Assert.Single(RetroAchievementsJson.ParseGameProgress(root, 1).Achievements); + Assert.False(achievement.Earned); + Assert.Null(achievement.DateEarned); + } + + [Fact] + public void SoftcoreOnlyUnlockIsNotHardcore() + { + var root = Parse(""" + { + "ID": 1, "Title": "Sonic the Hedgehog", + "Achievements": { + "9": { "ID": 9, "Title": "That Was Easy", "Description": "Complete act 1", + "Points": 3, "BadgeName": "250336", "DateEarned": "2016-03-12 17:47:29" } + } + } + """); + var achievement = Assert.Single(RetroAchievementsJson.ParseGameProgress(root, 1).Achievements); + Assert.True(achievement.Earned); + Assert.False(achievement.EarnedHardcore); + } + + [Fact] + public void MissingFieldsDefaultToEmptyAndZero() + { + var root = Parse("""{ "ID": 7, "Achievements": { "3": { "ID": 3 } } }"""); + var progress = RetroAchievementsJson.ParseGameProgress(root, 7); + Assert.Equal(7, progress.GameId); + Assert.Equal(string.Empty, progress.Title); + var achievement = Assert.Single(progress.Achievements); + Assert.Equal(3, achievement.Id); + Assert.Equal(string.Empty, achievement.Title); + Assert.Equal(0, achievement.Points); + Assert.False(achievement.Earned); + } + + [Fact] + public void EmptyAchievementSetSerializesAsAnObject() + { + // issue #484 on RAWeb: a game with no published set returns {} - never an array. + var root = Parse("""{ "ID": 7, "Title": "Empty", "Achievements": {} }"""); + var progress = RetroAchievementsJson.ParseGameProgress(root, 7); + Assert.Empty(progress.Achievements); + Assert.Equal(100, progress.Percent); // nothing to do counts as complete + } + + [Fact] + public void AchievementsAreSortedById() + { + var root = Parse(""" + { + "ID": 1, + "Achievements": { + "30": { "ID": 30, "Title": "C" }, + "2": { "ID": 2, "Title": "A" }, + "17": { "ID": 17, "Title": "B" } + } + } + """); + var progress = RetroAchievementsJson.ParseGameProgress(root, 1); + Assert.Equal([2, 17, 30], progress.Achievements.Select(a => a.Id).ToArray()); + } + + [Theory] + [InlineData("""{"ID": 1, "Title": "Sonic"}""", true)] + [InlineData("""{"ID": "not a number"}""", true)] // presence is what the client checks + [InlineData("""[]""", false)] // an empty array is the error shape + [InlineData("""{"error": "Unknown game"}""", false)] + public void LooksLikeGameOnlyAcceptsAnObjectWithAnId(string json, bool expected) => + Assert.Equal(expected, RetroAchievementsJson.LooksLikeGame(Parse(json))); + + [Fact] + public void LooksLikeProfileRejectsTheErrorShape() => + Assert.False(RetroAchievementsJson.LooksLikeProfile(Parse("""{"error": "Unknown user"}"""))); +} diff --git a/tests/PKForge.Domain.Tests/RomLinkTests.cs b/tests/PKForge.Domain.Tests/RomLinkTests.cs index 0d4be052..a60c981e 100644 --- a/tests/PKForge.Domain.Tests/RomLinkTests.cs +++ b/tests/PKForge.Domain.Tests/RomLinkTests.cs @@ -60,6 +60,28 @@ public void InstallationDetectsAnyKnownPackage() Assert.True(EmulatorCatalog.IsInstalled(EmulatorKind.RetroArch, id => id == "com.retroarch.aarch64")); Assert.False(EmulatorCatalog.IsInstalled(EmulatorKind.MelonDS, id => id == "com.retroarch")); } + + [Fact] + public void DisplayNamesAreStable() + { + Assert.Equal("melonDS", EmulatorCatalog.Name(EmulatorKind.MelonDS)); + Assert.Equal("DraStic", EmulatorCatalog.Name(EmulatorKind.DraStic)); + Assert.Equal("Pizza Boy GBA", EmulatorCatalog.Name(EmulatorKind.PizzaBoyGba)); + Assert.Equal("Pizza Boy GBC", EmulatorCatalog.Name(EmulatorKind.PizzaBoyGbc)); + Assert.Equal("Citra MMJ", EmulatorCatalog.Name(EmulatorKind.CitraMmj)); + Assert.Equal("RetroArch", EmulatorCatalog.Name(EmulatorKind.RetroArch)); + Assert.Equal("Eden", EmulatorCatalog.Name(EmulatorKind.Eden)); + Assert.Equal("Linkboy", EmulatorCatalog.Name(EmulatorKind.Linkboy)); + Assert.Equal("Azahar", EmulatorCatalog.Name(EmulatorKind.Azahar)); + Assert.Equal("Dolphin", EmulatorCatalog.Name(EmulatorKind.Dolphin)); + } + + [Fact] + public void DescribeNamesTheRomAndItsEmulator() + { + var link = new RomLink("save1", "file:///roms/emerald.gba", "emerald.gba", EmulatorKind.MelonDS, 3, "Pokémon Emerald"); + Assert.Equal("emerald.gba · melonDS", RomLinkRules.Describe(link)); + } } public sealed class RomLinkStoreTests : IDisposable diff --git a/tests/PKForge.Domain.Tests/TrophyTests.cs b/tests/PKForge.Domain.Tests/TrophyTests.cs index f03796e5..33448008 100644 --- a/tests/PKForge.Domain.Tests/TrophyTests.cs +++ b/tests/PKForge.Domain.Tests/TrophyTests.cs @@ -11,7 +11,7 @@ private static SaveScanFacts Facts( [Theory] [InlineData(TrophyKind.DexCaught, 60, 60)] - [InlineData(TrophyKind.DexCaught, 30, 59)] + [InlineData(TrophyKind.DexCaught, 30, 60)] [InlineData(TrophyKind.DexSeen, 100, 100)] [InlineData(TrophyKind.ShinyOwned, 5, 5)] [InlineData(TrophyKind.PlaytimeHours, 50, 50)] diff --git a/tests/PKForge.Engine.Tests/NicknameLimitTests.cs b/tests/PKForge.Engine.Tests/NicknameLimitTests.cs new file mode 100644 index 00000000..29ee001f --- /dev/null +++ b/tests/PKForge.Engine.Tests/NicknameLimitTests.cs @@ -0,0 +1,108 @@ +using PKForge.Domain; +using PKForge.Engine; +using PKHeX.Core; +using Xunit; + +namespace PKForge.Engine.Tests; + +/// +/// Nicknames and OT names must fit the mon's string buffer: a name longer than the format +/// stores would overflow it when encoded into the save. The box slot starts empty, so a +/// freshly built mon is placed first (the same write the generator performs). +/// +public sealed class NicknameLimitTests +{ + private static SaveEngineSession BlankSession(int generation) => + (SaveEngineSession)new SaveEngine().OpenBlankSession(generation); + + private static (int Box, int Slot) SeedMon(SaveEngineSession session) + { + var mon = session.SaveFile.BlankPKM; + mon.Species = (ushort)Species.Bulbasaur; + mon.CurrentLevel = 5; + mon.RefreshChecksum(); + var bytes = new byte[mon.SIZE_PARTY]; + mon.WriteDecryptedDataParty(bytes); + // Gen 1/2 blank saves hold the mon in the party (their box layout is a list the + // blank save does not initialise); every other generation takes a box slot. + var (box, slot) = mon.Format <= 2 ? (-1, 0) : (0, 0); + Assert.True(session.ImportSlot(box, slot, bytes), $"gen {mon.Format}: could not seed a mon"); + return (box, slot); + } + + // A blank Gen 1 session is Japanese (SaveEngine.VersionFor(1) => GameVersion.BU), so its + // mons carry 6-byte string buffers (limits 5) and the Gen 1 JP table has no Latin letters: + // the filler must be a kana. A blank Gen 2 session is English (limits 10/7, 'A' encodes). + [Theory] + [InlineData(1, 5, 'ア')] + [InlineData(2, 10, 'A')] + [InlineData(3, 10, 'A')] + [InlineData(4, 10, 'A')] + [InlineData(5, 10, 'A')] + [InlineData(6, 12, 'A')] + [InlineData(7, 12, 'A')] + [InlineData(8, 12, 'A')] + [InlineData(9, 12, 'A')] + public void EditTruncatesOverlongNicknames(int generation, int limit, char filler) + { + using var session = BlankSession(generation); + var (box, slot) = SeedMon(session); + session.ApplyEdit(box, slot, new EntityEdit(Nickname: new string(filler, limit + 5))); + Assert.Equal(limit, session.ReadEntity(box, slot).Nickname.Length); + } + + [Theory] + [InlineData(1, 5, 'ア')] + [InlineData(2, 7, 'A')] + [InlineData(3, 7, 'A')] + [InlineData(4, 7, 'A')] + [InlineData(5, 7, 'A')] + [InlineData(6, 12, 'A')] + [InlineData(7, 12, 'A')] + [InlineData(8, 12, 'A')] + [InlineData(9, 12, 'A')] + public void EditTruncatesOverlongOriginalTrainerNames(int generation, int limit, char filler) + { + using var session = BlankSession(generation); + var (box, slot) = SeedMon(session); + session.ApplyEdit(box, slot, new EntityEdit(OriginalTrainer: new string(filler, limit + 5))); + Assert.Equal(limit, session.ReadEntity(box, slot).OriginalTrainer.Length); + } + + [Fact] + public void ShortNamesPassThroughUnchanged() + { + using var session = BlankSession(3); + var (box, slot) = SeedMon(session); + session.ApplyEdit(box, slot, new EntityEdit(Nickname: "Sparky")); + Assert.Equal("Sparky", session.ReadEntity(box, slot).Nickname); + } + + [Theory] + [InlineData(1, LanguageID.Japanese, 5)] + [InlineData(1, LanguageID.English, 10)] + [InlineData(2, LanguageID.Japanese, 5)] + [InlineData(2, LanguageID.English, 10)] + [InlineData(3, LanguageID.English, 10)] + [InlineData(5, LanguageID.English, 10)] + [InlineData(9, LanguageID.English, 12)] + public void LimitFollowsTheLanguage(int generation, LanguageID language, int expected) + { + PKM mon; + if (generation is 1 or 2) + { + // GBPKML.Japanese derives from the OT buffer length, not the Language property: + // a Gen 1/2 mon is Japanese exactly when its buffers are 6 bytes long. + var jp = language == LanguageID.Japanese; + mon = generation == 1 ? new PK1(jp) : new PK2(jp); + } + else + { + using var session = BlankSession(generation); + mon = session.SaveFile.BlankPKM; + mon.Language = (int)language; + } + var trimmed = SaveEngineSession.TrimToNicknameLimit(new string('A', 20), mon); + Assert.Equal(expected, trimmed.Length); + } +}