From 37ec593c66bf526c6bb7bddf44dfaa4715567e3b Mon Sep 17 00:00:00 2001 From: NewBarkTownKris <349535944+NewBarkTownKris@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:56:16 -0500 Subject: [PATCH] feat: add read-only My Pokemon Ranch extraction --- README.md | 2 + .../Android/AndroidEmulatorScanner.cs | 36 ++- .../ViewModels/BoxBrowserViewModel.cs | 12 +- src/PKForge.App/Views/BoxBrowserPage.cs | 43 ++-- src/PKForge.App/Views/BoxGridRenderer.cs | 8 + src/PKForge.App/Views/HomePage.cs | 6 +- src/PKForge.Domain/Contracts.cs | 3 + src/PKForge.Domain/EntityEditing.cs | 6 + src/PKForge.Engine/BulkBoxActions.cs | 2 +- src/PKForge.Engine/CrossFormatConverter.cs | 9 +- src/PKForge.Engine/EventDatabaseService.cs | 4 +- src/PKForge.Engine/EvolutionService.cs | 2 +- src/PKForge.Engine/LegalityAssistService.cs | 2 +- src/PKForge.Engine/LegalizerService.cs | 20 +- src/PKForge.Engine/MonFieldService.cs | 2 +- src/PKForge.Engine/RanchFormat.cs | 79 +++++++ src/PKForge.Engine/SaveEngine.cs | 17 +- src/PKForge.Engine/SaveEngineSession.cs | 113 ++++++---- src/PKForge.Engine/SaveParser.cs | 6 + src/PKForge.Engine/ShowdownTeamService.cs | 2 +- src/PKForge.Engine/WriteSafety.cs | 2 + .../EmulatorSaveHeuristics.cs | 19 +- src/PKForge.Infrastructure/SafeSaveWriter.cs | 7 + .../EmulatorSaveHeuristicsTests.cs | 12 + tests/PKForge.Engine.Tests/RanchTests.cs | 213 ++++++++++++++++++ 25 files changed, 526 insertions(+), 101 deletions(-) create mode 100644 src/PKForge.Engine/RanchFormat.cs create mode 100644 tests/PKForge.Engine.Tests/RanchTests.cs diff --git a/README.md b/README.md index 7af6a7a5..2cb44245 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,7 @@ games and popular romhacks: - **Generation I:** Red, Blue, Green (JP), Yellow - **Generation II:** Gold, Silver, Crystal - **Generation III:** Ruby, Sapphire, Emerald, FireRed, LeafGreen, Pokémon Box: Ruby & Sapphire, Colosseum, XD: Gale of Darkness +- **My Pokémon Ranch:** read-only extraction from the original Diamond/Pearl format (verified with USA saves). Copy to Bank or export native RK4 files; conversion to another game's format explains the loss of Ranch ownership metadata. Deposits, edits and withdrawals are disabled. The Platinum revision is not yet verified. - **Generation IV:** Diamond, Pearl, Platinum, HeartGold, SoulSilver - **Generation V:** Black, White, Black 2, White 2 - **Generation VI:** X, Y, Omega Ruby, Alpha Sapphire @@ -154,6 +155,7 @@ Link a storage unit and PKForge finds your saves automatically: - **Game Boy Advance:** RetroArch, Linkboy, Pizza Boy A - **Nintendo DS:** melonDS, DraStic, RetroArch - **GameCube:** Dolphin +- **Wii storage:** Dolphin discovery of the USA My Pokémon Ranch main save (`savedata.bin`); automatic backups are excluded from discovery and can be opened explicitly. - **Nintendo 3DS:** Azahar, Lime3DS, Citra MMJ - **Nintendo Switch:** Eden diff --git a/src/PKForge.App/Platforms/Android/AndroidEmulatorScanner.cs b/src/PKForge.App/Platforms/Android/AndroidEmulatorScanner.cs index 08b4d5ee..7fb8a9c4 100644 --- a/src/PKForge.App/Platforms/Android/AndroidEmulatorScanner.cs +++ b/src/PKForge.App/Platforms/Android/AndroidEmulatorScanner.cs @@ -141,7 +141,7 @@ void OnFile(ChildDocument child) state.Trace($"RAW MEMORY CARD {child.Name}: individual GCI export required"); return; } - if (!EmulatorSaveHeuristics.IsCandidateFileName(child.Name, kind)) return; + if (!EmulatorSaveHeuristics.IsCandidateFileName(child.Name, kind, child.ScanPath ?? child.DocId)) return; if (TryDetect(treeUri, child, kind, gameLabel: child.Name, state: state) is { } save) { results.Add(save); @@ -152,9 +152,12 @@ void OnFile(ChildDocument child) } var rootChildren = ListChildren(treeUri, rootDocId); + // SAF providers may use opaque ids (e.g. msd:123). Walk display names for + // the Ranch title filter rather than assuming every document id is a path. + var rootPath = kind == EmulatorKind.Dolphin ? rootDocId + "/" + DocumentName(treeUri, rootDocId) : null; string[] preferredFolders = kind switch { - EmulatorKind.Dolphin => ["GC"], + EmulatorKind.Dolphin => ["GC", "Wii"], EmulatorKind.DraStic => ["backup"], EmulatorKind.PizzaBoyGba or EmulatorKind.PizzaBoyGbc => ["save", "saves"], _ => ["saves"], @@ -164,13 +167,14 @@ void OnFile(ChildDocument child) { state.Siblings = rootChildren.Where(x => !x.IsDirectory).Select(x => x.Name).ToArray(); foreach (var file in rootChildren.Where(x => !x.IsDirectory)) - OnFile(file); + OnFile(rootPath is null ? file : file with { ScanPath = rootPath + "/" + file.Name }); foreach (var savesDir in savesDirs) - FindFilesRecursive(treeUri, savesDir.DocId, maxDepth, cancellationToken, OnFile, state); + FindFilesRecursive(treeUri, savesDir.DocId, maxDepth, cancellationToken, OnFile, state, + scanPath: rootPath is null ? null : rootPath + "/" + savesDir.Name); } else { - FindFilesRecursive(treeUri, rootDocId, maxDepth, cancellationToken, OnFile, state); + FindFilesRecursive(treeUri, rootDocId, maxDepth, cancellationToken, OnFile, state, scanPath: rootPath); } return results; } @@ -346,7 +350,7 @@ IEnumerable> List(ChildDocument doc) => } } - private sealed record ChildDocument(string DocId, string Name, bool IsDirectory, DateTimeOffset? LastModified); + private sealed record ChildDocument(string DocId, string Name, bool IsDirectory, DateTimeOffset? LastModified, string? ScanPath = null); /// Android's last package update time: zero-once per install, stable after. private static long _installEpoch = -1; @@ -442,7 +446,7 @@ private static void Load() private void FindFilesRecursive(AndroidUri treeUri, string parentDocId, int maxDepth, CancellationToken cancellationToken, Action onFile, ScanState state, - bool diagnostic = false) + bool diagnostic = false, string? scanPath = null) { if (maxDepth <= 0) { @@ -463,16 +467,30 @@ private void FindFilesRecursive(AndroidUri treeUri, string parentDocId, int maxD if (diagnostic) state.Trace($"PRUNED directory {child.Name}"); continue; } - FindFilesRecursive(treeUri, child.DocId, maxDepth - 1, cancellationToken, onFile, state, diagnostic); + FindFilesRecursive(treeUri, child.DocId, maxDepth - 1, cancellationToken, onFile, state, diagnostic, + scanPath is null ? null : scanPath + "/" + child.Name); } else { state.Siblings = siblings; - onFile(child); + onFile(scanPath is null ? child : child with { ScanPath = scanPath + "/" + child.Name }); } } } + private static string? DocumentName(AndroidUri treeUri, string documentId) + { + try + { + var uri = DocumentsContract.BuildDocumentUriUsingTree(treeUri, documentId); + if (uri is null) return null; + using var cursor = Android.App.Application.Context.ContentResolver?.Query(uri, + [DocumentsContract.Document.ColumnDisplayName], null, null, null); + return cursor is not null && cursor.MoveToFirst() ? cursor.GetString(0) : null; + } + catch (Java.Lang.RuntimeException) { return null; } // optional hint; retain the document id + } + private static string? NavigatePath(AndroidUri treeUri, string fromDocId, string[] segments, Action? trace = null) { var current = fromDocId; diff --git a/src/PKForge.App/ViewModels/BoxBrowserViewModel.cs b/src/PKForge.App/ViewModels/BoxBrowserViewModel.cs index fbe12eab..7e564c8a 100644 --- a/src/PKForge.App/ViewModels/BoxBrowserViewModel.cs +++ b/src/PKForge.App/ViewModels/BoxBrowserViewModel.cs @@ -445,6 +445,12 @@ public async Task RunMutationAsync(Func= BoxCount) return; + if (box == -1 && _sessions.CurrentSession?.HasParty == false) return; PendingRectangle = null; BoxIndex = box; SelectedSlot = -1; @@ -945,9 +952,10 @@ public void ChangeBox(int delta) { if (Save is null || BoxCount == 0) return; // The party wraps around the boxes: last box, then PARTY, then box 1 again. + var first = _sessions.CurrentSession?.HasParty == false ? 0 : -1; var next = BoxIndex + delta; - if (next > BoxCount - 1) next = -1; - else if (next < -1) next = BoxCount - 1; + if (next > BoxCount - 1) next = first; + else if (next < first) next = BoxCount - 1; PendingRectangle = null; // a rectangle belongs to one page BoxIndex = next; SelectedSlot = -1; diff --git a/src/PKForge.App/Views/BoxBrowserPage.cs b/src/PKForge.App/Views/BoxBrowserPage.cs index 459ccdb9..5c34c778 100644 --- a/src/PKForge.App/Views/BoxBrowserPage.cs +++ b/src/PKForge.App/Views/BoxBrowserPage.cs @@ -135,7 +135,7 @@ public BoxBrowserPage(BoxBrowserViewModel viewModel, ISpriteService sprites, The var root = new Grid { RowDefinitions = [new(GridLength.Auto), new(GridLength.Auto), new(GridLength.Star), new(GridLength.Auto)], - Children = { DsChrome.TitleBar(), DsChrome.StatusStrip(title, "Connected"), bodyHost, _footerHost }, + Children = { DsChrome.TitleBar(), DsChrome.StatusStrip(title, _sessionsFor()?.ReadOnlyReason is null ? "Connected" : "Read-only"), bodyHost, _footerHost }, }; Grid.SetRow((View)root.Children[1], 1); Grid.SetRow(bodyHost, 2); @@ -359,8 +359,9 @@ private void SetBoxManageFooter() => _footerHost.Content = DsChrome.Footer( private static SaveGuard Guard => HardcoreMode.Guard; /// A menu entry that exists only while Hardcore mode allows its action; null hides it. - private static PadOption? Allowed(SaveAction action, PadOption option) => - Guard.Allows(action) ? option : null; + private PadOption? Allowed(SaveAction action, PadOption option, bool changesSource = true) => + Guard.Allows(action) && (_sessionsFor()?.ReadOnlyReason is null || + !changesSource || action is SaveAction.ExportFile or SaveAction.Backup) ? option : null; /// The menu's options without the entries Hardcore mode refuses. private static PadOption[] Menu(params PadOption?[] options) => @@ -389,7 +390,9 @@ private async Task DeniedAsync(SaveAction action) } /// The idle status line, carrying the marker so the mode is visible on the screen it gates. - private void ShowReady() => _viewModel.Status = HardcoreMode.IsOn + private void ShowReady() => _viewModel.Status = _sessionsFor()?.ReadOnlyReason is not null + ? "Read-only · export available" + : HardcoreMode.IsOn ? $"Ready · {HardcoreMode.StatusLine}" : LayoutMarker ?? "Ready"; @@ -495,7 +498,7 @@ private View BuildSidePanel() { PksmIcons.Icon("storage", 44), new Label { Text = "Select a Pokémon", TextColor = UiTokens.Ink1, FontFamily = DsChrome.PixelFont, FontSize = 15 }, - new Label { Text = "Tap an empty slot to add one", TextColor = UiTokens.Ink1, FontSize = UiTokens.TextSmall, HorizontalTextAlignment = TextAlignment.Center }, + new Label { Text = _sessionsFor()?.ReadOnlyReason is null ? "Tap an empty slot to add one" : "Inspect, copy or export Pokémon", TextColor = UiTokens.Ink1, FontSize = UiTokens.TextSmall, HorizontalTextAlignment = TextAlignment.Center }, }, }; @@ -1178,14 +1181,14 @@ private async Task ShowOrganizerMenuAsync() { options.Add(new("Clear marks", IconPath: "deselect")); options.AddRange(Menu( - new PadOption("Move to box…", IconPath: "move"), - new PadOption("Move to Bank", IconPath: "bank", Detail: "They leave this save and are stored in the Bank."), - Allowed(SaveAction.Duplicate, new("Copy to Bank", IconPath: "bank", Detail: "Copies go to the Bank; the originals stay here.")), - new PadOption("Move to another game…", IconPath: "send", Detail: "They leave this save and join another linked game."), - Allowed(SaveAction.Duplicate, new("Copy to another game…", IconPath: "copy", Detail: "Copies join another linked game; the originals stay here.")), + Allowed(SaveAction.Move, new("Move to box…", IconPath: "move")), + Allowed(SaveAction.Move, new("Move to Bank", IconPath: "bank", Detail: "They leave this save and are stored in the Bank.")), + Allowed(SaveAction.Duplicate, new("Copy to Bank", IconPath: "bank", Detail: "Copies go to the Bank; the originals stay here."), changesSource: false), + Allowed(SaveAction.Move, new("Move to another game…", IconPath: "send", Detail: "They leave this save and join another linked game.")), + Allowed(SaveAction.Duplicate, new("Copy to another game…", IconPath: "copy", Detail: "Copies join another linked game; the originals stay here."), changesSource: false), Allowed(SaveAction.Duplicate, new("Duplicate", IconPath: "copy", Detail: "Clone the marked Pokémon into the first free box slots.")), new PadOption("Export (.pk files)", IconPath: "export", Detail: "Share each marked Pokémon as its own file."), - new PadOption("Release", IconPath: "release"))); + Allowed(SaveAction.Release, new("Release", IconPath: "release")))); options.AddRange(BulkOptions()); } options.Add(new("Mark Pokémon holding…", IconPath: "item", Detail: "Find Pokémon holding an item, then mark them or go to one.")); @@ -3807,22 +3810,22 @@ private async Task ShowMonActionsAsync(int slot) } options.AddRange(Menu( new PadOption("Summary", IconPath: "info"), - new PadOption("Edit", IconPath: "editor"), + _sessionsFor()?.ReadOnlyReason is null ? new PadOption("Edit", IconPath: "editor") : null, Allowed(SaveAction.EditMon, new("Evolve…", IconPath: "evolve")), new PadOption("Send to Poképark", IconPath: "park", Detail: "Adds it to the Poképark visitors. The save is not changed."), - new PadOption("Move", IconPath: "move", Detail: "Pick it up and carry it to another slot."), + Allowed(SaveAction.Move, new("Move", IconPath: "move", Detail: "Pick it up and carry it to another slot.")), Allowed(SaveAction.Duplicate, new("Duplicate", IconPath: "copy", Detail: "Clone it into the next empty slot here.")), - new PadOption("Send to Bank", IconPath: "bank", Detail: "It leaves this save and is stored in the Bank."), - Allowed(SaveAction.Duplicate, new("Copy to Bank", IconPath: "copy", Detail: "A copy goes to the Bank; the original stays here.")), - new PadOption("Send to another game…", IconPath: "send", Detail: "It leaves this save and joins another linked game."), - Allowed(SaveAction.Duplicate, new("Copy to another game…", IconPath: "copy", Detail: "A copy joins another linked game; the original stays here.")), + Allowed(SaveAction.Move, new("Send to Bank", IconPath: "bank", Detail: "It leaves this save and is stored in the Bank.")), + Allowed(SaveAction.Duplicate, new("Copy to Bank", IconPath: "copy", Detail: "A copy goes to the Bank; the original stays here."), changesSource: false), + Allowed(SaveAction.Move, new("Send to another game…", IconPath: "send", Detail: "It leaves this save and joins another linked game.")), + Allowed(SaveAction.Duplicate, new("Copy to another game…", IconPath: "copy", Detail: "A copy joins another linked game; the original stays here."), changesSource: false), new PadOption("Export .pk file", IconPath: "export", Detail: "Share this Pokémon as a file."), new PadOption("Show as Showdown set", IconPath: "script", Detail: "Its set as Showdown text you can copy."), new PadOption("Show as QR code", IconPath: "qr", Detail: "Its Showdown set as a QR code."), new PadOption("Show as .pk QR", IconPath: "qr", Detail: "The whole Pokémon as a QR code that PKForge can scan into the Bank."), new PadOption("RNG / IVs", IconPath: "dice", Detail: "See its PID and IVs, and change its nature without losing shininess."), new PadOption("Lock / Unlock release", IconPath: "padlock", Detail: "A locked Pokémon cannot be released."), - new PadOption("Release", IconPath: "release"))); + Allowed(SaveAction.Release, new("Release", IconPath: "release")))); var choice = await PadMenu.ShowAsync(_hostGrid, nickname, Note(verdict is { Valid: false } ? verdict.Problem : null), options.ToArray()); switch (choice) @@ -4190,9 +4193,9 @@ 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); + var outcome = await transfer.SendToGameAsync(export.Data, nickname, target, format: export.Format); _viewModel.Status = outcome.Message; if (!outcome.Success || copyInsteadOfMove) return; diff --git a/src/PKForge.App/Views/BoxGridRenderer.cs b/src/PKForge.App/Views/BoxGridRenderer.cs index f42c5e37..887e9a67 100644 --- a/src/PKForge.App/Views/BoxGridRenderer.cs +++ b/src/PKForge.App/Views/BoxGridRenderer.cs @@ -183,6 +183,14 @@ internal static void PaintScene(SKCanvas canvas, SKImageInfo info, StorageScene for (var index = 0; index < Columns * Rows; index++) { var cell = layout.Cell(index); + // A capacity-limited storage save can end partway through a grid page. + if (index >= slots.Count) + { + using var unavailable = new SKPaint { Color = SKColors.Gray.WithAlpha(45), Style = SKPaintStyle.Stroke, StrokeWidth = 1 }; + canvas.DrawLine(cell.Left, cell.Top, cell.Right, cell.Bottom, unavailable); + canvas.DrawLine(cell.Right, cell.Top, cell.Left, cell.Bottom, unavailable); + continue; + } // Badges keep the square tile they were designed for, centered in the wide cell. var tile = SKRect.Create(cell.MidX - layout.CellHeight / 2, cell.Top, layout.CellHeight, layout.CellHeight); diff --git a/src/PKForge.App/Views/HomePage.cs b/src/PKForge.App/Views/HomePage.cs index e2a45b0b..a8ce399b 100644 --- a/src/PKForge.App/Views/HomePage.cs +++ b/src/PKForge.App/Views/HomePage.cs @@ -519,7 +519,7 @@ private async Task ShowLinkMenuAsync() new PadOption("Game Boy / Game Boy Color", IconPath: "platform-gb"), new PadOption("Game Boy Advance", IconPath: "platform-gba"), new PadOption("Nintendo DS", IconPath: "platform-ds"), - new PadOption("GameCube", IconPath: "platform-gc"), + new PadOption("GameCube / Wii", IconPath: "platform-gc"), new PadOption("Nintendo 3DS", IconPath: "azahar"), new PadOption("Nintendo Switch", IconPath: "eden"), new PadOption("Single save file", IconPath: "file")); @@ -545,7 +545,7 @@ private async Task ShowLinkMenuAsync() new PadOption("DraStic", IconPath: "drastic"), new PadOption("RetroArch", IconPath: "retroarch"), }, - "GameCube" => new[] { new PadOption("Dolphin", IconPath: "dolphin") }, + "GameCube / Wii" => new[] { new PadOption("Dolphin", IconPath: "dolphin") }, "Nintendo 3DS" => new[] { new PadOption("Azahar / Lime3DS", IconPath: "azahar"), @@ -557,7 +557,7 @@ private async Task ShowLinkMenuAsync() if (choice is null) continue; var guidance = choice switch { - "Dolphin" => "Save in game and stop emulation before editing Colosseum or XD. Select Dolphin's GC folder, a region folder, or Card A / Card B containing .gci saves. For .raw memory cards, export the game as GCI with Dolphin's Memory Card Manager, or configure that card slot as GCI Folder. After editing, start the game normally; loading an old save state can undo your edits.", + "Dolphin" => "Select Dolphin's user folder, GC, or Wii. GameCube saves use .gci files; My Pokémon Ranch uses savedata.bin and supports copy/export only. Save in game and stop emulation before editing GameCube saves. For .raw memory cards, export the game as GCI with Dolphin's Memory Card Manager, or configure that card slot as GCI Folder. After editing, start the game normally; loading an old save state can undo your edits.", "DraStic" => "Save in game and close DraStic. Select its backup folder containing .dsv battery saves, or the DraStic data folder. Save states are not supported. Restart the game normally after editing.", "Pizza Boy A (GBA)" or "Pizza Boy C (GB/GBC)" => "Save in game and close Pizza Boy. Select the folder containing its battery saves (.sav), not save states. If Android hides the folder, export the battery save in Pizza Boy and link that export. Import the edited export back into Pizza Boy, then restart the game normally.", "Azahar / Lime3DS" => "Save in game and close the emulator. Select the user folder you chose in its setup (the one containing sdmc); sdmc, Nintendo 3DS or a folder above the user folder also work. Restart the game normally after editing.", diff --git a/src/PKForge.Domain/Contracts.cs b/src/PKForge.Domain/Contracts.cs index f7a61ad4..ff83d685 100644 --- a/src/PKForge.Domain/Contracts.cs +++ b/src/PKForge.Domain/Contracts.cs @@ -2,6 +2,9 @@ namespace PKForge.Domain; public interface ISaveEngine { + /// A format-level restriction that applies even to restores and confirmed layout risks. + string? GetWriteRestriction(ReadOnlyMemory bytes) => null; + SaveSnapshot Open(ReadOnlyMemory bytes, string? displayName = null); ISaveEngineSession OpenSession(ReadOnlyMemory bytes, string? displayName = null); ReadOnlyMemory Serialize(SaveSnapshot snapshot); diff --git a/src/PKForge.Domain/EntityEditing.cs b/src/PKForge.Domain/EntityEditing.cs index fd050949..92798741 100644 --- a/src/PKForge.Domain/EntityEditing.cs +++ b/src/PKForge.Domain/EntityEditing.cs @@ -3,6 +3,12 @@ namespace PKForge.Domain; /// An engine-owned mutable save document. All access goes through this session; callers never see engine types. public interface ISaveEngineSession : IDisposable { + /// Why this source supports browsing and extraction but cannot be changed. + string? ReadOnlyReason => null; + + /// Whether storage includes a party page. + bool HasParty => true; + /// Called when this save becomes the one the player has open (legality era). void MakeActive() { } diff --git a/src/PKForge.Engine/BulkBoxActions.cs b/src/PKForge.Engine/BulkBoxActions.cs index 82dcb44f..20956a7c 100644 --- a/src/PKForge.Engine/BulkBoxActions.cs +++ b/src/PKForge.Engine/BulkBoxActions.cs @@ -162,6 +162,6 @@ private static (SaveEngineSession Engine, SaveFile Save) Require(ISaveEngineSess ArgumentNullException.ThrowIfNull(session); if (session is not SaveEngineSession engine) throw new NotSupportedException("Bulk edits need a stock game session; this ROM hack keeps its own format."); - return (engine, engine.SaveFile); + return (engine, engine.WritableSaveFile); } } diff --git a/src/PKForge.Engine/CrossFormatConverter.cs b/src/PKForge.Engine/CrossFormatConverter.cs index b8bfb65e..8c77cf75 100644 --- a/src/PKForge.Engine/CrossFormatConverter.cs +++ b/src/PKForge.Engine/CrossFormatConverter.cs @@ -52,11 +52,16 @@ public static class CrossFormatConverter // An official route wins whenever one exists; PKHeX already sanitizes those. var forward = EntityConverter.ConvertToType(source, destType, out var result); if (forward is not null && result is EntityConverterResult.Success or EntityConverterResult.None) - return new TransferConversion(forward, false, []); + return new TransferConversion(forward, false, RanchWarnings(source)); - return Downgrade(source, target); + var downgrade = Downgrade(source, target); + return downgrade is null ? null : downgrade with { Warnings = [.. RanchWarnings(source), .. downgrade.Warnings] }; } + private static string[] RanchWarnings(PKM source) => source is RK4 + ? ["Ranch ownership and handling-trainer metadata have no counterpart in this game and are not transferred. Keep the native RK4 export to retain them."] + : []; + /// /// Why cannot exist in at all, or null /// when it can (possibly with compromises). The sentence names the species and the game. diff --git a/src/PKForge.Engine/EventDatabaseService.cs b/src/PKForge.Engine/EventDatabaseService.cs index ba7034d6..39ff60c4 100644 --- a/src/PKForge.Engine/EventDatabaseService.cs +++ b/src/PKForge.Engine/EventDatabaseService.cs @@ -231,7 +231,7 @@ public GenerationOutcome Receive(ISaveEngineSession session, int giftId, int box { if (session is not SaveEngineSession engineSession) return new GenerationOutcome(false, "Unsupported session type."); - var save = engineSession.SaveFile; + var save = engineSession.WritableSaveFile; var gifts = GetRawGifts(save); if (giftId < 0 || giftId >= gifts.Count) @@ -250,7 +250,7 @@ public GenerationOutcome ReceiveItems(ISaveEngineSession session, int giftId) { if (session is not SaveEngineSession engineSession) return new GenerationOutcome(false, "Unsupported session type."); - var save = engineSession.SaveFile; + var save = engineSession.WritableSaveFile; var gifts = GetRawGifts(save); if (giftId < 0 || giftId >= gifts.Count || gifts[giftId] is not { IsItem: true } gift) return new GenerationOutcome(false, "Unknown item gift."); diff --git a/src/PKForge.Engine/EvolutionService.cs b/src/PKForge.Engine/EvolutionService.cs index a58df808..6a9641d9 100644 --- a/src/PKForge.Engine/EvolutionService.cs +++ b/src/PKForge.Engine/EvolutionService.cs @@ -55,7 +55,7 @@ public GenerationOutcome Evolve(ISaveEngineSession session, int box, int slot, E ArgumentNullException.ThrowIfNull(request); if (session is not SaveEngineSession engine) return new GenerationOutcome(false, "Evolving is not available for this game yet."); - var sav = engine.SaveFile; + var sav = engine.WritableSaveFile; var original = engine.GetEntity(box, slot); if (original.Species == 0 || original.IsEgg) return new GenerationOutcome(false, "Nothing here can evolve."); diff --git a/src/PKForge.Engine/LegalityAssistService.cs b/src/PKForge.Engine/LegalityAssistService.cs index 97735a1d..3535a1e3 100644 --- a/src/PKForge.Engine/LegalityAssistService.cs +++ b/src/PKForge.Engine/LegalityAssistService.cs @@ -150,7 +150,7 @@ public GenerationOutcome Apply(ISaveEngineSession session, LegalityFixPreview pr var updated = current.Clone(); preview.Candidate.Span.CopyTo(updated.Data); updated.RefreshChecksum(); - Place(engine.SaveFile, preview.Box, preview.Slot, updated); + Place(engine.WritableSaveFile, preview.Box, preview.Slot, updated); return new GenerationOutcome(true, $"{preview.Title}: {preview.Changes.Count} field(s) updated."); } diff --git a/src/PKForge.Engine/LegalizerService.cs b/src/PKForge.Engine/LegalizerService.cs index 772b9dfd..45714dda 100644 --- a/src/PKForge.Engine/LegalizerService.cs +++ b/src/PKForge.Engine/LegalizerService.cs @@ -32,7 +32,7 @@ public GenerationOutcome Generate(ISaveEngineSession session, int box, int slot, return unbound.GenerateInto(box, slot, request); if (session is RadicalRed.CfruEngineSession radicalRed) return radicalRed.GenerateInto(box, slot, request); - var text = BuildShowdownText(request, ((SaveEngineSession)session).SaveFile.Context); + var text = BuildShowdownText(request, ((SaveEngineSession)session).WritableSaveFile.Context); return GenerateFromShowdown(session, box, slot, text, request.AllowUnsupportedSpecies); } @@ -45,7 +45,7 @@ public GenerationOutcome GenerateFromShowdown(ISaveEngineSession session, int bo return radicalRed.GenerateFromShowdownText(box, slot, showdownText); if (session is not SaveEngineSession engineSession) return new GenerationOutcome(false, "Unsupported session type."); - var save = engineSession.SaveFile; + var save = engineSession.WritableSaveFile; var set = new ShowdownSet(showdownText); if (set.Species == 0) @@ -132,7 +132,7 @@ public GenerationOutcome LegalizeSlot(ISaveEngineSession session, int box, int s { if (session is not SaveEngineSession engineSession) return new GenerationOutcome(false, "Unsupported session type."); - var save = engineSession.SaveFile; + var save = engineSession.WritableSaveFile; // Box -1 is the party: it has its own accessors, and the box path would go out // of range and abort the whole mutation behind the loading overlay. @@ -293,7 +293,7 @@ public GenerationOutcome LegalizeSlots(ISaveEngineSession session, IReadOnlyList { if (session is not SaveEngineSession engineSession) return new GenerationOutcome(false, "Unsupported session type."); - var save = engineSession.SaveFile; + var save = engineSession.WritableSaveFile; var repaired = 0; var stuck = 0; @@ -334,14 +334,14 @@ public GenerationOutcome LegalizeSlots(ISaveEngineSession session, IReadOnlyList } public GeneratedEntity? GenerateData(ISaveEngineSession session, GenerationRequest request) => - GenerateDataFromShowdown(session, BuildShowdownText(request, ((SaveEngineSession)session).SaveFile.Context), + GenerateDataFromShowdown(session, BuildShowdownText(request, ((SaveEngineSession)session).WritableSaveFile.Context), request.AllowUnsupportedSpecies); public GeneratedEntity? GenerateDataFromShowdown(ISaveEngineSession session, string showdownText, bool allowUnsupportedSpecies = false) { if (session is not SaveEngineSession engineSession) return null; - var save = engineSession.SaveFile; + var save = engineSession.WritableSaveFile; var set = new ShowdownSet(showdownText); if (set.Species == 0) return null; @@ -372,7 +372,7 @@ public GenerationOutcome FillSpecies(ISaveEngineSession session, IReadOnlyList 0 }) return new GenerationOutcome(false, "No living dex bundle for this game - nothing written."); - var save = engineSession.SaveFile; + var save = engineSession.WritableSaveFile; var capacity = save.BoxCount * save.BoxSlotCount; var placed = engineSession.PlaceLivingDex(compressedBundle); onProgress?.Invoke(placed, capacity); diff --git a/src/PKForge.Engine/MonFieldService.cs b/src/PKForge.Engine/MonFieldService.cs index 6409f2e1..d01bb2cc 100644 --- a/src/PKForge.Engine/MonFieldService.cs +++ b/src/PKForge.Engine/MonFieldService.cs @@ -747,7 +747,7 @@ private static (SaveEngineSession Engine, PKM Entity) Read(ISaveEngineSession se private static void Write(SaveEngineSession engine, int box, int slot, PKM pk) { pk.RefreshChecksum(); - var save = engine.SaveFile; + var save = engine.WritableSaveFile; if (box == -1) save.SetPartySlotAtIndex(pk, slot, EntityImportSettings.None); else save.SetBoxSlotAtIndex(pk, box, slot, EntityImportSettings.None); } diff --git a/src/PKForge.Engine/RanchFormat.cs b/src/PKForge.Engine/RanchFormat.cs new file mode 100644 index 00000000..5d46a85e --- /dev/null +++ b/src/PKForge.Engine/RanchFormat.cs @@ -0,0 +1,79 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using PKHeX.Core; + +namespace PKForge.Engine; + +/// +/// Read-only My Pokémon Ranch boundary. The pinned SAV4Ranch constructor trusts +/// file offsets, and BulkStorage.ChecksumsValid does not check the Ranch SHA-1. +/// Layout and record sizes come from that pinned reader and its Ranch substructures. +/// Original-revision object-array framing is cross-checked with ignored USA DP +/// fixtures; RanchTests also exercises synthetic arrays and hostile offsets. +/// +internal static class RanchFormat +{ + // RK4 stored/party size in the pinned PKHeX reader; includes ownership metadata. + private const int RecordSize = 164; + internal const string ReadOnlyReason = "My Pokémon Ranch is read-only. Copy Pokémon to the Bank or export them; deposits, edits and withdrawals are not supported."; + + internal static bool IsCandidate(int length) => length is SaveUtil.SIZE_G4RANCH or SaveUtil.SIZE_G4RANCH_PLAT; + + internal static string? WriteRestriction(ReadOnlySpan data) => + IsCandidate(data.Length) || RetroArchSaveContainer.IsCompressed(data) && IsCandidate(RetroArchSaveContainer.Decode(data).Length) + ? ReadOnlyReason : null; + + internal static void Validate(ReadOnlySpan data) + { + if (data.Length != SaveUtil.SIZE_G4RANCH) + throw new InvalidDataException("This My Pokémon Ranch revision is not supported. Only the original Diamond/Pearl Ranch format has been verified."); + Span digest = stackalloc byte[20]; + SHA1.HashData(data[20..], digest); + if (!CryptographicOperations.FixedTimeEquals(data[..20], digest)) + throw new InvalidDataException("My Pokémon Ranch save checksum failed. Choose an intact save or its backup."); + + if (U32(data, 0x14) != 0x00030005) + throw new InvalidDataException("Unsupported My Pokémon Ranch header."); + Span offsets = stackalloc int[5]; + for (int i = 0; i < offsets.Length; i++) + { + if (U32(data, 0x18 + i * 8) != (uint)i) + throw new InvalidDataException("Invalid My Pokémon Ranch block table."); + uint offset = U32(data, 0x1C + i * 8); + if (offset > (uint)(data.Length - 8) || offset < 0x40 || (i > 0 && offset <= offsets[i - 1])) + throw new InvalidDataException("My Pokémon Ranch block offset is outside its data."); + offsets[i] = (int)offset; + } + if (offsets[0] != 0x40 || U32(data, offsets[0]) != 0x2260 || U32(data, offsets[0] + 4) != 1 || + offsets[1] != offsets[0] + 8 + 0x2260) + throw new InvalidDataException("Unsupported My Pokémon Ranch metadata layout."); + + int level = data[0x5A] + 1, planned = data[0x5B] + 1; + if (level is < 1 or > 25 || planned is < 1 or > 25) + throw new InvalidDataException("Invalid My Pokémon Ranch level."); + int capacity = RanchLevel.GetSlotCount(level); + CheckArray(data, offsets[1], offsets[2], RanchMii.SIZE, RanchLevel.GetMaxMiiCount(level)); + CheckArray(data, offsets[2], offsets[3], RanchTrainerMii.SIZE, RanchLevel.GetMaxMiiCount(level)); + CheckArray(data, offsets[3], offsets[4], RecordSize, capacity); + if (U32(data, offsets[4]) != RanchMii.SIZE || U32(data, offsets[4] + 4) != 0 || + (long)offsets[3] + 8 + (long)capacity * RecordSize > data.Length) + throw new InvalidDataException("Invalid My Pokémon Ranch storage extent or end marker."); + + int records = (int)U32(data, offsets[3] + 4); + for (int i = 0; i < records; i++) + { + byte owner = data[offsets[3] + 8 + i * RecordSize + 0x88]; + if (owner is not (0 or 1 or 4 or 5)) + throw new InvalidDataException("Unrecognized My Pokémon Ranch ownership type."); + } + } + + private static void CheckArray(ReadOnlySpan data, int start, int end, int size, int maximum) + { + uint count = U32(data, start + 4); + if (U32(data, start) != size || count > maximum || (long)start + 8 + (long)count * size != end) + throw new InvalidDataException("Invalid My Pokémon Ranch array size or count."); + } + + private static uint U32(ReadOnlySpan data, int offset) => BinaryPrimitives.ReadUInt32BigEndian(data[offset..]); +} diff --git a/src/PKForge.Engine/SaveEngine.cs b/src/PKForge.Engine/SaveEngine.cs index a4a21920..7179ac83 100644 --- a/src/PKForge.Engine/SaveEngine.cs +++ b/src/PKForge.Engine/SaveEngine.cs @@ -6,6 +6,9 @@ namespace PKForge.Engine; /// Adapts the pinned PKHeX.Core save parser without leaking engine types. public sealed class SaveEngine : IFormatAwareSaveEngine { + public string? GetWriteRestriction(ReadOnlyMemory bytes) => + RanchFormat.WriteRestriction(bytes.Span); + static SaveEngine() => LegalityRules.Apply(); /// @@ -56,6 +59,7 @@ public SaveSnapshot Open(ReadOnlyMemory bytes, string? displayName = null) { for (var slot = 0; slot < save.BoxSlotCount; slot++) { + if (save is SAV4Ranch && box * save.BoxSlotCount + slot >= save.SlotCount) break; var entity = save.GetBoxSlotAtIndex(box, slot); slots.Add(new SlotSummary(box, slot, entity.Species == 0 ? null : entity.Species, entity.IsNicknamed ? entity.Nickname : null, entity.IsShiny, @@ -187,8 +191,12 @@ public ISaveEngineSession OpenBlankSession(int generation, string? displayName = public SaveDescription? TryDescribe(ReadOnlyMemory bytes, string? displayName = null) { var raw = RetroArchSaveContainer.Decode(bytes.Span); - if (!SaveParser.TryGetSaveFile(raw, out var save) || save is null) - return null; + SaveFile? save; + try + { + if (!SaveParser.TryGetSaveFile(raw, out save) || save is null) return null; + } + catch (InvalidDataException) { return null; } if (SaveParser.IsLuminescentPlatinum(raw)) return new SaveDescription("Luminescent Platinum", save.Generation, save.OT, save.PlayTimeString, LanguageTag(save)); @@ -211,16 +219,17 @@ public ISaveEngineSession OpenBlankSession(int generation, string? displayName = if (SaveParser.IsPokemonRadicalRed(raw)) return new SaveDescription("Radical Red", save.Generation, save.OT, save.PlayTimeString, LanguageTag(save)); - // GameCube-only versions sit outside the handheld game-name table. + // Console storage games sit outside the handheld game-name table. var sideGameName = save switch { + SAV4Ranch => "My Pokémon Ranch", SAV3Colosseum => "Colosseum", SAV3XD => "XD: Gale of Darkness", SAV3RSBox => "Box: Ruby & Sapphire", _ => null, }; if (sideGameName is not null) - return new SaveDescription(sideGameName, save.Generation, save.OT, save.PlayTimeString, LanguageTag(save)); + return new SaveDescription(sideGameName, save.Generation, save.OT.TrimEnd('\0'), save.PlayTimeString, LanguageTag(save)); // These editions share one layout: the player's own Pokémon name the cartridge when // they agree, otherwise the pair is shown and the player picks once. diff --git a/src/PKForge.Engine/SaveEngineSession.cs b/src/PKForge.Engine/SaveEngineSession.cs index 40e57f69..cf599f8e 100644 --- a/src/PKForge.Engine/SaveEngineSession.cs +++ b/src/PKForge.Engine/SaveEngineSession.cs @@ -59,6 +59,16 @@ internal SaveEngineSession(SaveFile save, string? displayName) /// session (generate, import, move), not the state of the file at open time. public SaveSnapshot Snapshot => BuildSnapshot(_displayName); + public string? ReadOnlyReason => _save is SAV4Ranch ? RanchFormat.ReadOnlyReason : null; + + public bool HasParty => _save.HasParty; + + private void EnsureWritable() + { + ThrowIfDisposed(); + if (ReadOnlyReason is { } reason) throw new NotSupportedException(reason); + } + internal PKM GetEntity(int box, int slot) { ThrowIfDisposed(); @@ -68,10 +78,15 @@ internal PKM GetEntity(int box, int slot) /// Box -1 addresses the party (0-5, compact like the games). private PKM GetEntityCore(int box, int slot) - => box == -1 ? _save.GetPartySlotAtIndex(slot) : _save.GetBoxSlotAtIndex(box, slot); + { + ThrowIfDisposed(); + ValidateCoordinates(box, slot); + return box == -1 ? _save.GetPartySlotAtIndex(slot) : _save.GetBoxSlotAtIndex(box, slot); + } private void SetEntityCore(int box, int slot, PKM pk) { + EnsureWritable(); if (box == -1) _save.SetPartySlotAtIndex(pk, slot, ImportNone); else _save.SetBoxSlotAtIndex(pk, box, slot, ImportNone); } @@ -149,7 +164,7 @@ internal static Nature NatureEditTarget(PKM entity, Nature nature, out Nature st public void ApplyEdit(int box, int slot, EntityEdit edit) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentNullException.ThrowIfNull(edit); ValidateCoordinates(box, slot); var entity = GetEntityCore(box, slot); @@ -318,7 +333,7 @@ public PokerusInfo GetPokerus(int box, int slot) public void SetPokerus(int box, int slot, PokerusStatus status) { - ThrowIfDisposed(); + EnsureWritable(); ValidateCoordinates(box, slot); var entity = GetEntityCore(box, slot); if (entity.Species == 0) @@ -390,7 +405,7 @@ public IReadOnlyList GetRibbons(int box, int slot) Justification = "PKHeX.Core is preserve=all in the Android linker descriptor; ribbon properties are retained.")] public void SetRibbon(int box, int slot, string id, int value) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentException.ThrowIfNullOrWhiteSpace(id); ValidateCoordinates(box, slot); var entity = GetEntityCore(box, slot); @@ -439,7 +454,7 @@ public IReadOnlyDictionary GetObtainableRibbonMaxima(int box, int s Justification = "PKHeX.Core is preserve=all in the Android linker descriptor; ribbon properties are retained.")] public int AwardAllObtainableRibbons(int box, int slot) { - ThrowIfDisposed(); + EnsureWritable(); ValidateCoordinates(box, slot); var entity = GetEntityCore(box, slot); if (entity.Species == 0) @@ -489,7 +504,7 @@ public AffixedRibbonInfo GetAffixedRibbon(int box, int slot) public void SetAffixedRibbon(int box, int slot, int ribbonIndex) { - ThrowIfDisposed(); + EnsureWritable(); ValidateCoordinates(box, slot); var entity = GetEntityCore(box, slot); if (entity.Species == 0) @@ -519,6 +534,7 @@ private static string HumanizeRibbonName(string id) private void StoreEntity(int box, int slot, PKM entity) { + EnsureWritable(); entity.RefreshChecksum(); if (box == -1) _save.SetPartySlotAtIndex(entity, slot, ImportNone); @@ -540,9 +556,15 @@ internal PKHeX.Core.SaveFile SaveFile } } + /// Mutable engine access must respect extraction-only source formats. + internal SaveFile WritableSaveFile + { + get { EnsureWritable(); return _save; } + } + public bool DuplicateSlot(int fromBox, int fromSlot, int toBox, int toSlot) { - ThrowIfDisposed(); + EnsureWritable(); ValidateCoordinates(fromBox, fromSlot); ValidateCoordinates(toBox, toSlot); var source = GetEntityCore(fromBox, fromSlot); @@ -564,7 +586,7 @@ public bool DuplicateSlot(int fromBox, int fromSlot, int toBox, int toSlot) public void MoveSlot(int fromBox, int fromSlot, int toBox, int toSlot) { - ThrowIfDisposed(); + EnsureWritable(); if (fromBox == toBox && fromSlot == toSlot) return; var source = GetEntityCore(fromBox, fromSlot); @@ -659,11 +681,11 @@ private void DeleteEntityCore(int box, int slot) /// name of their own (a Diamond/Pearl file reports DP), so the name comes from the /// concrete games behind it. public IReadOnlyList GameNames => - [.. EncounterDatabase.ConcreteVersions(_save.Version).Select(GameInfo.GetVersionName)]; + _save is SAV4Ranch ? ["My Pokémon Ranch"] : [.. EncounterDatabase.ConcreteVersions(_save.Version).Select(GameInfo.GetVersionName)]; public int PlaceLivingDex(byte[] compressedBundle) { - ThrowIfDisposed(); + EnsureWritable(); using var input = new MemoryStream(compressedBundle); using var inflate = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress); using var raw = new MemoryStream(); @@ -692,7 +714,7 @@ public int PlaceLivingDex(byte[] compressedBundle) public int SortBoxes(SortCriteria criteria, IReadOnlyList? boxes = null, bool reverse = false) { - ThrowIfDisposed(); + EnsureWritable(); var targetBoxes = boxes ?? Enumerable.Range(0, _save.BoxCount).ToList(); var slotsPerBox = _save.BoxSlotCount; @@ -741,14 +763,14 @@ public int SortBoxes(SortCriteria criteria, IReadOnlyList? boxes = null, bo return mons.Count; } - public bool SupportsBoxTools => true; + public bool SupportsBoxTools => ReadOnlyReason is null; // Stock legality data describes retail games: on Luminescent Platinum (its own encounters, // often randomized) every Pokémon would read illegal, so the checks are off, as in PKLumiHex. - public bool SupportsLegalityAnalysis => !Luminescent.LumiData.IsLumi(_save); + public bool SupportsLegalityAnalysis => _save is not SAV4Ranch && !Luminescent.LumiData.IsLumi(_save); public int BatchApply(IReadOnlyList instructions, IReadOnlyList? boxes = null) { - ThrowIfDisposed(); + EnsureWritable(); var targetBoxes = boxes ?? Enumerable.Range(0, _save.BoxCount).ToList(); var touched = 0; foreach (var box in targetBoxes) @@ -765,7 +787,7 @@ public int BatchApply(IReadOnlyList instructions, IReadOnlyList? bo public int BatchApplySlots(IReadOnlyList<(int Box, int Slot)> slots, IReadOnlyList instructions) { - ThrowIfDisposed(); + EnsureWritable(); var touched = 0; foreach (var (box, slot) in slots) { @@ -920,7 +942,7 @@ public string GetBoxName(int box) public void SwapBoxes(int a, int b) { - ThrowIfDisposed(); + EnsureWritable(); if (a == b) return; if (!_save.SwapBox(a, b)) throw new InvalidOperationException("This save does not allow one of those boxes to move."); @@ -928,7 +950,7 @@ public void SwapBoxes(int a, int b) public void DeleteBox(int box) { - ThrowIfDisposed(); + EnsureWritable(); if ((uint)box >= (uint)_save.BoxCount) return; // Merge into the first box with room; anything that fits nowhere is released. for (var slot = 0; slot < _save.BoxSlotCount; slot++) @@ -965,7 +987,7 @@ public void DeleteBox(int box) public void ClearBox(int box) { - ThrowIfDisposed(); + EnsureWritable(); if ((uint)box >= (uint)_save.BoxCount) return; for (var slot = 0; slot < _save.BoxSlotCount; slot++) SetEntityCore(box, slot, _save.BlankPKM); @@ -1016,6 +1038,7 @@ public string ExportBoxShowdown(int box) var sets = new List(); for (var slot = 0; slot < _save.BoxSlotCount; slot++) { + if (_save is SAV4Ranch && box * _save.BoxSlotCount + slot >= _save.SlotCount) break; var entity = GetEntityCore(box, slot); if (entity.Species != 0) sets.Add(ShowdownParsing.GetShowdownText(entity)); @@ -1080,7 +1103,7 @@ internal static void SetEVsFromAppOrder(PKM entity, IReadOnlyList values) = public bool RerollNatureKeepShiny(int box, int slot, int nature) { - ThrowIfDisposed(); + EnsureWritable(); ValidateCoordinates(box, slot); var wanted = (Nature)Math.Clamp(nature, 0, 24); var entity = GetEntityCore(box, slot); @@ -1198,6 +1221,7 @@ public IReadOnlyList GetMissingSpecies() for (var box = 0; box < _save.BoxCount; box++) for (var slot = 0; slot < _save.BoxSlotCount; slot++) { + if (_save is SAV4Ranch && box * _save.BoxSlotCount + slot >= _save.SlotCount) break; var species = GetEntityCore(box, slot).Species; if (species != 0) owned.Add(species); } @@ -1218,7 +1242,7 @@ public DexEntryState GetDexEntry(int species) public void SetDexEntry(int species, bool seen, bool caught) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentOutOfRangeException.ThrowIfLessThan(species, 1); ArgumentOutOfRangeException.ThrowIfGreaterThan(species, _save.MaxSpeciesID); var id = (ushort)species; @@ -1364,6 +1388,7 @@ public IReadOnlyList GetNuzlockeReport() for (var box = 0; box < _save.BoxCount; box++) for (var slot = 0; slot < _save.BoxSlotCount; slot++) { + if (_save is SAV4Ranch && box * _save.BoxSlotCount + slot >= _save.SlotCount) break; var entity = GetEntityCore(box, slot); if (entity.Species != 0 && !entity.IsEgg && entity.MetLocation != 0) catches.Add((entity.Clone(), box, slot)); @@ -1429,7 +1454,7 @@ public IReadOnlyList GetEncounterCards(int species, int form) public GenerationOutcome PlaceEncounter(int species, int form, int cardIndex, int targetBox, int targetSlot) { - ThrowIfDisposed(); + EnsureWritable(); ValidateCoordinates(targetBox, targetSlot); if (targetBox != -1 && GetEntityCore(targetBox, targetSlot).Species != 0) return new GenerationOutcome(false, "The destination slot is occupied."); @@ -1470,7 +1495,7 @@ public GenerationOutcome PlaceEncounter(int species, int form, int cardIndex, in public void ReleaseSlot(int box, int slot) { - ThrowIfDisposed(); + EnsureWritable(); ValidateCoordinates(box, slot); DeleteEntityCore(box, slot); } @@ -1494,7 +1519,7 @@ public bool ImportSlot(int box, int slot, byte[] fileBytes, string? format = nul private TransferConversion? ImportCore(int box, int slot, byte[] fileBytes, string? format, bool allowBackwards, out string? refusal) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentNullException.ThrowIfNull(fileBytes); refusal = null; // Same-size formats (PK6/PK7, PK8/PB8, PK9/PA9) are ambiguous from bytes alone. A @@ -1535,7 +1560,7 @@ public TrainerInfo GetTrainer() public void SetTrainer(TrainerInfo trainer) { - ThrowIfDisposed(); + EnsureWritable(); if (_save is SAV3 sav3 && !string.Equals(_save.OT, trainer.Name, StringComparison.Ordinal)) PrefillTrainerName3(sav3.SmallBlock.OriginalTrainerTrash, sav3.Japanese); _save.OT = trainer.Name; @@ -1561,7 +1586,7 @@ private uint ReadMoneySafe() public GenerationOutcome MakeMine(int box, int slot, TrainerProfile? profile = null) { - ThrowIfDisposed(); + EnsureWritable(); ValidateCoordinates(box, slot); var source = GetEntity(box, slot); if (source.Species == 0) @@ -1687,7 +1712,7 @@ public DexProgress GetDexProgress() public void CompleteDex() { - ThrowIfDisposed(); + EnsureWritable(); for (ushort species = 1; species <= _save.MaxSpeciesID; species++) SetDexFlagsCore(species, seen: true, caught: true); } @@ -1723,7 +1748,7 @@ public IReadOnlyList GetPouchLegalItems(string pouchName) public int SetItemCount(string pouchName, int itemId, int count) { - ThrowIfDisposed(); + EnsureWritable(); var bag = _save.Inventory; var pouch = bag.Pouches.FirstOrDefault(p => p.Type.ToString() == pouchName) ?? throw new InvalidOperationException($"No pouch named {pouchName}."); @@ -1764,7 +1789,7 @@ public IReadOnlyList GetPokeBeans() public int SetPokeBeanCount(int index, int count) { - ThrowIfDisposed(); + EnsureWritable(); if (_save is not SAV7 sav) throw new NotSupportedException("This game has no Poké Pelago Bean storage."); ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual((uint)index, (uint)ResortSave7.BEANS_MAX); @@ -1796,7 +1821,7 @@ public IReadOnlyList GetGrandUndergroundItems() public int SetGrandUndergroundItemCount(int itemId, int count) { - ThrowIfDisposed(); + EnsureWritable(); if (_save is not SAV8BS sav) throw new NotSupportedException("This game has no Grand Underground inventory."); @@ -1852,7 +1877,7 @@ public DaycareInfo GetDaycare() public DaycareWithdrawal WithdrawDaycareToFirstEmptyBox(int facilityIndex, int slot) { - ThrowIfDisposed(); + EnsureWritable(); var facilities = GetDaycareFacilities(); ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual((uint)facilityIndex, (uint)facilities.Count); var facility = facilities[facilityIndex]; @@ -1906,7 +1931,7 @@ private bool TryGetFirstEmptyBoxSlot(out int box, out int slot) public void UnlockAllLegalFashion() { - ThrowIfDisposed(); + EnsureWritable(); switch (_save) { case SAV8SWSH swsh: swsh.Fashion.UnlockAllLegal(); break; @@ -1930,7 +1955,7 @@ public int GetStylePoints() public void SetStylePoints(int value) { - ThrowIfDisposed(); + EnsureWritable(); if (_save is not SAV6XY xy) throw new NotSupportedException("Style points exist in Pokémon X and Y only."); xy.Situation.Style = Math.Clamp(value, 0, MaxStylePoints); @@ -2007,7 +2032,7 @@ public TrainerStats GetTrainerStats() public void SetTrainerStats(TrainerStatsEdit edit) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentNullException.ThrowIfNull(edit); // Hours are clamped before PKHeX sees them: Gen 1's raw setter wipes the // minute/second counters when an over-range value reaches it unclamped. @@ -2081,7 +2106,7 @@ private void WriteCoins(int value) public void RepairRTC() { - ThrowIfDisposed(); + EnsureWritable(); switch (_save) { // Gen 2: the cartridge clock lives outside save data; arming the @@ -2165,7 +2190,7 @@ private static string LanguageName(PKM e) public void ApplyMetEdit(int box, int slot, MetEdit edit) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentNullException.ThrowIfNull(edit); ValidateCoordinates(box, slot); var e = GetEntityCore(box, slot); @@ -2310,7 +2335,7 @@ string TypeName(int id) => id == TeraTypeUtil.Stellar ? types[TeraTypeUtil.Stell public void ApplyPotentialEdit(int box, int slot, PotentialEdit edit) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentNullException.ThrowIfNull(edit); ValidateCoordinates(box, slot); var e = GetEntityCore(box, slot); @@ -2412,7 +2437,7 @@ public MoveDetails GetMoveDetails(int box, int slot) public void ApplyMoveDetails(int box, int slot, MoveDetailsEdit edit) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentNullException.ThrowIfNull(edit); ValidateCoordinates(box, slot); var e = GetEntityCore(box, slot); @@ -2505,7 +2530,7 @@ public MoveShopInfo GetMoveShop(int box, int slot) public void ApplyMoveShopEdit(int box, int slot, MoveShopEdit edit) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentNullException.ThrowIfNull(edit); ValidateCoordinates(box, slot); var e = GetEntityCore(box, slot); @@ -2576,7 +2601,7 @@ public CosmeticInfo GetCosmetics(int box, int slot) public void ApplyCosmeticEdit(int box, int slot, CosmeticEdit edit) { - ThrowIfDisposed(); + EnsureWritable(); ArgumentNullException.ThrowIfNull(edit); ValidateCoordinates(box, slot); var e = GetEntityCore(box, slot); @@ -2683,6 +2708,7 @@ private int[] GetTypes(ushort species, byte form) public ReadOnlyMemory Serialize() { ThrowIfDisposed(); + if (ReadOnlyReason is not null) return _originalBytes.ToArray(); return SramPadding.Restore(_save.Write().Span, _originalBytes); } @@ -2736,6 +2762,7 @@ public IReadOnlyList GetCompassSettings() public bool SetCompassSetting(string id, int choiceIndex) { + EnsureWritable(); if (_save is not SAV9SV sv) return false; var definition = Array.Find(CompassDefinitions, d => d.Id == id); @@ -2754,12 +2781,13 @@ private SaveSnapshot BuildSnapshot(string? displayName) for (var box = 0; box < _save.BoxCount; box++) for (var slot = 0; slot < _save.BoxSlotCount; slot++) { + if (_save is SAV4Ranch && box * _save.BoxSlotCount + slot >= _save.SlotCount) break; var entity = _save.GetBoxSlotAtIndex(box, slot); slots.Add(new SlotSummary(box, slot, entity.Species == 0 ? null : entity.Species, entity.IsNicknamed ? entity.Nickname : null, entity.IsShiny, entity.Species == 0 || entity.Valid, entity.Form, entity.IsEgg, entity.HeldItem, EntitySprite.Traits(entity))); } - for (var i = 0; i < SaveParser.PartySlots(_save); i++) + for (var i = 0; _save.HasParty && i < SaveParser.PartySlots(_save); i++) { var partyMon = _save.GetPartySlotAtIndex(i); slots.Add(new SlotSummary(-1, i, partyMon.Species == 0 ? null : partyMon.Species, @@ -2772,11 +2800,12 @@ private void ValidateCoordinates(int box, int slot) { if (box == -1) { - if ((uint)slot >= 6u) + if (!_save.HasParty || (uint)slot >= 6u) throw new ArgumentOutOfRangeException($"Party slot {slot} is outside this save's storage."); return; } - if ((uint)box >= (uint)_save.BoxCount || (uint)slot >= (uint)_save.BoxSlotCount) + if ((uint)box >= (uint)_save.BoxCount || (uint)slot >= (uint)_save.BoxSlotCount || + _save is SAV4Ranch && box * _save.BoxSlotCount + slot >= _save.SlotCount) throw new ArgumentOutOfRangeException($"Box/slot {box}/{slot} is outside this save's storage."); } diff --git a/src/PKForge.Engine/SaveParser.cs b/src/PKForge.Engine/SaveParser.cs index 2ed1899c..f57d05da 100644 --- a/src/PKForge.Engine/SaveParser.cs +++ b/src/PKForge.Engine/SaveParser.cs @@ -18,6 +18,12 @@ internal static class SaveParser internal static bool TryGetSaveFile(byte[] data, out SaveFile? save) { data = RetroArchSaveContainer.Decode(data); + if (RanchFormat.IsCandidate(data.Length)) + { + RanchFormat.Validate(data); + save = new SAV4Ranch(data); + return true; + } if (SaveUtil.TryGetSaveFile(data, out save)) return true; diff --git a/src/PKForge.Engine/ShowdownTeamService.cs b/src/PKForge.Engine/ShowdownTeamService.cs index d4f3cf8b..e07844fb 100644 --- a/src/PKForge.Engine/ShowdownTeamService.cs +++ b/src/PKForge.Engine/ShowdownTeamService.cs @@ -125,7 +125,7 @@ public static GenerationOutcome Place(ISaveEngineSession session, ILegalizerServ if (session is SaveEngineSession engine && !set.Candidate.IsEmpty) { var pk = Materialize(engine.SaveFile, set.Candidate.ToArray()); - ok = pk is not null && PlaceEntity(engine.SaveFile, slot, pk); + ok = pk is not null && PlaceEntity(engine.WritableSaveFile, slot, pk); } else if (session is not SaveEngineSession) { diff --git a/src/PKForge.Engine/WriteSafety.cs b/src/PKForge.Engine/WriteSafety.cs index f424aeb9..6803595d 100644 --- a/src/PKForge.Engine/WriteSafety.cs +++ b/src/PKForge.Engine/WriteSafety.cs @@ -166,6 +166,8 @@ private static IEnumerable Mons(SAV3 save) public static string? CheckWriteSafety(ReadOnlyMemory original, ReadOnlyMemory candidate, WriteScope? scope) { + if (RanchFormat.WriteRestriction(original.Span) is not null && !original.Span.SequenceEqual(candidate.Span)) + return RanchFormat.ReadOnlyReason; if (scope is { Unrestricted: true }) return null; diff --git a/src/PKForge.Infrastructure/EmulatorSaveHeuristics.cs b/src/PKForge.Infrastructure/EmulatorSaveHeuristics.cs index 923be16c..b5a78fd6 100644 --- a/src/PKForge.Infrastructure/EmulatorSaveHeuristics.cs +++ b/src/PKForge.Infrastructure/EmulatorSaveHeuristics.cs @@ -34,11 +34,26 @@ public static bool IsCandidateFileName(string fileName) } /// Dolphin links individual GCI saves, never whole multi-game memory cards. - public static bool IsCandidateFileName(string fileName, EmulatorKind kind) => + public static bool IsCandidateFileName(string fileName, EmulatorKind kind, string? documentPath = null) => kind == EmulatorKind.Dolphin - ? fileName.EndsWith(".gci", StringComparison.OrdinalIgnoreCase) + ? fileName.EndsWith(".gci", StringComparison.OrdinalIgnoreCase) || IsDolphinRanchSave(fileName, documentPath) : IsCandidateFileName(fileName); + /// Only the main save of the verified USA Ranch title, not its automatic backup or other Wii files. + public static bool IsDolphinRanchSave(string fileName, string? documentPath) + { + if (!fileName.Equals("savedata.bin", StringComparison.OrdinalIgnoreCase) || documentPath is null) return false; + var parts = documentPath.Replace('\\', '/').Split('/'); + if (parts.Any(p => p.Equals("backup", StringComparison.OrdinalIgnoreCase))) return false; + for (int i = 0; i < parts.Length - 1; i++) + { + if (parts[i].Equals("0001000157424d45", StringComparison.OrdinalIgnoreCase)) return true; + if (parts[i].Equals("00010001", StringComparison.OrdinalIgnoreCase) && + parts[i + 1].Equals("57424d45", StringComparison.OrdinalIgnoreCase)) return true; + } + return false; + } + public static bool IsDolphinMemoryCard(string fileName) => Path.GetExtension(fileName).Equals(".raw", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(fileName).Equals(".gcp", StringComparison.OrdinalIgnoreCase); diff --git a/src/PKForge.Infrastructure/SafeSaveWriter.cs b/src/PKForge.Infrastructure/SafeSaveWriter.cs index 12796273..b019adb4 100644 --- a/src/PKForge.Infrastructure/SafeSaveWriter.cs +++ b/src/PKForge.Infrastructure/SafeSaveWriter.cs @@ -49,6 +49,8 @@ private bool Accepted(string documentId) /// slot is compared, or null when the save accepts writes. private UnsafeSaveWriteException? Refusal(string documentId, SaveSnapshot original) { + if (engine.GetWriteRestriction(original.OriginalBytes) is { } restriction) + return new UnsafeSaveWriteException(restriction); // "Other CFRU hack" borrows the Radical Red / Unbound engine to READ the shared // CFRU layout, but species, growth-rate, base-stat, item and bag tables are // per-hack: a level edit would compute EXP and stats from the wrong game's @@ -127,6 +129,11 @@ private async ValueTask WriteCoreAsync( if (!engine.Validate(candidate)) throw new InvalidDataException("The candidate save failed engine validation; the original was not touched."); + // Extraction-only formats must also refuse unrestricted restores. Confirming a + // layout risk cannot turn an unimplemented native writer into a safe one. + if (engine.GetWriteRestriction(original.OriginalBytes) is { } restriction) + throw new UnsafeSaveWriteException(restriction); + // Structural safety net. A whole-file restore (Unrestricted) is the recovery path // and must stay open; every other write is refused when the engine is not sure of // the layout (a ROM hack parsed as vanilla rewrites checksums and slots in a layout diff --git a/tests/PKForge.Domain.Tests/EmulatorSaveHeuristicsTests.cs b/tests/PKForge.Domain.Tests/EmulatorSaveHeuristicsTests.cs index 34e7412e..918cd80d 100644 --- a/tests/PKForge.Domain.Tests/EmulatorSaveHeuristicsTests.cs +++ b/tests/PKForge.Domain.Tests/EmulatorSaveHeuristicsTests.cs @@ -6,6 +6,18 @@ namespace PKForge.Domain.Tests; public sealed class EmulatorSaveHeuristicsTests { + [Theory] + [InlineData("savedata.bin", "primary:Download/Wii/0001000157424d45/savedata.bin", true)] + [InlineData("savedata.bin", "msd:123/Wii/0001000157424d45/savedata.bin", true)] + [InlineData("SAVEDATA.BIN", "primary:Wii/title/00010001/57424D45/data/SAVEDATA.BIN", true)] + [InlineData("savedata.bin", "primary:Wii/0001000157424d45/backup/savedata.bin", false)] + [InlineData("savedata.bin", "primary:Wii/0001000157424d50/savedata.bin", false)] + [InlineData("savedata.bin", "primary:Wii/0001000157424d45-other/savedata.bin", false)] + [InlineData("banner.bin", "primary:Wii/0001000157424d45/banner.bin", false)] + [InlineData("savedata.bin", null, false)] + public void DolphinFindsOnlyTheVerifiedRanchMainSave(string name, string? path, bool expected) => + Assert.Equal(expected, EmulatorSaveHeuristics.IsCandidateFileName(name, EmulatorKind.Dolphin, path)); + [Theory] [InlineData("pokemon.srm", true)] [InlineData("Pokemon Platinum.sav", true)] diff --git a/tests/PKForge.Engine.Tests/RanchTests.cs b/tests/PKForge.Engine.Tests/RanchTests.cs new file mode 100644 index 00000000..7ce6c6d4 --- /dev/null +++ b/tests/PKForge.Engine.Tests/RanchTests.cs @@ -0,0 +1,213 @@ +using System.Buffers.Binary; +using System.Reflection; +using System.Security.Cryptography; +using PKForge.Domain; +using PKForge.Engine; +using PKForge.Infrastructure; +using PKHeX.Core; +using Xunit; + +namespace PKForge.Engine.Tests; + +public sealed class RanchTests +{ + private static readonly SaveEngine Engine = new(); + + // Synthetic original-revision object arrays, not player data. Dimensions and + // offsets follow the pinned SAV4Ranch/RanchMii/RanchTrainerMii/RK4 readers. + private static byte[] Save(int level = 25, int last = 0) + { + var data = new byte[SaveUtil.SIZE_G4RANCH]; + data[0x5A] = data[0x5B] = (byte)(level - 1); + int[] offsets = [0x40, 0x22A8, 0x22D8, 0x230C, 0x230C + 8 + (last + 1) * 164]; + int[] sizes = [0x2260, 0x28, 0x2C, 164, 0x28]; + int[] counts = [1, 1, 1, last + 1, 0]; + Set(data, 0x14, 0x00030005); + for (int i = 0; i < 5; i++) + { + Set(data, 0x18 + i * 8, (uint)i); + Set(data, 0x1C + i * 8, (uint)offsets[i]); + Set(data, offsets[i], (uint)sizes[i]); + Set(data, offsets[i] + 4, (uint)counts[i]); + } + var mon = new RK4 { Species = 25, PID = 12345, ID32 = 23456, Language = 2, + Version = GameVersion.D, OwnershipType = RanchOwnershipType.Trainer, + HandlingTrainerTID = 99, HandlingTrainerSID = 88, HandlingTrainerName = "HANDLER" }; + mon.RefreshChecksum(); + mon.WriteEncryptedDataStored(data.AsSpan(0x2314 + last * 164, 164)); + Hash(data); + return data; + } + + private static void Set(byte[] data, int offset, uint value) => BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(offset), value); + private static void Hash(byte[] data) => SHA1.HashData(data.AsSpan(20), data.AsSpan(0, 20)); + + [Theory] + [InlineData(1, 20)] + [InlineData(2, 25)] + [InlineData(3, 30)] + [InlineData(25, 1000)] + public void CapacityAndNativeExportAreExact(int level, int capacity) + { + var source = Save(level, capacity - 1); + using var session = Engine.OpenSession(source); + Assert.True(Engine.Validate(source)); + Assert.Equal("My Pokémon Ranch", Engine.TryDescribe(source)!.GameName); + Assert.Equal(["My Pokémon Ranch"], session.GameNames); + Assert.False(session.HasParty); + Assert.NotNull(session.ReadOnlyReason); + Assert.False(session.SupportsBoxTools); + Assert.Equal(capacity, session.Snapshot.Slots.Count); + Assert.Equal(capacity, Engine.Open(source).Slots.Count); + var last = session.Snapshot.Slots[^1]; + var exported = session.ExportSlot(last.Box, last.Slot); + Assert.Equal("RK4", exported.Format); + var native = new RK4(exported.Data); + Assert.Equal(25, native.Species); + Assert.Equal(RanchOwnershipType.Trainer, native.OwnershipType); + Assert.Equal(99, native.HandlingTrainerTID); + Assert.Equal(88, native.HandlingTrainerSID); + Assert.Equal("HANDLER", native.HandlingTrainerName); + Assert.True(native.ConvertToPK4().ChecksumValid); + Assert.True(session.Serialize().Span.SequenceEqual(source)); + Assert.DoesNotContain(25, session.GetMissingSpecies()); + Assert.NotEmpty(session.ExportBoxShowdown(last.Box)); + session.GetNuzlockeReport(); + Assert.Throws(() => session.ReadEntity(-1, 0)); + Assert.Throws(() => session.ExportSlot(capacity / 30, capacity % 30)); + } + + [Theory] + [InlineData(0x00, 1u)] // file hash + [InlineData(0x14, 0u)] // unsupported schema + [InlineData(0x1C, 0xFFFFFFFCu)] // overflow/outside file + [InlineData(0x24, 0x40u)] // backward/overlapping block + [InlineData(0x22AC, 21u)] // more Miis than the ranch allows + [InlineData(0x2310, 1001u)] // count beyond capacity + [InlineData(0x230C, 136u)] // PK4 is not an RK4 record + [InlineData(0x3C, 0x2314u)] // end marker inside Pokemon record + public void CorruptOrUnknownLayoutsDoNotReachTheCoreReader(int offset, uint value) + { + var data = Save(); + Set(data, offset, value); + if (offset != 0) Hash(data); // independently valid file hash must not hide invalid structure + Assert.False(Engine.Validate(data)); + Assert.Null(Engine.TryDescribe(data)); + Assert.Throws(() => Engine.OpenSession(data)); + } + + [Theory] + [InlineData(0x5A, 25)] + [InlineData(0x5B, 255)] + [InlineData(0x2314 + 0x88, 3)] + public void InvalidLevelsAndOwnershipAreRejected(int offset, byte value) + { + var data = Save(); data[offset] = value; Hash(data); + Assert.False(Engine.Validate(data)); + } + + [Fact] + public void PortableConversionExplainsLossAndKeepsNativeOwnership() + { + using var session = Engine.OpenSession(Save()); + var native = new RK4(session.ExportSlot(0, 0).Data); + var conversion = CrossFormatConverter.Convert(native, new SAV4DP(), out var refusal); + Assert.Null(refusal); + Assert.NotNull(conversion); + Assert.IsType(conversion.Entity); + Assert.Contains(conversion.Warnings, s => s.Contains("Ranch ownership", StringComparison.Ordinal)); + Assert.Equal(25, conversion.Entity.Species); + Assert.Equal(RanchOwnershipType.Trainer, native.OwnershipType); + Assert.Equal("HANDLER", native.HandlingTrainerName); + } + + [Fact] + public void UnverifiedPlatinumRevisionIsRefused() + { + var data = new byte[SaveUtil.SIZE_G4RANCH_PLAT]; + Assert.False(Engine.Validate(data)); + Assert.Throws(() => Engine.OpenSession(data)); + Assert.NotNull(Engine.GetWriteRestriction(data)); + } + + [Fact] + public void EverySessionMutationRefusesBeforeChangingSource() + { + var data = Save(); + using var session = Engine.OpenSession(data); + var methods = typeof(ISaveEngineSession).GetMethods().Where(m => !m.IsSpecialName && + !m.Name.StartsWith("Get", StringComparison.Ordinal) && !m.Name.StartsWith("Is", StringComparison.Ordinal) && + !m.Name.StartsWith("Read", StringComparison.Ordinal) && !m.Name.StartsWith("Export", StringComparison.Ordinal) && + m.Name is not ("Serialize" or "MakeActive" or "Dispose")); + foreach (var method in methods) + { + var args = method.GetParameters().Select(p => p.ParameterType.IsValueType ? Activator.CreateInstance(p.ParameterType) : null).ToArray(); + var error = Assert.Throws(() => method.Invoke(session, args)); + Assert.IsType(error.InnerException); + Assert.True(session.Serialize().Span.SequenceEqual(data), method.Name); + } + } + + [Fact] + public void SiblingEditorsCannotBypassTheReadOnlySession() + { + var data = Save(); using var session = Engine.OpenSession(data); + Assert.Throws(() => new LegalizerService().LegalizeSlot(session, 0, 0)); + Assert.Throws(() => MonFieldService.SetPid(session, 0, 0, 0x87654321)); + Assert.Throws(() => BulkBoxActions.Heal(session, [(0, 0)])); + Assert.Throws(() => new EventDatabaseService().Receive(session, 0, 0, 0)); + Assert.True(session.Serialize().Span.SequenceEqual(data)); + Assert.Equal(12345u, new RK4(session.ExportSlot(0, 0).Data).PID); + } + + [Fact] + public async Task SafeWriterRefusesEvenUnrestrictedRestoresBeforeBackupOrWrite() + { + var source = Save(); var candidate = source.ToArray(); candidate[0x60] ^= 1; Hash(candidate); + var storage = new NoWrites(); + var writer = new SafeSaveWriter(Engine, storage, storage); + writer.ConfirmLayoutRisk("ranch"); + Assert.NotNull(writer.WhyWritesAreRefused("ranch", Engine.Open(source))); + Assert.NotNull(Engine.CheckWriteSafety(source, candidate, WriteScope.Everything)); + await Assert.ThrowsAsync(() => writer.WriteScopedAsync("ranch", Engine.Open(source), candidate, WriteScope.Everything).AsTask()); + Assert.Equal(0, storage.Writes); + Assert.Equal(0, storage.Backups); + } + + [Theory] + [InlineData("ranch-a.bin", 975)] + [InlineData("ranch-a-backup.bin", 975)] + [InlineData("ranch-b.bin", 992)] + [InlineData("ranch-b-backup.bin", 992)] + public void OptionalPrivateFixturesKeepAllNativeRecords(string file, int occupied) + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "PKForge.sln"))) directory = directory.Parent; + var path = directory is null ? null : Path.Combine(directory.FullName, ".local-testdata", "ranch", file); + if (path is null || !File.Exists(path)) return; + var source = File.ReadAllBytes(path); + using var session = Engine.OpenSession(source); + var records = session.Snapshot.Slots.Where(s => s.Species is not null).ToList(); + Assert.Equal(occupied, records.Count); + foreach (var slot in records) + { + var raw = session.ExportSlot(slot.Box, slot.Slot); + Assert.Equal(slot.Species, Engine.TryDescribeEntity(raw.Data, "test", raw.Format)!.Species); + Assert.True(new RK4(raw.Data).ChecksumValid); + } + Assert.True(session.Serialize().Span.SequenceEqual(source)); + Assert.Equal(source, File.ReadAllBytes(path)); + } + + private sealed class NoWrites : IBackupService, ISaveFileAccess + { + public int Writes { get; private set; } + public int Backups { get; private set; } + public ValueTask CreateAsync(SaveSnapshot source, string? changeDescription = null, string? documentId = null, CancellationToken cancellationToken = default) + { Backups++; throw new InvalidOperationException("No backup expected"); } + public ValueTask WriteAtomicallyAsync(string documentId, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) + { Writes++; throw new InvalidOperationException("No write expected"); } + public ValueTask> ListAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); + public ValueTask> ReadAsync(string documentId, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } +}