diff --git a/PEANUTS.md b/PEANUTS.md index 821d6489..575e3e3e 100644 --- a/PEANUTS.md +++ b/PEANUTS.md @@ -9,6 +9,9 @@ Banana Native ships several releases a day, so this fork is kept as a **thin ove - `android/app/src/main/java/dev/peanuts/` — launcher side: the `Presentation` on the second display, its view, the JNI bridge. - `dm/peanuts/` — host side: companion package loader, guest readers, tick, input injection (plain C). - `peanuts/` — companion packages, docs, tests, `scripts/`. + - `android/app/src/main/java/io/github/davdxpx/mistel/` — Mistel's MIT library for `.mncf` cheat files (`io.github.davdxpx.mistel.mncf`), a copy of + Mistel's `format/lib/java` that is never edited here: `peanuts/scripts/mncf-vendor.sh` copies it with its LICENSE and `MISTEL.sha256` (the commit and + every file's hash), and `peanuts/tests/test_mncf_vendor.py` fails on any change to the copy. Fixes go to Mistel first. 2. **Hooks into upstream files are one-liners, each tagged `PEANUTS`.** A hook is a call-out to Peanuts code, never logic. Allowed hook sites (keep this list current): - `android/app/src/main/java/dev/nxnative/android/GameActivity.java` — create/destroy the companion `Presentation`; (2026-11-13) one line in @@ -119,6 +122,18 @@ Banana Native ships several releases a day, so this fork is kept as a **thin ove `build`'s first line hands the page to `GamePagePort.build` on a window 600 dp wide or more; its `wide` and sections lines build the narrow column with every section while the port takes upstream's rows off its tabs (`GamePagePort.harvesting`); `stepTab` asks `GamePagePort.step` after Mods & Cheats' own line; `openOn` (Round 61's line) tells the port the tab, so Settings › Users opens the area Saves. `GamePagePort.java` is Peanuts' own file in upstream's package. + - `android/app/src/main/java/dev/nxnative/android/SidePanel.java`, `GameActivity.java`, `SaveStore.java` — (2026-11-24, the in-game menus, `InGamePanel`, + `dev.peanuts.ingame`) the one side panel becomes two menus. SidePanel is the quick menu: `TAB_CONTROLS` not final (Cheats and Mods come before it); + its constructor hands its sheet to `InGamePanel.frame` (a rail of the tabs at the left, a header with Back and the tab's name); `tabBar`'s first line + `InGamePanel.rail`; `showTab` keeps the focus on the rail (`InGamePanel.railFocused`); `open` and `close` slide through `InGamePanel.slideIn`/`slideOut`; + `padKey`'s back key is `InGamePanel.panelBack`; `look` ends with `InGamePanel.laid` (what moved to the game menu). GameActivity: `attach` in `onCreate` + (the game menu, a swipe in from the left edge), the combination through `InGamePanel.key` (Home held: the quick menu) and `InGamePanel.toggle` (Home + pressed, − and + held: the game menu), the controller's own Back through `InGamePanel.backKey` (pressed the game menu, held the quick menu: the + Thor's Home is Android's), `menuKey` and `menuMotion` (the game menu has the controller), Back through `InGamePanel.back`, and `runSave()` + (the save the game runs on). SaveStore: `backupLocked` not private (the game menu's Back up the save, under the running game's own lock). + (2026-11-24, one menu: Layout) SidePanel: `rows()` gives the panel's rows to a second panel, the one menu at the right or on the bottom screen + (`InGamePanel.openRight`, `openBottom`); `open()` starts with `InGamePanel.instead` (one menu at the right: the swipe and the controls' button open it). + `peanuts/UPSTREAM-EDITS.md` "In-game menus". 3. **Settings go through upstream's own mechanisms**: `env.txt` keys named `PN_*`, `settings.tsv` rows, `DM_CTL` lines. No new settings UI inside upstream classes. 4. **Never reformat or "fix" upstream files.** A general fix belongs upstream as a PR to Banana Native (its AGENTS.md prefers general changes), then it arrives by rebase. 5. **Branches:** `upstream/android` is Banana Native; `peanuts` is this overlay, always a linear set of commits on top of a Banana Native tag. History is rewritten on every update (rebase, never merge). diff --git a/android/NOTICE.md b/android/NOTICE.md index e9d3fcda..e3bb4890 100644 --- a/android/NOTICE.md +++ b/android/NOTICE.md @@ -39,6 +39,11 @@ atomics in `AstOptimizer.cs`, of else-ifs for SPIR-V and of TMML's negative LOD, The six default Miis (`mii_defs` in `dm/host/hle_mii.c`, `MiiStore.DEFAULTS` in the launcher's Mii editor) are the console's default Mii parameters as [Ryujinx](https://github.com/Ryubing/Ryujinx) (MIT, Copyright (c) Ryujinx Team and Contributors) and [Eden](https://git.eden-emu.dev/eden-emu/eden) (`src/core/hle/service/mii/types/raw_data.cpp`, GPL-3.0-or-later) hold them, converted to CharInfo values; the MIT permission notice is in [dm/third_party/ryujinx/LICENSE.txt](../dm/third_party/ryujinx/LICENSE.txt). Thanks to them. +The launcher reads, checks and writes cheat files in the Mistel Native Cheat Format (`.mncf`, packs `.mncp`) with the Java library of +[Mistel](https://github.com/davdxpx/mistel)'s `format/` folder by davdxpx and the Mistel contributors (MIT: "Copyright (c) 2026 davdxpx and the Mistel contributors"), +copied unchanged into `android/app/src/main/java/io/github/davdxpx/mistel/` with its permission notice there (`LICENSE`) and the commit it came from (`MISTEL.sha256`). +Only that folder of Mistel is MIT; nothing of its GPL parts is in this repository. + The launcher draws the Miis (`android/app/src/main/java/dev/peanuts/mii/`) with the colour tables and the face's layout of [vee](https://github.com/j0lol/vee) by Jo Null (MIT or Apache-2.0, used here under MIT: "Copyright (c) Jo Null"), which took them from the decompilation of the Wii U's face library (FFL), and `MiiPixels.java` ports the BC4, BC5 and BC7 decoders of [bcdec](https://github.com/iOrange/bcdec) by Sergii Kudlai (MIT: "Copyright (c) 2022 Sergii Kudlai"); the MIT permission notice is in [LICENSE](../LICENSE). The Mii parts themselves are read from the player's own firmware at run time and are no part of this code. Thanks to them. Animal Crossing: New Horizons' 60 fps choice (Game settings, Frame rate cap) uses ["ACNH 60 FPS + SpeedFix"](https://github.com/tmouh/acnh-60fps) v1.4.5 by tmouh, under the Creative Commons Attribution-NonCommercial 4.0 International licence ([CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/)): its main code patch for 3.0.3, converted to the rewriter's cut rows, and its four changed game files, converted to rows of changed bytes that the app applies to the player's own files (no game file is shipped). The mod's content is unchanged; `dm/games/01006F8002326000/speedfix60/NOTICE.md` says what was converted and how. The NonCommercial term applies to that data. Thanks to tmouh. diff --git a/android/app/src/jvmtest/java/dev/peanuts/mods/CheatLoaderJvmTest.java b/android/app/src/jvmtest/java/dev/peanuts/mods/CheatLoaderJvmTest.java index ee549e81..aacefc7d 100644 --- a/android/app/src/jvmtest/java/dev/peanuts/mods/CheatLoaderJvmTest.java +++ b/android/app/src/jvmtest/java/dev/peanuts/mods/CheatLoaderJvmTest.java @@ -16,7 +16,8 @@ /** * The cheat loader of the game page (SPEC-mod-menu.md, Package B) on the JVM, driven by peanuts/tests/test_cheat_loader.py. args[0]: an empty folder; args[1] * (optional): a real cheat file to read as a smoke test (never part of the repository). Prints "ok" or throws. Covers the parse (groups, masters, credits, - * restore entries, kinds and hold buttons), the import's layouts and its choice of build, the sources and the merged file. + * restore entries, kinds and hold buttons), the import's layouts and its choice of build, the sources (.mncf files: MncfConvert, MncfMain, MncfBuild), the + * merged file, the number field, export and packs. */ public final class CheatLoaderJvmTest { static final String TID = "0100AAAA0BBB0000", B = "0123456789ABCDEF", OTHER = "FEDCBA9876543210"; @@ -108,6 +109,7 @@ public static void main(String[] a) throws Exception { merge(new File(root, "merge-case")); status(); values(new File(root, "values-case")); + mncf(new File(root, "mncf-case")); if (a.length > 1 && !a[1].isEmpty()) real(new File(a[1])); System.out.println("ok"); } @@ -361,87 +363,141 @@ static void layouts(File root) throws Exception { check(paths.contains("Fake Pack/atmosphere/contents/" + TID + "/romfs/") && !paths.contains("Fake Pack/atmosphere/contents/" + TID + "/romfs/x/"), "romfs is not walked into: " + paths); } + // ---- A pack's main for the .mncf sources (MncfMain): made up, as patch_nso.py writes one ---- + + /** A made-up pack: main.patched.bin (text up to 0x8000, read-only data to 0xC000, data to 0x10000), its layout, and the words SITE's restore code names */ + static File pack(File dir, String bid, int shift) throws Exception { + check(dir.mkdirs() || dir.isDirectory(), "mkdirs " + dir); + byte[] img = new byte[0x10000 + shift]; + new java.util.Random(7).nextBytes(img); + for (int i = 0; i < 0x80; i += 4) put(img, shift + 0x7000 + i, 0xD503201FL); // nop padding a pattern does not match by chance + put(img, shift + 0x1000, 0xB9004008L); + put(img, shift + 0x1004, 0x94000123L); + put(img, shift + 0x2000, 0x52800000L); put(img, shift + 0x2004, 0x52800000L); put(img, shift + 0x2008, 0x2BCA1F01L); + put(img, shift + 0x3000, 0x1E2E1000L); put(img, shift + 0x3004, 0x1E201001L); + put(img, shift + 0x4000, 0x52800000L); put(img, shift + 0x4004, 0x2BCA1F01L); + Files.write(new File(dir, "main.patched.bin").toPath(), img); + Files.write(new File(dir, "main.fixups.tsv").toPath(), u(String.format("# PATCH_OFF\t0x%x\n# TEXT_END\t0x%x\n# RO_OFF\t0x%x\n# DATA_OFF\t0x%x\n# BUILD_ID\t%s0000000000000000\n", + 0x10000 + shift, 0x8000 + shift, 0x8000 + shift, 0xC000 + shift, bid))); + return dir; + } + + static void put(byte[] b, int at, long w) { for (int i = 0; i < 4; i++) b[at + i] = (byte) (w >>> (8 * i)); } + + static MncfConvert.Known known(File pack, String author) { + return new MncfConvert.Known(TID, "Example Game", author, B, Map.of(B, "1.0.0"), MncfConvert.of(pack)); + } + + static MncfBuild.Game game(String build, File pack) { return new MncfBuild.Game(TID, build, build.equals(B) ? "1.0.0" : null, pack); } + + static io.github.davdxpx.mistel.mncf.MncfFile load(File f) throws Exception { return io.github.davdxpx.mistel.mncf.Mncf.load(Files.readAllBytes(f.toPath())); } + // ---- The sources ---- static void sources(File folder) throws Exception { + File pk = pack(new File(folder.getParentFile(), "sources-pack"), B, 0); + MncfConvert.Known k = known(pk, "Tester"); check(CheatSources.list(folder).isEmpty() && CheatSources.appEnabled(folder) == null, "nothing yet"); - CheatSources.Source s1 = CheatSources.add(folder, "pack", CheatSources.FROM_ZIP, Map.of(B, SITE, OTHER, SMALL), 1000); - CheatSources.Source s2 = CheatSources.add(folder, "Pack", CheatSources.FROM_FILE, Map.of(B, SMALL), 2000); - CheatSources.Source s3 = CheatSources.add(folder, "../odd/name?", CheatSources.FROM_FOLDER, Map.of(B, SMALL + "[X]\n04000000 00000010 00000001\n"), 1500); + CheatSources.Source s1 = CheatSources.add(folder, "pack", CheatSources.FROM_ZIP, Map.of(B, SITE, OTHER, SMALL), 1000, k, "pack.zip"); + CheatSources.Source s2 = CheatSources.add(folder, "Pack", CheatSources.FROM_FILE, Map.of(B, SMALL), 2000, k, "Pack.txt"); + CheatSources.Source s3 = CheatSources.add(folder, "../odd/name?", CheatSources.FROM_FOLDER, Map.of(B, SMALL + "[X]\n04000000 00000010 00000001\n"), 1500, k, null); List l = CheatSources.list(folder); check(l.size() == 3 && l.get(0).id.equals(s1.id) && l.get(1).id.equals(s3.id) && l.get(2).id.equals(s2.id), "by when they were added: " + l); check(s2.name.equals("Pack 2"), "a name is unique without case: " + s2.name); check(!s3.id.contains("/") && !s3.id.startsWith("."), "a folder name of its own: " + s3.id); - check(s1.files().keySet().equals(Set.of(B, OTHER)) && s1.text(B).equals(SITE) && s1.text("1111111111111111") == null, "its files by build"); - check(CheatSources.sameAs(folder, B, SMALL.replace("\n", "\r\n")) != null && CheatSources.sameAs(folder, B, "[New]\n04000000 0 1\n") == null, "the same file again is found"); + // one .mncf a source, for all of its builds, with what is known: the game, the versions, where it came from, who made it + String[] kept = s1.dir.list(); + check(kept != null && java.util.Arrays.asList(kept).containsAll(List.of(CheatSources.MNCF, CheatSources.STATE)) && !new File(s1.dir, B + ".txt").exists(), "an .mncf, no Atmosphère file: " + java.util.Arrays.toString(kept)); + io.github.davdxpx.mistel.mncf.MncfFile f1 = load(s1.file()); + check(f1.gameId().equals(TID) && "Example Game".equals(f1.gameName()) && new java.util.HashSet<>(s1.builds()).equals(Set.of(B, OTHER)), "the game and both builds: " + s1.builds()); + check("1.0.0".equals(MncfBuild.version(f1, B)) && MncfBuild.version(f1, OTHER) == null, "the version the app knows names its build: " + MncfBuild.version(f1, B) + " " + MncfBuild.version(f1, OTHER) + " " + f1.builds().keySet()); + check(f1.authors().equals(List.of("Example Team")), "the authors its credits name, not the player: " + f1.authors()); + check("atmosphere".equals(f1.origin().get("format")) && "pack.zip".equals(f1.origin().get("name")) && "example-cheats.com".equals(f1.origin().get("site")), "its origin: " + f1.origin()); + check(f1.about() != null && f1.about().contains("enjoy"), "its credit lines in about: " + f1.about()); + check(load(s2.file()).authors().equals(List.of("Tester")), "no credits: the player who adds it"); + check(load(CheatSources.add(folder, "nobody", CheatSources.FROM_FILE, Map.of(B, "[N]\n04000000 00000020 00000001\n"), 2500, + new MncfConvert.Known(TID, null, null, null, null, null), null).file()).authors().isEmpty(), "no credits and no name: no author"); + CheatSources.remove(folder, "nobody"); + // a note line Mistel's reader would refuse is kept in about, the file is still converted + CheatSources.Source noted = CheatSources.add(folder, "noted", CheatSources.FROM_FILE, Map.of(B, "Made for fun\n[Coins]\n04000000 00001000 00000063\nsee the site\n"), 2600, k, null); + check(load(noted.file()).about().contains("Made for fun") && load(noted.file()).about().contains("see the site") && load(noted.file()).cheats().size() == 1, "notes in about"); + CheatSources.remove(folder, noted.id); + check(CheatSources.sameAs(folder, SMALL.replace("\n", "\r\n")) != null && CheatSources.sameAs(folder, "[New]\n04000000 0 1\n") == null, "the same file again is found"); + check(CheatSources.sameMncf(folder, Files.readAllBytes(s1.file().toPath())) != null && CheatSources.sameMncf(folder, u("format = \"mncf/1\"\n")) == null, "the same .mncf again is found"); CheatSources.enabled(folder, s2.id, false); check(!CheatSources.find(folder, s2.id).enabled && CheatSources.find(folder, s1.id).enabled, "a source off as a whole"); check(CheatSources.remove(folder, s3.id) && CheatSources.find(folder, s3.id) == null && !CheatSources.remove(folder, "..") && !CheatSources.remove(folder, CheatSources.APP), "a source removed, nothing else"); CheatSources.appEnabled(folder, false); check(Boolean.FALSE.equals(CheatSources.appEnabled(folder)) && CheatSources.list(folder).size() == 2, "the app's state is not a source"); - // upstream's earlier imports move over + // upstream's earlier imports move over, as .mncf File old = new File(folder, "imported"); check(old.mkdirs(), "mkdirs imported"); Files.write(new File(old, "b old.txt").toPath(), u("build " + B + "\n" + SMALL)); Files.write(new File(old, "a old.txt").toPath(), u("build " + B + "\n[Y]\n04000000 00000010 00000001\n")); - List moved = CheatSources.migrate(folder, 3000); - check(moved.size() == 2 && moved.get(0).name.equals("a old") && moved.get(1).name.equals("b old") && !old.exists(), "imported/ became sources: " + moved); - check(CheatSources.migrate(folder, 4000).isEmpty(), "once"); - // Export cheats…: upstream's format, each source's file of this build with its build line, and the toggles; an import reads it back - ByteArrayOutputStream ex = new ByteArrayOutputStream(); - int n = CheatSources.exportZip(ex, TID, B, folder, true, new java.util.LinkedHashSet<>(List.of("Coins", "Y"))); - Map got = new LinkedHashMap<>(); - try (java.util.zip.ZipInputStream z = new java.util.zip.ZipInputStream(new ByteArrayInputStream(ex.toByteArray()))) { - for (ZipEntry e; (e = z.getNextEntry()) != null; ) got.put(e.getName(), new String(z.readAllBytes(), StandardCharsets.UTF_8)); - } - check(n == 4 && got.size() == 5 && got.containsKey("toggles.json"), "4 sources with a file of this build and the toggles: " + got.keySet()); - for (Map.Entry e : got.entrySet()) if (!e.getKey().equals("toggles.json")) check(e.getKey().startsWith("cheats/") && e.getValue().startsWith("build " + B + "\n"), "a build line first: " + e.getKey()); - check(got.get("toggles.json").equals("{\"title_id\": \"" + TID + "\", \"build\": \"" + B + "\", \"cheats\": true, \"on\": [\"Coins\", \"Y\"]}\n"), got.get("toggles.json")); - List paths = new ArrayList<>(); - CheatImport.Found back = CheatImport.read(CheatImport.fromZip(new ByteArrayInputStream(ex.toByteArray()), paths), paths, TID, BUILDS, "export.zip"); - check(back.forGame.size() == 3 && back.otherVersion.isEmpty(), "the export reads back by its build lines (two sources with one text are one file): " + back.forGame); - check(CheatSources.withBuild("\n\nbuild 0123456789abcdef\n[A]\n", B).equals("build " + B + "\n[A]\n"), "an earlier build line is replaced"); + List moved = CheatSources.migrate(folder, 3000, k); + check(moved.size() == 2 && moved.get(0).name.equals("a old") && moved.get(1).name.equals("b old") && !old.exists() && moved.get(0).file().isFile(), "imported/ became sources: " + moved); + check(CheatSources.migrate(folder, 4000, k).isEmpty(), "once"); + // an earlier version of the app kept a source as Atmosphère files by build: it becomes one .mncf, the files go + File earlier = new File(CheatSources.root(folder), "earlier"); + check(earlier.mkdirs(), "mkdirs earlier"); + Files.write(new File(earlier, B + ".txt").toPath(), u(SITE)); + Files.write(new File(earlier, OTHER + ".txt").toPath(), u(SMALL)); + Files.write(new File(earlier, CheatSources.STATE).toPath(), u("name\tEarlier\nfrom\tzip\nadded\t500\nenabled\t1\n")); + check(CheatSources.upgrade(folder, k) == 1 && CheatSources.upgrade(folder, k) == 0, "once"); + CheatSources.Source up = CheatSources.find(folder, "earlier"); + check(up.file().isFile() && !new File(earlier, B + ".txt").exists() && new java.util.HashSet<>(up.builds()).equals(Set.of(B, OTHER)) && CheatSources.sameAs(folder, SMALL) != null, "an .mncf of both builds: " + up.builds()); // the export imported again (upstream's Import cheats…: imported/, then sources): what the game has already is not added twice int before = CheatSources.list(folder).size(); check(old.mkdirs(), "mkdirs imported again"); - Files.write(new File(old, "again.txt").toPath(), u("build " + B + "\n" + SITE)); // s1 keeps SITE without a build line: the same cheats + Files.write(new File(old, "again.txt").toPath(), u("build " + B + "\n" + SITE)); // s1 was made from SITE: the same cheats Files.write(new File(old, "fresh.txt").toPath(), u("build " + B + "\n[Fresh]\n04000000 00000010 00000001\n")); Files.write(new File(old, "fresh2.txt").toPath(), u("build " + B + "\n[Fresh]\n04000000 00000010 00000001\n")); - int stay = CheatSources.dropDuplicates(folder, CheatSources.migrate(folder, 5000), B); + int stay = CheatSources.dropDuplicates(folder, CheatSources.migrate(folder, 5000, k)); check(stay == 1 && CheatSources.list(folder).size() == before + 1, "one new source, the copies gone: " + CheatSources.list(folder)); } // ---- The merged file ---- static void merge(File folder) throws Exception { + File pk = pack(new File(folder.getParentFile(), "merge-pack"), B, 0); + MncfConvert.Known k = known(pk, null); + MncfBuild.Game g = game(B, pk); String app = "[Coins]\n04000000 00001000 00000001\n[Moon]\n04000000 00001004 00000001\n"; - CheatSources.add(folder, "site", CheatSources.FROM_ZIP, Map.of(B, SITE + "[Coins]\n04000000 00001008 00000001\n"), 1000); - CheatSources.Source off = CheatSources.add(folder, "second", CheatSources.FROM_FILE, Map.of(B, "[Moon]\n04000000 00001010 00000001\n[Odd]\n04000000 00001014 00000001\n"), 2000); - CheatSources.add(folder, "third", CheatSources.FROM_FILE, Map.of(B, "[Moon]\n04000000 00001018 00000001\n[ODD]\n04000000 0000101C 00000001\n"), 3000); + CheatSources.add(folder, "site", CheatSources.FROM_ZIP, Map.of(B, SITE + "[Coins]\n04000000 00001008 00000001\n"), 1000, k, null); + CheatSources.Source off = CheatSources.add(folder, "second", CheatSources.FROM_FILE, Map.of(B, "[Moon]\n04000000 00001010 00000001\n[Odd]\n04000000 00001014 00000001\n"), 2000, k, null); + CheatSources.add(folder, "third", CheatSources.FROM_FILE, Map.of(B, "[Moon]\n04000000 00001018 00000001\n[ODD]\n04000000 0000101C 00000001\n"), 3000, k, null); CheatSources.enabled(folder, off.id, false); - CheatSources.Merged m = CheatSources.merge(CheatSources.blocks(folder, app, true, B, 0x200000)); + CheatSources.Merged m = CheatSources.merge(CheatSources.blocks(folder, app, true, g, 0x8000, true)); List keys = m.keys(); - check(keys.equals(List.of("Coins", "Moon", "1. Lots of coins", "2. No item cost", "3. Coins as a number", "4. Fast run (Hold ZL)", "5. High jump (Hold B)", - "7. Two buttons", "8. Data in main", "8. Data in main #2", "Coins (site)", "Moon (third)", "ODD (third)")), "the keys, the switched-off source's names kept free: " + keys); + check(keys.equals(List.of("Coins", "Moon", "1. Lots of coins", "2. No item cost", "4. Fast run (Hold ZL)", "5. High jump (Hold B)", + "7. Two buttons", "8. Data in main", "8. Data in main #2", "Coins (site)", "Moon (third)", "ODD (third)")), "the keys the Atmosphère files had, the switched-off source's names kept free: " + keys); check(m.key(off.id, "Moon").equals("Moon (second)") && m.key(off.id, "Odd").equals("Odd"), "a source that is off keeps its names for when it is on again"); - check(m.key("site", "6. Pause trick") == null, "Not supported has no key"); + check(m.key("site", "6. Pause trick") == null && m.key("site", "3. Coins as a number") == null, "what cannot run has no key"); + CheatSources.Block site = null; + for (CheatSources.Block b : m.blocks) if (b.id.equals("site")) site = b; + check(site != null && site.parsed.mncf != null && site.error == null && !site.pending, "the source's block is its .mncf made ready"); + CheatFile.Cheat pointer = cheat(site.parsed, "3. Coins as a number"), pause = cheat(site.parsed, "6. Pause trick"); + check("outside".equals(pointer.reason()) && pointer.kind == CheatFile.Kind.UNSUPPORTED && !pointer.switchable(), "a place outside the made-up main: refused with the spec's reason: " + pointer.reason()); + check(pause.reason() == null && pause.kind == CheatFile.Kind.UNSUPPORTED && pause.why.startsWith("opcode"), "raw code the host does not run: Not supported, as before"); + check(CheatFile.describe(pointer).equals("Its place lies outside the game. It stays off."), CheatFile.describe(pointer)); String t = m.text; check(!t.contains("Restore Code") && !t.contains("Pause trick") && !t.contains("Odd width") && !t.contains("www.") && !t.contains("TID=") && !t.contains("20000001"), - "credits, titles, headings, Restore Code and Not supported are left out:\n" + t); + "credits, titles, headings, Restore Code and what cannot run are left out:\n" + t); check(!t.contains("[Moon (second)]"), "a source that is off is not in the file"); check(t.indexOf("{Setup}") < t.indexOf("[1. Lots of coins]") && t.indexOf("{Setup}") > t.indexOf("[Moon]"), "a source's master comes before its cheats"); - check(t.contains("[--SectionStart:site: Items--]\n[1. Lots of coins]\n040A0000 00001000 B9004009\n") && t.contains("[--SectionEnd:site: Items--]\n[--SectionStart:site: Moving--]"), - "the groups as sections, with the source's name when more than one is on:\n" + t); - CheatFile.Parsed again = CheatFile.parse(t, 0x200000); + check(t.contains("[--SectionStart:site: Items--]\n[1. Lots of coins]\n04000000 00001000 B9004009\n") && t.contains("[--SectionEnd:site: Items--]\n[--SectionStart:site: Moving--]"), + "the groups as sections, with the source's name when more than one is on, the code made from the cheat's patch:\n" + t); + check(t.contains("[4. Fast run (Hold ZL)]\n80000100\n04000000 00003000 1E241000\n21000000\n04000000 00003000 1E2E1000\n20000000\n"), "a hold with the original back on release:\n" + t); + CheatFile.Parsed again = CheatFile.parse(t, 0x8000); java.util.Set low = new java.util.HashSet<>(); for (CheatFile.Cheat c : again.cheats) check(low.add(c.key.toLowerCase()), "unique without case: " + c.key); - check(again.cheats.size() == m.cheats && m.cheats == 13 && again.masters.size() == 1, "the merged file reads back: " + again.cheats.size()); - check(again.groups.equals(List.of("Comes with the app", "site: Items", "site: Moving", "site: Extras", "site", "third")), "its groups, a cheat outside one under its source's name: " + again.groups); + check(again.cheats.size() == m.cheats && m.cheats == 12 && again.masters.size() == 1, "the merged file reads back: " + again.cheats.size()); + check(again.groups.equals(List.of("Comes with the app", "site: Items", "site: Moving", "site: Extras", "site", "third")), "its groups, EdiZon's sections among them: " + again.groups); // one source alone: its groups without its name; a long name still fits a header File one = new File(folder.getParentFile(), "merge-one"); - CheatSources.add(one, "solo", CheatSources.FROM_ZIP, Map.of(B, SITE), 1); - check(CheatSources.merge(CheatSources.blocks(one, null, true, B, -1)).text.contains("[--SectionStart:Items--]"), "one source: the group alone"); + CheatSources.add(one, "solo", CheatSources.FROM_ZIP, Map.of(B, SITE), 1, k, null); + check(CheatSources.merge(CheatSources.blocks(one, null, true, g, -1, true)).text.contains("[--SectionStart:Items--]"), "one source: the group alone"); String longName = "x".repeat(127); CheatSources.Merged lm = CheatSources.merge(List.of( new CheatSources.Block("a", "a", true, CheatFile.parse("[" + longName + "]\n04000000 00000010 00000001\n", -1)), @@ -449,6 +505,395 @@ static void merge(File folder) throws Exception { check(lm.keys().get(1).length() == 127 && lm.keys().get(1).endsWith(" (bee)"), "a long clashing name is cut to fit: " + lm.keys().get(1).length()); } + // ---- .mncf for the build that runs (MncfMain, MncfBuild, the number field, export, packs) ---- + + static final String HAND = String.join("\n", + "format = \"mncf/1\"", + "name = \"Hand-made\"", + "authors = [\"someone\"]", + "extensions = { optional = [\"arm64-imm/1\"] }", + "", + "[game]", + "platform = \"switch\"", + "id = \"" + TID + "\"", + "", + "[[cheat]]", + "id = \"coins\"", + "name = \"Coins by pattern\"", + "about = \"Buying keeps your coins\"", + "tags = [\"touches_save\"]", + "", + " [[cheat.patch]]", + " at = { module = \"main\", find = \"08 40 00 B9 23 01 00 94\" }", + " expect = \"08 40 00 B9\"", + " bytes = \"09 40 00 B9\"", + "", + "[[cheat]]", + "id = \"count\"", + "name = \"A count\"", + "radio = \"r\"", + "", + " [cheat.values.n]", + " type = \"u16\"", + " min = 1", + " max = 500", + " default = 5", + " unit = \"coins\"", + "", + " [[cheat.patch]]", + " at = { module = \"main\", find = \"00 00 80 52 00 00 80 52\" }", + " expect = \"00 00 80 52\"", + " encode = { insn = \"movz\", width = 32, rd = 0, value = \"$n\" }", + "", + "[[cheat]]", + "id = \"other\"", + "name = \"The other one\"", + "radio = \"r\"", + "requires = [\"coins\"]", + "", + " [[cheat.write]]", + " at = { region = \"heap\", offset = 0x100 }", + " type = \"u32\"", + " value = 1", + "", + "[[cheat]]", + "id = \"view\"", + "name = \"A monitor\"", + "run = \"monitor\"", + "", + " [[cheat.read]]", + " at = { region = \"heap\", offset = 0x100 }", + " type = \"u32\"", + " label = \"N\"", + "", + "[[cheat]]", + "id = \"once\"", + "name = \"Once\"", + "run = \"once\"", + "", + " [[cheat.write]]", + " at = { region = \"heap\", offset = 0x104 }", + " type = \"u32\"", + " value = 2", + "", + "[[cheat]]", + "id = \"gone\"", + "name = \"Not in this version\"", + "", + " [[cheat.patch]]", + " at = { module = \"main\", find = \"DE AD BE EF 11 22 33 44\" }", + " expect = \"DE AD BE EF\"", + " bytes = \"00 00 00 00\"", + ""); + + static void mncf(File root) throws Exception { + File pk = pack(new File(root, "pack"), B, 0), po = pack(new File(root, "pack-orig"), B, 0); + // MncfMain: the image with the original words back where the rewriter changed them + byte[] img = Files.readAllBytes(new File(po, "main.patched.bin").toPath()); + byte[] orig = java.util.Arrays.copyOfRange(img, 0x1000, 0x1008); + put(img, 0x1000, 0x14000000L); put(img, 0x1004, 0x14000001L); // the rewriter's branches + Files.write(new File(po, "main.patched.bin").toPath(), img); + Files.write(new File(po, "main.changed.tsv").toPath(), u("# BUILD_ID\t" + B.toLowerCase() + "\n0x1000\t0x8\n")); + Files.write(new File(po, "main.orig.bin").toPath(), orig); + io.github.davdxpx.mistel.mncf.CodeModule main = MncfMain.of(po); + check(main != null && main.image().length == 0x10000 && (main.image()[0x1000] & 0xFF) == 0x08 && main.exclude().isEmpty(), "the original words are back"); + check(main.sectionStart("code") == 0 && main.sectionEnd("code") == 0x8000 && main.sectionStart("data") == 0xC000 && main.sectionEnd("data") == 0x10000, "the sections"); + File noOrig = pack(new File(root, "pack-no-orig"), B, 0); + Files.write(new File(noOrig, "main.changed.tsv").toPath(), u("# BUILD_ID\t" + B.toLowerCase() + "\n0x1000\t0x8\n")); + check(MncfMain.of(noOrig).excluded(0x1000, 4) && !MncfMain.of(noOrig).excluded(0x2000, 4), "without orig.bin the changed runs stay out of every search"); + check(MncfMain.of(new File(root, "nothing")) == null, "no pack: no main"); + + // A file of the player's: its cheats for this build, the spec's reasons, the code for the host + File folder = new File(root, "folder"); + CheatSources.Source s = CheatSources.addMncf(folder, "hand", CheatSources.FROM_FILE, u(HAND), 1); + check(java.util.Arrays.equals(Files.readAllBytes(s.file().toPath()), u(HAND)), "an .mncf is kept byte for byte"); + MncfBuild.Ready r = s.ready(game(B, pk)); + check(r.error == null && r.buildKey == null && r.signature.equals("unsigned") && r.signer == null && !r.verified(), "no build of its own, unsigned: loaded as any file, no mark"); + Map by = new LinkedHashMap<>(); + for (MncfBuild.Cheat c : r.cheats) by.put(c.id, c); + check(by.get("coins").reason == null && by.get("coins").lines.equals(List.of("04000000 00001000 B9004009")), "found by its pattern in the game's own main: " + by.get("coins").lines + " " + by.get("coins").reason); + check(by.get("count").reason == null && by.get("count").lines.equals(List.of("04000000 00002000 528000A0")) && by.get("count").value != null, "a value in the instruction: " + by.get("count").lines + " " + by.get("count").reason); + check(by.get("other").reason == null && by.get("other").lines.equals(List.of("04100000 00000100 00000001")), "a write into the heap: " + by.get("other").lines); + check("capability-missing:display".equals(by.get("view").reason), "a monitor: Peanuts has no display yet: " + by.get("view").reason); + check("runtime:unsupported:run.once".equals(by.get("once").reason), "run once: a part of the core Atmosphère code cannot say (section 11.1): " + by.get("once").reason); + check(MncfWords.reason(by.get("once").reason, by.get("once")).equals("It runs once when you turn it on, which Peanuts cannot do yet."), MncfWords.reason(by.get("once").reason, null)); + check("pattern-not-found".equals(by.get("gone").reason), by.get("gone").reason); + check(new File(s.dir, "build/" + B + ".mncf").isFile() && new File(s.dir, "build/" + B + ".tsv").isFile(), "kept for the build"); + String pinned = new String(Files.readAllBytes(new File(s.dir, "build/" + B + ".mncf").toPath()), StandardCharsets.UTF_8); + check(pinned.contains("at = { module = \"main\", offset = 0x1000 }") && !pinned.contains("08 40 00 B9 23 01 00 94"), "the pinned file has the place as an offset:\n" + pinned); + MncfBuild.Ready again = MncfBuild.kept(s.file(), game(B, null)); + check(again != null && again.cheats.size() == r.cheats.size() && again.cheats.get(0).lines.equals(r.cheats.get(0).lines), "a later start reads the kept one without main"); + check(MncfBuild.kept(s.file(), game(OTHER, null)) == null, "another build is made again"); + // made while the pack has no main yet (a game not built): kept, so the page does not look it up again and again; made again once main is there + File early = new File(root, "early"); + CheatSources.Source es = CheatSources.addMncf(early, "hand", CheatSources.FROM_FILE, u(HAND), 1); + MncfBuild.Ready e1 = es.ready(game(B, new File(root, "not-built-yet"))); + check("runtime:no-main".equals(e1.cheats.get(0).reason) && MncfBuild.kept(es.file(), game(B, new File(root, "not-built-yet"))) != null, "kept without main: " + e1.cheats.get(0).reason); + check(MncfBuild.kept(es.file(), game(B, pk)) == null && es.ready(game(B, pk)).cheats.get(0).reason == null && MncfBuild.kept(es.file(), game(B, pk)) != null, + "made again with the pack's main, its pattern found"); + + // The page and the tab: kinds, words, the number field + CheatFile.Parsed p = CheatFile.fromMncf(r, 0x8000); + CheatFile.Cheat coins = cheat(p, "Coins by pattern"), count = cheat(p, "A count"); + check(coins.kind == CheatFile.Kind.CODE && coins.number == null && p.credits.equals(List.of("someone")), "a code cheat, its file's author as its credit"); + check(CheatFile.describe(coins).startsWith("Buying keeps your coins. Changes 1 place"), CheatFile.describe(coins)); + check(CheatFile.describe(cheat(p, "A monitor")).equals("It shows values from the game, which Peanuts cannot do yet. It stays off."), CheatFile.describe(cheat(p, "A monitor"))); + check(count.number != null && count.number.own() == 5 && count.number.min() == 1 && count.number.max() == 500 && "coins".equals(count.number.unit()), "the value's range and unit"); + check(CheatValues.lines(count, 300).equals(List.of("04000000 00002000 52802580")) && CheatValues.lines(count, 9999).equals(CheatValues.lines(count, 500)), "the number made into the instruction, kept inside its range"); + check(CheatFile.describe(count, 300).endsWith("Its number is 300 coins."), CheatFile.describe(count, 300)); + File vf = new File(root, "values"); + check(vf.mkdirs(), "mkdirs values"); + CheatValues.keep(vf, "A count", count, 42); + Map kv = CheatValues.read(vf); + check(kv.get("a count").width == 0 && kv.get("a count").original == 5 && CheatValues.of(kv, "A count", count) == 42, "kept by its value, not by a place in the words"); + String mt = CheatSources.merge(List.of(new CheatSources.Block("hand", "hand", true, p)), kv).text; + check(mt.contains("[A count]\n04000000 00002000 52800540\n"), "a start writes the kept number:\n" + mt); + check(CheatValues.patch("[A count]\n04000000 00002000 528000A0\n[Next]\n", "A count", count, 7).equals("[A count]\n04000000 00002000 528000E0\n[Next]\n"), "the tab's patch of the merged file"); + + // Relations (section 7.8): on a radio the other goes off; what it requires goes on + CheatSources.Merged m = CheatSources.merge(List.of(new CheatSources.Block("hand", "hand", true, p))); + Set on = new java.util.LinkedHashSet<>(List.of("A count")); + Set changed = m.related(on, "The other one", true); + on.add("The other one"); + check(changed.equals(Set.of("A count", "Coins by pattern")) && on.equals(Set.of("Coins by pattern", "The other one")), "radio and requires: " + changed + " " + on); + + // Another build: the pattern still finds the place, per-build offsets and raw code of other builds do not + File pk2 = pack(new File(root, "pack2"), OTHER, 0x100); + MncfBuild.Ready r2 = MncfBuild.of(s.file(), game(OTHER, pk2)); + check(r2.cheats.get(0).lines.equals(List.of("04000000 00001100 B9004009")), "the place moved with the code: " + r2.cheats.get(0).lines); + File conv = new File(root, "conv"); + CheatSources.Source cs = CheatSources.add(conv, "cheatslips", CheatSources.FROM_ZIP, Map.of(B, "[Coins]\n040A0000 00001000 B9004009\n[Restore]\n040A0000 00001000 B9004008\n"), 1, known(pk, null), null); + MncfBuild.Ready r3 = MncfBuild.of(cs.file(), game(OTHER, pk2)); + check(r3.cheats.size() == 1 && r3.cheats.get(0).lines.equals(List.of("04000000 00001100 B9004009")), "an Atmosphère cheat converted with the game's main works on the next build: " + r3.cheats.get(0).lines + " " + r3.cheats.get(0).reason); + + // A place the rewriter changed: refused before the game runs (runtime:rewritten) + File pk3 = pack(new File(root, "pack3"), B, 0); + Files.write(new File(pk3, "main.changed.tsv").toPath(), u("# BUILD_ID\t" + B.toLowerCase() + "\n0x2000\t0x4\n")); + Files.write(new File(pk3, "main.orig.bin").toPath(), java.util.Arrays.copyOfRange(Files.readAllBytes(new File(pk3, "main.patched.bin").toPath()), 0x2000, 0x2004)); + File rw = new File(root, "rw"); + MncfBuild.Ready r4 = CheatSources.addMncf(rw, "hand", CheatSources.FROM_FILE, u(HAND), 1).ready(game(B, pk3)); + check("runtime:rewritten".equals(r4.cheats.get(1).reason) && r4.cheats.get(0).reason == null, "the count's place was rewritten: " + r4.cheats.get(1).reason); + + // A file Peanuts cannot read at all + File bad = new File(root, "bad"); + MncfBuild.Ready r5 = CheatSources.addMncf(bad, "bad", CheatSources.FROM_FILE, u("format = \"mncf/1\"\nname = \"x\"\n"), 1).ready(game(B, pk)); + check(r5.error != null && r5.error.startsWith("schema") && r5.cheats.isEmpty(), "its error code: " + r5.error); + CheatSources.Block bb = CheatSources.blocks(bad, null, true, game(B, pk), -1, true).get(0); + check(bb.error != null && bb.parsed.cheats.isEmpty(), "its block says so"); + check(CheatSources.blocks(conv, null, true, game(B, pk), -1, false).get(0).pending, "not made ready for a build and not to be made now: pending"); + + // Export: one source an .mncf with what is on as default = true and the set number as default; several an .mncp + CheatSources.Merged em = CheatSources.merge(CheatSources.blocks(folder, null, true, game(B, pk), 0x8000, true)); + MncfExport.Out one = MncfExport.make(folder, "Example Game", em, Set.of("Coins by pattern"), kv); + check(one != null && !one.pack && one.fileName.equals("Example Game cheats.mncf") && one.sources == 1, "one file: " + (one == null ? null : one.fileName)); + io.github.davdxpx.mistel.mncf.MncfFile ex = io.github.davdxpx.mistel.mncf.Mncf.load(one.bytes); + check(ex.cheats().get(0).isDefault() && !ex.cheats().get(1).isDefault() && Long.valueOf(42).equals(ex.cheats().get(1).values().get("n").defaultValue()), "the switches and the number travel with it"); + check(java.util.Arrays.equals(MncfExport.make(folder, "Example Game", em, Set.of(), new LinkedHashMap<>()).bytes, u(HAND)), "nothing changed: its own bytes, a signature stays good"); + CheatSources.add(folder, "site", CheatSources.FROM_ZIP, Map.of(B, SITE), 2, known(pk, null), null); + MncfExport.Out two = MncfExport.make(folder, "Example Game", CheatSources.merge(CheatSources.blocks(folder, null, true, game(B, pk), 0x8000, true)), Set.of(), kv); + check(two.pack && two.fileName.endsWith(".mncp") && two.sources == 2, "two sources: a pack"); + io.github.davdxpx.mistel.mncf.Pack pack = io.github.davdxpx.mistel.mncf.PackReader.read(two.bytes, MncfBuild.TRUST); + check(pack.usable() && pack.files().size() == 2 && pack.files().get(0).status().equals("ok") && pack.files().get(1).status().equals("ok"), "its manifest and hashes read back: " + pack.files()); + // The export back in: a pack's files, a bare .mncf, one in a zip + List paths = new ArrayList<>(), broken = new ArrayList<>(); + CheatImport.Found back = CheatImport.read(CheatImport.fromPack(two.bytes, paths, broken), paths, TID, BUILDS, "Example Game cheats.mncp"); + check(back.mncf.size() == 2 && broken.isEmpty() && back.forGame.isEmpty(), "the pack's two files: " + back.mncf); + ByteArrayOutputStream to = new ByteArrayOutputStream(); // the same manifest, one file changed after it was packed + try (java.util.zip.ZipInputStream zi = new java.util.zip.ZipInputStream(new ByteArrayInputStream(two.bytes)); ZipOutputStream zo2 = new ZipOutputStream(to)) { + for (ZipEntry e; (e = zi.getNextEntry()) != null; ) { + byte[] d = zi.readAllBytes(); + if (e.getName().equals(pack.files().get(1).path())) d = (new String(d, StandardCharsets.UTF_8) + "# changed\n").getBytes(StandardCharsets.UTF_8); + zo2.putNextEntry(new ZipEntry(e.getName())); + zo2.write(d); + zo2.closeEntry(); + } + } + List b2 = new ArrayList<>(); + List left = CheatImport.fromPack(to.toByteArray(), new ArrayList<>(), b2); + check(left.size() == 1 && b2.size() == 1 && b2.get(0).endsWith(": hash"), "a file changed after packing is left out: " + b2); + paths.clear(); + CheatImport.Found bare = CheatImport.read(List.of(new CheatImport.In("Hand.mncf", u(HAND))), List.of("Hand.mncf"), TID, BUILDS, "Hand.mncf"); + check(bare.mncf.size() == 1 && bare.mncf.get(0).name().equals("Hand") && bare.mncf.get(0).cheats() == 6 && bare.cheats() == 6, "a bare .mncf"); + CheatImport.Found otherGame = CheatImport.read(List.of(new CheatImport.In("x.mncf", u(HAND.replace(TID, "0100BBBB0CCC0000")))), List.of("x.mncf"), TID, BUILDS, "x"); + check(otherGame.mncf.isEmpty() && otherGame.mncfOtherGame.size() == 1, "another game's"); + CheatImport.Found broken2 = CheatImport.read(List.of(new CheatImport.In("x.mncf", u("format = \"mncf/2\"\n"))), List.of("x.mncf"), TID, BUILDS, "x"); + check(broken2.mncfBroken.size() == 1 && "format".equals(broken2.mncfBroken.get(0).error), "a file of another version: " + broken2.mncfBroken); + ByteArrayOutputStream zo = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(zo)) { z.putNextEntry(new ZipEntry("cheats/Hand.mncf")); z.write(u(HAND)); z.closeEntry(); } + paths.clear(); + CheatImport.Found inZip = CheatImport.read(CheatImport.fromZip(new ByteArrayInputStream(zo.toByteArray()), paths), paths, TID, BUILDS, "hand.zip"); + check(inZip.mncf.size() == 1 && !inZip.pack, "an .mncf in a zip"); + check(MncfExport.fileName("A/B: C?", false).equals("A B C cheats.mncf"), MncfExport.fileName("A/B: C?", false)); + zip(root, folder, pk, kv); + limits(root, pk); + + // What a file brings, for the Add dialog: counted from the file itself + MncfFacts hf = MncfFacts.of(io.github.davdxpx.mistel.mncf.Mncf.load(u(HAND))); + check(hf.cheats == 6 && hf.checked == 3 && hf.patterns == 3 && hf.values == 1 && hf.described == 1 && hf.rawOnly == 0 && hf.versions.isEmpty() && hf.signer == null, + "the hand-made file: " + hf.cheats + " " + hf.checked + " " + hf.patterns + " " + hf.values + " " + hf.described); + MncfFacts sf = MncfFacts.of(load(CheatSources.find(folder, "site").file())); + check(sf.versions.equals(List.of("1.0.0")) && "1.0.0".equals(sf.versionWords()) && sf.rawOnly > 0 && sf.checked > 0, "a converted file: " + sf.versions + " raw " + sf.rawOnly); + } + + /** The cheats a source's file made ready for the build can run, by name → their Atmosphère code */ + static Map> runnable(File folder, MncfBuild.Game g) throws Exception { + Map> out = new LinkedHashMap<>(); + for (CheatSources.Source s : CheatSources.list(folder)) for (MncfBuild.Cheat c : s.ready(g).cheats) if (c.reason == null && !c.master) out.put(out.containsKey(c.name) ? c.name + " #2" : c.name, c.lines); + return out; + } + + /** Export as a ZIP for other emulators (folder: the hand-made file and the site's, kv: the count's number 42), then that ZIP added again */ + static void zip(File root, File folder, File pk, Map kv) throws Exception { + MncfBuild.Game g = game(B, pk); + CheatSources.Merged m = CheatSources.merge(CheatSources.blocks(folder, null, true, g, 0x8000, true)); + MncfExport.Zip z = MncfExport.zip(folder, "Example Game", g, m, kv); + check(z != null && z.fileName.equals("Example Game cheats.zip") && MncfExport.zipName("A/B").equals("A B cheats.zip"), "its name"); + Map files = new LinkedHashMap<>(); + try (java.util.zip.ZipInputStream zi = new java.util.zip.ZipInputStream(new ByteArrayInputStream(z.bytes))) { + for (ZipEntry e; (e = zi.getNextEntry()) != null; ) files.put(e.getName(), new String(zi.readAllBytes(), StandardCharsets.UTF_8)); + } + String path = "atmosphere/contents/" + TID + "/cheats/" + B + ".txt", t = files.get(path); + check(files.keySet().equals(Set.of(path)) && z.builds.equals(Map.of(B, z.cheats)) && "1.0.0".equals(z.versions.get(B)), "Atmosphère's layout, one file a build: " + files.keySet() + " " + z.builds); + Map> before = runnable(folder, g); + // what an Atmosphère file cannot hold, or what does not fit the game, is left out and named; everything else is in + Map left = new LinkedHashMap<>(); + for (String[] l : z.left) left.put(l[0], l[1]); + check(left.keySet().equals(Set.of("A monitor", "Once", "Not in this version")), "left out: " + left); + check(left.get("Once").equals("It runs once when you turn it on, which an Atmosphère file cannot say.") && left.get("A monitor").equals("It shows values from the game, which an Atmosphère file cannot do.") + && left.get("Not in this version").equals("Its place was not found in this version of the game."), "and why, from the converter's stable reasons: " + left); + // every cheat the file can run here, the raw one Peanuts' host does not run among them; and the pointer whose base lies past the made-up main, which + // Peanuts refuses (outside) but whose own raw code for the build the converter writes as it is (spec section 15: it checks what it makes from a + // cheat's operations, never a raw entry) + check(z.cheats == before.size() + 1 && before.containsKey("6. Pause trick") && t.contains("[3. Coins as a number]"), "what goes in: " + z.cheats + " " + before.keySet()); + check(t.startsWith("{Setup}\n") && t.indexOf("{") == t.lastIndexOf("{"), "one master code, first:\n" + t); + check(t.contains("[A count]\n04000000 00002000 52800540\n"), "the number set in the game's tab (42) in its instruction:\n" + t); + check(t.contains("[Items]\n\n[1. Lots of coins]\n") && t.contains("[Extras]\n20000001\n") && t.contains("[6. Pause trick]\n") && !t.contains("SectionStart"), + "the groups as the spec writes them (a name, then an entry of only 20000001 where a cheat in no group follows), the raw code as it came:\n" + t); + // added again: the same cheats, the same code, for everything that went in + List paths = new ArrayList<>(); + CheatImport.Found back = CheatImport.read(CheatImport.fromZip(new ByteArrayInputStream(z.bytes), paths), paths, TID, BUILDS, z.fileName); + check(back.forGame.size() == 1 && back.mncf.isEmpty(), "read back as an Atmosphère file of this game's build: " + back.forGame.size()); + File again = new File(root, "zip-again"); + for (Map.Entry> e : back.sources().entrySet()) CheatSources.add(again, e.getKey(), CheatSources.FROM_ZIP, e.getValue(), 1, known(pk, null), z.fileName); + Map> after = runnable(again, g); + before.put("A count", List.of("04000000 00002000 52800540")); // the number set, now the file's own + for (Map.Entry> e : before.entrySet()) check(e.getValue().equals(after.get(e.getKey())), "the same code for " + e.getKey() + ": " + e.getValue() + " " + after.get(e.getKey())); + check(after.keySet().equals(before.keySet()), "the same cheats: " + after.keySet() + " " + before.keySet()); + MncfBuild.Ready ra = CheatSources.list(again).get(0).ready(g); + for (MncfBuild.Cheat c : ra.cheats) if (c.name.equals("1. Lots of coins")) check(c.group.equals("Items"), "its group came back: " + c.group); + // a file of two builds: each build's own file, the other build's cheats as their own code for it + File two = new File(root, "zip-two"); + CheatSources.add(two, "both", CheatSources.FROM_ZIP, Map.of(B, "[Coins]\n04000000 00001000 B9004009\n", OTHER, SMALL), 1, known(pk, null), null); + MncfExport.Zip z2 = MncfExport.zip(two, "Example Game", g, CheatSources.merge(CheatSources.blocks(two, null, true, g, 0x8000, true)), new LinkedHashMap<>()); + Map f2 = new LinkedHashMap<>(); + try (java.util.zip.ZipInputStream zi = new java.util.zip.ZipInputStream(new ByteArrayInputStream(z2.bytes))) { + for (ZipEntry e; (e = zi.getNextEntry()) != null; ) f2.put(e.getName(), new String(zi.readAllBytes(), StandardCharsets.UTF_8)); + } + // with the game's main every patch is checked before it is written, so the ZIP never writes over other code; without it a pattern cannot be placed + String checked = String.join("\n", "format = \"mncf/1\"", "name = \"Checked\"", "", "[game]", "platform = \"switch\"", "id = \"" + TID + "\"", "", + "[builds.\"1.0.0\"]", "modules = { main = \"" + B + "\" }", "", + "[[cheat]]", "id = \"wrong\"", "name = \"Made for other code\"", "", + " [[cheat.patch]]", " at = { module = \"main\", offset = 0x1000 }", " expect = \"DE AD BE EF\"", " bytes = \"1F 20 03 D5\"", "", + "[[cheat]]", "id = \"found\"", "name = \"Found by its pattern\"", "", + " [[cheat.patch]]", " at = { module = \"main\", find = \"08 40 00 B9 23 01 00 94\" }", " expect = \"08 40 00 B9\"", " bytes = \"09 40 00 B9\"", "", + "[[cheat]]", "id = \"far\"", "name = \"Far pointer\"", "", + " [[cheat.write]]", " at = { module = \"main\", offset = 0x200000, path = [0x10] }", " type = \"u32\"", " value = 1", ""); + File ck = new File(root, "zip-checked"); + CheatSources.addMncf(ck, "checked", CheatSources.FROM_FILE, u(checked), 1); + MncfExport.Zip zc = MncfExport.zip(ck, "Example Game", g, null, new LinkedHashMap<>()); + String tc; + try (java.util.zip.ZipInputStream zi = new java.util.zip.ZipInputStream(new ByteArrayInputStream(zc.bytes))) { zi.getNextEntry(); tc = new String(zi.readAllBytes(), StandardCharsets.UTF_8); } + Map lc = new LinkedHashMap<>(); + for (String[] l : zc.left) lc.put(l[0], l[1]); + check(tc.equals("[Found by its pattern]\n04000000 00001000 B9004009\n") && lc.size() == 2 + && "The game's code at its place is not what the cheat was made for: it is for another version.".equals(lc.get("Made for other code")) + && "Its place lies outside the game.".equals(lc.get("Far pointer")), "checked against main, a pointer's base too: " + tc + " " + lc); + MncfExport.Zip zn = MncfExport.zip(ck, "Example Game", game(B, null), null, new LinkedHashMap<>()); + check(zn.cheats == 2 && zn.left.size() == 1 && zn.left.get(0)[0].equals("Found by its pattern") + && zn.left.get(0)[1].equals("Its place is found by the code around it, and Peanuts can look it up only in the version it has built."), "no main: " + zn.left.get(0)[1]); + String other = "atmosphere/contents/" + TID + "/cheats/" + OTHER + ".txt"; + check(f2.keySet().equals(Set.of(path, other)) && f2.get(other).equals("[Coins]\n04000000 00001000 00000063\n") && z2.left.isEmpty() + && new ArrayList<>(z2.builds.keySet()).equals(List.of(B, OTHER)), "both builds, the running one first: " + f2 + " " + z2.builds); + } + + /** An .mncf of n cheats, each a write of its own place in main (the first in, of them, in group "Few"), and two masters ahead of them */ + static String many(int n, int in) { + StringBuilder sb = new StringBuilder(String.join("\n", "format = \"mncf/1\"", "name = \"Many\"", "", "[game]", "platform = \"switch\"", "id = \"" + TID + "\"", "", + "[builds.\"1.0.0\"]", "modules = { main = \"" + B + "\" }", "", "")); + for (int m = 0; m < 2; m++) { + sb.append("[[cheat]]\nid = \"setup").append(m).append("\"\nname = \"Setup ").append(m).append("\"\nmaster = true\n\n [[cheat.write]]\n at = { module = \"main\", offset = 0x") + .append(Integer.toHexString(0x8000 + 4 * m)).append(" }\n type = \"u32\"\n value = ").append(m + 1).append("\n\n"); + } + for (int i = 0; i < n; i++) { + sb.append("[[cheat]]\nid = \"c").append(i).append("\"\nname = \"Cheat ").append(i).append("\"\n").append(i < in ? "group = \"Few\"\n" : "") + .append("\n [[cheat.write]]\n at = { module = \"main\", offset = 0x").append(Integer.toHexString(0x1000 + 4 * i)).append(" }\n type = \"u32\"\n value = ").append(i).append("\n\n"); + } + return sb.toString(); + } + + /** An Atmosphère file whose master writes words places from at, and two cheats: one on the master's first place (so it requires it), one apart */ + static String withMaster(String name, int at, int words) { + StringBuilder sb = new StringBuilder("{" + name + " setup}\n"); + for (int i = 0; i < words / 3; i++) sb.append(String.format("04000000 %08X 00000001\n", at + 4 * i)); + sb.append(String.format("\n[%s on the setup]\n04000000 %08X 00000002\n\n[%s apart]\n04000000 %08X 00000003\n", name, at, name, at + 0x800)); + return sb.toString(); + } + + /** Atmosphère's limits (spec section 15) in the ZIP, across sources; Peanuts' own engine is not held to them */ + static void limits(File root, File pk) throws Exception { + MncfBuild.Game g = game(B, pk); + // more than 127 cheats: Peanuts runs them all, the ZIP has 127 and names the rest; group entries that would leave cheats out are not written + File big = new File(root, "zip-many"); + CheatSources.addMncf(big, "many", CheatSources.FROM_FILE, u(many(130, 3)), 1); + MncfBuild.Ready r = CheatSources.list(big).get(0).ready(g); + int runs = 0, masters = 0; + for (MncfBuild.Cheat c : r.cheats) { + if (c.reason == null && !c.master) runs++; + if (c.master && c.reason == null && c.lines.size() == 1) masters++; + } + check(runs == 130 && masters == 2, "Peanuts runs every cheat, each master with its own code: " + runs + " " + masters); + MncfExport.Zip z = MncfExport.zip(big, "Example Game", g, null, new LinkedHashMap<>()); + String t; + try (java.util.zip.ZipInputStream zi = new java.util.zip.ZipInputStream(new ByteArrayInputStream(z.bytes))) { zi.getNextEntry(); t = new String(zi.readAllBytes(), StandardCharsets.UTF_8); } + check(z.cheats == 127 && z.left.size() == 3 && z.left.get(0)[0].equals("Cheat 127") && z.left.get(0)[1].equals("An Atmosphère file holds at most 127 cheats.") + && !t.contains("[Few]") && t.startsWith("{Setup 0}\n04000000 00008000 00000001\n04000000 00008004 00000002\n"), "127 cheats, one master: " + z.cheats + " " + z.left.size()); + CheatSources.addMncf(new File(root, "zip-few"), "few", CheatSources.FROM_FILE, u(many(5, 3)), 1); + MncfExport.Zip zf = MncfExport.zip(new File(root, "zip-few"), "Example Game", g, null, new LinkedHashMap<>()); + try (java.util.zip.ZipInputStream zi = new java.util.zip.ZipInputStream(new ByteArrayInputStream(zf.bytes))) { zi.getNextEntry(); t = new String(zi.readAllBytes(), StandardCharsets.UTF_8); } + check(t.contains("[Few]\n\n[Cheat 0]\n") && t.contains("[Few]\n20000001\n\n[Cheat 3]\n") && zf.cheats == 5, "where there is room, the groups:\n" + t); + // the master codes of several sources are one entry of at most 256 words: a master past that stays out, with the cheats of its source that need it + File two = new File(root, "zip-masters"); + CheatSources.add(two, "first", CheatSources.FROM_ZIP, Map.of(B, withMaster("First", 0x1000, 210)), 1, known(pk, null), null); + CheatSources.add(two, "second", CheatSources.FROM_ZIP, Map.of(B, withMaster("Second", 0x4000, 210)), 1, known(pk, null), null); + MncfExport.Zip zm = MncfExport.zip(two, "Example Game", g, null, new LinkedHashMap<>()); + try (java.util.zip.ZipInputStream zi = new java.util.zip.ZipInputStream(new ByteArrayInputStream(zm.bytes))) { zi.getNextEntry(); t = new String(zi.readAllBytes(), StandardCharsets.UTF_8); } + Map left = new LinkedHashMap<>(); + for (String[] l : zm.left) left.put(l[0], l[1]); + check(t.startsWith("{First setup}\n") && !t.contains("00004000 00000001") && t.contains("[Second apart]") && t.contains("[First on the setup]") + && left.keySet().equals(Set.of("Second on the setup")) + && left.get("Second on the setup").equals("It needs a code that is always on, and that code does not fit in one Atmosphère file beside the others."), + "one master of at most 256 words: " + left + "\n" + t.substring(0, Math.min(t.length(), 60))); + // a file of 64 KB or more Atmosphère refuses: the cheats that would make it that big stay out; a name keeps the 63 bytes Atmosphère keeps + StringBuilder huge = new StringBuilder(); + for (int i = 0; i < 40; i++) { + huge.append(i == 0 ? "[" + "A very long name ".repeat(5).trim() + "]\n" : "[Long " + i + "]\n"); + for (int k = 0; k < 67; k++) huge.append(String.format("04000000 %08X 00000001\n", 0x1000 + 4 * (67 * i + k))); + huge.append('\n'); + } + File hf = new File(root, "zip-huge"); + CheatSources.add(hf, "huge", CheatSources.FROM_ZIP, Map.of(B, huge.toString()), 1, known(pk, null), null); + MncfExport.Zip zh = MncfExport.zip(hf, "Example Game", g, null, new LinkedHashMap<>()); + byte[] file; + try (java.util.zip.ZipInputStream zi = new java.util.zip.ZipInputStream(new ByteArrayInputStream(zh.bytes))) { zi.getNextEntry(); file = zi.readAllBytes(); } + t = new String(file, StandardCharsets.UTF_8); + boolean allBig = !zh.left.isEmpty(); + for (String[] l : zh.left) allBig &= l[1].equals("An Atmosphère file can be at most 64 KB, and the cheats before this one fill it."); + String first = t.substring(1, t.indexOf(']')); + check(file.length < 0x10000 && zh.cheats + zh.left.size() == 40 && zh.cheats > 30 && allBig && zh.left.get(zh.left.size() - 1)[0].equals("Long 39"), + "under 64 KB: " + file.length + " " + zh.cheats + " " + zh.left.size()); + check(first.getBytes(StandardCharsets.UTF_8).length <= 63 && first.startsWith("A very long name A very long name"), "a name of at most 63 bytes: " + first); + } + // ---- A real file, when one is given (never in the repository) ---- static void real(File f) throws Exception { diff --git a/android/app/src/main/java/dev/nxnative/android/CheatsBridge.java b/android/app/src/main/java/dev/nxnative/android/CheatsBridge.java index 09dbad46..a80122e2 100644 --- a/android/app/src/main/java/dev/nxnative/android/CheatsBridge.java +++ b/android/app/src/main/java/dev/nxnative/android/CheatsBridge.java @@ -24,6 +24,10 @@ import dev.peanuts.mods.CheatImport; import dev.peanuts.mods.CheatPick; import dev.peanuts.mods.CheatSources; +import dev.peanuts.mods.CheatValues; +import dev.peanuts.mods.MncfBuild; +import dev.peanuts.mods.MncfConvert; +import dev.peanuts.mods.MncfExport; /** * PEANUTS: Game settings' Cheat files for every game, on the game's cheat sources (dev.peanuts.mods.CheatSources) instead of upstream's imported/ folder. A @@ -33,8 +37,9 @@ *
  • Import cheat file… takes a .txt or a .zip, Import cheat folder… a folder, each in the Atmosphère, Eden / Yuzu or Ryujinx layout or as a bare build file * (dev.peanuts.mods.CheatImport): the files of the game's build become a source, the other versions' files are kept with it; another game's, a file that * names no build, or another version alone are refused with upstream's words.
  • - *
  • A source's line: on or off as a whole, or removed. Export cheats… writes the sources in upstream's export format; Import cheats… reads one as before (into - * imported/, which a start or this sheet makes sources: CheatSources.migrate).
  • + *
  • A source's line: on or off as a whole, or removed. Export cheats… writes the sources as .mncf (one) or .mncp (several: dev.peanuts.mods.MncfExport); + * Import cheats… reads upstream's export zip as before (into imported/, which a start or this sheet makes sources: CheatSources.migrate).
  • + *
  • Every source is an .mncf file: an Atmosphère file the player adds is converted with what the app knows of the game ({@link #known}).
  • * */ public final class CheatsBridge { @@ -77,9 +82,51 @@ public static String appText(String packDir, String build) { try { return new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8); } catch (IOException e) { return null; } } - /** Upstream's imported/ files made sources (once; CheatSources.migrate), quietly: a failure leaves them where they are, and a start reads them there */ - static void migrate(File folder) { - try { CheatSources.migrate(folder, System.currentTimeMillis()); } catch (IOException | RuntimeException e) { android.util.Log.w("peanuts", "cheats: imported files not moved: " + e); } + /** + * Upstream's imported/ files made sources (once; CheatSources.migrate) and an earlier version's Atmosphère sources made .mncf (CheatSources.upgrade), quietly: + * a failure leaves them where they are, and a start tries again + */ + static void migrate(File folder, MncfConvert.Known k) { + try { CheatSources.migrate(folder, System.currentTimeMillis(), k); } catch (IOException | RuntimeException e) { android.util.Log.w("peanuts", "cheats: imported files not moved: " + e); } + try { CheatSources.upgrade(folder, k); } catch (RuntimeException e) { android.util.Log.w("peanuts", "cheats: earlier sources not converted: " + e); } + } + + /** + * What a conversion to .mncf knows of the game (MncfConvert.Known): its title ID and name, every build's version the profile names, the pack's build and its + * own main (read only when a file is converted), and who adds the file: the name of the user games start with, unless it is still the host's "Player" + */ + public static MncfConvert.Known known(Context c, String titleId, String gameName, String packDir) { + Map versions = new java.util.LinkedHashMap<>(); + Profile p = Profile.of(titleId); + if (p != null) { + try { + for (Map.Entry> e : p.buildMap().entrySet()) { + String main = e.getValue().get("main"), d = p.display(e.getKey()); + if (main != null && main.length() >= 16 && d != null) versions.put(main.substring(0, 16).toUpperCase(Locale.ROOT), d); + } + } catch (RuntimeException ignored) { } + } + String author = null; + try { + String uid = Users.defaultUid(c); + for (Users.User u : Users.list(c)) if (u.uid.equals(uid) && !u.name.equals("Player") && !u.name.trim().isEmpty()) author = u.name.trim(); + } catch (RuntimeException ignored) { } + File pack = packDir == null || packDir.isEmpty() ? null : new File(packDir); + String build = first(builds(titleId, packDir)); + return new MncfConvert.Known(titleId, gameName, author, pack != null && dev.peanuts.mods.MncfMain.has(pack) ? build : null, versions, MncfConvert.of(pack)); + } + + /** Upstream's imported files and an earlier version's Atmosphère sources made .mncf now (CheatSources.migrate, upgrade), with what the app knows of the game */ + public static void convert(Context c, String titleId, String gameName, String packDir) { + File folder = folder(c, titleId); + boolean any = new File(folder, "imported").isDirectory(); + for (CheatSources.Source s : CheatSources.list(folder)) any |= CheatSources.unconverted(s); + if (any) migrate(folder, known(c, titleId, gameName, packDir)); + } + + /** The game for the .mncf sources (MncfBuild.Game): its build that runs, that build's version, its pack (the game's own main) */ + public static MncfBuild.Game game(String titleId, String build, String packDir) { + return new MncfBuild.Game(titleId, build, version(titleId, build), packDir == null || packDir.isEmpty() ? null : new File(packDir)); } private static String first(Set s) { return s.isEmpty() ? null : s.iterator().next(); } @@ -105,9 +152,26 @@ public static long textEnd(String packDir) { * cheat's key; textEnd gives the kinds (CheatFile.parse). The page switches by these keys */ public static CheatSources.Merged merged(Context c, String titleId, String gameDir, String packDir, String build, long textEnd) { + return merged(c, titleId, gameDir, packDir, build, textEnd, false); + } + + /** + * The same; make: a source's .mncf not made ready for the build yet is made now (MncfBuild: it reads the game's main, seconds for a large game, so not on + * the main thread); without, it is listed as pending (CheatSources.Block.pending) until {@link #prepare} has made it + */ + public static CheatSources.Merged merged(Context c, String titleId, String gameDir, String packDir, String build, long textEnd, boolean make) { String app = appText(packDir, build); List mods = ModCheats.of(modDirs(gameDir, titleId, packDir), build, null); - return CheatSources.merge(ModCheats.blocks(app == null ? "" : app, folder(c, titleId), build, mods, textEnd)); + return CheatSources.merge(ModCheats.blocks(app == null ? "" : app, folder(c, titleId), game(titleId, build, packDir), mods, textEnd, make)); + } + + /** Every source of the game made ready for the build (off the main thread): what a page shows as pending is listed once this is done */ + public static void prepare(Context c, String titleId, String packDir, String build) { + MncfBuild.Game g = game(titleId, build, packDir); + for (CheatSources.Source s : CheatSources.list(folder(c, titleId))) { + if (!s.file().isFile()) continue; + try { s.ready(g); } catch (IOException | RuntimeException e) { android.util.Log.w("peanuts", "cheats: " + s.name + " not made ready for " + build + ": " + e); } + } } /** The enabled mods' cheats folders, as GameActivity.start finds them (dev.peanuts.mods.ModRuntime.cheatsDirs beside the game) */ @@ -136,15 +200,16 @@ public static boolean wanted(Context c, String titleId, boolean master) { try { Profile p = Profile.of(titleId); if (!CheatSources.appKnown(folder) && (master || p != null && p.cheats)) CheatSources.appEnabled(folder, master); // only a game that has had the switch writes a state - List moved = CheatSources.migrate(folder, System.currentTimeMillis()); - if (!moved.isEmpty()) android.util.Log.i("peanuts", "cheats: " + titleId + ": " + moved.size() + " imported file(s) are sources now"); } catch (IOException | RuntimeException e) { android.util.Log.w("peanuts", "cheats: " + titleId + ": the earlier state could not be moved: " + e); return master; } + // upstream's imported files and an earlier version's Atmosphère sources count as they are: the start (ModCheats.install) and the page make them .mncf, + // where the pack is known, so the converter has the game's own main for patterns if (Boolean.TRUE.equals(CheatSources.appEnabled(folder))) return true; - for (CheatSources.Source s : CheatSources.list(folder)) if (s.enabled && !s.files().isEmpty()) return true; - return false; + for (CheatSources.Source s : CheatSources.list(folder)) if (s.enabled && (s.file().isFile() || CheatSources.unconverted(s))) return true; + File[] imported = new File(folder, "imported").listFiles((d, n) -> n.toLowerCase(Locale.ROOT).endsWith(".txt")); + return imported != null && imported.length > 0; } // ---- For the in-game Mods tab (dev.peanuts.mods.ModsTab, Part E), in the game's process ---- @@ -175,7 +240,7 @@ public static int set(String key, boolean on) { /** CheatsUi.rows (PEANUTS hook): Cheat files, what the game has, opening the sheet. Its tile is the Peanuts folder icon (the sheet imports files and folders) */ static Ui.Setting filesRow(MainActivity a, Game g, Runnable again) { File folder = folder(a, g.titleId); - migrate(folder); + migrate(folder, known(a, g.titleId, g.name, g.packDir)); int n = CheatSources.list(folder).size(); Profile p = Profile.of(g.titleId); boolean own = p != null && p.cheats; // a profile with its own cheat file @@ -189,7 +254,7 @@ static Ui.Setting filesRow(MainActivity a, Game g, Runnable again) { /** The sheet: the game's own file, each source (a tap: on or off, remove), then Import cheat file…, Import cheat folder…, Export cheats…, Import cheats… */ static void sheet(MainActivity a, Game g, Runnable again) { File folder = folder(a, g.titleId); - migrate(folder); + migrate(folder, known(a, g.titleId, g.name, g.packDir)); String build = first(builds(g.titleId, g.packDir)); Profile p = Profile.of(g.titleId); File shipped = g.packDir != null && build != null ? Cheats.packFile(new File(g.packDir), build) : null; @@ -197,7 +262,7 @@ static void sheet(MainActivity a, Game g, Runnable again) { List items = new ArrayList<>(); boolean own = p != null && p.cheats; if (own) items.add(shipped != null ? a.getString(R.string.cheats_shipped, shipped.getName()) : a.getString(R.string.cheats_shipped_missing)); - for (CheatSources.Source s : sources) items.add(sourceLine(s, build)); + for (CheatSources.Source s : sources) items.add(sourceLine(s, game(g.titleId, build, g.packDir))); items.add(a.getString(R.string.cheats_import_file)); items.add("Import cheat folder…"); items.add(a.getString(R.string.cheats_export)); @@ -205,31 +270,41 @@ static void sheet(MainActivity a, Game g, Runnable again) { int base = own ? 1 : 0; new PadFocus.Builder(a).setTitle(a.getString(R.string.cheats_files_title)).setItems(items.toArray(new String[0]), (d, w) -> { if (w < base) return; // the game's own file: nothing to do - if (w < base + sources.size()) { source(a, folder, sources.get(w - base), build, again); return; } + if (w < base + sources.size()) { source(a, folder, sources.get(w - base), game(g.titleId, build, g.packDir), again); return; } pendingFor = g; pendingAgain = again; int k = w - base - sources.size(); if (k == 0) pick(a, new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*"), REQ_FILE); else if (k == 1) pick(a, new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), REQ_FOLDER); - else if (k == 2) pick(a, new Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("application/zip") - .putExtra(Intent.EXTRA_TITLE, Cheats.zipName(g.titleId, new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ROOT).format(new Date()))), REQ_EXPORT); + else if (k == 2) pick(a, new Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("application/octet-stream") + .putExtra(Intent.EXTRA_TITLE, MncfExport.fileName(g.name, sources.size() > 1)), REQ_EXPORT); else pick(a, new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*"), REQ_IMPORT_ZIP); }).setNegativeButton("Close", null).show(); } + /** A source's cheats that can run for this build (its kept .mncf for it; -1 when it was not made ready yet) */ + static int count(CheatSources.Source s, MncfBuild.Game g) { + try { + MncfBuild.Ready r = MncfBuild.kept(s.file(), g); + if (r == null) return -1; + int n = 0; + for (MncfBuild.Cheat c : r.cheats) if (!c.master && !c.refused()) n++; + return n; + } catch (IOException | RuntimeException e) { + return 0; + } + } + /** A source's line in the sheet: its name, how many cheats it has for this build, off */ - static String sourceLine(CheatSources.Source s, String build) { - String t = null; - try { t = s.text(build); } catch (IOException ignored) { } - String what = t == null ? "for another version" : CheatFile.parse(t, -1).switchable() + " cheats"; + static String sourceLine(CheatSources.Source s, MncfBuild.Game g) { + int n = count(s, g); + String what = n < 0 ? "not checked for this build yet" : n == 0 ? "none for this build" : n + " cheats"; return s.name + " (" + what + (s.enabled ? "" : ", off") + ")"; } - private static void source(MainActivity a, File folder, CheatSources.Source s, String build, Runnable again) { - String t = null; - try { t = s.text(build); } catch (IOException ignored) { } - int n = t == null ? 0 : CheatFile.parse(t, -1).switchable(); - String msg = (t == null ? "None of its cheats are for this game's build: they start to work when the game is that version." : n + " cheats for this game's build.") + private static void source(MainActivity a, File folder, CheatSources.Source s, MncfBuild.Game g, Runnable again) { + int n = count(s, g); + String msg = (n == 0 ? "None of its cheats are for this game's build." : n < 0 ? "Its cheats are checked for this game's build when you open Mods & Cheats." : n + " cheats for this game's build.") + (s.enabled ? " They are listed in the in-game panel from the next start." : " It is off: its cheats are not in the in-game panel."); new PadFocus.Builder(a).setTitle(s.name).setMessage(msg) .setPositiveButton(s.enabled ? "Turn off" : "Turn on", (x, y) -> { @@ -270,9 +345,12 @@ public static boolean result(Activity act, int request, int result, Intent data) } try { if (request == REQ_EXPORT) { + String b = first(builds); + MncfExport.Out out = MncfExport.make(folder, g.name, b == null ? null : merged(a, g.titleId, g.gameDir, g.packDir, b, textEnd(g.packDir)), Prefs.cheatsOn(a, g.titleId), CheatValues.read(folder)); + if (out == null) throw new IOException("there are no imported cheats to export"); try (OutputStream os = a.getContentResolver().openOutputStream(doc)) { if (os == null) throw new IOException("the place picked cannot be written"); - CheatSources.exportZip(os, g.titleId, first(builds), folder, Prefs.cheats(a, g.titleId), Prefs.cheatsOn(a, g.titleId)); + os.write(out.bytes); } Toast.makeText(a, a.getString(R.string.cheats_exported), Toast.LENGTH_LONG).show(); } else { // upstream's Import cheats…: its zip into imported/, then made sources @@ -282,7 +360,7 @@ public static boolean result(Activity act, int request, int result, Intent data) c = Cheats.readZip(in, g.titleId, builds); } Cheats.takeZip(folder, c, builds); - int n = CheatSources.dropDuplicates(folder, CheatSources.migrate(folder, System.currentTimeMillis()), first(builds)); // its files as sources; one the game has already is not added twice + int n = CheatSources.dropDuplicates(folder, CheatSources.migrate(folder, System.currentTimeMillis(), known(a, g.titleId, g.name, g.packDir))); // its files as sources (.mncf); one the game has already is not added twice if (c.master != null) Prefs.cheats(a, g.titleId, c.master); if (c.on != null) Prefs.cheatsOn(a, g.titleId, c.on); Toast.makeText(a, a.getString(R.string.cheats_zip_done, n), Toast.LENGTH_LONG).show(); @@ -316,11 +394,12 @@ static void taken(MainActivity a, Game g, File folder, Set builds, Cheat List added = new ArrayList<>(), same = new ArrayList<>(); try { long now = System.currentTimeMillis(); + MncfConvert.Known k = known(a, g.titleId, g.name, g.packDir); for (Map.Entry> e : f.sources().entrySet()) { CheatSources.Source had = null; - for (Map.Entry file : e.getValue().entrySet()) if (builds.contains(file.getKey())) had = CheatSources.sameAs(folder, file.getKey(), file.getValue()); + for (Map.Entry file : e.getValue().entrySet()) if (builds.contains(file.getKey())) had = CheatSources.sameAs(folder, file.getValue()); if (had != null) { same.add(had.name); continue; } - added.add(CheatSources.add(folder, e.getKey(), r.from, e.getValue(), now++).name); + added.add(CheatSources.add(folder, e.getKey(), r.from, e.getValue(), now++, k, r.display != null ? r.display : r.name).name); } } catch (IOException | RuntimeException e) { android.util.Log.w("peanuts", "cheats: keeping a source: " + e); diff --git a/android/app/src/main/java/dev/nxnative/android/GameActivity.java b/android/app/src/main/java/dev/nxnative/android/GameActivity.java index 7af7de65..500fa966 100644 --- a/android/app/src/main/java/dev/nxnative/android/GameActivity.java +++ b/android/app/src/main/java/dev/nxnative/android/GameActivity.java @@ -74,7 +74,7 @@ public final class GameActivity extends Activity implements SurfaceHolder.Callba private PadPanel.Combo combo = new PadPanel.Combo(PadPanel.OPEN_BOTH); private final HashMap> gameKeys = new HashMap<>(); private final HashSet panelKeys = new HashSet<>(); - private final Runnable comboHeld = () -> { if (panel != null && combo.fire(android.os.SystemClock.uptimeMillis())) panel.padToggle(); }; + private final Runnable comboHeld = () -> { if (panel != null && combo.fire(android.os.SystemClock.uptimeMillis())) InGamePanel.toggle(this, true); }; // PEANUTS: − and + held open the game menu (InGamePanel) private File log; private final Handler ui = new Handler(Looper.getMainLooper()); private PadMotion padMotion; // a gamepad's own gyroscope and accelerometer as its player's six-axis sensor (PadMotion), the phone's own sensors stay the host's @@ -177,6 +177,7 @@ public final class GameActivity extends Activity implements SurfaceHolder.Callba controls.onSwitch = v -> handle.setVisibility(v ? View.VISIBLE : View.GONE); controls.setMode(TouchControls.mode(this)); root.addOnLayoutChangeListener((v, l, t, r, b, ol, ot, or, ob) -> handle.setTranslationY((b - t) * 0.3f - 70 * dp)); + InGamePanel.attach(this, root, panel); // PEANUTS: the game menu at the left (dev.peanuts.ingame.GameMenu) and its swipe in from the left edge // Paused (pause(): the in-game panel's Pause, or the screen coming back with pause-on-return on): the game is suspended until a tap, or A / Start on a gamepad. // Under the panel and its handle, so Stop stays reachable pausedView = new TextView(this); @@ -912,9 +913,10 @@ private void cheatsEnv(String id, Pack pack, File packDir, List env) { File folder = CheatsUi.folder(this, id), shipped = Cheats.packFile(packDir, build); try { // PEANUTS begin: was Cheats.install(shipped, folder, build, Prefs.cheatsOn(this, id)): the enabled mods' cheat files are in the one list too (ModCheats), - // the cheats a mod's own .enabled turns on are on the first time they are listed, and a mod's file that cannot be read is a note, not a start without cheats + // the cheats a mod's own .enabled turns on are on the first time they are listed, and a mod's file that cannot be read is a note, not a start without cheats; + // the player's sources are .mncf files, made ready for this build with the game's own main from the pack (dev.peanuts.mods.MncfBuild) java.util.Set con = Prefs.cheatsOn(this, id); int con0 = con.size(); List cnotes = new ArrayList<>(); - List l = ModCheats.install(shipped, folder, build, con, cheatMods, cnotes); + List l = ModCheats.install(shipped, folder, build, con, cheatMods, cnotes, CheatsBridge.known(this, id, getIntent().getStringExtra("name"), packDir.getPath()), CheatsBridge.game(id, build, packDir.getPath())); if (con.size() != con0) Prefs.cheatsOn(this, id, con); for (String n : cnotes) unknownNotes.add("[nxlaunch] Cheats: " + n); // PEANUTS end @@ -1266,6 +1268,7 @@ private void end() { // never runs beside the game (SaveUi asks SaveStore.inUse); the process ending releases it ---- private static SaveStore.Lock saveLock; private static File saveLocked; + static File runSave() { return saveLocked; } // PEANUTS: the save this game runs on, for the game menu's Back up the save (InGamePanel) private static synchronized void holdLock(File save) throws IOException { if (saveLock != null && SaveStore.same(saveLocked, save)) return; // this process holds it already (the game's screen opened again) @@ -1737,14 +1740,16 @@ private void padConnected(int id) { // through it and the game gets no pad keys. A key the panel took a press of stays the panel's until it comes up int k = e.getKeyCode(); boolean down = e.getAction() == KeyEvent.ACTION_DOWN, up = e.getAction() == KeyEvent.ACTION_UP; + if (InGamePanel.backKey(this, e)) return true; // PEANUTS: the controller's Back pressed opens the game menu, held the quick menu if (gamepad(e.getSource()) || k == KeyEvent.KEYCODE_BUTTON_MODE) { - int c = combo.key(k, down, e.getRepeatCount(), e.getEventTime()); - if (c == PadPanel.TOGGLE) { panel.padToggle(); return true; } + int c = InGamePanel.key(this, combo, k, down, e.getRepeatCount(), e.getEventTime()); // PEANUTS: Home held opens the quick menu + if (c == PadPanel.TOGGLE) { InGamePanel.toggle(this, true); return true; } // PEANUTS: Home pressed opens the game menu, or closes either menu if (c == PadPanel.EAT) { if (up) panelKeys.remove(k); return true; } // the pair's release after it fired (the panel may have taken its press) long due = combo.due(); ui.removeCallbacks(comboHeld); if (due >= 0) ui.postAtTime(comboHeld, due); // the event's time is uptimeMillis } + if (InGamePanel.menuKey(this, e, gamepad(e.getSource()))) return true; // PEANUTS: the game menu has the controller while it is open if (panel.isOpen() && gamepad(e.getSource())) { boolean took = panel.padKey(e); if (took && down) panelKeys.add(k); @@ -1789,6 +1794,7 @@ private int[] axesOf(InputDevice d, int source) { @Override public boolean onGenericMotionEvent(MotionEvent e) { if (dev.peanuts.build.ShaderCapture.active(this)) return true; // PEANUTS: no gameplay input during preparation + if (InGamePanel.menuMotion(this, e)) return true; // PEANUTS: the stick moves the game menu's selection if (panel != null && panel.isOpen() && (e.getSource() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) return panel.padMotion(e); // the panel's, never the game's if (!input || panel.isOpen() || paused || (e.getSource() & InputDevice.SOURCE_JOYSTICK) != InputDevice.SOURCE_JOYSTICK || e.getAction() != MotionEvent.ACTION_MOVE || e.getDevice() == null) return super.onGenericMotionEvent(e); @@ -1803,7 +1809,7 @@ private int[] axesOf(InputDevice d, int source) { /** Back (the phone's button or its edge swipe) opens and closes the in-game panel, which has Stop; while the controller applet's join screen shows, it cancels that */ @SuppressWarnings("deprecation") - @Override public void onBackPressed() { if (prewarmCover != null) return; /* PEANUTS: Preparing shaders has its own Close; the panel is under it */ if (dev.peanuts.build.ShaderCapture.active(this)) { dev.peanuts.build.ShaderCapture.cancel(this); return; } /* PEANUTS: Back cancels preparation */ if (panel != null && !panel.isOpen() && CtrlScreen.back()) return; if (panel != null) panel.toggle(); else end(); } + @Override public void onBackPressed() { if (prewarmCover != null) return; /* PEANUTS: Preparing shaders has its own Close; the panel is under it */ if (dev.peanuts.build.ShaderCapture.active(this)) { dev.peanuts.build.ShaderCapture.cancel(this); return; } /* PEANUTS: Back cancels preparation */ if (panel != null && !panel.isOpen() && CtrlScreen.back()) return; if (panel != null) InGamePanel.back(this); /* PEANUTS: the game menu, or one step back in the quick menu (InGamePanel) */ else end(); } // For CtrlScreen: the view tree it goes into (under the in-game panel), and whether a gamepad is connected (then the on-screen controls are hidden and cannot join) FrameLayout rootView() { return rootView; } diff --git a/android/app/src/main/java/dev/nxnative/android/InGamePanel.java b/android/app/src/main/java/dev/nxnative/android/InGamePanel.java new file mode 100644 index 00000000..498bcf20 --- /dev/null +++ b/android/app/src/main/java/dev/nxnative/android/InGamePanel.java @@ -0,0 +1,819 @@ +package dev.nxnative.android; + +import android.app.Activity; +import android.content.ClipData; +import android.content.Intent; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.net.Uri; +import android.os.Handler; +import android.os.Looper; +import android.view.InputDevice; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.function.IntConsumer; + +import dev.peanuts.ingame.GameMenu; +import dev.peanuts.ingame.GameRows; +import dev.peanuts.ingame.Look; +import dev.peanuts.ingame.Rail; + +/** + * PEANUTS: the in-game menus (the canvas "Peanuts Settings Redesign", page "In-game menus"). Upstream's one side panel becomes two menus: the game menu at the + * left (dev.peanuts.ingame.GameMenu: this session's rows, Stop) and the quick menu at the right (upstream's SidePanel with its tabs on a rail, + * dev.peanuts.ingame.Rail). A Peanuts file in upstream's launcher package, as ModsPanel, for the package-private parts of GameActivity, SidePanel and the saves. + *

    + * How they open: Home pressed, − and + held, Back and a swipe in from the left edge open the game menu; Home held (half a second, while it is still down), + * a swipe in from the right edge, a long press on the on-screen controls' button and the game menu's Quick menu row open the quick menu. Home pressed again + * closes either. B in the quick menu goes back to the game menu when that opened it, else to the game. + *

    + * GameActivity's hooks: {@link #attach} (onCreate), {@link #key} and {@link #toggle} (the controller's combination), {@link #menuKey} and {@link #menuMotion} + * (the game menu has the controller while it is open), {@link #back} (Back). SidePanel's: {@link #frame}, {@link #rail}, {@link #railFocused}, {@link #slideIn}, + * {@link #slideOut}, {@link #laid}, {@link #panelBack}. + */ +public final class InGamePanel { + private InGamePanel() {} + + private static final Handler UI = new Handler(Looper.getMainLooper()); + private static GameMenu menu; + private static SidePanel panelOf; + private static GameMenu.Item backupRow; + private static boolean fromGame; // the quick menu was opened from the game menu: B goes back there + private static boolean padOpened; // ... with a controller + private static final java.util.Map rails = new java.util.WeakHashMap<>(); + private static GameRows makingBottom; // the one menu's Game, while its panel is made (frame) + private static SidePanel bottomPanel; // the menu on the bottom screen: a second quick menu, Game first on its rail + private static dev.peanuts.ingame.BottomScreen bottomScreen; + private static int shownTab = -1; // the tab the quick menu's rows show (a new one fades in) + + // ---- GameActivity ---- + + /** onCreate, once the panel and its handle are in place: the game menu over the panel, a handle at the left edge, the rows' work */ + static void attach(Activity a, FrameLayout root, SidePanel panel) { + panelOf = panel; + float scale = PanelLook.textScale(Prefs.panelText(a)); + int size = Prefs.panelSize(a); + int screen = a.getResources().getDisplayMetrics().widthPixels; + int w = Math.round(Math.min(Look.dp(a, size == 0 ? 280 : size == 2 ? 340 : 300), screen * 0.48f)); + menu = new GameMenu(a, w, Math.round(PanelLook.rowPx(size, a.getResources().getDisplayMetrics().density) * 0.92f), scale); // a little under the panel's rows: all six and Stop fit 411 dp (the Thor) + String id = String.valueOf(a.getIntent().getStringExtra("title_id")), name = a.getIntent().getStringExtra("name"); + menu.game(name, null, dev.peanuts.Companion::startedAt); // read when the menu opens: Companion.start comes after attach + List rows = new ArrayList<>(); + rows.add(new GameMenu.Item("play", "Back to the game", false, () -> menu.close(null))); + rows.add(new GameMenu.Item("pause", "Pause the game", false, () -> menu.close(() -> { if (a instanceof GameActivity) ((GameActivity) a).pause(); }))); + quickRow = new GameMenu.Item("panel", "Quick menu", true, () -> quick(a, true, padOpened)); + rows.add(quickRow); + backupRow = new GameMenu.Item("save-up", "Back up the save", false, () -> backup(a)); + rows.add(backupRow); + rows.add(new GameMenu.Item("buttons", "Button mapping", true, () -> PadMapUi.forGame(a, game(a), () -> {}))); // applies at the next start, as its page says + rows.add(new GameMenu.Item("log", "Share log", false, () -> menu.close(() -> shareLog(a, id, name)))); + GameMenu.Item stop = new GameMenu.Item("stop", "Stop the game", false, () -> { + Native.note("stopped by the user"); + ExitWatch.stopped(); + if (a instanceof GameActivity) ((GameActivity) a).backToFrontend(); + android.os.Process.killProcess(android.os.Process.myPid()); + }); + menu.items(rows, stop); + menuRows = rows; + menuStop = stop; + a.registerActivityLifecycleCallbacks(new android.app.Application.ActivityLifecycleCallbacks() { // the game leaves the screen: the bottom one is given back + @Override public void onActivityPaused(Activity x) { if (x == a) closeBottom(true); } + @Override public void onActivityCreated(Activity x, android.os.Bundle b) {} + @Override public void onActivityStarted(Activity x) {} + @Override public void onActivityResumed(Activity x) {} + @Override public void onActivityStopped(Activity x) {} + @Override public void onActivitySaveInstanceState(Activity x, android.os.Bundle b) {} + @Override public void onActivityDestroyed(Activity x) { if (x == a) closeBottom(true); } + }); + dev.peanuts.ingame.BottomMenu.opener = () -> { if (bottomMode(a)) openBottom(a, true, false); }; + root.addView(menu, root.indexOfChild(panel) + 1, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + + // The cover (the launcher's copy of the game's icon) and the version, read off the main thread + new Thread(() -> { + File f = new File(dev.peanuts.PeanutsPrefs.iconsDir(a), id + ".png"); + Bitmap b = f.isFile() ? BitmapFactory.decodeFile(f.getPath()) : null; + if (b != null) UI.post(() -> { menu.cover(b); cover(b); }); + }, "peanuts-menu-cover").start(); + String game = a.getIntent().getStringExtra("game"); + if (game != null) GameMeta.load(new File(game), m -> { if (m != null && m.icon != null) UI.post(() -> { menu.cover(m.icon); cover(m.icon); }); if (m != null) UI.post(() -> { menu.version(m.version); version(m.version); }); }); + + // A swipe in from the left edge opens the game menu: a strip as upstream's at the right, shown while that one shows (the on-screen controls) + float dp = a.getResources().getDisplayMetrics().density; + View left = new View(a); + float[] downX = {-1}; + left.setOnTouchListener((v, e) -> { + int act = e.getActionMasked(); + if (act == MotionEvent.ACTION_DOWN) downX[0] = e.getRawX(); + else if (act == MotionEvent.ACTION_MOVE && downX[0] >= 0 && e.getRawX() - downX[0] > 24 * dp) { downX[0] = -1; openGame(a, false); } + else if (act == MotionEvent.ACTION_UP || act == MotionEvent.ACTION_CANCEL) downX[0] = -1; + return true; + }); + left.setContentDescription("Open the game menu"); + left.setFocusable(false); // never the controller's focus (its default highlight would show over the game) + left.setDefaultFocusHighlightEnabled(false); + left.setOnClickListener(v -> openGame(a, false)); + root.addView(left, root.indexOfChild(panel), new FrameLayout.LayoutParams(Math.round(20 * dp), Math.round(140 * dp), android.view.Gravity.START | android.view.Gravity.TOP)); + root.addOnLayoutChangeListener((v, l, t, r, bo, ol, ot, or, ob) -> left.setTranslationY((bo - t) * 0.3f - 70 * dp)); + root.getViewTreeObserver().addOnGlobalLayoutListener(() -> { + View right = rightHandle(root); + int vis = right != null ? right.getVisibility() : View.VISIBLE; + if (rightMode(a)) vis = View.GONE; // one menu at the right: the left edge is the game's + if (left.getVisibility() != vis) left.setVisibility(vis); + // Under gesture navigation the system takes a swipe in from either edge as Back (which opens the game menu): the two strips are kept out of + // that, so the left one opens the game menu and the right one the quick menu (140 dp each, under Android's 200 dp a side) + exclude(left); + if (right != null) exclude(right); + }); + } + + private static void exclude(View v) { + java.util.List was = v.getSystemGestureExclusionRects(); + android.graphics.Rect r = new android.graphics.Rect(0, 0, v.getWidth(), v.getHeight()); + if (v.getVisibility() != View.VISIBLE) r.setEmpty(); + if (was.size() == 1 && was.get(0).equals(r)) return; + v.setSystemGestureExclusionRects(java.util.Collections.singletonList(r)); + } + + private static View rightHandle(FrameLayout root) { + for (int i = 0; i < root.getChildCount(); i++) { + View v = root.getChildAt(i); + if ("Open the in-game panel".contentEquals(v.getContentDescription() == null ? "" : v.getContentDescription())) return v; + } + return null; + } + + private static SidePanel panel(Activity a) { return panelOf; } + private static GameMenu.Item quickRow; // the game menu's Quick menu row: B from the quick menu comes back to it + + /** The running game as the launcher's pages see it (GameActivity.game's fields, from the start's extras) */ + private static Game game(Activity a) { + Intent i = a.getIntent(); + return new Game(String.valueOf(i.getStringExtra("title_id")), String.valueOf(i.getStringExtra("name")), String.valueOf(i.getStringExtra("game")), String.valueOf(i.getStringExtra("pack"))); + } + + // Home: pressed or held. EAT on its press as upstream; held HOLD_MS while nothing has fired yet: the quick menu (while still down), its release then eaten + private static boolean homeHeld; + private static Runnable holdRun; + + /** GameActivity.dispatchKeyEvent: upstream's combination (PadPanel.Combo) with Home held for the quick menu */ + static int key(Activity a, PadPanel.Combo combo, int k, boolean down, int repeat, long t) { + int c = combo.key(k, down, repeat, t); + if (k != PadPanel.KEY_MODE || c == PadPanel.PASS) return c; + if (down) { + if (repeat == 0) { + homeHeld = false; + if (holdRun != null) UI.removeCallbacks(holdRun); + holdRun = () -> { homeHeld = true; held(a); }; + UI.postDelayed(holdRun, PadPanel.HOLD_MS); + } + return PadPanel.EAT; + } + if (holdRun != null) UI.removeCallbacks(holdRun); + if (homeHeld) { homeHeld = false; return PadPanel.EAT; } + return PadPanel.TOGGLE; + } + + /** Home or the controller's Back held: the quick menu (from the game menu when that is open), unless it is open already */ + private static void held(Activity a) { + SidePanel p = panel(a); + if (p != null && p.isOpen() || one() != null) return; + if (oneMode(a)) { if (menu != null && menu.isOpen()) menu.close(null); openOne(a, false, true); return; } + quick(a, menu != null && menu.isOpen(), true); + } + + // The controller's own Back, for a device whose Home is Android's (the AYN Thor: Home goes to the launcher and closes the game, Back is the button at the + // bottom right): pressed it opens the game menu with the controller's selection, held HOLD_MS the quick menu, as Home does elsewhere. In the quick menu + // it goes one step back as before (onBackPressed); a Back Android made from an unused B (FLAG_FALLBACK) and the edge swipe's go there too + private static boolean backDown, backHeld; + private static Runnable backRun; + + /** GameActivity.dispatchKeyEvent: true when it was the controller's Back and taken here */ + static boolean backKey(Activity a, KeyEvent e) { + if (!controllerBack(e)) return false; + if (e.getAction() == KeyEvent.ACTION_DOWN) { + if (e.getRepeatCount() > 0) return backDown; + SidePanel p = panel(a); + backDown = (p == null || !p.isOpen()) && one() == null; + if (!backDown) return false; + backHeld = false; + if (backRun != null) UI.removeCallbacks(backRun); + backRun = () -> { backHeld = true; held(a); }; + UI.postDelayed(backRun, PadPanel.HOLD_MS); + return true; + } + if (e.getAction() != KeyEvent.ACTION_UP || !backDown) return false; + backDown = false; + if (backRun != null) UI.removeCallbacks(backRun); + if (backHeld || e.isCanceled()) { backHeld = false; return true; } // a Back another app took while held (a screen swap) comes up cancelled + toggle(a, true); // the game menu, with the selection shown; or it closes + return true; + } + + /** + * Back from a controller's own key: Android gives such a key the keyboard's source alone (a gamepad's source only to its buttons), so the device tells + * it, a real one that is a gamepad. Not a Back Android made from an unused B (FLAG_FALLBACK), nor the navigation bar's or the edge swipe's + */ + private static boolean controllerBack(KeyEvent e) { + if (e.getKeyCode() != KeyEvent.KEYCODE_BACK || (e.getFlags() & KeyEvent.FLAG_FALLBACK) != 0 || e.getDeviceId() == android.view.KeyCharacterMap.VIRTUAL_KEYBOARD) return false; + InputDevice d = e.getDevice(); + return d != null && !d.isVirtual() && d.supportsSource(InputDevice.SOURCE_GAMEPAD); + } + + /** Home pressed, − and + held, the controller's Back pressed: the game menu, or either menu closes */ + static void toggle(Activity a, boolean pad) { + SidePanel o = one(); + if (o != null) { o.close(); return; } + SidePanel p = panel(a); + if (p != null && p.isOpen()) { fromGame = false; p.close(); return; } + if (menu != null && menu.isOpen()) { menu.close(null); return; } + if (oneMode(a)) { openOne(a, true, pad); return; } + openGame(a, pad); + } + + /** + * Back (the phone's button or its edge swipe, a controller's Back that backKey did not take): one step back in the quick menu, the game menu closes, + * else it opens, with the selection shown while a controller is attached. A tool that watches the keys (an accessibility service: on the AYN Thor a + * screen swap on Back held) hands the Back key on as Android's own, which no longer tells the controller's + */ + static void back(Activity a) { + SidePanel o = one(); + if (o != null) { o.close(); return; } + SidePanel p = panel(a); + if (p != null && p.isOpen()) { panelBack(p); return; } + if (menu != null && menu.isOpen()) { menu.close(null); return; } + boolean pad = padAttached(); + if (oneMode(a)) { openOne(a, true, pad); return; } + openGame(a, pad); + } + + /** A controller is attached (a real device that is a gamepad: the AYN Thor's own always is) */ + private static boolean padAttached() { + for (int id : InputDevice.getDeviceIds()) { + InputDevice d = InputDevice.getDevice(id); + if (d != null && !d.isVirtual() && d.supportsSource(InputDevice.SOURCE_GAMEPAD)) return true; + } + return false; + } + + private static void openGame(Activity a, boolean pad) { + SidePanel p = panel(a); + if (menu == null) return; + if (one() != null) one().close(); // one menu at a time + if (p != null && p.onOpen != null) p.onOpen.run(); // the game's held buttons released (GameActivity.releaseGameInput) + padOpened = pad; + menu.open(pad); + if (backupRow != null && !"Backing up".equals(backupRow.valueText())) new Thread(() -> { String v = lastBackup(a); UI.post(() -> backupRow.value(v, false)); }, "peanuts-menu-backups").start(); + } + + /** The quick menu: from the game menu (it slides out to the left while the quick menu comes in), or on its own */ + private static void quick(Activity a, boolean fromGameMenu, boolean pad) { + SidePanel p = panel(a); + if (p == null) return; + fromGame = fromGameMenu; + if (menu != null && menu.isOpen()) menu.close(null); + if (one() != null) one().close(); + if (pad) p.padToggle(); else p.open(); + } + + // The keys a menu took a press of: their release is the menu's too, also after it closed + private static final HashSet taken = new HashSet<>(); + private static int heldDir = PadPanel.NONE, stickDir = PadPanel.NONE, repeats; + private static Runnable repeat; + + /** GameActivity.dispatchKeyEvent: while the game menu is open it has the controller (D-pad and A, B); no pad key reaches the game. True when taken */ + static boolean menuKey(Activity a, KeyEvent e, boolean gamepad) { + int k = e.getKeyCode(); + boolean down = e.getAction() == KeyEvent.ACTION_DOWN, up = e.getAction() == KeyEvent.ACTION_UP; + SidePanel shown = shownPanel(a); + if (shown != null && gamepad && down && e.getRepeatCount() == 0 && k == keys(a)[0]) dev.peanuts.ui.MenuFeel.select(shown.findFocus()); // A in the quick menu + SidePanel o = one(); + if (gamepad && o != null && k != KeyEvent.KEYCODE_BACK) { // the one menu (at the right or on the bottom screen): L and R over Game and the tabs + if (down) taken.add(k); else if (up) taken.remove(k); + // The bottom screen's window never has the keys' focus, so it does not hear that a key left touch mode: it leaves it here, or the focus would + // move without its frame (SidePanel.focusMoved draws none in touch mode) + if (down && o.isInTouchMode()) { View f = o.findFocus(); if (f != null) f.requestFocusFromTouch(); } + Rail r = rails.get(o); + if ((k == KeyEvent.KEYCODE_BUTTON_L1 || k == KeyEvent.KEYCODE_BUTTON_R1) && r != null) { if (down && e.getRepeatCount() == 0) r.step(k == KeyEvent.KEYCODE_BUTTON_L1 ? -1 : 1); return true; } + o.padKey(e); + return true; + } + if (gamepad && up && taken.remove(k)) { if (PadPanel.ofKey(k) == heldDir) release(); return true; } + if (menu == null || !menu.isOpen() || !gamepad || k == KeyEvent.KEYCODE_BACK) return false; + if (down) taken.add(k); + if (!down || e.getRepeatCount() > 0) return true; + int dir = PadPanel.ofKey(k); + if (dir != PadPanel.NONE) { press(dir); return true; } + int[] cb = keys(a); + if (k == cb[0] || k == KeyEvent.KEYCODE_DPAD_CENTER || k == KeyEvent.KEYCODE_ENTER) menu.confirm(); + else if (k == cb[1]) menu.back(); + return true; + } + + /** GameActivity.onGenericMotionEvent: the stick and the hat move the game menu's selection; the game gets none of it */ + static boolean menuMotion(Activity a, MotionEvent e) { + SidePanel o = one(); + if (o != null && (e.getSource() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) return o.padMotion(e); + if (menu == null || !menu.isOpen() || (e.getSource() & InputDevice.SOURCE_JOYSTICK) != InputDevice.SOURCE_JOYSTICK) return false; + if (e.getAction() != MotionEvent.ACTION_MOVE) return true; + int d = PadPanel.stick(e.getAxisValue(MotionEvent.AXIS_HAT_X), e.getAxisValue(MotionEvent.AXIS_HAT_Y), stickDir); + if (d == PadPanel.NONE) d = PadPanel.stick(e.getAxisValue(MotionEvent.AXIS_X), e.getAxisValue(MotionEvent.AXIS_Y), stickDir); + if (d != stickDir) { + if (stickDir != PadPanel.NONE && stickDir == heldDir) release(); + stickDir = d; + if (d != PadPanel.NONE) press(d); + } + return true; + } + + private static void press(int dir) { + if (dir == heldDir) return; + heldDir = dir; + repeats = 0; + step(dir); + if (repeat != null) UI.removeCallbacks(repeat); + repeat = () -> { + if (heldDir == PadPanel.NONE || menu == null || !menu.isOpen()) return; + step(heldDir); + UI.postDelayed(repeat, PadPanel.repeatDelay(++repeats)); + }; + UI.postDelayed(repeat, PadPanel.repeatDelay(0)); + } + + private static void release() { heldDir = PadPanel.NONE; if (repeat != null) UI.removeCallbacks(repeat); } + + private static void step(int dir) { menu.move(dir == PadPanel.UP, dir == PadPanel.DOWN, dir == PadPanel.LEFT, dir == PadPanel.RIGHT); } + + /** The controller's confirm and back keys: the Switch's A and B in this game, as the panel takes them (PadPanel.confirmBack) */ + /** The quick menu while it is open (the panel's own key handling presses its rows), else null */ + private static SidePanel shownPanel(Activity a) { + if (one() != null) return one(); + SidePanel p = panel(a); + return p != null && p.isOpen() ? p : null; + } + + private static int[] keys(Activity a) { + String id = String.valueOf(a.getIntent().getStringExtra("title_id")); + return PadPanel.confirmBack(Prefs.padMap(a, id), Prefs.xboxButtons(a, id) == 2 ? 2 : 0); + } + + // ---- The game menu's rows ---- + + /** + * Back up the save while the game runs: the save the game started with (GameActivity.runSave, the player's), copied where Back up saves puts its copies + * (SaveUi.target). This process holds the save's lock, so the copy runs as SaveStore's own under it (backupLocked); the host writes a save only by an atomic + * swap at the game's Commit, and SaveStore checks the save twice around the copy, so a Commit in between fails the copy, which is tried again (3 times) + */ + private static void backup(Activity a) { + File save = GameActivity.runSave(); + if (save == null) { backupRow.value("No save yet", false); return; } + Game g = game(a); + File to = SaveUi.target(a, g); + backupRow.value("Backing up", false); + menu.note(null, false); + new Thread(() -> { + String err = null; + SaveStore.Backup b = null; + for (int i = 0; i < 3 && b == null; i++) { + try { b = SaveStore.backupLocked(save, to, SaveUi.stamp()); err = null; } + catch (IOException | RuntimeException e) { + err = String.valueOf(e.getMessage()); + if (!err.contains("changed while")) break; + try { Thread.sleep(400); } catch (InterruptedException ie) { break; } + } + } + SaveStore.Backup done = b; + String why = err; + if (why != null) Native.note("[RED] [peanuts] in-game save backup: " + why); + else Native.note("save backed up from the game menu: " + done.files + " files, " + done.bytes + " bytes"); + UI.post(() -> { + if (done != null) { backupRow.value("Just now", false); return; } + backupRow.value("Not backed up", true); + menu.note(why.contains("no save folder") ? "This game has no save yet." + : why.contains("changed while") ? "The game kept saving while it was copied. Try again in a moment." + : "The backup did not finish. The save was only read, never changed.", true); + }); + }, "peanuts-menu-backup").start(); + } + + /** The newest backup of the running save, as "Today 14:02" (null: none) */ + private static String lastBackup(Activity a) { + try { + File dir = SaveUi.target(a, game(a)); + long newest = 0; + for (SaveStore.Backup b : SaveStore.list(dir)) newest = Math.max(newest, b.dir.lastModified()); + if (newest == 0) return null; + Calendar now = Calendar.getInstance(), then = Calendar.getInstance(); + then.setTimeInMillis(newest); + String hm = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date(newest)); + if (now.get(Calendar.YEAR) == then.get(Calendar.YEAR) && now.get(Calendar.DAY_OF_YEAR) == then.get(Calendar.DAY_OF_YEAR)) return "Today " + hm; + now.add(Calendar.DAY_OF_YEAR, -1); + if (now.get(Calendar.YEAR) == then.get(Calendar.YEAR) && now.get(Calendar.DAY_OF_YEAR) == then.get(Calendar.DAY_OF_YEAR)) return "Yesterday " + hm; + return new SimpleDateFormat("d MMM", Locale.getDefault()).format(new Date(newest)); + } catch (RuntimeException e) { + return null; + } + } + + /** Share log from the game menu: the game's newest run (this one, so far) or its build, as everywhere (BuildLogUi.shareLog) */ + private static void shareLog(Activity a, String id, String name) { + dev.peanuts.ui.BuildLogUi.shareLog(a, id, name, null, () -> { + File log = newestRun(a, id); + if (log == null) { android.widget.Toast.makeText(a, "No log of this game yet.", android.widget.Toast.LENGTH_LONG).show(); return; } + Uri uri = LogProvider.uri(log); + Intent send = new Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_STREAM, uri).putExtra(Intent.EXTRA_SUBJECT, "nxnative log " + log.getName()); + send.setClipData(ClipData.newRawUri(log.getName(), uri)); + send.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + a.startActivity(Intent.createChooser(send, "Share " + log.getName())); + }); + } + + private static File newestRun(Activity a, String id) { + File ext = a.getExternalFilesDir(null); + String t = id.trim().toUpperCase(Locale.ROOT) + "-"; + File[] l = ext == null ? null : new File(ext, "logs").listFiles((d, n) -> n.endsWith(".log") && n.toUpperCase(Locale.ROOT).startsWith(t)); + if (l == null || l.length == 0) return null; + File best = l[0]; + for (File f : l) if (f.lastModified() > best.lastModified()) best = f; + return best; + } + + // ---- SidePanel: the quick menu ---- + + /** SidePanel's constructor: its sheet as rail | (header over rows) */ + static void frame(SidePanel p, LinearLayout sheet, LinearLayout tabs, ScrollView rows) { + rails.put(p, new Rail(p.getContext(), sheet, tabs, rows, () -> panelBack(p), makingBottom)); + // Each step of the controller's focus in the quick menu: the fine tick (and the menu sound when on); a touch moves no focus + p.getViewTreeObserver().addOnGlobalFocusChangeListener((old, now) -> { + if (now == null || !p.isOpen() || p.isInTouchMode() || !within(now, sheet)) return; + View chosen = dev.peanuts.ui.PanelPolish.chosen(old, now); // into a track of choices, or the first focus there: onto the chosen one + // After this change has reached every listener: moved inside it, SidePanel's frame would be drawn for this change after the next one's + if (chosen != null) { chosen.post(() -> { if (p.isOpen() && now.isFocused()) chosen.requestFocus(); }); return; } + if (old != null) dev.peanuts.ui.MenuFeel.move(now); // a step ticks; the first focus of an opening has the opening's sound + }); + } + + private static boolean within(View v, View in) { + for (Object o = v; o instanceof View; o = ((View) o).getParent()) if (o == in) return true; + return false; + } + + /** SidePanel.tabBar: the rail instead of the bar (true: done); show switches the tab */ + static boolean rail(SidePanel p, int tab, IntConsumer show) { + Rail r = rails.get(p); + if (r == null) return false; + r.action(null, null, null); // a tab's build sets its own again (ModsTab: All off) + r.tabs(SidePanel.TAB_NAMES, tab, show); + return true; + } + + /** ModsPanel's tabs: their own action in the header (the Cheats tab's All off) */ + static void action(SidePanel p, String key, String label, Runnable run) { Rail r = rails.get(p); if (r != null) r.action(key, label, run); } + + /** SidePanel.showTab: a tab switched from the rail keeps the controller's focus on the rail */ + static boolean railFocused() { for (Rail r : rails.values()) if (r.focused()) return true; return false; } + + /** SidePanel.open: the sheet slides in (OPEN_MS, decelerating), the scrim fades in */ + static void slideIn(SidePanel p, View sheet) { + dev.peanuts.ui.MenuFeel.open(sheet); + View scrim = p.getChildAt(0); + sheet.animate().cancel(); + if (p == bottomPanel) { // up from the bottom edge, decelerating; the live stats behind it dim, and the game on the top screen a little + bottomSheet(p, sheet); + if (p.getContext() instanceof Activity) dimTop((Activity) p.getContext(), true); + sheet.setTranslationX(0); + sheet.setTranslationY(p.getResources().getDisplayMetrics().heightPixels); + sheet.animate().translationY(0).setDuration(Look.UP_MS).setInterpolator(Look.OUT).withLayer().start(); + if (scrim != null && scrim != sheet) { scrim.animate().cancel(); scrim.setAlpha(0f); scrim.animate().alpha(1f).setDuration(Look.UP_MS).setInterpolator(Look.OUT).start(); } + return; + } + sheet.setTranslationX(sheet.getLayoutParams().width); + sheet.animate().translationX(0).setDuration(Look.OPEN_MS).setInterpolator(Look.OUT).withLayer().start(); + if (scrim != null && scrim != sheet) { scrim.animate().cancel(); scrim.setAlpha(0f); scrim.animate().alpha(1f).setDuration(Look.OPEN_MS).setInterpolator(Look.OUT).start(); } + shownTab = -1; + } + + /** SidePanel.close: the sheet slides out (CLOSE_MS, accelerating), the scrim fades; then gone (end) */ + static void slideOut(SidePanel p, View sheet, Runnable end) { + dev.peanuts.ui.MenuFeel.back(sheet); + View scrim = p.getChildAt(0); + sheet.animate().cancel(); + if (p == bottomPanel) { // back down, accelerating; then the window goes and the screen is given back + if (p.getContext() instanceof Activity) dimTop((Activity) p.getContext(), false); + sheet.animate().translationY(Math.max(sheet.getHeight(), 1)).setDuration(Look.DOWN_MS).setInterpolator(Look.IN).withLayer().withEndAction(() -> { end.run(); closeBottom(false); }).start(); + if (scrim != null && scrim != sheet) scrim.animate().alpha(0f).setDuration(Look.DOWN_MS).setInterpolator(Look.IN).start(); + return; + } + sheet.animate().translationX(sheet.getLayoutParams().width).setDuration(Look.CLOSE_MS).setInterpolator(Look.IN).withLayer().withEndAction(end).start(); + if (scrim != null && scrim != sheet) scrim.animate().alpha(0f).setDuration(Look.CLOSE_MS).setInterpolator(Look.IN).start(); + } + + /** SidePanel.padKey's back key, the header's back button: back to the game menu when that opened the quick menu, else to the game */ + static void panelBack(SidePanel p) { + if (p == bottomPanel || p == rightPanel) { p.close(); return; } + boolean back = fromGame; + fromGame = false; + p.close(); + if (back && p.getContext() instanceof Activity) { + openGame((Activity) p.getContext(), padOpened || !p.isInTouchMode()); + if (menu != null && quickRow != null) menu.at(quickRow); // back on the row it came from, as a console's menus do + } + } + + /** + * SidePanel.look, after a tab is built: what the two menus moved. General (the menu's own settings) keeps the panel's size and text size and Pause when the + * game comes back; Pause, Stop and Back to the game are the game menu's. Controls' Button mapping is the game menu's too. A tab switched to fades in + */ + static void laid(SidePanel p, LinearLayout box, int tab) { + String name = tab >= 0 && tab < SidePanel.TAB_NAMES.length ? SidePanel.TAB_NAMES[tab] : ""; + if (p == bottomPanel) bottomSheet(p, p.getChildAt(1)); + if ("General".equals(name)) { + for (int i = box.getChildCount() - 1; i >= 0; i--) { + View v = box.getChildAt(i); + if (!(v instanceof TextView)) continue; + String s = String.valueOf(((TextView) v).getText()); + if (s.equals("Pause the game") || s.equals("Stop the game") || s.equals("Back to the game") || s.startsWith("The game runs on behind this panel")) box.removeViewAt(i); + else if (s.equalsIgnoreCase("Panel")) ((TextView) v).setText("Menu"); + else if (s.startsWith("Pause when the game comes back") && i > 0) box.addView(head(p, "This game"), i); + } + feelSwitches(p, box); + layoutSetting(p, box); + } else if ("Controls".equals(name)) { + View map = box.findViewById(5300); // SidePanel.ID_MAP: Button mapping, now the game menu's + if (map != null && map.getParent() == box) { + int i = box.indexOfChild(map); + box.removeViewAt(i); + View before = i > 0 ? box.getChildAt(i - 1) : null; // "Next start" with nothing under it + if (before instanceof TextView && "Next start".contentEquals(((TextView) before).getText()) && i - 1 == box.getChildCount() - 1) box.removeViewAt(i - 1); + } + } + dev.peanuts.ui.PanelPolish.apply(box); + if (shownTab >= 0 && shownTab != tab && p.isOpen()) { // a tab switched to: its rows come up 8 dp and fade in + dev.peanuts.ui.MenuFeel.tab(box); + box.setAlpha(0f); + box.setTranslationY(Look.dp(p.getContext(), 8)); + box.animate().alpha(1f).translationY(0f).setStartDelay(Look.TAB_OUT_MS).setDuration(Look.TAB_IN_MS).setInterpolator(Look.OUT).withLayer().start(); + } + shownTab = tab; + } + + /** The menu's feel in its own settings, at the end of its Menu section: Vibrate on each step (on), Menu sounds (off) (dev.peanuts.ui.MenuFeel) */ + private static void feelSwitches(SidePanel p, LinearLayout box) { + android.content.Context c = p.getContext(); + int at = box.getChildCount(); + for (int i = 0; i < box.getChildCount(); i++) { + View v = box.getChildAt(i); + if (v instanceof TextView && !(v instanceof android.widget.CompoundButton) && "This game".contentEquals(((TextView) v).getText())) { at = i; break; } + } + android.widget.CheckBox vib = new android.widget.CheckBox(c), snd = new android.widget.CheckBox(c); + vib.setText("Vibrate on each step"); + vib.setChecked(dev.peanuts.ui.MenuFeel.haptics(c)); + vib.setOnCheckedChangeListener((b, on) -> { dev.peanuts.ui.MenuFeel.haptics(c, on); if (on) dev.peanuts.ui.MenuFeel.select(b); }); + snd.setText("Menu sounds"); + snd.setChecked(dev.peanuts.ui.MenuFeel.sounds(c)); + snd.setOnCheckedChangeListener((b, on) -> { dev.peanuts.ui.MenuFeel.sounds(c, on); if (on) dev.peanuts.ui.MenuFeel.select(b); }); + box.addView(vib, at); + box.addView(snd, at + 1); + ModsPanel.style(c, vib); + ModsPanel.style(c, snd); + } + + private static TextView head(SidePanel p, String s) { + TextView h = new TextView(p.getContext()); + h.setText(s); + h.setTypeface(android.graphics.Typeface.DEFAULT_BOLD); + h.setTextSize(15); + h.setPadding(0, Math.round(18 * p.getResources().getDisplayMetrics().density), 0, 0); + return h; + } + + // ---- One menu instead of two (Menu settings › Layout; two menus by default): at the right over the game, or on the bottom screen of a dual-screen + // device such as the AYN Thor. Each is a second quick menu (upstream's SidePanel, the same rows) whose rail starts with Game, the game menu's rows ---- + + private static SidePanel rightPanel; // one menu at the right, in the game's window + private static GameRows gameRows, rightRows; // Game on the bottom screen's menu, on the right one + private static List menuRows; // the game menu's rows and Stop, for Game + private static GameMenu.Item menuStop; + private static Bitmap cover; + private static String version; + + /** The one menu that is open (at the right or on the bottom screen), else null */ + private static SidePanel one() { + if (bottomPanel != null && bottomPanel.isOpen()) return bottomPanel; + if (rightPanel != null && rightPanel.isOpen()) return rightPanel; + return null; + } + + /** Whether Home, Back and − + open one menu instead of the game menu and the quick menu */ + static boolean oneMode(Activity a) { return dev.peanuts.PeanutsPrefs.menuLayout(a) != dev.peanuts.PeanutsPrefs.LAYOUT_TWO; } + + /** Whether the one menu is the bottom screen's: that layout and a second display now */ + static boolean bottomMode(Activity a) { + if (dev.peanuts.PeanutsPrefs.menuLayout(a) != dev.peanuts.PeanutsPrefs.LAYOUT_BOTTOM) return false; + android.hardware.display.DisplayManager dm = (android.hardware.display.DisplayManager) a.getSystemService(android.content.Context.DISPLAY_SERVICE); + return dm != null && dev.peanuts.Companion.second(a, dm) != null; + } + + /** Whether the one menu is at the right (that layout, or the bottom screen's without a second display now) */ + static boolean rightMode(Activity a) { return oneMode(a) && !bottomMode(a); } + + /** Opens the one menu on Game (onGame) or on the tab shown last; pad: a controller opened it, the focus shows at once */ + private static void openOne(Activity a, boolean onGame, boolean pad) { if (bottomMode(a)) openBottom(a, onGame, pad); else openRight(a, onGame, pad); } + + /** + * SidePanel.open: with one menu at the right, what opens the quick menu (the swipe in from the right edge, the on-screen controls' button) opens that + * menu on the tab shown last instead. True when it did + */ + static boolean instead(SidePanel p) { + if (p != panelOf || !(p.getContext() instanceof Activity) || !rightMode((Activity) p.getContext())) return false; + openRight((Activity) p.getContext(), false, !p.isInTouchMode()); + return true; + } + + /** Game's rows for one menu (host): the game menu's without Quick menu (the rail is there), Back to the game and Pause closing that menu */ + private static GameRows gameRows(Activity a, java.util.function.Supplier host) { + GameRows g = new GameRows(a, PanelLook.rowPx(Prefs.panelSize(a), a.getResources().getDisplayMetrics().density)); + g.game(a.getIntent().getStringExtra("name"), version, dev.peanuts.Companion.startedAt()); + if (cover != null) g.cover(cover); + List some = new ArrayList<>(); + for (GameMenu.Item it : menuRows) { + if ("Quick menu".equals(it.title())) continue; + if ("Back to the game".equals(it.title())) some.add(new GameMenu.Item(it.icon(), it.title(), false, () -> { if (host.get() != null) host.get().close(); })); + else if ("Pause the game".equals(it.title())) some.add(new GameMenu.Item(it.icon(), it.title(), false, () -> { if (host.get() != null) host.get().close(); if (a instanceof GameActivity) ((GameActivity) a).pause(); })); + else some.add(it); + } + g.items(some, menuStop); + return g; + } + + /** The cover and the version, once read: the game menu has its own, Game's rows take them too */ + private static void cover(Bitmap b) { cover = b; if (gameRows != null) gameRows.cover(b); if (rightRows != null) rightRows.cover(b); } + private static void version(String v) { version = v; if (gameRows != null) gameRows.version(v); if (rightRows != null) rightRows.version(v); } + + /** A one menu made: its rail with Game (frame takes makingBottom), the controller's buttons, the game's input released when it opens */ + private static SidePanel oneMenu(Activity a, GameRows g) { + SidePanel p; + makingBottom = g; + try { p = new SidePanel(a, panelOf.rows()); } finally { makingBottom = null; } + p.padButtons(keys(a)); + p.onOpen = panelOf.onOpen; + return p; + } + + /** A one menu slides in, on Game (onGame) or on the tab shown last; with the controller (pad) the focus on Game's first row or the panel's */ + private static void show(SidePanel p, GameRows g, boolean onGame, boolean pad) { + g.refresh(); + if (pad) p.padToggle(); else p.open(); + Rail r = rails.get(p); + if (onGame && r != null) { + r.game(); + if (pad) p.post(() -> { View f = r.firstGameRow(); if (f != null) f.requestFocusFromTouch(); }); + } + } + + /** Opens one menu at the right, over the game as the quick menu is (in the game's window, above the quick menu) */ + static void openRight(Activity a, boolean onGame, boolean pad) { + if (panelOf == null || !(panelOf.getParent() instanceof ViewGroup) || menuRows == null) return; + if (rightPanel == null) { + rightRows = gameRows(a, () -> rightPanel); + rightPanel = oneMenu(a, rightRows); + ViewGroup root = (ViewGroup) panelOf.getParent(); + root.addView(rightPanel, root.indexOfChild(panelOf) + 1, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + } + if (rightPanel.isOpen()) return; + if (panelOf.isOpen()) panelOf.close(); + if (menu != null && menu.isOpen()) menu.close(null); + if (bottomPanel != null && bottomPanel.isOpen()) bottomPanel.close(); + show(rightPanel, rightRows, onGame, pad); + } + + /** + * Opens the bottom screen's menu: its window on the second display (BottomScreen), the panel sliding up in it, on Game (onGame) or on the tab shown last. + * pad: a controller opened it, the focus shows at once. Without a second display now, the one menu at the right opens instead + */ + static void openBottom(Activity a, boolean onGame, boolean pad) { + android.hardware.display.DisplayManager dm = (android.hardware.display.DisplayManager) a.getSystemService(android.content.Context.DISPLAY_SERVICE); + android.view.Display d = dm == null ? null : dev.peanuts.Companion.second(a, dm); + if (d == null || panelOf == null || menuRows == null) { openRight(a, onGame, pad); return; } + if (bottomPanel == null) { + gameRows = gameRows(a, () -> bottomPanel); + bottomPanel = oneMenu(a, gameRows); + } + if (bottomPanel.isOpen()) return; + if (panelOf.isOpen()) panelOf.close(); + if (menu != null && menu.isOpen()) menu.close(null); + if (rightPanel != null && rightPanel.isOpen()) rightPanel.close(); + if (bottomScreen == null) { + try { bottomScreen = new dev.peanuts.ingame.BottomScreen(a, d, bottomPanel); bottomScreen.show(); } + catch (RuntimeException e) { Native.note("[RED] [peanuts] the bottom screen's menu could not open: " + e); bottomScreen = null; openRight(a, onGame, pad); return; } + } + show(bottomPanel, gameRows, onGame, pad); + } + + private static View topDim; // the game on the top screen, dimmed a little while the bottom screen's menu is open: it runs on, but is not being played + + /** The top screen's dim in (with the bottom menu's slide up) or out (with its slide down); a touch on it closes the menu, as a scrim's does */ + private static void dimTop(Activity a, boolean on) { + if (panelOf == null || !(panelOf.getParent() instanceof ViewGroup)) return; + if (topDim == null) { + topDim = new View(a); + topDim.setBackgroundColor(0x66000000); // SidePanel's scrim + topDim.setAlpha(0f); + topDim.setVisibility(View.GONE); + topDim.setFocusable(false); + topDim.setOnClickListener(v -> { if (bottomPanel != null && bottomPanel.isOpen()) bottomPanel.close(); }); + ViewGroup root = (ViewGroup) panelOf.getParent(); + root.addView(topDim, root.indexOfChild(panelOf), new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + } + View d = topDim; + d.animate().cancel(); + if (on) { + d.setVisibility(View.VISIBLE); + d.animate().alpha(1f).setDuration(Look.UP_MS).setInterpolator(Look.OUT).start(); + } else { + d.animate().alpha(0f).setDuration(Look.DOWN_MS).setInterpolator(Look.IN).withEndAction(() -> { if (d.getAlpha() == 0f) d.setVisibility(View.GONE); }).start(); + } + } + + /** The bottom screen's window goes (after the panel slid down, or at once: the game left the screen) */ + static void closeBottom(boolean now) { + if (now && bottomPanel != null && bottomPanel.isOpen()) { bottomPanel.close(); } + if (now && topDim != null) { topDim.animate().cancel(); topDim.setAlpha(0f); topDim.setVisibility(View.GONE); } + if (bottomScreen == null) return; + if (!now && bottomPanel != null && bottomPanel.isOpen()) return; + dev.peanuts.ingame.BottomScreen s = bottomScreen; + bottomScreen = null; + s.release(); + try { s.dismiss(); } catch (RuntimeException ignored) { } + } + + /** The bottom sheet: the whole width of the bottom screen under a strip of what is behind it, its top corners round */ + private static void bottomSheet(SidePanel p, View sheet) { + if (sheet == null) return; + android.widget.FrameLayout.LayoutParams lp = (android.widget.FrameLayout.LayoutParams) sheet.getLayoutParams(); + int top = Look.dp(p.getContext(), 18); + if (lp.width != ViewGroup.LayoutParams.MATCH_PARENT || lp.topMargin != top) { + lp.width = ViewGroup.LayoutParams.MATCH_PARENT; + lp.topMargin = top; + lp.gravity = android.view.Gravity.BOTTOM; + sheet.setLayoutParams(lp); + } + if (!(sheet.getBackground() instanceof android.graphics.drawable.GradientDrawable)) { + float r = Look.dp(p.getContext(), 18); + android.graphics.drawable.GradientDrawable bg = new android.graphics.drawable.GradientDrawable(); + bg.setColor(0xFF202124); + bg.setCornerRadii(new float[] {r, r, r, r, 0, 0, 0, 0}); + sheet.setBackground(bg); + sheet.setClipToOutline(true); + } + } + + /** General (the menu's own settings): Layout, two menus, one menu at the right, or (a device with a second screen) one menu on the bottom screen */ + private static void layoutSetting(SidePanel p, LinearLayout box) { + Activity a = (Activity) p.getContext(); + box.addView(head(p, "Layout")); + boolean second = dev.peanuts.Companion.hasSecondDisplay(a); + String[] names = {"Two menus: the game at the left, settings at the right", "One menu at the right", "One menu on the bottom screen"}; + String[] notes = { + "Home or Back opens the game menu at the left, held the quick menu at the right.", + "Home or Back opens one menu at the right with Game first; held, on the tab shown last.", + "Home or Back opens one menu on the bottom screen, and the game stays in full view on top."}; + android.widget.RadioGroup g = new android.widget.RadioGroup(a); + int[] ids = new int[names.length]; + for (int i = 0; i < names.length; i++) { + if (i == dev.peanuts.PeanutsPrefs.LAYOUT_BOTTOM && !second) continue; + android.widget.RadioButton b = new android.widget.RadioButton(a); + ids[i] = View.generateViewId(); + b.setId(ids[i]); + b.setText(names[i]); + g.addView(b); + } + int now = dev.peanuts.PeanutsPrefs.menuLayout(a); + if (now == dev.peanuts.PeanutsPrefs.LAYOUT_BOTTOM && !second) now = dev.peanuts.PeanutsPrefs.LAYOUT_RIGHT; + g.check(ids[now]); + box.addView(g); + TextView n = new TextView(a); + n.setText(notes[now]); + n.setTextSize(12); + n.setTextColor(android.graphics.Color.LTGRAY); + box.addView(n); + g.setOnCheckedChangeListener((group, id) -> { + for (int i = 0; i < ids.length; i++) if (ids[i] == id && id != 0) { dev.peanuts.PeanutsPrefs.menuLayout(a, i); n.setText(notes[i]); } + }); + } +} diff --git a/android/app/src/main/java/dev/nxnative/android/ModCheats.java b/android/app/src/main/java/dev/nxnative/android/ModCheats.java index e3394748..f0e437fe 100644 --- a/android/app/src/main/java/dev/nxnative/android/ModCheats.java +++ b/android/app/src/main/java/dev/nxnative/android/ModCheats.java @@ -12,6 +12,8 @@ import dev.peanuts.mods.CheatFile; import dev.peanuts.mods.CheatSources; +import dev.peanuts.mods.MncfBuild; +import dev.peanuts.mods.MncfConvert; /** * PEANUTS: the one merged cheat file a start hands the host (DM_CHEATS), from the game's cheat sources (dev.peanuts.mods.CheatSources: the cheats that come @@ -29,6 +31,9 @@ *

  • A mod's file that cannot be read is left out with a note; the other cheats are installed.
  • *
  • Upstream's earlier imports (<folder>/imported/) become sources first (CheatSources.migrate); a toggle kept as "Name (imported)" is given the cheat's new * key as well.
  • + *
  • The player's sources are .mncf files (CheatSources): each is made ready for the build that runs (dev.peanuts.mods.MncfBuild, with the game's own main + * from the pack) and goes into the merged file as Atmosphère code, which the host runs as before. Sources an earlier version kept as Atmosphère files + * become .mncf first (CheatSources.upgrade).
  • * */ final class ModCheats { @@ -100,9 +105,10 @@ static List of(List modCheatDirs, String build, List note * The merge's blocks: the app's file (shipped) and the player's sources (CheatSources.blocks), upstream's imported files of this build that are still in * imported/ (each as a source of its own, by its file name), then the mods' files; textEnd as CheatFile.parse takes it */ - static List blocks(String shipped, File folder, String build, List mods, long textEnd) { + static List blocks(String shipped, File folder, MncfBuild.Game g, List mods, long textEnd, boolean make) { Boolean appOn = CheatSources.appEnabled(folder); - List blocks = CheatSources.blocks(folder, shipped, appOn == null || appOn, build, textEnd); + List blocks = CheatSources.blocks(folder, shipped, appOn == null || appOn, g, textEnd, make); + String build = g.build; try { for (Cheats.Named n : Cheats.importedOf(folder, build)) blocks.add(new CheatSources.Block(IMPORTED + n.label, n.label, true, CheatFile.parse(n.text, textEnd))); } catch (IOException e) { /* an imported file that cannot be read: left out, as a source's */ } @@ -131,10 +137,18 @@ static void legacyKeys(Set on, List moved, CheatSou * added to: the cheats a mod's own .enabled names, the first time they enter the list, and an earlier import's renamed keys (the caller keeps on when it grew) */ static List install(File shipped, File folder, String build, Set on, List modCheatDirs, List notes) throws IOException { + return install(shipped, folder, build, on, modCheatDirs, notes, new MncfConvert.Known(folder.getName(), null, null, null, null, null), new MncfBuild.Game(folder.getName(), build, null, null)); + } + + /** The same; known: what a conversion of an earlier file knows (CheatsBridge.known), g: the game for the .mncf sources (its pack: the game's own main) */ + static List install(File shipped, File folder, String build, Set on, List modCheatDirs, List notes, MncfConvert.Known known, MncfBuild.Game g) throws IOException { List mods = of(modCheatDirs, build, notes); - List moved = CheatSources.migrate(folder, System.currentTimeMillis()); + List moved = CheatSources.migrate(folder, System.currentTimeMillis(), known); + CheatSources.upgrade(folder, known); String s = shipped != null ? new String(Files.readAllBytes(shipped.toPath()), StandardCharsets.UTF_8) : ""; - CheatSources.Merged m = CheatSources.merge(blocks(s, folder, build, mods, -1), dev.peanuts.mods.CheatValues.read(folder)); // with the numbers set in the game's Mods tab + List blocks = blocks(s, folder, g, mods, -1, true); + if (notes != null) for (CheatSources.Block b : blocks) if (b.error != null) notes.add("the cheat file of " + b.name + " cannot be used (" + b.error + ")"); + CheatSources.Merged m = CheatSources.merge(blocks, dev.peanuts.mods.CheatValues.read(folder)); // with the numbers set in the game's Mods tab legacyKeys(on, moved, m); if (!folder.isDirectory() && !folder.mkdirs()) throw new IOException("cannot create " + folder); File[] old = folder.listFiles((d, n) -> n.endsWith(".txt") || n.endsWith(".enabled")); diff --git a/android/app/src/main/java/dev/nxnative/android/ModsPanel.java b/android/app/src/main/java/dev/nxnative/android/ModsPanel.java index 5b9e2d17..4656495d 100644 --- a/android/app/src/main/java/dev/nxnative/android/ModsPanel.java +++ b/android/app/src/main/java/dev/nxnative/android/ModsPanel.java @@ -32,15 +32,25 @@ final class ModsPanel { private ModsPanel() {} - static final String MODS = "Mods"; - private static final String[] BASE = {"Performance", "Display", "Controls", "General"}, WITH = {"Performance", "Display", "Controls", MODS, "General"}; - private static boolean shows, opened; + static final String MODS = "Mods", CHEATS = "Cheats"; + private static final String[] BASE = {"Performance", "Display", "Controls", "General"}; + private static boolean shows, opened; // shows: the Cheats tab shows (General's cheat switches go there) /** SidePanel.open: the tabs (SidePanel.TAB_NAMES, TAB_GENERAL) and the tab to open on; tab: the one the panel has now */ static int opening(SidePanel p, Activity a, String titleId, int tab) { String was = SidePanel.TAB_NAMES[Math.min(tab, SidePanel.TAB_NAMES.length - 1)]; - shows = ModsTab.wanted(a, titleId, a.getIntent().getStringExtra("game"), a.getIntent().getStringExtra("pack")); - SidePanel.TAB_NAMES = shows ? WITH : BASE; + // The quick menu's tabs (InGamePanel, dev.peanuts.ingame.Rail): Performance, Display, Cheats, Mods, Controls, General (the menu's own settings). + // Cheats and Mods each only when there is something to show (ModsTab.wanted, by half) + String g = a.getIntent().getStringExtra("game"), pk = a.getIntent().getStringExtra("pack"); + shows = ModsTab.wanted(a, titleId, g, pk, ModsTab.CHEATS); + boolean mods = ModsTab.wanted(a, titleId, g, pk, ModsTab.MODS); + java.util.List names = new java.util.ArrayList<>(java.util.Arrays.asList("Performance", "Display")); + if (shows) names.add(CHEATS); + if (mods) names.add(MODS); + names.add("Controls"); + names.add("General"); + SidePanel.TAB_NAMES = names.toArray(new String[0]); + SidePanel.TAB_CONTROLS = names.indexOf("Controls"); SidePanel.TAB_GENERAL = SidePanel.TAB_NAMES.length - 1; String want = opened ? was : ModsTab.lastTab(a); // the first opening of this run: the tab shown last, in this run or an earlier one opened = true; @@ -52,11 +62,12 @@ static int opening(SidePanel p, Activity a, String titleId, int tab) { static boolean build(SidePanel p, Activity a, LinearLayout box, int tab) { String name = SidePanel.TAB_NAMES[Math.min(tab, SidePanel.TAB_NAMES.length - 1)]; ModsTab.lastTab(a, name); - if (!MODS.equals(name)) { ModsTab.left(); return false; } + if (!MODS.equals(name) && !CHEATS.equals(name)) { ModsTab.left(); return false; } ModsTab.fill(a, box, new ModsTab.Host() { @Override public void close() { p.close(); } @Override public void style(View v) { ModsPanel.style(a, v); } - }); + @Override public void action(String key, String label, Runnable run) { InGamePanel.action(p, key, label, run); } + }, CHEATS.equals(name) ? ModsTab.CHEATS : ModsTab.MODS); return true; } diff --git a/android/app/src/main/java/dev/nxnative/android/SaveStore.java b/android/app/src/main/java/dev/nxnative/android/SaveStore.java index 0d29179e..3f110133 100644 --- a/android/app/src/main/java/dev/nxnative/android/SaveStore.java +++ b/android/app/src/main/java/dev/nxnative/android/SaveStore.java @@ -350,7 +350,7 @@ static Backup backup(File save, File backups, String name) throws IOException { } } - private static Backup backupLocked(File save, File backups, String name) throws IOException { + static Backup backupLocked(File save, File backups, String name) throws IOException { // PEANUTS: not private (InGamePanel: the game menu's Back up the save, under the running game's own lock) recoverLocked(save); Map parts = parts(save); if (!save.isDirectory() && !parts.containsKey(DEVICE)) throw new IOException("there is no save folder at " + save); diff --git a/android/app/src/main/java/dev/nxnative/android/SidePanel.java b/android/app/src/main/java/dev/nxnative/android/SidePanel.java index 4a26e5a2..c2bab7a1 100644 --- a/android/app/src/main/java/dev/nxnative/android/SidePanel.java +++ b/android/app/src/main/java/dev/nxnative/android/SidePanel.java @@ -45,7 +45,7 @@ final class SidePanel extends FrameLayout { // The tabs: each a builder of its own (build); Performance's rows refresh twice a second while it shows static String[] TAB_NAMES = {"Performance", "Display", "Controls", "General"}; // PEANUTS: not final, ModsPanel.opening puts Mods between Controls and General - private static final int TAB_PERF = 0, TAB_DISPLAY = 1, TAB_CONTROLS = 2; static int TAB_GENERAL = 3; // PEANUTS: TAB_GENERAL not final, the last tab (4 while Mods shows: ModsPanel) + private static final int TAB_PERF = 0, TAB_DISPLAY = 1; static int TAB_CONTROLS = 2, TAB_GENERAL = 3; // PEANUTS: TAB_CONTROLS and TAB_GENERAL not final: ModsPanel puts Cheats and Mods before Controls, General last private int tab = TAB_PERF; private static final int FOCUS = 0xFFFFD54F; // the tab bar's selected tab and the focus frame: a banana yellow, dark text on it @@ -91,6 +91,7 @@ interface Rows { sh.addView(scroll, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)); addView(sh, new LayoutParams(PanelLook.widthPx(Prefs.panelSize(a), dp, a.getResources().getDisplayMetrics().widthPixels), LayoutParams.MATCH_PARENT, Gravity.END)); sheet = sh; + InGamePanel.frame(this, sh, tabs, scroll); // PEANUTS: the quick menu, its tabs on a rail at the left with a header over the rows (dev.peanuts.ingame.Rail) getViewTreeObserver().addOnGlobalFocusChangeListener(this::focusMoved); setVisibility(GONE); } @@ -99,12 +100,14 @@ interface Rows { void padButtons(int[] cb) { confirm = cb[0]; back = cb[1]; } boolean isOpen() { return open; } + Rows rows() { return rows; } // PEANUTS: the bottom screen's menu builds the same rows (InGamePanel) void toggle() { if (open) close(); else open(); } /** Opened or closed by a controller (GameActivity: Home, or − and + held): opened, the focus on its first row, out of touch mode */ void padToggle() { if (open) close(); else { open(); post(this::ensureFocus); } } void open() { if (open) return; + if (InGamePanel.instead(this)) return; // PEANUTS: with one menu at the right, the swipe and the controls' button open that menu instead open = true; if (onOpen != null) onOpen.run(); box.removeAllViews(); @@ -112,8 +115,7 @@ void open() { build(); look(); setVisibility(VISIBLE); - sheet.setTranslationX(sheet.getLayoutParams().width); - sheet.animate().translationX(0).setDuration(180).start(); + InGamePanel.slideIn(this, sheet); // PEANUTS: in from the right, decelerating, the scrim fading in (dev.peanuts.ingame.Look's motion) post(() -> { if (open && !isInTouchMode()) focusFirst(); }); removeCallbacks(tick); refresh(); @@ -124,7 +126,7 @@ void close() { open = false; heldDir = stickHeld = PadPanel.NONE; removeCallbacks(repeat); - sheet.animate().translationX(sheet.getLayoutParams().width).setDuration(150).withEndAction(() -> { if (!open) setVisibility(GONE); }).start(); + InGamePanel.slideOut(this, sheet, () -> { if (!open) setVisibility(GONE); }); // PEANUTS: out to the right, accelerating, the scrim fading } /** @@ -140,7 +142,7 @@ boolean padKey(KeyEvent e) { if (!press) return true; if (ModsPanel.padKey(k, findFocus(), confirm)) return true; // PEANUTS: Y (details) and X (All off) on the Mods tab boolean lost = findFocus() == null || isInTouchMode(); - if (k == back) close(); + if (k == back) InGamePanel.panelBack(this); // PEANUTS: back to the game menu when that opened the quick menu, else to the game else if (k == KeyEvent.KEYCODE_BUTTON_L1 || k == KeyEvent.KEYCODE_BUTTON_R1) { if (lost) ensureFocus(); showTab(PadPanel.tab(tab, k == KeyEvent.KEYCODE_BUTTON_L1 ? -1 : 1, TAB_NAMES.length)); } else if (k == confirm || k == KeyEvent.KEYCODE_DPAD_CENTER || k == KeyEvent.KEYCODE_ENTER) { if (lost) ensureFocus(); else activate(); } // the first press only shows where the focus is return true; @@ -262,6 +264,7 @@ private AlertDialog padDialog(AlertDialog d) { /** The tab bar: one button per tab (the selected one filled), then ✕; large enough to tap (the panel's row height, 48 dp at least), named for TalkBack */ private void tabBar() { + if (InGamePanel.rail(this, tab, this::showTab)) return; // PEANUTS: the rail instead of the bar tabs.removeAllViews(); float dp = getResources().getDisplayMetrics().density; int h = Math.max(Math.round(48 * dp), PanelLook.rowPx(Prefs.panelSize(act), dp)), pad = Math.round(4 * dp); @@ -322,7 +325,7 @@ private void showTab(int k) { build(); look(); scroll.scrollTo(0, 0); - if (!isInTouchMode()) focusFirst(); + if (!isInTouchMode() && !InGamePanel.railFocused()) focusFirst(); // PEANUTS: a tab switched from the rail keeps the focus there refresh(); } @@ -333,6 +336,7 @@ private void look() { if (sheet.getLayoutParams().width != w) { sheet.getLayoutParams().width = w; sheet.requestLayout(); } look(box, PanelLook.textScale(Prefs.panelText(act)), PanelLook.rowPx(size, dp)); dev.peanuts.ui.PanelPolish.apply(box); // PEANUTS: the panel's segmented choices, headings, notes and buttons + InGamePanel.laid(this, box, tab); // PEANUTS: what moved to the game menu (Pause, Stop, Back to the game, Button mapping); a new tab fades in } private static void look(View v, float text, int row) { if (v instanceof TextView) { diff --git a/android/app/src/main/java/dev/peanuts/Companion.java b/android/app/src/main/java/dev/peanuts/Companion.java index 3563a4cb..7b9ca7a3 100644 --- a/android/app/src/main/java/dev/peanuts/Companion.java +++ b/android/app/src/main/java/dev/peanuts/Companion.java @@ -562,6 +562,9 @@ static Display secondDisplay(Activity game, DisplayManager dm) { return builtIn != null && builtIn.isValid() ? builtIn : null; } + /** The second display for the game's in-game menu on the bottom screen (dev.nxnative.android.InGamePanel), as secondDisplay */ + public static Display second(Activity game, DisplayManager dm) { return secondDisplay(game, dm); } + /** Whether the device has a second screen of its own now (dev.peanuts.Screens; a TV or a cast does not count): what a title's companion settings default to * while the user has not chosen (CompanionSection.secondScreen, PeanutsPrefs.installCompanion). True when the displays cannot be read: the old default */ public static boolean hasSecondDisplay(android.content.Context c) { diff --git a/android/app/src/main/java/dev/peanuts/PeanutsPrefs.java b/android/app/src/main/java/dev/peanuts/PeanutsPrefs.java index 79a1d768..0818a9cf 100644 --- a/android/app/src/main/java/dev/peanuts/PeanutsPrefs.java +++ b/android/app/src/main/java/dev/peanuts/PeanutsPrefs.java @@ -237,6 +237,29 @@ public static boolean installCompanion(Context c, String titleId) { public static boolean modsTabAll(Context c) { return of(c).getBoolean("mods_tab", true); } public static void modsTabAll(Context c, boolean on) { of(c).edit().putBoolean("mods_tab", on).apply(); } + /** + * The in-game menus' layout: two menus (the game menu at the left, the quick menu at the right), one menu at the right, or one menu on the bottom screen. + * Picked once in the launcher's question (dev.peanuts.ui.LayoutChoice, kept in "peanuts", which the launcher writes) and changed later in the menu's own + * settings (Layout, dev.nxnative.android.InGamePanel, kept in the game's prefs file, which its process writes): each with when, the newer one counts. + * Two menus until one is picked + */ + public static final int LAYOUT_TWO = 0, LAYOUT_RIGHT = 1, LAYOUT_BOTTOM = 2; + private static SharedPreferences panel(Context c) { return c.getSharedPreferences("peanuts_panel", Context.MODE_PRIVATE); } + public static int menuLayout(Context c) { + SharedPreferences game = panel(c), launcher = of(c); + boolean inGame = game.contains("menu_layout") && game.getLong("menu_layout_at", 0) >= launcher.getLong("menu_layout_pick_at", 0); + int v = inGame ? game.getInt("menu_layout", LAYOUT_TWO) : launcher.getInt("menu_layout_pick", LAYOUT_TWO); + return v == LAYOUT_RIGHT || v == LAYOUT_BOTTOM ? v : LAYOUT_TWO; + } + /** The menu's own settings (the game's process) */ + public static void menuLayout(Context c, int layout) { panel(c).edit().putInt("menu_layout", layout).putLong("menu_layout_at", System.currentTimeMillis()).apply(); } + /** The launcher's question */ + public static void menuLayoutPick(Context c, int layout) { + of(c).edit().putInt("menu_layout_pick", layout).putLong("menu_layout_pick_at", System.currentTimeMillis()).apply(); + } + /** A layout was picked, in the launcher's question or in the menu's own settings: the question is not asked again */ + public static boolean menuLayoutPicked(Context c) { return of(c).contains("menu_layout_pick") || panel(c).contains("menu_layout"); } + /** The in-game panel's tab shown last (its name), so it opens there again; "" none yet. In a file of its own: the game's process writes it, and the launcher's * process, which keeps "peanuts" in memory, would write its older copy back over it */ public static String panelTab(Context c) { return c.getSharedPreferences("peanuts_panel", Context.MODE_PRIVATE).getString("tab", ""); } diff --git a/android/app/src/main/java/dev/peanuts/ingame/BottomMenu.java b/android/app/src/main/java/dev/peanuts/ingame/BottomMenu.java new file mode 100644 index 00000000..3113d9e4 --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/ingame/BottomMenu.java @@ -0,0 +1,53 @@ +package dev.peanuts.ingame; + +import android.content.Context; +import android.graphics.drawable.GradientDrawable; +import android.view.Gravity; +import android.view.MotionEvent; +import android.view.View; +import android.widget.FrameLayout; + +/** + * The second screen's side of the bottom screen's menu (dev.nxnative.android.InGamePanel opens it): the game's live stats page (dev.peanuts.ui.GameScreen, + * StatsView) gets a faint grip at its bottom edge, which moves with the page's pixel shifter, and a swipe up from that edge opens the menu on Game. + * Only while the layout (Menu settings › Layout) is One menu on the bottom screen. + */ +public final class BottomMenu { + private BottomMenu() {} + + /** Opens the menu on Game (InGamePanel.attach sets it for the running game) */ + public static Runnable opener; + + public static boolean on(Context c) { return dev.peanuts.PeanutsPrefs.menuLayout(c) == dev.peanuts.PeanutsPrefs.LAYOUT_BOTTOM; } + + /** The grip: 40 x 4 dp, the panel's row grey, at the bottom centre of the stats page's shifting content */ + public static View grip(Context c) { + View g = new View(c); + GradientDrawable d = new GradientDrawable(); + d.setColor(0xFF3A3B3E); + d.setCornerRadius(Look.dp(c, 2)); + g.setBackground(d); + FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(Look.dp(c, 40), Look.dp(c, 4), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); + lp.bottomMargin = Look.dp(c, 6); + g.setLayoutParams(lp); + return g; + } + + /** The bottom edge's strip (28 dp): a swipe up of 32 dp from it opens the menu; a tap goes on to the page under it (which wakes it) */ + public static View edge(Context c) { + View s = new View(c); + float dp = c.getResources().getDisplayMetrics().density; + float[] downY = {-1}; + s.setOnTouchListener((v, e) -> { + int a = e.getActionMasked(); + if (a == MotionEvent.ACTION_DOWN) { downY[0] = e.getRawY(); return true; } + if (a == MotionEvent.ACTION_MOVE && downY[0] >= 0 && downY[0] - e.getRawY() > 32 * dp) { downY[0] = -1; if (opener != null) opener.run(); return true; } + if (a == MotionEvent.ACTION_UP || a == MotionEvent.ACTION_CANCEL) downY[0] = -1; + return true; + }); + s.setContentDescription("Open the menu"); + s.setOnClickListener(v -> { if (opener != null) opener.run(); }); + s.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, Math.round(28 * dp), Gravity.BOTTOM)); + return s; + } +} diff --git a/android/app/src/main/java/dev/peanuts/ingame/BottomScreen.java b/android/app/src/main/java/dev/peanuts/ingame/BottomScreen.java new file mode 100644 index 00000000..860ebbe6 --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/ingame/BottomScreen.java @@ -0,0 +1,46 @@ +package dev.peanuts.ingame; + +import android.app.Presentation; +import android.content.Context; +import android.graphics.PixelFormat; +import android.graphics.drawable.ColorDrawable; +import android.os.Bundle; +import android.view.Display; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.FrameLayout; + +/** + * The window of the menu on the bottom screen (Menu settings › Layout: One menu on the bottom screen; the canvas page "In-game menus", board "Menü unten"): + * a see-through window on the second display, over whatever shows there (the game's live stats, a companion, Android's launcher), made when the menu opens + * and gone when it has slid back down, so the screen is given back. It never takes the input focus: the controller stays with the game's window, which + * hands its keys to the menu (dev.nxnative.android.InGamePanel). + */ +public final class BottomScreen extends Presentation { + private final View content; + + public BottomScreen(Context game, Display d, View content) { + super(game, d); + this.content = content; + } + + @Override protected void onCreate(Bundle saved) { + super.onCreate(saved); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); + getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); + getWindow().setFormat(PixelFormat.TRANSLUCENT); + getWindow().setBackgroundDrawable(new ColorDrawable(0)); + getWindow().setDecorFitsSystemWindows(false); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); // the whole screen, under a navigation bar if the display has one + getWindow().setNavigationBarColor(0); + getWindow().setStatusBarColor(0); + FrameLayout root = new FrameLayout(getContext()); + if (content.getParent() instanceof ViewGroup) ((ViewGroup) content.getParent()).removeView(content); + root.addView(content, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + setContentView(root); + } + + /** The menu leaves the window (before it goes): the panel is reused the next time */ + public void release() { if (content.getParent() instanceof ViewGroup) ((ViewGroup) content.getParent()).removeView(content); } +} diff --git a/android/app/src/main/java/dev/peanuts/ingame/GameMenu.java b/android/app/src/main/java/dev/peanuts/ingame/GameMenu.java new file mode 100644 index 00000000..268c1038 --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/ingame/GameMenu.java @@ -0,0 +1,448 @@ +package dev.peanuts.ingame; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Outline; +import android.graphics.Rect; +import android.graphics.Typeface; +import android.graphics.drawable.Drawable; +import android.text.TextUtils; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewOutlineProvider; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import dev.peanuts.ui.MenuFeel; + +import java.util.ArrayList; +import java.util.List; + +/** + * The game menu (the canvas page "In-game menus", board "Spielmenü links"): everything about this session, on a sheet that slides in from the left over the + * running game. A header with the game's cover, name, version and how long this session has run; the rows (Back to the game, Pause the game, Quick menu, + * Back up the save, Button mapping, Share log); Stop the game set apart at the bottom, which asks once, inline. The header and Stop stay while the rows + * scroll on a short screen. The controller moves a selection (up and down, A, B); a touch presses a row. The caller (dev.nxnative.android.InGamePanel) + * gives the rows their work and routes the keys. + */ +public final class GameMenu extends FrameLayout { + + /** One row: its solid icon, title, a value at its end (or a chevron), and what it does */ + public static final class Item { + final String icon, title; + final boolean chevron; + final Runnable run; + View row; + final List values = new ArrayList<>(); // the value at the row's end, in each menu that shows the row (the game menu, the bottom screen's Game) + String valueText; + boolean valueBad; + + public Item(String icon, String title, boolean chevron, Runnable run) { this.icon = icon; this.title = title; this.chevron = chevron; this.run = run; } + + public String icon() { return icon; } + public String title() { return title; } + public boolean chevron() { return chevron; } + public void run() { if (run != null) run.run(); } + /** A value view of another menu that shows this row (GameRows) */ + public void bind(TextView v) { values.add(v); value(valueText, valueBad); } + + public String valueText() { return valueText; } + + /** The value at the row's end (null: none); bad shows it in the colour of something that did not finish */ + public void value(String v, boolean bad) { + valueText = v; valueBad = bad; + for (TextView value : values) { + value.setText(v == null ? "" : v); + value.setTextColor(bad ? Look.BAD : Look.QUIET); + value.setVisibility(v == null || v.isEmpty() ? GONE : VISIBLE); + } + } + } + + private final View scrim; + private final LinearLayout sheet, list; + private final ScrollView scroll; + private final ImageView cover; + private final TextView name, version, time, note; + private final FrameLayout bottom; + private final List items = new ArrayList<>(); + private final int widthPx, rowPx; + private final float text; + private Item stop; + private View stopRow; + private LinearLayout ask; + private TextView keep, stopNow; + private int sel; // the selected row (items, then Stop at items.size()) + private int askSel; // inline Stop: 0 Keep playing, 1 Stop + private boolean open, asking, pad; + private java.util.function.LongSupplier startedAt = () -> 0; // read at each opening: the game's start is known only after the menu is made + /** After it has closed (gone) */ + public Runnable onClosed; + + public GameMenu(Context c, int widthPx, int rowPx, float text) { + super(c); + this.widthPx = widthPx; + this.rowPx = Math.max(rowPx, Look.dp(c, 40)); + this.text = text; + scrim = new View(c); + scrim.setBackgroundColor(Look.SCRIM); + scrim.setOnClickListener(v -> close(null)); + scrim.setContentDescription("Back to the game"); + addView(scrim, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); + + sheet = new LinearLayout(c); + sheet.setOrientation(LinearLayout.VERTICAL); + sheet.setBackgroundColor(Look.SHEET); + sheet.setElevation(Look.dp(c, 16)); + sheet.setPadding(Look.dp(c, 10), Look.dp(c, 12), Look.dp(c, 10), Look.dp(c, 10)); + sheet.setClickable(true); // a touch on the sheet's empty part does not reach the scrim or the game + addView(sheet, new LayoutParams(widthPx, LayoutParams.MATCH_PARENT, Gravity.START)); + + // The header: cover, name, version and this session's time + LinearLayout head = new LinearLayout(c); + head.setOrientation(LinearLayout.HORIZONTAL); + head.setGravity(Gravity.CENTER_VERTICAL); + head.setPadding(Look.dp(c, 4), Look.dp(c, 2), Look.dp(c, 4), Look.dp(c, 10)); + cover = new ImageView(c); + cover.setScaleType(ImageView.ScaleType.CENTER_CROP); + cover.setBackground(Look.round(Look.CHIP, Look.dp(c, 12))); + cover.setOutlineProvider(new ViewOutlineProvider() { + @Override public void getOutline(View v, Outline o) { o.setRoundRect(0, 0, v.getWidth(), v.getHeight(), Look.dp(c, 12)); } + }); + cover.setClipToOutline(true); + int cs = Look.dp(c, 52); + head.addView(cover, new LinearLayout.LayoutParams(cs, cs)); + LinearLayout col = new LinearLayout(c); + col.setOrientation(LinearLayout.VERTICAL); + col.setPadding(Look.dp(c, 12), 0, 0, 0); + name = label(c, 16, Look.TEXT, Typeface.BOLD); + name.setMaxLines(2); + name.setEllipsize(TextUtils.TruncateAt.END); + col.addView(name); + LinearLayout line = new LinearLayout(c); + line.setOrientation(LinearLayout.HORIZONTAL); + line.setGravity(Gravity.CENTER_VERTICAL); + line.setPadding(0, Look.dp(c, 5), 0, 0); + version = label(c, 12, Look.TEXT, Typeface.NORMAL); + version.setBackground(Look.round(Look.CHIP, Look.dp(c, 999))); + version.setPadding(Look.dp(c, 9), Look.dp(c, 3), Look.dp(c, 9), Look.dp(c, 3)); + version.setVisibility(GONE); + line.addView(version); + time = label(c, 13, Look.QUIET, Typeface.NORMAL); + time.setSingleLine(true); + LinearLayout.LayoutParams tl = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + tl.leftMargin = Look.dp(c, 8); + line.addView(time, tl); + col.addView(line); + head.addView(col, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); + sheet.addView(head); + + // The rows, scrolling between the header and Stop + scroll = new ScrollView(c); + scroll.setVerticalScrollBarEnabled(false); + scroll.setFadingEdgeLength(Look.dp(c, 24)); + scroll.setVerticalFadingEdgeEnabled(true); + list = new LinearLayout(c); + list.setOrientation(LinearLayout.VERTICAL); + scroll.addView(list); + sheet.addView(scroll, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); + note = label(c, 12, Look.TAN, Typeface.NORMAL); + note.setPadding(Look.dp(c, 8), Look.dp(c, 4), Look.dp(c, 8), Look.dp(c, 4)); + note.setVisibility(GONE); + sheet.addView(note); + + // Stop, set apart + View hair = new View(c); + hair.setBackgroundColor(Look.HAIRLINE); + LinearLayout.LayoutParams hl = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Math.max(1, Look.dp(c, 1))); + hl.topMargin = hl.bottomMargin = Look.dp(c, 6); + sheet.addView(hair, hl); + bottom = new FrameLayout(c); + sheet.addView(bottom, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + + // The selection is the menu's own (move, confirm): nothing in it takes Android's focus. The menu itself takes it when a controller opens it, which + // leaves touch mode at once, so the framework does not eat the first D-pad press to leave it (and give the focus to a scrolling list) + scroll.setFocusable(false); + setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS); + setFocusable(true); + setDefaultFocusHighlightEnabled(false); + setVisibility(GONE); + } + + TextView label(Context c, float sp, int color, int style) { + TextView t = new TextView(c); + t.setTextSize(TypedValue.COMPLEX_UNIT_SP, sp * text); + t.setTextColor(color); + t.setTypeface(style == Typeface.BOLD ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT); + t.setIncludeFontPadding(false); + return t; + } + + /** The game: its name, its version (null until read) and when this session started (SystemClock.elapsedRealtime, 0 unknown; asked at each opening) */ + public void game(String gameName, String ver, java.util.function.LongSupplier started) { + name.setText(gameName == null ? "" : gameName); + version(ver); + startedAt = started == null ? () -> 0 : started; + } + + public void version(String ver) { + version.setText(ver == null ? "" : ver); + version.setVisibility(ver == null || ver.isEmpty() ? GONE : VISIBLE); + } + + public void cover(Bitmap b) { if (b != null) cover.setImageBitmap(b); } + + /** The rows, top to bottom, and Stop */ + public void items(List rows, Item stopItem) { + items.clear(); + list.removeAllViews(); + for (Item it : rows) { + items.add(it); + it.row = row(it); + list.addView(it.row); + } + stop = stopItem; + stopRow = row(stopItem); + bottom.removeAllViews(); + bottom.addView(stopRow); + sel = 0; + paint(); + } + + private View row(Item it) { + Context c = getContext(); + LinearLayout r = new LinearLayout(c); + r.setOrientation(LinearLayout.HORIZONTAL); + r.setGravity(Gravity.CENTER_VERTICAL); + r.setMinimumHeight(rowPx); + r.setPadding(Look.dp(c, 8), 0, Look.dp(c, 8), 0); + ImageView ic = new ImageView(c); + Drawable d = Look.icon(c, it.icon, Look.Ink.MENU); + if (d != null) ic.setImageDrawable(d); + ic.setScaleType(ImageView.ScaleType.CENTER); + int is = Look.dp(c, 30); + r.addView(ic, new LinearLayout.LayoutParams(is, is)); + TextView t = label(c, 15, Look.TEXT, Typeface.NORMAL); + t.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + t.setText(it.title); + t.setSingleLine(true); + t.setEllipsize(TextUtils.TruncateAt.END); + t.setPadding(Look.dp(c, 10), 0, Look.dp(c, 8), 0); + r.addView(t, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); + TextView value = label(c, 13, Look.QUIET, Typeface.NORMAL); + value.setSingleLine(true); + r.addView(value); + it.bind(value); + if (it.chevron) { + ImageView ch = new ImageView(c); + Drawable cd = dev.peanuts.ui.Icons.get(c, "chevron-right", dev.peanuts.ui.Icons.Ink.QUIET); + if (cd != null) { cd = cd.mutate(); cd.setTint(Look.QUIET); ch.setImageDrawable(cd); } + int chs = Look.dp(c, 18); + LinearLayout.LayoutParams cl = new LinearLayout.LayoutParams(chs, chs); + cl.leftMargin = Look.dp(c, 4); + r.addView(ch, cl); + } + r.setClickable(true); + r.setContentDescription(it.title); + r.setOnClickListener(v -> { pad = false; sel = indexOf(it); paint(); press(it); }); + return r; + } + + private int indexOf(Item it) { int i = items.indexOf(it); return i >= 0 ? i : items.size(); } + + private void press(Item it) { + if (it == stop) { askStop(); return; } + if (it.run != null) it.run.run(); + } + + // ---- Stop asks once, inline: Keep playing (the safe choice first) or Stop ---- + + private void askStop() { + Context c = getContext(); + asking = true; + askSel = 0; + ask = new LinearLayout(c); + ask.setOrientation(LinearLayout.VERTICAL); + ask.setPadding(Look.dp(c, 8), Look.dp(c, 4), Look.dp(c, 8), Look.dp(c, 2)); + TextView q = label(c, 15, Look.TEXT, Typeface.BOLD); + q.setText("Stop the game?"); + ask.addView(q); + TextView w = label(c, 13, Look.QUIET, Typeface.NORMAL); + w.setText("Unsaved progress is lost. The log stays for Share log."); + w.setPadding(0, Look.dp(c, 4), 0, Look.dp(c, 8)); + ask.addView(w); + LinearLayout b = new LinearLayout(c); + b.setOrientation(LinearLayout.HORIZONTAL); + keep = button(c, "Keep playing", v -> { pad = false; cancelStop(); }); + stopNow = button(c, "Stop", v -> { pad = false; if (stop.run != null) stop.run.run(); }); + stopNow.setTextColor(Look.BAD); + LinearLayout.LayoutParams kl = new LinearLayout.LayoutParams(0, rowPx, 1); + LinearLayout.LayoutParams sl = new LinearLayout.LayoutParams(0, rowPx, 1); + sl.leftMargin = Look.dp(c, 8); + b.addView(keep, kl); + b.addView(stopNow, sl); + ask.addView(b); + bottom.removeAllViews(); + bottom.addView(ask); + ask.setAlpha(0f); + ask.animate().alpha(1f).setDuration(Look.TAB_IN_MS).setInterpolator(Look.OUT); + paint(); + } + + private TextView button(Context c, String s, View.OnClickListener l) { + TextView t = label(c, 14, Look.TEXT, Typeface.NORMAL); + t.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + t.setText(s); + t.setGravity(Gravity.CENTER); + t.setBackground(Look.round(Look.ROW, Look.dp(c, 10))); + t.setClickable(true); + t.setOnClickListener(l); + return t; + } + + private void cancelStop() { + asking = false; + bottom.removeAllViews(); + bottom.addView(stopRow); + paint(); + } + + // ---- The selection ---- + + /** The selected row's frame (only while a controller is in use); the inline question's buttons */ + private void paint() { + Context c = getContext(); + for (int i = 0; i <= items.size(); i++) { + View r = i < items.size() ? items.get(i).row : stopRow; + if (r != null) r.setBackground(pad && !asking && i == sel ? Look.focus(c, 12) : null); + } + if (asking && keep != null) { + keep.setBackground(pad && askSel == 0 ? withRing(c) : Look.round(Look.ROW, Look.dp(c, 10))); + stopNow.setBackground(pad && askSel == 1 ? withRing(c) : Look.round(Look.ROW, Look.dp(c, 10))); + } + } + + private Drawable withRing(Context c) { + android.graphics.drawable.GradientDrawable d = Look.round(Look.ROW, Look.dp(c, 10)); + d.setStroke(Math.round(2.5f * c.getResources().getDisplayMetrics().density), Look.YELLOW); + return d; + } + + private void reveal() { + View r = sel < items.size() ? items.get(sel).row : null; + if (r == null) return; + r.post(() -> r.requestRectangleOnScreen(new Rect(0, -Look.dp(getContext(), 8), r.getWidth(), r.getHeight() + Look.dp(getContext(), 8)), false)); + } + + /** A controller direction (dev.nxnative.android.PadPanel's UP, DOWN, LEFT, RIGHT) */ + public void move(boolean up, boolean down, boolean left, boolean right) { + boolean was = pad; + pad = true; + if (!was) { paint(); return; } // the first press only shows where the selection is + if (asking) { + int was2 = askSel; + if (left) askSel = 0; else if (right) askSel = 1; + if (askSel != was2) MenuFeel.move(this); else if (left || right) MenuFeel.edge(this); + paint(); + return; + } + int from = sel; + if (up && sel > 0) sel--; + else if (down && sel < items.size()) sel++; + if (sel != from) MenuFeel.move(this); else if (up || down) MenuFeel.edge(this); + paint(); + reveal(); + } + + /** The controller's A */ + public void confirm() { + boolean was = pad; + pad = true; + if (!was) { paint(); return; } + MenuFeel.select(this); + if (asking) { + if (askSel == 0) cancelStop(); else if (stop.run != null) stop.run.run(); + return; + } + press(sel < items.size() ? items.get(sel) : stop); + } + + /** The controller's B: the inline question goes, else the menu closes */ + public void back() { + MenuFeel.back(this); + if (asking) { cancelStop(); return; } + close(null); + } + + /** A line under the rows (a backup that did not finish), null to hide it */ + public void note(String s, boolean bad) { + note.setText(s == null ? "" : s); + note.setTextColor(bad ? Look.BAD : Look.TAN); + note.setVisibility(s == null ? GONE : VISIBLE); + } + + // ---- Open and close ---- + + public boolean isOpen() { return open; } + + /** The selection on a row (it): where the player comes back to, as from the quick menu to its row */ + public void at(Item it) { + int i = items.indexOf(it); + if (i < 0 || !open) return; + sel = i; + paint(); + } + + /** Slides in from the left (OPEN_MS, decelerating) while the scrim fades in; withPad: a controller opened it, the selection shows at once */ + public void open(boolean withPad) { + if (open) return; + open = true; + pad = withPad; + MenuFeel.open(this); + asking = false; + if (stopRow != null && stopRow.getParent() == null) { bottom.removeAllViews(); bottom.addView(stopRow); } + sel = 0; + note(null, false); + time.setText(played()); + paint(); + scroll.scrollTo(0, 0); + setVisibility(VISIBLE); + if (withPad) post(() -> { if (open) requestFocusFromTouch(); }); + sheet.animate().cancel(); + scrim.animate().cancel(); + sheet.setTranslationX(-widthPx); + scrim.setAlpha(0f); + sheet.animate().translationX(0).setDuration(Look.OPEN_MS).setInterpolator(Look.OUT).withLayer().start(); + scrim.animate().alpha(1f).setDuration(Look.OPEN_MS).setInterpolator(Look.OUT).start(); + } + + /** Slides out to the left (CLOSE_MS, accelerating); then runs after it is gone, and onClosed */ + public void close(Runnable then) { + if (!open) { if (then != null) then.run(); return; } + open = false; + clearFocus(); + sheet.animate().cancel(); + scrim.animate().cancel(); + scrim.animate().alpha(0f).setDuration(Look.CLOSE_MS).setInterpolator(Look.IN).start(); + sheet.animate().translationX(-widthPx).setDuration(Look.CLOSE_MS).setInterpolator(Look.IN).withLayer().withEndAction(() -> { + if (!open) setVisibility(GONE); + if (then != null) then.run(); + if (onClosed != null) onClosed.run(); + }).start(); + } + + /** "Playing for 42 min", from when this session started */ + private String played() { + long t = startedAt.getAsLong(); + if (t <= 0) return ""; + long min = (android.os.SystemClock.elapsedRealtime() - t) / 60000; + if (min < 1) return "Just started"; + if (min < 60) return "Playing for " + min + " min"; + return "Playing for " + (min / 60) + " h" + (min % 60 > 0 ? " " + (min % 60) + " min" : ""); + } +} diff --git a/android/app/src/main/java/dev/peanuts/ingame/GameRows.java b/android/app/src/main/java/dev/peanuts/ingame/GameRows.java new file mode 100644 index 00000000..0351111c --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/ingame/GameRows.java @@ -0,0 +1,202 @@ +package dev.peanuts.ingame; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Outline; +import android.graphics.Typeface; +import android.graphics.drawable.Drawable; +import android.text.TextUtils; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewOutlineProvider; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import java.util.List; + +/** + * The bottom screen's Game (the canvas page "In-game menus", board "Menü unten"): the game menu's rows inside the one menu on the bottom screen, under its + * header (cover, name, version, this session's time), Stop set apart and asked once inline. Unlike GameMenu's own selection these rows take Android's focus, + * so the quick menu's panel (upstream's SidePanel, which the bottom screen's menu is) moves over them as over its other rows, and a touch presses them. + */ +public final class GameRows extends LinearLayout { + private final ImageView cover; + private final TextView name, version, time; + private final FrameLayout bottom; + private final LinearLayout footer; // the hairline and Stop, kept at the sheet's bottom under the rows (Rail), as the game menu's + private final int rowPx; + private GameMenu.Item stop; + private View stopRow; + private long startedAt; + + public GameRows(Context c, int rowPx) { + super(c); + this.rowPx = Math.max(rowPx, Look.dp(c, 44)); + setOrientation(VERTICAL); + setPadding(Look.dp(c, 4), Look.dp(c, 2), Look.dp(c, 4), Look.dp(c, 4)); + LinearLayout head = new LinearLayout(c); + head.setOrientation(HORIZONTAL); + head.setGravity(Gravity.CENTER_VERTICAL); + head.setPadding(Look.dp(c, 4), 0, Look.dp(c, 4), Look.dp(c, 8)); + cover = new ImageView(c); + cover.setScaleType(ImageView.ScaleType.CENTER_CROP); + cover.setBackground(Look.round(Look.CHIP, Look.dp(c, 11))); + cover.setOutlineProvider(new ViewOutlineProvider() { + @Override public void getOutline(View v, Outline o) { o.setRoundRect(0, 0, v.getWidth(), v.getHeight(), Look.dp(c, 11)); } + }); + cover.setClipToOutline(true); + int cs = Look.dp(c, 48); + head.addView(cover, new LayoutParams(cs, cs)); + LinearLayout col = new LinearLayout(c); + col.setOrientation(VERTICAL); + col.setPadding(Look.dp(c, 12), 0, 0, 0); + name = text(c, 15, Look.TEXT, true); + name.setMaxLines(2); + name.setEllipsize(TextUtils.TruncateAt.END); + col.addView(name); + LinearLayout line = new LinearLayout(c); + line.setOrientation(HORIZONTAL); + line.setGravity(Gravity.CENTER_VERTICAL); + line.setPadding(0, Look.dp(c, 4), 0, 0); + version = text(c, 12, Look.TEXT, false); + version.setBackground(Look.round(Look.CHIP, Look.dp(c, 999))); + version.setPadding(Look.dp(c, 9), Look.dp(c, 3), Look.dp(c, 9), Look.dp(c, 3)); + version.setVisibility(GONE); + line.addView(version); + time = text(c, 13, Look.QUIET, false); + LayoutParams tl = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + tl.leftMargin = Look.dp(c, 8); + line.addView(time, tl); + col.addView(line); + head.addView(col, new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); + addView(head); + bottom = new FrameLayout(c); + footer = new LinearLayout(c); + footer.setOrientation(VERTICAL); + footer.setPadding(Look.dp(c, 14), 0, Look.dp(c, 14), Look.dp(c, 8)); // under the rows' own sides (their scroll's 10 dp and these rows' 4 dp) + } + + /** The hairline and Stop: the rail puts them under the rows, so Stop stays in sight on a short screen while the rows scroll */ + public View footer() { return footer; } + + private static TextView text(Context c, float sp, int color, boolean bold) { + TextView t = new TextView(c); + t.setTextSize(TypedValue.COMPLEX_UNIT_SP, sp); + t.setTextColor(color); + t.setTypeface(bold ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT); + t.setIncludeFontPadding(false); + return t; + } + + public void game(String gameName, String ver, long started) { name.setText(gameName == null ? "" : gameName); version(ver); startedAt = started; time.setText(played()); } + public void version(String ver) { version.setText(ver == null ? "" : ver); version.setVisibility(ver == null || ver.isEmpty() ? GONE : VISIBLE); } + public void cover(Bitmap b) { if (b != null) cover.setImageBitmap(b); } + public void refresh() { time.setText(played()); if (stopRow != null && stopRow.getParent() == null) { bottom.removeAllViews(); bottom.addView(stopRow); } } + + /** The rows, top to bottom, and Stop */ + public void items(List rows, GameMenu.Item stopItem) { + for (GameMenu.Item it : rows) addView(row(it, () -> it.run())); + View hair = new View(getContext()); + hair.setBackgroundColor(Look.HAIRLINE); + LayoutParams hl = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Math.max(1, Look.dp(getContext(), 1))); + hl.topMargin = hl.bottomMargin = Look.dp(getContext(), 6); + footer.addView(hair, hl); + stop = stopItem; + stopRow = row(stopItem, this::askStop); + bottom.addView(stopRow); + footer.addView(bottom); + } + + private View row(GameMenu.Item it, Runnable press) { + Context c = getContext(); + LinearLayout r = new LinearLayout(c); + r.setOrientation(HORIZONTAL); + r.setGravity(Gravity.CENTER_VERTICAL); + r.setMinimumHeight(rowPx); + r.setPadding(Look.dp(c, 8), 0, Look.dp(c, 8), 0); + r.setBackground(Look.round(0, Look.dp(c, 12))); + ImageView ic = new ImageView(c); + Drawable d = Look.icon(c, it.icon(), Look.Ink.MENU); + if (d != null) ic.setImageDrawable(d); + ic.setScaleType(ImageView.ScaleType.CENTER); + int is = Look.dp(c, 30); + r.addView(ic, new LayoutParams(is, is)); + TextView t = text(c, 15, Look.TEXT, false); + t.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + t.setText(it.title()); + t.setSingleLine(true); + t.setEllipsize(TextUtils.TruncateAt.END); + t.setPadding(Look.dp(c, 10), 0, Look.dp(c, 8), 0); + r.addView(t, new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); + TextView value = text(c, 13, Look.QUIET, false); + value.setSingleLine(true); + r.addView(value); + it.bind(value); + if (it.chevron()) { + ImageView ch = new ImageView(c); + Drawable cd = dev.peanuts.ui.Icons.get(c, "chevron-right", dev.peanuts.ui.Icons.Ink.QUIET); + if (cd != null) { cd = cd.mutate(); cd.setTint(Look.QUIET); ch.setImageDrawable(cd); } + int chs = Look.dp(c, 18); + LayoutParams cl = new LayoutParams(chs, chs); + cl.leftMargin = Look.dp(c, 4); + r.addView(ch, cl); + } + r.setFocusable(true); + r.setClickable(true); + r.setContentDescription(it.title()); + r.setOnClickListener(v -> press.run()); + return r; + } + + /** Stop asks once, inline: Keep playing (the focus) or Stop */ + private void askStop() { + Context c = getContext(); + LinearLayout ask = new LinearLayout(c); + ask.setOrientation(VERTICAL); + ask.setPadding(Look.dp(c, 8), Look.dp(c, 2), Look.dp(c, 8), 0); + TextView q = text(c, 15, Look.TEXT, true); + q.setText("Stop the game?"); + ask.addView(q); + TextView w = text(c, 13, Look.QUIET, false); + w.setText("Unsaved progress is lost. The log stays for Share log."); + w.setPadding(0, Look.dp(c, 4), 0, Look.dp(c, 8)); + ask.addView(w); + LinearLayout b = new LinearLayout(c); + b.setOrientation(HORIZONTAL); + TextView keep = button(c, "Keep playing", v -> { bottom.removeAllViews(); bottom.addView(stopRow); stopRow.requestFocus(); }); + TextView now = button(c, "Stop", v -> stop.run()); + now.setTextColor(Look.BAD); + LayoutParams sl = new LayoutParams(0, rowPx, 1); + sl.leftMargin = Look.dp(c, 8); + b.addView(keep, new LayoutParams(0, rowPx, 1)); + b.addView(now, sl); + ask.addView(b); + bottom.removeAllViews(); + bottom.addView(ask); + if (!isInTouchMode()) keep.requestFocus(); + } + + private TextView button(Context c, String s, View.OnClickListener l) { + TextView t = text(c, 14, Look.TEXT, false); + t.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + t.setText(s); + t.setGravity(Gravity.CENTER); + t.setBackground(Look.round(Look.ROW, Look.dp(c, 10))); + t.setFocusable(true); + t.setClickable(true); + t.setOnClickListener(l); + return t; + } + + private String played() { + if (startedAt <= 0) return ""; + long min = (android.os.SystemClock.elapsedRealtime() - startedAt) / 60000; + if (min < 1) return "Just started"; + if (min < 60) return "Playing for " + min + " min"; + return "Playing for " + (min / 60) + " h" + (min % 60 > 0 ? " " + (min % 60) + " min" : ""); + } +} diff --git a/android/app/src/main/java/dev/peanuts/ingame/Look.java b/android/app/src/main/java/dev/peanuts/ingame/Look.java new file mode 100644 index 00000000..a4ed5ec0 --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/ingame/Look.java @@ -0,0 +1,81 @@ +package dev.peanuts.ingame; + +import android.content.Context; +import android.content.res.Resources; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.GradientDrawable; +import android.view.animation.Interpolator; +import android.view.animation.PathInterpolator; + +import java.util.HashMap; +import java.util.Map; + +/** + * The in-game menus' look (the canvas "Peanuts Settings Redesign", page "In-game menus"): upstream's grey panel, the banana-yellow focus, the peanut browns, + * and the solid icons (res drawable/pis_*.xml from design/peanuts-native/icons, colours per state from res values/peanuts_ingame.xml). Also their motion. + */ +public final class Look { + private Look() {} + + // The panel (SidePanel, ModsTab): the sheet, a row, a chip, text, quiet text, the yellow and the text on it + public static final int SHEET = 0xF5202124, ROW = 0xFF2D2E31, CHIP = 0xFF3A3B3E, TEXT = 0xFFE8EAED, QUIET = 0xFFB0B3B8, YELLOW = 0xFFFFD54F, ON_YELLOW = 0xFF2A1D0C; + // The rail: its ground, its edge, the selected block (peanut brown); a section head (peanut tan); a line that went wrong; the scrim over the game + public static final int RAIL = 0xFF151618, RAIL_EDGE = 0xFF2A2B2E, PEANUT = 0xFF4A3920, TAN = 0xFFCDB48C, BAD = 0xFFFF9670, SCRIM = 0x66000000, HAIRLINE = 0xFF3A3B3E; + + /** The solid icons' colours: REST (the rail, not selected), SELECTED (the selected tab), MENU (the game menu's rows, the back button) */ + public enum Ink { + REST("PeanutsSolidRest"), SELECTED("PeanutsSolidSelected"), MENU("PeanutsSolidMenu"); + final String style; + Ink(String style) { this.style = style; } + } + + private static final Map IDS = new HashMap<>(); + private static final Map THEMES = new HashMap<>(); + + private static int id(Context c, String name, String type) { + String key = type + "/" + name; + Integer v = IDS.get(key); + if (v == null) { v = c.getResources().getIdentifier(name, type, c.getPackageName()); IDS.put(key, v); } + return v; + } + + /** The solid icon named (bolt, cheats, ...: pis_) in these colours, at its own 24 dp; null when this build has none */ + public static Drawable icon(Context c, String name, Ink ink) { + int d = id(c, "pis_" + name.replace('-', '_'), "drawable"); + if (d == 0) return null; + Resources.Theme t = THEMES.get(ink); + if (t == null) { + int s = id(c, ink.style, "style"); + if (s == 0) return null; + t = c.getResources().newTheme(); + t.setTo(c.getTheme()); + t.applyStyle(s, true); + THEMES.put(ink, t); + } + try { return c.getResources().getDrawable(d, t).mutate(); } catch (Resources.NotFoundException e) { return null; } + } + + public static int dp(Context c, float v) { return Math.round(v * c.getResources().getDisplayMetrics().density); } + + public static GradientDrawable round(int fill, float radiusPx) { + GradientDrawable d = new GradientDrawable(); + d.setColor(fill); + d.setCornerRadius(radiusPx); + return d; + } + + /** The controller's focus: the panel's own frame (SidePanel.focusMoved), a yellow ring with a light yellow tint, here with the row's corners */ + public static GradientDrawable focus(Context c, float radiusDp) { + GradientDrawable d = new GradientDrawable(); + d.setColor(0x26FFD54F); + d.setStroke(Math.round(2.5f * c.getResources().getDisplayMetrics().density), YELLOW); + d.setCornerRadius(radiusDp * c.getResources().getDisplayMetrics().density); + return d; + } + + // ---- Motion: calm, no overshoot. In with a long deceleration, out a little quicker, accelerating ---- + public static final int OPEN_MS = 240, CLOSE_MS = 180, TAB_OUT_MS = 60, TAB_IN_MS = 100, BLOCK_MS = 160; + /** The bottom screen's menu: up from the bottom edge, back down */ + public static final int UP_MS = 280, DOWN_MS = 220; + public static final Interpolator OUT = new PathInterpolator(0.2f, 0f, 0f, 1f), IN = new PathInterpolator(0.3f, 0f, 1f, 1f); +} diff --git a/android/app/src/main/java/dev/peanuts/ingame/Rail.java b/android/app/src/main/java/dev/peanuts/ingame/Rail.java new file mode 100644 index 00000000..5156e39b --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/ingame/Rail.java @@ -0,0 +1,408 @@ +package dev.peanuts.ingame; + +import android.content.Context; +import android.graphics.Typeface; +import android.graphics.drawable.Drawable; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.IntConsumer; + +/** + * The quick menu's frame (the canvas page "In-game menus", board "Schnellmenü rechts"): upstream's side panel keeps building its tabs, and this turns its + * sheet around. The tab bar becomes a dark rail of solid icons at the left (the menu's own settings at its bottom), the selected tab a peanut-brown block + * across the rail that slides to the next one; the tab's rows get a header with a back button and the tab's name. With a controller, up and down on the + * rail switch the tab at once, right goes into the rows, left from a row comes back to the selected tab. + *

    + * On the bottom screen (board "Menü unten") the rail starts with Game, above the tabs and apart from them: the game menu's rows (GameRows) in place of + * the panel's own. + */ +public final class Rail { + private final Context c; + private final LinearLayout tabs; // upstream's tab bar, now the rail's items in tab order (SidePanel.tabs: getChildAt(tab) still finds a tab's item) + private final FrameLayout box; // the rail: the moving block under the items + private final View block; + private final TextView title; + private final LinearLayout head; + private final View content; // the tab's rows beside the rail (the panel's scroll) + private View action; // the shown tab's own action at the right of the header (the Cheats tab's All off) + private final List items = new ArrayList<>(); + private final View gameItem; // the bottom screen's Game (null on the top screen) + private final ScrollView gameRows; + private final View gameFoot; // Game's Stop under its rows (GameRows.footer) + private String[] names = new String[0]; + private int selected = -1; + private boolean onGame; + private IntConsumer show; + private boolean placed; + + /** Takes the panel's sheet (upstream: the tab bar over the rows) apart and puts it together as rail | (header over rows). back: the header's button */ + public Rail(Context c, LinearLayout sheet, LinearLayout tabs, View rows, Runnable back) { this(c, sheet, tabs, rows, back, null); } + + /** The same with the bottom screen's Game first on the rail (game: its rows), null for the top screen's quick menu */ + public Rail(Context c, LinearLayout sheet, LinearLayout tabs, View rows, Runnable back, GameRows game) { + this.c = c; + this.tabs = tabs; + this.content = rows; + sheet.removeAllViews(); + sheet.setOrientation(LinearLayout.HORIZONTAL); + sheet.setBackgroundColor(Look.SHEET); + + box = new FrameLayout(c) { + // Right from the rail goes into the rows beside it (the first one in sight), not to the header's Back (the nearer one by the default search) + @Override public View focusSearch(View focused, int direction) { + if (direction == View.FOCUS_RIGHT) { View r = firstRow(); if (r != null) return r; } + return super.focusSearch(focused, direction); + } + }; + box.setBackgroundColor(Look.RAIL); + block = new View(c); + block.setBackgroundColor(Look.PEANUT); + block.setVisibility(View.INVISIBLE); + box.addView(block, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight())); + LinearLayout column = new LinearLayout(c); + column.setOrientation(LinearLayout.VERTICAL); + column.setPadding(0, Look.dp(c, game != null ? 14 : 8), 0, Look.dp(c, 8)); + if (game != null) { + gameItem = item("game", "Game"); + gameItem.setOnClickListener(v -> game()); + column.addView(gameItem, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight())); + View sep = new View(c); + sep.setBackgroundColor(Look.ROW); + LinearLayout.LayoutParams sl = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Math.max(1, Look.dp(c, 1))); + sl.leftMargin = sl.rightMargin = Look.dp(c, 12); + sl.topMargin = sl.bottomMargin = Look.dp(c, 4); + column.addView(sep, sl); + } else gameItem = null; + tabs.setOrientation(LinearLayout.VERTICAL); + tabs.setBackground(null); + tabs.setPadding(0, 0, 0, 0); + column.addView(tabs, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); + box.addView(column, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + sheet.addView(box, new LinearLayout.LayoutParams(Look.dp(c, game != null ? 56 : 60), ViewGroup.LayoutParams.MATCH_PARENT)); + View edge = new View(c); + edge.setBackgroundColor(Look.RAIL_EDGE); + sheet.addView(edge, new LinearLayout.LayoutParams(Math.max(1, Look.dp(c, 1)), ViewGroup.LayoutParams.MATCH_PARENT)); + + LinearLayout col = new LinearLayout(c) { + // Left from the rows comes back to the selected tab on the rail (on the bottom screen's Game: to Game), not to the header's Back above them + // (the nearer one by the default search) + @Override public View focusSearch(View focused, int direction) { + if (direction == View.FOCUS_LEFT && focused != null && !inside(focused, head)) { + if (onGame && gameItem != null) return gameItem; + if (selected >= 0 && selected < items.size()) return items.get(selected); + } + return super.focusSearch(focused, direction); + } + }; + col.setOrientation(LinearLayout.VERTICAL); + head = new LinearLayout(c); + head.setOrientation(LinearLayout.HORIZONTAL); + head.setGravity(Gravity.CENTER_VERTICAL); + head.setPadding(Look.dp(c, 12), Look.dp(c, game != null ? 14 : 10), Look.dp(c, 12), Look.dp(c, 2)); + ImageView b = new ImageView(c); + Drawable bd = Look.icon(c, "back", Look.Ink.MENU); + if (bd != null) b.setImageDrawable(bd); + b.setScaleType(ImageView.ScaleType.FIT_CENTER); + int p = Look.dp(c, 7); + b.setPadding(p, p, p, p); + b.setBackground(Look.round(Look.ROW, Look.dp(c, 8))); + b.setFocusable(true); + b.setClickable(true); + b.setDefaultFocusHighlightEnabled(false); // the panel's yellow frame alone shows the focus (no grey veil over the button) + b.setContentDescription("Back"); + b.setOnClickListener(v -> back.run()); + head.addView(b, new LinearLayout.LayoutParams(Look.dp(c, 36), Look.dp(c, 32))); + title = new TextView(c); + title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); + title.setTextColor(Look.TEXT); + title.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + title.setSingleLine(true); + title.setPadding(Look.dp(c, 12), 0, 0, 0); + head.addView(title, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); + col.addView(head); + col.addView(rows, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); + if (game != null) { + gameRows = new ScrollView(c); + gameRows.setVerticalScrollBarEnabled(false); + gameRows.setVerticalFadingEdgeEnabled(true); // a row cut by the screen's edge or by Stop below fades out instead of ending in a hard line + gameRows.setFadingEdgeLength(Look.dp(c, 28)); + gameRows.setPadding(Look.dp(c, 10), Look.dp(c, 16), Look.dp(c, 10), 0); // no bottom padding: the fade lies on the edge where the rows are cut + gameRows.setClipToPadding(false); + gameRows.addView(game); + gameRows.setVisibility(View.GONE); + col.addView(gameRows, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); + gameFoot = game.footer(); + gameFoot.setVisibility(View.GONE); + col.addView(gameFoot, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + } else { gameRows = null; gameFoot = null; } + sheet.addView(col, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1)); + + // Up and down on the rail switch the tab; left from the rows comes back to the selected tab only (the others take no focus then) + sheet.getViewTreeObserver().addOnGlobalFocusChangeListener((old, now) -> { + if (now != null && now == gameItem) { focusable(true); if (!onGame) game(); return; } + int i = items.indexOf(now); + if (i >= 0) { + focusable(true); + if (i != selected || onGame) pick(i); + } else if (now != null && inside(now, sheet)) focusable(false); + }); + } + + /** The first row in sight beside the rail (Game's on Game): where Right from the rail goes */ + public View firstRow() { return onGame && gameRows != null ? firstGameRow() : firstIn(content); } + + /** The first focusable in (top to bottom) that is mostly in sight, else the first at all (a track's chosen choice); null when there is none */ + static View firstIn(View in) { + if (in == null || in.getVisibility() != View.VISIBLE) return null; + ArrayList all = new ArrayList<>(); + in.addFocusables(all, View.FOCUS_DOWN); + android.graphics.Rect r = new android.graphics.Rect(); + for (View v : all) if (v.isShown() && v.getGlobalVisibleRect(r) && r.height() * 2 > v.getHeight()) return dev.peanuts.ui.PanelPolish.landing(v); + for (View v : all) if (v.isShown()) return dev.peanuts.ui.PanelPolish.landing(v); + return null; + } + + private int itemHeight() { return Look.dp(c, gameItem != null || names.length > 6 ? 46 : 50); } + + private View item(String icon, String name) { + FrameLayout item = new FrameLayout(c); + ImageView ic = new ImageView(c); + ic.setScaleType(ImageView.ScaleType.CENTER); + Drawable d = Look.icon(c, icon, Look.Ink.REST); + if (d != null) ic.setImageDrawable(d); + item.addView(ic, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + item.setFocusable(true); + item.setClickable(true); + item.setDefaultFocusHighlightEnabled(false); // the yellow frame alone, over the peanut block + item.setContentDescription(name); + item.setId(View.generateViewId()); + return item; + } + + private static boolean inside(View v, View in) { + for (Object p = v; p instanceof View; p = ((View) p).getParent()) if (p == in) return true; + return false; + } + + private void focusable(boolean all) { + for (int k = 0; k < items.size(); k++) items.get(k).setFocusable(all || (!onGame && k == selected)); + if (gameItem != null) gameItem.setFocusable(all || onGame); + } + + /** + * The shown tab's own action at the right of its header, as a console's menus show one: the controller's button for it and its name ("X All off"), + * a tap does it too. Not a focus stop: the button is the controller's way. Null label: none (each tab's build starts without one) + */ + public void action(String key, String label, Runnable run) { + if (action != null) { head.removeView(action); action = null; } + if (label == null) return; + LinearLayout a = new LinearLayout(c); + a.setOrientation(LinearLayout.HORIZONTAL); + a.setGravity(Gravity.CENTER_VERTICAL); + a.setPadding(Look.dp(c, 5), Look.dp(c, 4), Look.dp(c, 14), Look.dp(c, 4)); + a.setBackground(Look.round(Look.ROW, Look.dp(c, 999))); + TextView k = new TextView(c); + k.setText(key); + k.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12); + k.setTypeface(Typeface.DEFAULT_BOLD); + k.setTextColor(Look.SHEET | 0xFF000000); + k.setGravity(Gravity.CENTER); + k.setIncludeFontPadding(false); + android.graphics.drawable.GradientDrawable dot = new android.graphics.drawable.GradientDrawable(); + dot.setShape(android.graphics.drawable.GradientDrawable.OVAL); + dot.setColor(Look.TEXT); + k.setBackground(dot); + a.addView(k, new LinearLayout.LayoutParams(Look.dp(c, 24), Look.dp(c, 24))); + TextView t = new TextView(c); + t.setText(label); + t.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); + t.setTextColor(Look.TEXT); + t.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + t.setSingleLine(true); + t.setPadding(Look.dp(c, 8), 0, 0, 0); + a.addView(t); + a.setFocusable(false); + a.setClickable(true); + a.setContentDescription(label); + a.setOnClickListener(v -> run.run()); + head.addView(a, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + action = a; + } + + /** Whether the controller's focus is on the rail (a tab switched from there keeps it there) */ + public boolean focused() { + if (gameItem != null && gameItem.isFocused()) return true; + for (View v : items) if (v.isFocused()) return true; + return false; + } + + /** Whether the bottom screen's Game shows */ + public boolean onGame() { return onGame; } + + /** A tab picked on the rail: from Game back to the panel's rows, and the panel to that tab unless it shows it already */ + private void pick(int i) { + boolean was = onGame; + if (onGame) leaveGame(); + if (i != selected && show != null) show.accept(i); + else if (was) select(selected); + } + + /** The bottom screen's Game: its rows in place of the panel's; the panel keeps its tab for the way back */ + public void game() { + if (gameRows == null) return; + onGame = true; + content.setVisibility(View.GONE); + if (content instanceof ViewGroup && ((ViewGroup) content).getChildCount() > 0) // the panel's own rows take no focus while hidden (SidePanel.focusFirst) + ((ViewGroup) ((ViewGroup) content).getChildAt(0)).setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); + gameRows.setVisibility(View.VISIBLE); + gameFoot.setVisibility(View.VISIBLE); + gameRows.scrollTo(0, 0); + head.setVisibility(View.GONE); // Game's own header (the cover, the name) is the top, as in the game menu: its first row goes back to the game + title.setText("Game"); + paintIcons(); + if (!focused()) focusable(false); + moveBlock(gameItem, placed); + gameRows.setAlpha(0f); + gameRows.setTranslationY(Look.dp(c, 8)); + gameRows.animate().alpha(1f).translationY(0f).setStartDelay(Look.TAB_OUT_MS).setDuration(Look.TAB_IN_MS).setInterpolator(Look.OUT).withLayer().start(); + } + + private void leaveGame() { + onGame = false; + gameRows.setVisibility(View.GONE); + gameFoot.setVisibility(View.GONE); + head.setVisibility(View.VISIBLE); + if (content instanceof ViewGroup && ((ViewGroup) content).getChildCount() > 0) + ((ViewGroup) ((ViewGroup) content).getChildAt(0)).setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); + content.setVisibility(View.VISIBLE); + } + + /** The first of Game's rows (a controller's first focus there), null on the top screen */ + public View firstGameRow() { + if (gameRows == null || gameRows.getChildCount() == 0) return null; + java.util.ArrayList f = gameRows.getChildAt(0).getFocusables(View.FOCUS_FORWARD); + return f.isEmpty() ? null : f.get(0); + } + + /** The tab after (+1) or before (-1) on the rail, with Game first on the bottom screen: for L and R there (dev.nxnative.android.InGamePanel) */ + public void step(int dir) { + int n = names.length; + if (n == 0) return; + if (gameRows == null) { if (show != null) show.accept(Math.floorMod(selected + dir, n)); return; } + int at = onGame ? -1 : selected, to = at + dir; // -1 is Game + if (to < -1) to = n - 1; + if (to >= n) to = -1; + View f = tabs.getRootView().findFocus(); + boolean inRows = f != null && !inside(f, tabs) && !inside(f, head); // the controller was in the rows: it stays in the rows of the next tab + if (to == -1) game(); else pick(to); + if (inRows) tabs.post(() -> { View r = firstRow(); if (r != null) r.requestFocus(); }); + } + + /** + * The rail for these tabs (upstream's names; icons and titles by name), tab selected; show switches the panel to a tab. Built once for a set of tabs, then + * only the selection moves (a rebuild would take the focus away from the item the controller is on) + */ + public void tabs(String[] tabNames, int tab, IntConsumer show) { + this.show = show; + if (!java.util.Arrays.equals(tabNames, names)) { + names = tabNames.clone(); + items.clear(); + tabs.removeAllViews(); + selected = -1; + placed = false; + int h = itemHeight(); + for (int i = 0; i < names.length; i++) { + int k = i; + View item = item(iconOf(names[i]), titleOf(names[i]) + " tab, " + (i + 1) + " of " + names.length); + item.setOnClickListener(v -> { if (this.show != null && (k != selected || onGame)) pick(k); }); + items.add(item); + if (i == names.length - 1) { // the menu's own settings, at the bottom of the rail + FrameLayout rest = new FrameLayout(c); + rest.addView(item, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, h, Gravity.BOTTOM)); + tabs.addView(rest, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); + } else { + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, h); + lp.bottomMargin = Look.dp(c, 2); + tabs.addView(item, lp); + } + } + // Up and down stay on the rail (the next item by id): the nearest focusable below the last tab would be a row of the content, since the + // settings sit at the rail's bottom + List all = new ArrayList<>(); + if (gameItem != null) all.add(gameItem); + all.addAll(items); + for (int i = 0; i < all.size(); i++) { + all.get(i).setNextFocusUpId(all.get(Math.max(0, i - 1)).getId()); + all.get(i).setNextFocusDownId(all.get(Math.min(all.size() - 1, i + 1)).getId()); + } + } + select(tab); + } + + private void select(int tab) { + selected = tab; + if (onGame) { paintIcons(); return; } // the panel rebuilt a tab while Game shows: the rail stays on Game + paintIcons(); + for (int i = 0; i < items.size(); i++) items.get(i).setSelected(i == tab); + if (!focused()) focusable(false); + title.setText(titleOf(tab >= 0 && tab < names.length ? names[tab] : "")); + if (tab >= 0 && tab < items.size()) moveBlock(items.get(tab), placed); + } + + private void paintIcons() { + for (int i = 0; i < items.size(); i++) { + ImageView ic = (ImageView) ((FrameLayout) items.get(i)).getChildAt(0); + Drawable d = Look.icon(c, iconOf(names[i]), !onGame && i == selected ? Look.Ink.SELECTED : Look.Ink.REST); + if (d != null) ic.setImageDrawable(d); + } + if (gameItem != null) { + Drawable d = Look.icon(c, "game", onGame ? Look.Ink.SELECTED : Look.Ink.REST); + if (d != null) ((ImageView) ((FrameLayout) gameItem).getChildAt(0)).setImageDrawable(d); + } + } + + private View blockAt; // the item the block goes to: a later choice wins over an earlier one still waiting for the rail's first layout + + /** The block to an item: sliding (BLOCK_MS) from where it was, or placed at once (the first time, or before the rail is laid out) */ + private void moveBlock(View it, boolean slide) { + blockAt = it; + Runnable go = () -> { + View to = blockAt; + if (to == null || to.getHeight() == 0) return; + int y = 0; + for (View v = to; v != null && v != box; v = v.getParent() instanceof View ? (View) v.getParent() : null) y += v.getTop(); + block.setVisibility(View.VISIBLE); + block.animate().cancel(); + if (block.getLayoutParams().height != to.getHeight()) { block.getLayoutParams().height = to.getHeight(); block.requestLayout(); } + if (slide && placed) block.animate().translationY(y).setDuration(Look.BLOCK_MS).setInterpolator(Look.OUT).start(); + else block.setTranslationY(y); + placed = true; + }; + if (it.getHeight() > 0) go.run(); else box.post(go); + } + + /** The solid icon of a tab, by upstream's name (dev.nxnative.android.ModsPanel's names) */ + public static String iconOf(String tab) { + switch (tab) { + case "Performance": return "bolt"; + case "Display": return "display"; + case "Cheats": return "cheats"; + case "Mods": return "mods"; + case "Controls": return "controller"; + default: return "settings"; + } + } + + /** A tab's title in the header ("General", the menu's own settings, reads Menu settings) */ + public static String titleOf(String tab) { return "General".equals(tab) ? "Menu settings" : tab; } +} diff --git a/android/app/src/main/java/dev/peanuts/mods/CheatFile.java b/android/app/src/main/java/dev/peanuts/mods/CheatFile.java index 81571ded..18ab08af 100644 --- a/android/app/src/main/java/dev/peanuts/mods/CheatFile.java +++ b/android/app/src/main/java/dev/peanuts/mods/CheatFile.java @@ -33,6 +33,17 @@ private CheatFile() {} public static final int NAME_MAX = 127; // a header's name, as the host cuts it (CHEAT_NAME_MAX) + /** A number the player sets for a cheat (the in-game Mods tab's field): the file's own, the range, and the cheat's code lines for a number */ + public interface Number { + long own(); + long min(); + long max(); + /** Shown after the number ("coins"), null for none */ + String unit(); + /** The cheat's code lines writing v (v inside min and max); null when it cannot be written */ + List lines(long v); + } + /** What a cheat does, from its opcodes. label: the chip's word */ public enum Kind { CODE("Code"), DATA("Data"), VALUE("Value"), UNSUPPORTED("Not supported"); @@ -54,15 +65,25 @@ public static final class Cheat { public final boolean pointers; // reads a pointer chain (opcode 5) public final int valueWord, valueWidth; // Value: the index of the number's first word in words, and its width in bytes; else -1, 0 public final long[] words; + public final MncfBuild.Cheat mncf; // the .mncf cheat this one is, for the build that runs (MncfBuild); null for a cheat of an Atmosphère file + public final Number number; // the number the player sets in the in-game tab (Part F's field), null when it has none + + Cheat(String name, String key, String group, boolean master, List lines, long[] words, Shape s) { this(name, key, group, master, lines, words, s, null, null); } - Cheat(String name, String key, String group, boolean master, List lines, long[] words, Shape s) { + Cheat(String name, String key, String group, boolean master, List lines, long[] words, Shape s, MncfBuild.Cheat mncf, MncfBuild.Ready ready) { this.name = name; this.key = key; this.group = group; this.master = master; this.lines = Collections.unmodifiableList(lines); this.words = words; kind = s.kind; hold = Collections.unmodifiableList(s.hold); why = s.why; codePlaces = s.codePlaces; pointers = s.pointers; valueWord = s.valueWord; valueWidth = s.valueWidth; + this.mncf = mncf; + if (mncf != null && mncf.value != null && ready != null && !mncf.refused()) number = CheatValues.mncf(ready, mncf, lines); + else number = CheatValues.plainValue(this) ? CheatValues.atmosphere(this) : null; } public boolean switchable() { return !master && kind != Kind.UNSUPPORTED; } + /** The .mncf reason it cannot run here (Appendix B, or runtime:<why>), null for one that can and for an Atmosphère cheat */ + public String reason() { return mncf == null ? null : mncf.reason; } + /** The hold chip's words: "Hold ZL", "Hold B or ZL"; null without a key-press condition */ public String holdLabel() { return hold.isEmpty() ? null : "Hold " + String.join(" or ", hold); } @@ -86,6 +107,7 @@ public static final class Parsed { public final List restores = new ArrayList<>(); // the hidden "Restore Code" entries public final List titles = new ArrayList<>(); // the file's title labels (TID=, BID=) public String build; // a first line "build ": its first 16 hex digits, upper case; else null + public MncfBuild.Ready mncf; // the .mncf file these cheats are of, made ready for the build (MncfBuild); null for an Atmosphère file /** The cheats a player may switch (not the Not supported ones) */ public int switchable() { int n = 0; for (Cheat c : cheats) if (c.switchable()) n++; return n; } @@ -223,6 +245,44 @@ public static Parsed parse(String text, long textEnd) { return p; } + /** + * An .mncf file made ready for the build (MncfBuild.Ready) as the page and the tab read a file: its cheats in the file's order with their groups, their + * Atmosphère code for this build (kind and hold buttons from it, as for any file), the refused ones as Not supported with their reason; masters apart; + * the file's authors as its credit. Names are made unique as parse makes them ("Name #2"), so a converted file keeps the keys its Atmosphère file had + */ + public static Parsed fromMncf(MncfBuild.Ready r, long textEnd) { + Parsed p = new Parsed(); + p.mncf = r; + if (r.file != null) for (String a : r.file.authors()) p.credits.add(a); + Map seen = new HashMap<>(); + for (MncfBuild.Cheat c : r.cheats) { + String name = c.name.length() > NAME_MAX ? c.name.substring(0, NAME_MAX) : c.name; + int dup = seen.merge(name, 1, Integer::sum) - 1; + String key = dup == 0 ? name : name + " #" + (dup + 1); + List ws = new ArrayList<>(); + for (String l : c.lines) if (codeLine(l)) words(l, ws); + long[] w = new long[ws.size()]; + for (int i = 0; i < w.length; i++) w[i] = ws.get(i); + Shape s = c.refused() ? refusedShape(c.reason) : classify(w, textEnd); + String group = c.group; + Cheat x = new Cheat(name, key, group, c.master, new ArrayList<>(c.lines), w, s, c, r); + if (c.master) { // not a switch; a refused one is left out (the cheats that require it say why: requires:) + if (!c.refused()) p.masters.add(x); + continue; + } + p.cheats.add(x); + if (!group.isEmpty() && !p.groups.contains(group)) p.groups.add(group); + } + return p; + } + + private static Shape refusedShape(String reason) { + Shape s = new Shape(); + s.kind = Kind.UNSUPPORTED; + s.why = reason; + return s; + } + /** No code, or only end / else words (opcode 2): what cheatslips puts under a group heading */ static boolean noop(long[] w) { for (long x : w) if ((x >>> 28) != 2) return false; @@ -369,8 +429,16 @@ static String buttons(long mask) { /** What a cheat changes, in the player's words, for the bottom screen and its details (no developer terms: UI-RULES 5) */ public static String describe(Cheat c) { return describe(c, c.value()); } - /** The same, a Value cheat writing value (the number set in the in-game Mods tab, CheatValues) */ + /** The same, a Value cheat writing value (the number set in the in-game Mods tab, CheatValues); an .mncf cheat's own words (its about) first */ public static String describe(Cheat c, long value) { + if (c.mncf != null && c.mncf.refused()) return MncfWords.reason(c.mncf.reason, c.mncf) + " It stays off."; + String d = describeKind(c, value); + if (c.number != null && c.kind != Kind.VALUE) d += " Its number is " + value + (c.number.unit() == null ? "" : " " + c.number.unit()) + "."; + String about = c.mncf == null || c.mncf.about == null ? null : c.mncf.about.trim(); + return about == null || about.isEmpty() ? d : (about.matches(".*[.!?]$") ? about : about + ".") + " " + d; + } + + private static String describeKind(Cheat c, long value) { String hold = c.hold.isEmpty() ? null : String.join(" or ", c.hold); switch (c.kind) { case UNSUPPORTED: diff --git a/android/app/src/main/java/dev/peanuts/mods/CheatImport.java b/android/app/src/main/java/dev/peanuts/mods/CheatImport.java index 5270a800..55676aca 100644 --- a/android/app/src/main/java/dev/peanuts/mods/CheatImport.java +++ b/android/app/src/main/java/dev/peanuts/mods/CheatImport.java @@ -26,7 +26,9 @@ *

  • Eden and Yuzu: load/<TID>/<name>/cheats/<BID>.txt, also without load/;
  • *
  • Ryujinx: mods/contents/<TID>/<name>/cheats/<BID>.txt;
  • *
  • a mod's own folder: <name>/cheats/<BID>.txt;
  • - *
  • a bare <BID>.txt, or any .txt whose first line is "build <BID>".
  • + *
  • a bare <BID>.txt, or any .txt whose first line is "build <BID>";
  • + *
  • an .mncf file anywhere in it (the Mistel Native Cheat Format: one file for all of a game's builds), or the .mncf files of an .mncp pack + * ({@link #fromPack}: its manifest and every file's hash checked).
  • * * BID is 16 hex digits (the first 8 bytes of main's build ID) or 32. A file whose BID is one of the game's main builds is for the game; any other is "for another * version", with its BID; one under another game's TID is left out. A pick with romfs or exefs folders is a mod and goes to the mod import (ModImporter), which @@ -36,6 +38,8 @@ public final class CheatImport { private CheatImport() {} public static final int MAX_FILE = 256 * 1024, MAX_TXT = 64, MAX_PATHS = 20000; + public static final int MAX_MNCF = io.github.davdxpx.mistel.mncf.Mncf.MAX_FILE; // an .mncf may be larger than an Atmosphère file: the format's own limit + public static final int MAX_PACK = 32 * 1024 * 1024; // an .mncp read whole (cheat packs are small; a mod's zip is not read this way) /** A .txt of the pick: its path in it ('/' between folders) and its bytes */ public static final class In { @@ -57,14 +61,29 @@ public static final class Hit { @Override public String toString() { return path + ":" + bid + (set != null ? "/" + set : "") + ":" + cheats(); } } + /** One .mncf file found: its path, its bytes as they are (kept so; a signature stays good), the file read (null: it cannot be used, error says why) */ + public static final class MncfHit { + public final String path, error; + public final byte[] data; + public final io.github.davdxpx.mistel.mncf.MncfFile file; + MncfHit(String path, byte[] data, io.github.davdxpx.mistel.mncf.MncfFile file, String error) { this.path = path; this.data = data; this.file = file; this.error = error; } + /** Its cheats (not the masters) */ + public int cheats() { int n = 0; if (file != null) for (io.github.davdxpx.mistel.mncf.Cheat c : file.cheats()) if (!c.isMaster()) n++; return n; } + /** The name it is added under: its file's name without .mncf */ + public String name() { return new File(path).getName().replaceFirst("(?i)\\.mncf$", ""); } + @Override public String toString() { return path + ":" + (file == null ? error : cheats() + " cheats"); } + } + /** What the pick holds */ public static final class Found { public final List forGame = new ArrayList<>(), otherVersion = new ArrayList<>(), otherGame = new ArrayList<>(); public final List noBuild = new ArrayList<>(); // cheat files that name no build (their paths) + public final List mncf = new ArrayList<>(), mncfOtherGame = new ArrayList<>(), mncfBroken = new ArrayList<>(); // .mncf files: the game's, another game's, unreadable ones + public boolean pack; // a pick with pack.toml at its root: an .mncp, read again whole (fromPack) public boolean mod; // romfs or exefs folders in it: a mod public String name; // the source's name - public int cheats() { int n = 0; for (Hit h : forGame) n += h.parsed.switchable(); return n; } + public int cheats() { int n = 0; for (Hit h : forGame) n += h.parsed.switchable(); for (MncfHit m : mncf) n += m.cheats(); return n; } /** The game's cheats that are Not supported (listed, never switched) */ public int unsupported() { int n = 0; for (Hit h : forGame) n += h.parsed.unsupported(); return n; } public int otherCheats() { int n = 0; for (Hit h : otherVersion) n += h.cheats(); return n; } @@ -141,8 +160,10 @@ static String name(String hint, List hits) { public static Found read(List files, List paths, String titleId, Set builds, String nameHint) { Found f = new Found(); for (String p : paths) if (modPath(p)) { f.mod = true; break; } + for (String p : paths) if (norm(p).equals("pack.toml")) { f.pack = true; break; } List taken = new ArrayList<>(); // the game's files' texts: one zip with the same file in two layouts adds it once for (In in : files) { + if (in.path.toLowerCase(Locale.ROOT).endsWith(".mncf")) { mncf(f, in, titleId); continue; } if (in.data.length > MAX_FILE) continue; String text = new String(in.data, StandardCharsets.UTF_8); if (text.indexOf('\0') >= 0) continue; @@ -167,6 +188,42 @@ else if (builds.contains(bid)) { return f; } + /** An .mncf of the pick: the game's (its game ID the game's, or that of another program of it), another game's, or one that cannot be used */ + static void mncf(Found f, In in, String titleId) { + String path = norm(in.path); + for (MncfHit h : f.mncf) if (java.util.Arrays.equals(h.data, in.data)) return; // the same file twice in one pick + try { + io.github.davdxpx.mistel.mncf.MncfFile m = io.github.davdxpx.mistel.mncf.Mncf.load(in.data, MncfBuild.TRUST); + MncfHit h = new MncfHit(path, in.data, m, null); + if (!"switch".equals(m.platform().name()) || titleId != null && !sameGame(m.gameId(), titleId)) f.mncfOtherGame.add(h); + else f.mncf.add(h); + } catch (io.github.davdxpx.mistel.mncf.MncfException e) { + f.mncfBroken.add(new MncfHit(path, in.data, null, e.code())); + } + } + + /** + * An .mncp pack read whole (Mistel's spec, section 13): its .mncf files whose hash its manifest holds, as the pick's files; paths gets every file it + * lists. IOException when the pack cannot be used at all (not a pack, its manifest's signature invalid or revoked); a file whose hash differs or that is + * missing is left out and named in broken + */ + public static List fromPack(byte[] zip, List paths, List broken) throws IOException { + io.github.davdxpx.mistel.mncf.Pack pack; + try { + pack = io.github.davdxpx.mistel.mncf.PackReader.read(zip, MncfBuild.TRUST); + } catch (io.github.davdxpx.mistel.mncf.MncfException e) { + throw new IOException("It is not a cheat pack Peanuts can read (" + e.code() + ").", e); + } + if (!pack.usable()) throw new IOException("The pack was changed after it was signed, so none of its cheats were added."); + List out = new ArrayList<>(); + for (io.github.davdxpx.mistel.mncf.PackFile pf : pack.files()) { + if (paths.size() < MAX_PATHS) paths.add(pf.path()); + if (!io.github.davdxpx.mistel.mncf.PackFile.OK.equals(pf.status())) { broken.add(pf.path() + ": " + pf.status()); continue; } + if (pf.path().toLowerCase(Locale.ROOT).endsWith(".mncf")) out.add(new In(pf.path(), pf.data())); + } + return out; + } + // ---- Reading a pick ---- private static byte[] readMax(InputStream in, int max) throws IOException { @@ -179,15 +236,16 @@ private static byte[] readMax(InputStream in, int max) throws IOException { return o.toByteArray(); } - /** A zip's .txt files (at most MAX_TXT, each at most MAX_FILE) and every path in it into paths */ + /** A zip's .txt files (at most MAX_TXT, each at most MAX_FILE) and .mncf files (each at most MAX_MNCF), and every path in it into paths */ public static List fromZip(InputStream in, List paths) throws IOException { List out = new ArrayList<>(); try (ZipInputStream z = new ZipInputStream(in)) { for (ZipEntry e; (e = z.getNextEntry()) != null; ) { String n = e.getName(); if (paths.size() < MAX_PATHS) paths.add(n); - if (e.isDirectory() || !n.toLowerCase(Locale.ROOT).endsWith(".txt") || out.size() >= MAX_TXT) continue; - byte[] b = readMax(z, MAX_FILE); + boolean mncf = n.toLowerCase(Locale.ROOT).endsWith(".mncf"); + if (e.isDirectory() || !mncf && !n.toLowerCase(Locale.ROOT).endsWith(".txt") || out.size() >= MAX_TXT) continue; + byte[] b = readMax(z, mncf ? MAX_MNCF : MAX_FILE); if (b != null) out.add(new In(n, b)); } } catch (IllegalArgumentException e) { // a name the zip's charset cannot read @@ -212,7 +270,8 @@ private static void walk(File dir, String rel, int depth, List out, List= MAX_PATHS) return; paths.add(f.isDirectory() ? p + "/" : p); if (f.isDirectory()) { if (!modPath(p)) walk(f, p, depth + 1, out, paths); continue; } - if (!f.getName().toLowerCase(Locale.ROOT).endsWith(".txt") || out.size() >= MAX_TXT || f.length() > MAX_FILE) continue; + boolean mncf = f.getName().toLowerCase(Locale.ROOT).endsWith(".mncf"); + if (!mncf && !f.getName().toLowerCase(Locale.ROOT).endsWith(".txt") || out.size() >= MAX_TXT || f.length() > (mncf ? MAX_MNCF : MAX_FILE)) continue; out.add(new In(p, Files.readAllBytes(f.toPath()))); } } diff --git a/android/app/src/main/java/dev/peanuts/mods/CheatImportUi.java b/android/app/src/main/java/dev/peanuts/mods/CheatImportUi.java index dc54c72f..f5b29ae7 100644 --- a/android/app/src/main/java/dev/peanuts/mods/CheatImportUi.java +++ b/android/app/src/main/java/dev/peanuts/mods/CheatImportUi.java @@ -4,6 +4,7 @@ import android.app.AlertDialog; import android.content.Intent; import android.net.Uri; +import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; @@ -24,13 +25,16 @@ * Mods & Cheats › Add (SPEC-mod-menu.md, Package B 2): a file (.zip or .txt) or a folder from this device, read off the UI thread * (CheatImport), then one dialog in the app's AlertDialog look: the cheats for the game's version ("Add cheats"), or why not (another version, another game, no * build named, nothing found). A pick with romfs or exefs folders is a mod: it goes to the mod import (ModsSection) on the page's Mods tab. Nothing is downloaded. + * An .mncf (or an .mncp pack of them) is added as it is; any other cheat file becomes an .mncf as it is added (CheatSources.add: MncfConvert), off the UI thread, + * and is made ready for the game's build before the page lists it. Export ({@link #export}) writes the game's sources as .mncf or .mncp, or as a ZIP in + * Atmosphère's folders for other emulators (MncfExport). * The pickers' results come back through MainActivity.onActivityResult → dev.peanuts.ui.LibrarySettings.result → {@link #result}. */ public final class CheatImportUi { private CheatImportUi() {} - public static final int REQ_FILE = CheatsBridge.REQ_FILE, REQ_FOLDER = CheatsBridge.REQ_FOLDER; // the cheat rows' codes: this page replaces those rows - private static boolean waiting; // a pick of this page is open (the rows' sheet uses the same codes) + public static final int REQ_FILE = CheatsBridge.REQ_FILE, REQ_FOLDER = CheatsBridge.REQ_FOLDER, REQ_EXPORT = CheatsBridge.REQ_EXPORT; // the cheat rows' codes: this page replaces those rows + private static boolean waiting, exporting; // a pick or an export of this page is open (the rows' sheet uses the same codes) /** Add: a file or a folder */ static void add(Activity a, String titleId) { @@ -38,7 +42,7 @@ static void add(Activity a, String titleId) { box.setOrientation(LinearLayout.VERTICAL); AlertDialog[] d = new AlertDialog[1]; PUi.add(box, PUi.body(a, "Cheats or a mod for this game, from this device. Peanuts never downloads any."), 0); - PUi.Setting file = new PUi.Setting(a, "", "A file", Feel.row(v -> { d[0].dismiss(); pick(a, false); })).value("A .zip or a .txt").chevron(a); + PUi.Setting file = new PUi.Setting(a, "", "A file", Feel.row(v -> { d[0].dismiss(); pick(a, false); })).value("A .zip, a .txt, an .mncf or an .mncp").chevron(a); Icons.tile((TextView) file.view.getChildAt(0), "list"); PUi.add(box, file.view, 12); PUi.Setting folder = new PUi.Setting(a, "", "A folder", Feel.row(v -> { d[0].dismiss(); pick(a, true); })).value("With Atmosphère, Eden or Ryujinx folders, or a mod's").chevron(a); @@ -51,14 +55,220 @@ static void add(Activity a, String titleId) { private static void pick(Activity a, boolean folder) { Intent i = folder ? new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) : new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*") - .putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"application/zip", "application/x-zip-compressed", "text/plain", "application/octet-stream"}); + .putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"application/zip", "application/x-zip-compressed", "text/plain", "application/octet-stream", "application/toml"}); i.putExtra(android.provider.DocumentsContract.EXTRA_INITIAL_URI, Uri.parse("content://com.android.externalstorage.documents/document/primary%3A")); try { waiting = true; a.startActivityForResult(i, folder ? REQ_FOLDER : REQ_FILE); } catch (android.content.ActivityNotFoundException e) { Toast.makeText(a, "This device has no file picker.", Toast.LENGTH_LONG).show(); } } - /** LibrarySettings.result (PEANUTS: Mods & Cheats' pickers, asked before CheatsBridge's): true when the request was Add's, the one this page started */ + private static boolean exportZip; // the export that is open: a ZIP for other emulators, else .mncf / .mncp + private static MncfExport.Zip exportPlan; // the ZIP the dialog worked out (it reads the game's main once), written as it is; null: worked out when written + + /** + * Export: one dialog with the two ways the cheats leave Peanuts. The Mistel cheat file (one .mncf, or an .mncp for several sources), recommended and picked: + * every cheat for every version, with what is on and the numbers set. Or a ZIP in Atmosphère's folders for other emulators: one file for each version, + * with what Atmosphère code can say; which cheats cannot go in (and why) is worked out off the UI thread and shown under it, before anything is written + */ + static void export(Activity a, CheatsPage.Game g, int sources) { + LinearLayout box = new LinearLayout(a); + box.setOrientation(LinearLayout.VERTICAL); + boolean[] zip = {false}; + MncfExport.Zip[] plan = new MncfExport.Zip[1]; + boolean[] planned = new boolean[1]; + AlertDialog[] d = new AlertDialog[1]; + LinearLayout mncf = choice(a, "check", "Mistel cheat file", "Recommended", (sources == 1 ? "One .mncf" : "An .mncp of " + sources + " files") + + ": every cheat for every version, with what you turned on and the numbers you set."); + LinearLayout other = choice(a, "folder", "ZIP for other emulators", null, "Atmosphère's folders, one file for each version, for Atmosphère, Eden, Ryujinx and others."); + LinearLayout details = new LinearLayout(a); + details.setOrientation(LinearLayout.VERTICAL); + details.setVisibility(View.GONE); + details.addView(PUi.progress(a), PUi.wrap()); // until the plan is known + PUi.add(other, details, 0); + Runnable show = () -> { + select(a, mncf, !zip[0]); + select(a, other, zip[0]); + details.setVisibility(zip[0] ? View.VISIBLE : View.GONE); + if (zip[0]) box.post(() -> ((android.widget.ScrollView) box.getParent()).smoothScrollTo(0, other.getTop())); // what goes in and what stays out, in view + if (d[0] != null && d[0].getButton(AlertDialog.BUTTON_POSITIVE) != null) + d[0].getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(!zip[0] || !planned[0] || plan[0] != null && plan[0].cheats > 0); + }; + mncf.setOnClickListener(Feel.row(v -> { zip[0] = false; show.run(); })); + other.setOnClickListener(Feel.row(v -> { zip[0] = true; show.run(); })); + mncf.setContentDescription("Mistel cheat file, recommended"); + other.setContentDescription("ZIP for other emulators"); + box.addView(mncf); + PUi.add(box, other, 10); + d[0] = PUi.sheet(a, "Export cheats", box).setNegativeButton("Cancel", null) + .setPositiveButton("Export", Feel.confirm((x, w) -> pickExport(a, g, sources, zip[0], zip[0] ? plan[0] : null))).create(); + Feel.dialog(d[0]); + d[0].show(); + show.run(); + new Thread(() -> { + MncfExport.Zip z = null; + try { + z = zipOf(a, g); + } catch (IOException | RuntimeException e) { + android.util.Log.w("peanuts", "cheats: export: the ZIP's plan: " + e); + } + MncfExport.Zip zz = z; + a.runOnUiThread(() -> { + if (!d[0].isShowing()) return; + plan[0] = zz; + planned[0] = true; + details.removeAllViews(); + zipLines(a, g, zz, details); + show.run(); + }); + }, "peanuts-cheat-export").start(); + } + + /** One way to export, as a card the player picks: a tile, its title (with a badge), a line under it; select() draws it picked or not */ + private static LinearLayout choice(Activity a, String icon, String title, String badge, String sub) { + LinearLayout card = new LinearLayout(a); + card.setOrientation(LinearLayout.VERTICAL); + card.setPadding(PUi.dp(a, 14), PUi.dp(a, 10), PUi.dp(a, 14), PUi.dp(a, 10)); + card.setClickable(true); + card.setFocusable(true); + LinearLayout row = PUi.row(a); + row.setGravity(android.view.Gravity.CENTER_VERTICAL); + TextView tile = PUi.text(a, "", 12, R.color.bn_text, 400); + tile.setTag(icon); + row.addView(tile, new LinearLayout.LayoutParams(PUi.dp(a, 44), PUi.dp(a, 44))); + LinearLayout col = new LinearLayout(a); + col.setOrientation(LinearLayout.VERTICAL); + col.setPadding(PUi.dp(a, 14), 0, PUi.dp(a, 8), 0); + LinearLayout head = PUi.row(a); + head.setGravity(android.view.Gravity.CENTER_VERTICAL); + head.addView(PUi.text(a, title, 17, R.color.bn_text, 800), PUi.wrap()); + if (badge != null) { + LinearLayout.LayoutParams lp = PUi.wrap(); + lp.leftMargin = PUi.dp(a, 8); + head.addView(CheatsPage.chip(a, badge, true), lp); + } + col.addView(head); + TextView s = PUi.small(a, sub); + s.setLineSpacing(0, 1.1f); + col.addView(s); + row.addView(col, PUi.weight()); + TextView mark = new TextView(a); // the pick: a ring with a dot, or an empty ring + row.addView(mark, new LinearLayout.LayoutParams(PUi.dp(a, 24), PUi.dp(a, 24))); + card.addView(row); + return card; + } + + /** A choice card drawn picked (tinted, banana outline, banana tile, a dot in the ring) or not (an outline, a quiet tile, an empty ring) */ + private static void select(Activity a, LinearLayout card, boolean on) { + LinearLayout row = (LinearLayout) card.getChildAt(0); + TextView tile = (TextView) row.getChildAt(0), mark = (TextView) row.getChildAt(2); + card.setBackground(PUi.ripple(a, PUi.round(PUi.col(a, on ? R.color.bn_tint : R.color.bn_card), PUi.dp(a, 16), PUi.col(a, on ? R.color.bn_banana : R.color.bn_card_stroke), PUi.dp(a, on ? 2 : 1)))); + tile.setBackground(PUi.round(PUi.col(a, on ? R.color.bn_banana : R.color.bn_tint), PUi.dp(a, 13), 0, 0)); + android.graphics.drawable.Drawable icon = Icons.get(a, (String) tile.getTag(), on ? Icons.Ink.ON_BANANA : Icons.Ink.NORMAL); + tile.setForeground(icon == null ? null : new android.graphics.drawable.InsetDrawable(icon, PUi.dp(a, 10))); + mark.setBackground(PUi.round(android.graphics.Color.TRANSPARENT, PUi.dp(a, 12), PUi.col(a, on ? R.color.bn_banana : R.color.bn_text_2), PUi.dp(a, 2))); + mark.setForeground(on ? new android.graphics.drawable.InsetDrawable(PUi.round(PUi.col(a, R.color.bn_banana), PUi.dp(a, 6), 0, 0), PUi.dp(a, 6)) : null); + card.setSelected(on); + } + + /** The ZIP of the game's sources as it would be written now (MncfExport.zip) */ + private static MncfExport.Zip zipOf(Activity a, CheatsPage.Game g) throws IOException { + File folder = CheatsBridge.folder(a, g.titleId); + String build = CheatsBridge.builds(g.titleId, g.packDir).stream().findFirst().orElse(null); + CheatSources.Merged m = build == null ? null : CheatsBridge.merged(a, g.titleId, g.gameDir, g.packDir, build, CheatsBridge.textEnd(g.packDir), true); + return MncfExport.zip(folder, g.name, CheatsBridge.game(g.titleId, build, g.packDir), m, CheatValues.read(folder)); + } + + /** Most of the cheats left out the dialog names one by one; the rest are counted */ + static final int LEFT_NAMED = 5; + + /** Under the ZIP's card: how many cheats go in, for which versions, and calmly, which ones cannot and why (the Mistel cheat file keeps them) */ + private static void zipLines(Activity a, CheatsPage.Game g, MncfExport.Zip z, LinearLayout to) { + List lines = new ArrayList<>(); + if (z == null) { + lines.add(new String[] {"info", "Checked when you export", "Which cheats fit an Atmosphère file is worked out as the ZIP is written."}); + } else if (z.cheats == 0) { + lines.add(new String[] {"info", "None of them fits a ZIP", "An Atmosphère file cannot hold what these cheats do. The Mistel cheat file keeps them all."}); + } else { + List per = new ArrayList<>(); + for (Map.Entry e : z.builds.entrySet()) { + String v = z.versions.get(e.getKey()); + if (v == null) v = CheatsBridge.version(g.titleId, e.getKey()); + per.add(per.isEmpty() ? CheatsPage.count(e.getValue(), "cheat") + " for " + (v != null ? v : "build " + CheatsPage.shortBuild(e.getKey())) : e.getValue() + " for " + (v != null ? v : "build " + CheatsPage.shortBuild(e.getKey()))); + } + lines.add(new String[] {"check", String.join(", ", per), z.builds.size() == 1 ? "One file, where Atmosphère and the others look for it." : "One file for each version, where Atmosphère and the others look for them."}); + if (!z.left.isEmpty()) lines.add(new String[] {"info", (z.left.size() == 1 ? "1 stays out" : z.left.size() + " stay out") + " of the ZIP", + "An Atmosphère file cannot hold what " + (z.left.size() == 1 ? "it does" : "they do") + ". The Mistel cheat file keeps " + (z.left.size() == 1 ? "it." : "them.")}); + } + for (String[] line : lines) PUi.add(to, line(a, line), 12); + if (z == null || z.left.isEmpty() || z.cheats == 0) return; + LinearLayout names = new LinearLayout(a); + names.setOrientation(LinearLayout.VERTICAL); + names.setPadding(PUi.dp(a, 44), 0, 0, 0); // under the line's text, past its tile + for (int i = 0; i < z.left.size() && i < LEFT_NAMED; i++) { + TextView n = PUi.text(a, z.left.get(i)[0], 14, R.color.bn_text, 600); + n.setSingleLine(true); + n.setEllipsize(android.text.TextUtils.TruncateAt.END); + PUi.add(names, n, i == 0 ? 0 : 8); + TextView why = PUi.small(a, z.left.get(i)[1]); + why.setLineSpacing(0, 1.1f); + names.addView(why); + } + if (z.left.size() > LEFT_NAMED) PUi.add(names, PUi.small(a, "And " + (z.left.size() - LEFT_NAMED) + " more."), 8); + PUi.add(to, names, 10); + } + + /** The export's file picked: the name and kind of the format chosen */ + private static void pickExport(Activity a, CheatsPage.Game g, int sources, boolean zip, MncfExport.Zip plan) { + Intent i = new Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType(zip ? "application/zip" : "application/octet-stream") + .putExtra(Intent.EXTRA_TITLE, zip ? MncfExport.zipName(g.name) : MncfExport.fileName(g.name, sources > 1)); + try { exporting = true; exportZip = zip; exportPlan = plan; a.startActivityForResult(i, REQ_EXPORT); } + catch (android.content.ActivityNotFoundException e) { exporting = false; Toast.makeText(a, "This device has no file picker.", Toast.LENGTH_LONG).show(); } + } + + /** The export written to the document picked, off the UI thread; a ZIP as the dialog worked it out (plan), or worked out now when it had not yet */ + private static void exported(Activity a, CheatsPage.Game g, Uri u, boolean zip, MncfExport.Zip plan) { + CheatPick.work(a, "Export cheats", () -> { + File folder = CheatsBridge.folder(a, g.titleId); + byte[] bytes; + String done; + if (zip) { + MncfExport.Zip z = plan != null ? plan : zipOf(a, g); + if (z == null) throw new IOException("There are no added cheats to export."); + if (z.cheats == 0) throw new IOException("None of the cheats fits an Atmosphère file. Export them as a Mistel cheat file, which keeps them all."); + bytes = z.bytes; + done = "Exported " + CheatsPage.count(z.cheats, "cheat") + " as a ZIP" + (z.left.isEmpty() ? "." : ". " + (z.left.size() == 1 ? "1 could" : z.left.size() + " could") + " not go in."); + } else { + String build = CheatsBridge.builds(g.titleId, g.packDir).stream().findFirst().orElse(null); + CheatSources.Merged m = build == null ? null : CheatsBridge.merged(a, g.titleId, g.gameDir, g.packDir, build, CheatsBridge.textEnd(g.packDir), true); + MncfExport.Out out = MncfExport.make(folder, g.name, m, CheatsBridge.on(a, g.titleId), CheatValues.read(folder)); + if (out == null) throw new IOException("There are no added cheats to export."); + bytes = out.bytes; + done = "Exported " + CheatsPage.count(out.cheats, "cheat") + (out.pack ? " of " + out.sources + " sources as a pack." : "."); + } + try (java.io.OutputStream os = a.getContentResolver().openOutputStream(u)) { + if (os == null) throw new IOException("The place picked cannot be written. Pick another one."); + os.write(bytes); + } + return done; + }, done -> { + Feel.accepted(a); + Toast.makeText(a, done, Toast.LENGTH_LONG).show(); + }, e -> { + Feel.refused(a); + android.util.Log.w("peanuts", "cheats: export: " + e); + message(a, "Not exported", e instanceof IOException && e.getMessage() != null && e.getMessage().endsWith(".") ? e.getMessage() : "The cheats could not be written there. Nothing was changed here."); + }); + } + + /** LibrarySettings.result (PEANUTS: Mods & Cheats' pickers, asked before CheatsBridge's): true when the request was Add's or Export's, the ones this page started */ public static boolean result(Activity a, int request, int result, Intent data) { + if (request == REQ_EXPORT && exporting) { + exporting = false; + CheatsPage.Game g = CheatsPage.shown(); + MncfExport.Zip plan = exportPlan; + exportPlan = null; + if (result == Activity.RESULT_OK && data != null && data.getData() != null && g != null) exported(a, g, data.getData(), exportZip, plan); + return true; + } if (request != REQ_FILE && request != REQ_FOLDER || !waiting) return false; waiting = false; if (result != Activity.RESULT_OK || data == null || data.getData() == null) return true; @@ -85,23 +295,27 @@ static void decide(Activity a, CheatsPage.Game g, CheatImport.Found f, String wh } if (build == null) { message(a, "Build the game first", "Cheats are made for one build of the game, and this game's build is not known yet. Prepare the game, then add them."); return; } File folderOf = CheatsBridge.folder(a, g.titleId); + if (!f.mncf.isEmpty()) { decideMncf(a, g, f, what, from, build, yours); return; } if (!f.forGame.isEmpty()) { for (CheatImport.Hit h : f.forGame) { - CheatSources.Source same = CheatSources.sameAs(folderOf, h.bid, h.text); + CheatSources.Source same = CheatSources.sameAs(folderOf, h.text); if (same != null && f.forGame.size() == 1) { message(a, "Added already", same.name + " has the same cheats. Nothing was added."); return; } } int n = f.cheats(); List lines = new ArrayList<>(); lines.add(new String[] {"check", CheatsPage.count(n, "cheat") + " for your version", "Build " + CheatsPage.shortBuild(build) + ", the one your game was built from." + (f.groups() > 0 ? " " + CheatsPage.count(f.groups(), "group") + "." : "")}); + lines.add(new String[] {"lock", "Checked before every write", "Each cheat that changes the game's code names the code it expects there, taken from your game. Peanuts compares it before it writes."}); + lines.add(new String[] {"update", "Ready for game updates", "Its places are found again by the code around them, so the cheats keep working after an update."}); if (f.unsupported() > 0) lines.add(new String[] {"info", f.unsupported() + " more " + (f.unsupported() == 1 ? "is" : "are") + " not supported", "They use a part of the cheat format Peanuts does not run. They are listed and stay off."}); if (f.restores()) lines.add(new String[] {"info", "Restore Code is left out", "Peanuts puts the original code back by itself when you turn a cheat off."}); if (!f.otherVersion.isEmpty()) lines.add(new String[] {"info", CheatsPage.count(f.otherVersion.size(), "file") + " for another version", "Kept with them: they work when the game is that version."}); if (!folder && CheatSources.FROM_ZIP.equals(from)) lines.add(new String[] {"info", "No mods in this zip", "Mods go in the same way: a zip with romfs or exefs folders."}); - dialog(a, "Add cheats", "From " + what + " for " + g.name + (version != null ? " " + version : "") + ".", lines, - "Cancel", null, "Add " + CheatsPage.count(n, "cheat"), () -> take(a, f, from, n)); + View card = formatCard(a, "update", "Becomes a Mistel cheat file", "Atmosphère cheats from " + what + ". Peanuts keeps them as one .mncf for every version of the game.", null); + dialog(a, "Add cheats", card, null, lines, + "Cancel", null, "Add " + CheatsPage.count(n, "cheat"), () -> take(a, f, from, n, display != null ? display : what)); return; } if (!f.otherVersion.isEmpty()) { @@ -113,11 +327,17 @@ static void decide(Activity a, CheatsPage.Game g, CheatImport.Found f, String wh "Your game: " + yours + ", build " + CheatsPage.shortBuild(build) + ". None of the " + CheatsPage.count(n, "cheat") + " would hit the right places."}); lines.add(new String[] {"info", "Look for cheats for " + yours, "The file has to be named " + build + ".txt or start with that build."}); dialog(a, "These cheats are for another version", "Cheats only work on the exact build they were made for.", lines, - "Keep them anyway", () -> take(a, f, from, 0), "OK", null); + "Keep them anyway", () -> take(a, f, from, 0, display != null ? display : what), "OK", null); + return; + } + if (!f.otherGame.isEmpty() || !f.mncfOtherGame.isEmpty()) { + String other = !f.otherGame.isEmpty() ? f.otherGame.get(0).tid : f.mncfOtherGame.get(0).file.gameId(); + message(a, "These cheats are for another game", "The " + kind + " has them under the title ID " + other + ", not this game's. Nothing was added."); return; } - if (!f.otherGame.isEmpty()) { - message(a, "These cheats are for another game", "The " + kind + " has them under the title ID " + f.otherGame.get(0).tid + ", not this game's. Nothing was added."); + if (!f.mncfBroken.isEmpty()) { + android.util.Log.w("peanuts", "cheats: .mncf files that cannot be read: " + f.mncfBroken); + message(a, "These cheats cannot be read", "The " + kind + " has a Mistel cheat file Peanuts cannot read: it is damaged or of a newer kind. Nothing was added."); return; } if (!f.noBuild.isEmpty()) { @@ -129,25 +349,174 @@ static void decide(Activity a, CheatsPage.Game g, CheatImport.Found f, String wh message(a, "No cheats in it", "There is no cheat file in the " + kind + ". Cheats are text files in the Atmosphère, Eden or Ryujinx folders; a mod is a zip or a folder with romfs or exefs folders."); } - /** The pick's sources added (one per Eden or Ryujinx set, else one), on; n: the game's cheats, for the line after */ - private static void take(Activity a, CheatImport.Found f, String from, int n) { + /** An .mncf pick (one or more files, or an .mncp): one dialog, the files added as they are */ + private static void decideMncf(Activity a, CheatsPage.Game g, CheatImport.Found f, String what, String from, String build, String yours) { + File folderOf = CheatsBridge.folder(a, g.titleId); + List fresh = new ArrayList<>(); + List had = new ArrayList<>(); + for (CheatImport.MncfHit h : f.mncf) { CheatSources.Source same = CheatSources.sameMncf(folderOf, h.data); if (same != null) had.add(same.name); else fresh.add(h); } + if (fresh.isEmpty()) { message(a, "Added already", String.join(", ", had) + (had.size() == 1 ? " has" : " have") + " the same cheats. Nothing was added."); return; } + List files = new ArrayList<>(); + boolean ours = false; + List authors = new ArrayList<>(); + for (CheatImport.MncfHit h : fresh) { + files.add(h.file); + if (MncfBuild.builds(h.file).contains(build)) ours = true; + for (String x : h.file.authors()) if (!authors.contains(x)) authors.add(x); + } + MncfFacts x = MncfFacts.of(files); + int n = x.cheats; + String by = authors.isEmpty() ? "" : " by " + String.join(", ", authors); + View card = formatCard(a, "check", "Mistel cheat file", (fresh.size() == 1 ? fresh.get(0).name() + ".mncf" : fresh.size() + " files of a pack") + by, x.signer); + List lines = facts(x, yours, ours); + lines.add(new String[] {"search", "Looked up in your game next", "Peanuts finds each cheat's place in " + yours + " and lists the ones that cannot work, with the reason."}); + if (!had.isEmpty()) lines.add(new String[] {"info", "Added already: " + String.join(", ", had), "Those are not added again."}); + dialog(a, "Add cheats", card, null, lines, "Cancel", null, "Add " + CheatsPage.count(n, "cheat"), () -> takeMncf(a, fresh, from, n)); + } + + /** What an .mncf brings, as the dialog's lines (only what it has): its cheats and versions, the checks, the updates, the numbers, the words */ + static List facts(MncfFacts x, String yours, boolean ours) { + List lines = new ArrayList<>(); + String v = x.versionWords(); + lines.add(new String[] {"check", CheatsPage.count(x.cheats, "cheat"), ours ? (x.versions.size() > 1 ? "Made for " + v + ", " + yours + " among them." : "Made for " + yours + ", your version.") + : v == null ? "It names no version: the cheats that find their place in the game's code work on any." : "Made for " + v + ". The cheats that find their place in the game's code can work on " + yours + " too."}); + if (x.checked > 0) lines.add(checked(x.checked, x.cheats)); + if (x.patterns > 0) lines.add(updates(x.patterns)); + if (x.values > 0) lines.add(new String[] {"scale", CheatsPage.count(x.values, "number") + " you can set", "In the game's Mods tab, within the range the file gives."}); + if (x.described > 0) lines.add(new String[] {"info", x.described == x.cheats ? (x.cheats == 1 ? "It says what it does" : "Each says what it does") : x.described == 1 ? "1 says what it does" : x.described + " say what they do", + "Shown on the cheat and on the second screen."}); + return lines; + } + + static String[] checked(int checked, int cheats) { + String who = checked == cheats ? (cheats == 1 ? "It changes" : "Each changes") : checked == 1 ? "1 of them changes" : checked + " of them change"; + return new String[] {"lock", "Checked before every write", who + " the game's code only where the code it expects is, so nothing is written into the wrong place."}; + } + + static String[] updates(int patterns) { + return new String[] {"update", "Ready for game updates", (patterns == 1 ? "1 cheat finds its place by the code around it, so it keeps" : patterns + " cheats find their place by the code around it, so they keep") + + " working after an update."}; + } + + /** + * The card at the top of the Add dialog and the sheet after it: the Mistel cheat file, what it is called and who made it, and who signed it when a key + * Peanuts trusts did (an unsigned file gets no mark: it is as any other) + */ + static View formatCard(Activity a, String icon, String title, String sub, String signer) { + LinearLayout card = PUi.row(a); + card.setGravity(android.view.Gravity.CENTER_VERTICAL); + card.setPadding(PUi.dp(a, 14), PUi.dp(a, 12), PUi.dp(a, 14), PUi.dp(a, 12)); + card.setBackground(PUi.round(PUi.col(a, R.color.bn_tint), PUi.dp(a, 16), 0, 0)); + TextView tile = PUi.text(a, "", 12, R.color.bn_on_banana, 400); + tile.setBackground(PUi.round(PUi.col(a, R.color.bn_banana), PUi.dp(a, 13), 0, 0)); + card.addView(tile, new LinearLayout.LayoutParams(PUi.dp(a, 44), PUi.dp(a, 44))); + android.graphics.drawable.Drawable mark = Icons.get(a, icon, Icons.Ink.ON_BANANA); // on the banana tile: Icons.tile draws in the row tile's colours + if (mark != null) tile.setForeground(new android.graphics.drawable.InsetDrawable(mark, PUi.dp(a, 10))); + LinearLayout col = new LinearLayout(a); + col.setOrientation(LinearLayout.VERTICAL); + col.setPadding(PUi.dp(a, 14), 0, PUi.dp(a, 8), 0); + TextView t = PUi.text(a, title, 17, R.color.bn_text, 800); + col.addView(t); + TextView s = PUi.small(a, sub); + s.setMaxLines(3); + s.setEllipsize(android.text.TextUtils.TruncateAt.END); + col.addView(s); + card.addView(col, PUi.weight()); + if (signer != null) card.addView(CheatsPage.chip(a, "Signed by " + signer, true), PUi.wrap()); + return card; + } + + /** The pick's sources added (one per Eden or Ryujinx set, else one), each made one .mncf, on; n: the game's cheats, for the line after */ + private static void take(Activity a, CheatImport.Found f, String from, int n, String origin) { CheatsPage.Game g = CheatsPage.shown(); if (g == null) return; File folder = CheatsBridge.folder(a, g.titleId); - List added = new ArrayList<>(); - try { + added(a, g, n, true, () -> { + List out = new ArrayList<>(); long now = System.currentTimeMillis(); - for (Map.Entry> e : f.sources().entrySet()) added.add(CheatSources.add(folder, e.getKey(), from, e.getValue(), now++).name); - } catch (IOException | RuntimeException e) { + MncfConvert.Known k = CheatsBridge.known(a, g.titleId, g.name, g.packDir); + for (Map.Entry> e : f.sources().entrySet()) out.add(CheatSources.add(folder, e.getKey(), from, e.getValue(), now++, k, origin)); + return out; + }); + } + + /** .mncf files added as they are, on */ + private static void takeMncf(Activity a, List files, String from, int n) { + CheatsPage.Game g = CheatsPage.shown(); + if (g == null) return; + File folder = CheatsBridge.folder(a, g.titleId); + added(a, g, n, false, () -> { + List out = new ArrayList<>(); + long now = System.currentTimeMillis(); + for (CheatImport.MncfHit h : files) out.add(CheatSources.addMncf(folder, h.name(), from, h.data, now++)); + return out; + }); + } + + /** What adding sources gave: the cheats it switched on (the file's defaults) and what the new files bring */ + private static final class Added { + final java.util.Set on = new java.util.LinkedHashSet<>(); + MncfFacts facts; + String version; + int work, refused; // the new sources' cheats that work on this version, and the ones that cannot (listed with the reason) + String named; // the new files as the card names them: "Example cheats.mncf by Example Team" + } + + /** + * Sources added off the UI thread (add: makes them; a conversion reads the game's main, so the wait says it looks up the cheats there), then made ready for + * the game's build, and their cheats that are on by default (an export's: the ones that were on) switched on; then a sheet with what the new Mistel cheat + * files bring (converted: what the conversion made of them), and the page again. A failure leaves what was added before it + */ + private static void added(Activity a, CheatsPage.Game g, int n, boolean converted, java.util.concurrent.Callable> add) { + CheatPick.work(a, "Add cheats", converted ? "Finding each cheat's place in your game's code." : null, () -> { + List made = add.call(); + Added out = new Added(); + String build = CheatsBridge.builds(g.titleId, g.packDir).stream().findFirst().orElse(null); + out.version = build == null ? null : CheatsBridge.version(g.titleId, build); + if (build != null) { + CheatSources.Merged m = CheatsBridge.merged(a, g.titleId, g.gameDir, g.packDir, build, CheatsBridge.textEnd(g.packDir), true); + java.util.Set ids = new java.util.HashSet<>(); + for (CheatSources.Source s : made) ids.add(s.id); + for (CheatSources.Row r : m.rows) if (ids.contains(r.block.id) && r.cheat.mncf != null && r.cheat.mncf.isDefault && r.cheat.switchable()) out.on.add(r.key); + for (CheatSources.Block b : m.blocks) if (ids.contains(b.id)) for (CheatFile.Cheat c : b.parsed.cheats) { if (c.switchable()) out.work++; else out.refused++; } + } + List files = new ArrayList<>(); + List authors = new ArrayList<>(); + for (CheatSources.Source s : made) { + try { files.add(io.github.davdxpx.mistel.mncf.Mncf.load(java.nio.file.Files.readAllBytes(s.file().toPath()))); } catch (IOException | io.github.davdxpx.mistel.mncf.MncfException ignored) { } + } + for (io.github.davdxpx.mistel.mncf.MncfFile f : files) for (String x : f.authors()) if (!authors.contains(x)) authors.add(x); + out.facts = MncfFacts.of(files); + out.named = (made.size() == 1 ? made.get(0).name + ".mncf" : made.size() + " files") + (authors.isEmpty() ? "" : " by " + String.join(", ", authors)); + return out; + }, out -> { + if (!out.on.isEmpty()) { java.util.Set all = CheatsBridge.on(a, g.titleId); all.addAll(out.on); CheatsBridge.on(a, g.titleId, all); } + Feel.accepted(a); + CheatsPage.rebuild(); + if (n == 0) { Toast.makeText(a, "Kept for another version.", Toast.LENGTH_LONG).show(); return; } + String yours = out.version != null ? out.version : "your version"; + MncfFacts x = out.facts; + List lines = new ArrayList<>(); + int all = out.work + out.refused; + lines.add(new String[] {"check", out.refused == 0 ? (all == 1 ? "It works on " + yours : "All " + all + " work on " + yours) : out.work + " of " + all + " work on " + yours, + "Each was looked up in your game's code."}); + if (out.refused > 0) lines.add(new String[] {"info", out.refused == 1 ? "1 cannot work here" : out.refused + " cannot work here", "Listed with the reason, and off."}); + if (x.checked > 0) lines.add(checked(x.checked, x.cheats)); + if (x.patterns > 0) lines.add(updates(x.patterns)); + if (x.values > 0) lines.add(new String[] {"scale", CheatsPage.count(x.values, "number") + " you can set", "In the game's Mods tab, within the range the file gives."}); + if (converted && x.rawOnly > 0) lines.add(new String[] {"layers", x.rawOnly == 1 ? "1 kept as its own code" : x.rawOnly + " kept as their own code", + "Code that does more than change places Peanuts can name runs as it came, on " + yours + "."}); + lines.add(new String[] {"controller", out.on.isEmpty() ? "Turn on the ones you want" : (out.on.size() == 1 ? "1 is on" : out.on.size() + " are on") + ", as the file has them", + "Here or in the game's Mods tab. A cheat switches at once in a running game."}); + View card = formatCard(a, converted ? "update" : "check", converted ? "Now a Mistel cheat file" : "Mistel cheat file", + converted ? "One .mncf for every version of " + g.name + ": " + out.named : out.named, x.signer); + dialog(a, "Cheats added", card, null, lines, null, null, "Done", null); + }, e -> { Feel.refused(a); android.util.Log.w("peanuts", "cheats: adding a source: " + e); - message(a, "Not added", "The cheats could not be kept in the app's storage" + (added.isEmpty() ? "" : " (" + String.join(", ", added) + " was)") + ". Free some space and add them again."); + message(a, "Not added", "The cheats could not be kept in the app's storage. Free some space and add them again."); CheatsPage.rebuild(); - return; - } - Feel.accepted(a); - Toast.makeText(a, n > 0 ? "Added " + CheatsPage.count(n, "cheat") + ". Turn on the ones you want." : "Kept for another version.", Toast.LENGTH_LONG).show(); - CheatsPage.rebuild(); + }); } // ---- The dialogs, in the app's AlertDialog look ---- @@ -160,28 +529,20 @@ private static void message(Activity a, String title, String text) { /** A dialog with a lead and lines of an icon, a heading and a line under it (icon: check, info, warning) */ private static void dialog(Activity a, String title, String lead, List lines, String negative, Runnable onNegative, String positive, Runnable onPositive) { + dialog(a, title, null, lead, lines, negative, onNegative, positive, onPositive); + } + + /** The same with a card above the lead (formatCard); lead null: none */ + private static void dialog(Activity a, String title, View card, String lead, List lines, String negative, Runnable onNegative, String positive, Runnable onPositive) { LinearLayout box = new LinearLayout(a); box.setOrientation(LinearLayout.VERTICAL); - TextView l = PUi.body(a, lead); - l.setLineSpacing(0, 1.15f); - box.addView(l); - for (String[] line : lines) { - LinearLayout r = PUi.row(a); - r.setGravity(android.view.Gravity.TOP); - TextView tile = PUi.text(a, "", 12, R.color.bn_text, 400); - tile.setBackground(PUi.round(PUi.col(a, R.color.bn_tint), PUi.dp(a, 10), 0, 0)); - r.addView(tile, new LinearLayout.LayoutParams(PUi.dp(a, 32), PUi.dp(a, 32))); - Icons.tile(tile, line[0]); - LinearLayout col = new LinearLayout(a); - col.setOrientation(LinearLayout.VERTICAL); - col.setPadding(PUi.dp(a, 12), PUi.dp(a, 1), 0, 0); - col.addView(PUi.text(a, line[1], 15, R.color.bn_text, 600)); - TextView sub = PUi.small(a, line[2]); - sub.setLineSpacing(0, 1.1f); - col.addView(sub); - r.addView(col, PUi.weight()); - PUi.add(box, r, 14); + if (card != null) box.addView(card); + if (lead != null) { + TextView l = PUi.body(a, lead); + l.setLineSpacing(0, 1.15f); + PUi.add(box, l, card != null ? 14 : 0); } + for (String[] line : lines) PUi.add(box, line(a, line), 14); AlertDialog.Builder b = PUi.sheet(a, title, box); if (positive != null) b.setPositiveButton(positive, onPositive == null ? null : Feel.confirm((x, w) -> onPositive.run())); if (negative != null) b.setNegativeButton(negative, onNegative == null ? null : (x, w) -> onNegative.run()); @@ -190,4 +551,23 @@ private static void dialog(Activity a, String title, String lead, List d.show(); } + /** One of a dialog's lines: {icon, heading, the line under it} */ + private static View line(Activity a, String[] line) { + LinearLayout r = PUi.row(a); + r.setGravity(android.view.Gravity.TOP); + TextView tile = PUi.text(a, "", 12, R.color.bn_text, 400); + tile.setBackground(PUi.round(PUi.col(a, R.color.bn_tint), PUi.dp(a, 10), 0, 0)); + r.addView(tile, new LinearLayout.LayoutParams(PUi.dp(a, 32), PUi.dp(a, 32))); + Icons.tile(tile, line[0]); + LinearLayout col = new LinearLayout(a); + col.setOrientation(LinearLayout.VERTICAL); + col.setPadding(PUi.dp(a, 12), PUi.dp(a, 1), 0, 0); + col.addView(PUi.text(a, line[1], 15, R.color.bn_text, 600)); + TextView sub = PUi.small(a, line[2]); + sub.setLineSpacing(0, 1.1f); + col.addView(sub); + r.addView(col, PUi.weight()); + return r; + } + } diff --git a/android/app/src/main/java/dev/peanuts/mods/CheatPick.java b/android/app/src/main/java/dev/peanuts/mods/CheatPick.java index 5aecb4e2..3f288e3f 100644 --- a/android/app/src/main/java/dev/peanuts/mods/CheatPick.java +++ b/android/app/src/main/java/dev/peanuts/mods/CheatPick.java @@ -63,10 +63,21 @@ public static void read(Activity a, Uri u, boolean folder, String titleId, Set CheatImport.MAX_PACK) throw new IOException("It is larger than " + CheatImport.MAX_PACK / (1024 * 1024) + " MB: not a cheat pack."); + List broken = new ArrayList<>(); + paths = new ArrayList<>(); + in = CheatImport.fromPack(b, paths, broken); + if (!broken.isEmpty()) android.util.Log.w("peanuts", "cheats: the pack's files left out: " + broken); + } } else { + boolean mncf = display != null && display.toLowerCase(java.util.Locale.ROOT).endsWith(".mncf"); + int max = mncf ? CheatImport.MAX_MNCF : CheatImport.MAX_FILE; byte[] b; - try (InputStream s = open(a, u)) { b = readMax(s, CheatImport.MAX_FILE + 1); } - if (b.length > CheatImport.MAX_FILE) throw new IOException("It is larger than " + CheatImport.MAX_FILE / 1024 + " KB: not a cheat file."); + try (InputStream s = open(a, u)) { b = readMax(s, max + 1); } + if (b.length > max) throw new IOException("It is larger than " + max / 1024 + " KB: not a cheat file."); String n = display != null ? display : "cheats.txt"; in = new ArrayList<>(); in.add(new CheatImport.In(n, b)); @@ -84,6 +95,42 @@ public static void read(Activity a, Uri u, boolean folder, String titleId, Set void work(Activity a, String title, java.util.concurrent.Callable job, Consumer done, Consumer failed) { work(a, title, null, job, done, failed); } + + /** The same with a line under the spinner that says what is being done (not "Loading": the spinner shows that), null for none */ + public static void work(Activity a, String title, String doing, java.util.concurrent.Callable job, Consumer done, Consumer failed) { + LinearLayout box = new LinearLayout(a); + box.setOrientation(LinearLayout.VERTICAL); + box.setGravity(Gravity.CENTER); + int p = Math.round(18 * a.getResources().getDisplayMetrics().density); + box.setPadding(p, p, p, p); + box.addView(new ProgressBar(a)); + if (doing != null) { + android.widget.TextView t = dev.peanuts.ui.PUi.small(a, doing); + t.setGravity(Gravity.CENTER); + t.setPadding(0, p / 2, 0, 0); + box.addView(t); + } + AlertDialog wait = new AlertDialog.Builder(a).setTitle(title).setView(box).setCancelable(false).create(); + wait.show(); + new Thread(() -> { + T out = null; + Exception err = null; + try { out = job.call(); } catch (Exception e) { err = e; } + T o = out; + Exception x = err; + UI.post(() -> { + wait.dismiss(); + if (a.isFinishing() || a.isDestroyed()) return; + if (x != null) failed.accept(x); else done.accept(o); + }); + }, "peanuts-cheat-work").start(); + } + private static InputStream open(Context c, Uri u) throws IOException { InputStream in = c.getContentResolver().openInputStream(u); if (in == null) throw new IOException("the pick cannot be opened"); @@ -93,8 +140,8 @@ private static InputStream open(Context c, Uri u) throws IOException { /** Whether the picked file is a zip: its name, else its first bytes ("PK") */ private static boolean zip(Context c, Uri u, String display) throws IOException { String n = display == null ? "" : display.toLowerCase(java.util.Locale.ROOT); - if (n.endsWith(".zip")) return true; - if (n.endsWith(".txt")) return false; + if (n.endsWith(".zip") || n.endsWith(".mncp")) return true; + if (n.endsWith(".txt") || n.endsWith(".mncf")) return false; try (InputStream in = open(c, u)) { return in.read() == 'P' && in.read() == 'K'; } } diff --git a/android/app/src/main/java/dev/peanuts/mods/CheatSources.java b/android/app/src/main/java/dev/peanuts/mods/CheatSources.java index 3760fa0e..6684aa53 100644 --- a/android/app/src/main/java/dev/peanuts/mods/CheatSources.java +++ b/android/app/src/main/java/dev/peanuts/mods/CheatSources.java @@ -12,12 +12,16 @@ import java.util.Map; import java.util.Set; +import io.github.davdxpx.mistel.mncf.ConvertException; + /** * The player's cheat sources of a game (SPEC-mod-menu.md, Package B 3) and the one merged file the host reads (DM_CHEATS: <folder>/<build>.txt). No * Android classes: CheatLoaderJvmTest runs it. The folder is the launcher's cheats folder of the game (<files>/cheats/<title ID>/, CheatsUi.folder). *
      - *
    • Each import is a source: <folder>/sources/<id>/ with its files by build (<BID>.txt, the game's build and any other the pick held) and - * source.tsv (its name, where it came from, when it was added, on or off). A source is switched off or removed as a whole.
    • + *
    • Each import is a source: <folder>/sources/<id>/ with one cheat file in the Mistel Native Cheat Format, cheats.mncf, for all of its builds, + * and source.tsv (its name, where it came from, when it was added, on or off). An .mncf is kept as it was added (its signature stays good); any other cheat + * file becomes one (MncfConvert), and so do the Atmosphère files an earlier version of the app kept by build ({@link #upgrade}). build/ beside it keeps the + * file made ready for each build the game ran as (MncfBuild). A source is switched off or removed as a whole.
    • *
    • The cheats that come with the app (the profile's file in the pack) are one more source, {@link #APP}, whose on / off is <folder>/sources/.app.tsv.
    • *
    • {@link #merge}: the enabled sources' cheats of the build, in order (the app's first, then by when they were added, then the mods' files), each source's * masters first and its groups as EdiZon's section markers. Credits, titles, group headings, "Restore Code" entries and Not supported cheats are left out.
    • @@ -29,7 +33,7 @@ public final class CheatSources { private CheatSources() {} - public static final String APP = ".app", STATE = "source.tsv", APP_STATE = ".app.tsv"; + public static final String APP = ".app", STATE = "source.tsv", APP_STATE = ".app.tsv", MNCF = "cheats.mncf"; public static final String FROM_ZIP = "zip", FROM_FILE = "file", FROM_FOLDER = "folder", FROM_EARLIER = "earlier", FROM_APP = "app", FROM_MOD = "mod"; /** One source */ @@ -38,22 +42,34 @@ public static final class Source { public final File dir; public final long added; public final boolean enabled; - Source(String id, String name, String from, File dir, long added, boolean enabled) { this.id = id; this.name = name; this.from = from; this.dir = dir; this.added = added; this.enabled = enabled; } + final List atmosphere; // the SHA-256 of each Atmosphère file (its body) it was made from, for sameAs; empty for an .mncf added as it was + Source(String id, String name, String from, File dir, long added, boolean enabled, List atmosphere) { + this.id = id; this.name = name; this.from = from; this.dir = dir; this.added = added; this.enabled = enabled; this.atmosphere = atmosphere; + } + + /** Its cheat file, for all of its builds */ + public File file() { return new File(dir, MNCF); } + + /** Its file made ready for the game's build (MncfBuild.of: the kept one, else made now) */ + public MncfBuild.Ready ready(MncfBuild.Game g) throws IOException { return MncfBuild.of(file(), g); } + + /** The build IDs of main its file names (16 hex digits, upper case); empty when it names none or cannot be read */ + public List builds() { + try { + return MncfBuild.builds(io.github.davdxpx.mistel.mncf.Mncf.load(Files.readAllBytes(file().toPath()))); + } catch (IOException | io.github.davdxpx.mistel.mncf.MncfException | RuntimeException e) { + return new ArrayList<>(); + } + } - /** Its files by build (BID → the file), sorted by build */ - public Map files() { + /** The Atmosphère files an earlier version of the app kept by build (BID → the file), sorted by build; {@link #upgrade} makes them one .mncf */ + Map txtFiles() { Map out = new java.util.TreeMap<>(); File[] l = dir == null ? null : dir.listFiles((d, n) -> n.matches("(?i)[0-9a-f]{16}\\.txt")); if (l != null) for (File f : l) out.put(f.getName().substring(0, 16).toUpperCase(Locale.ROOT), f); return out; } - /** Its file of this build, read; null when it has none */ - public String text(String build) throws IOException { - File f = build == null ? null : files().get(build.toUpperCase(Locale.ROOT)); - return f == null ? null : new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8); - } - @Override public String toString() { return id + "(" + name + (enabled ? "" : ", off") + ")"; } } @@ -79,11 +95,13 @@ static void writeState(File f, Map m) throws IOException { write(f, sb.toString()); } - static void write(File f, String text) throws IOException { + static void write(File f, String text) throws IOException { write(f, text.getBytes(StandardCharsets.UTF_8)); } + + static void write(File f, byte[] bytes) throws IOException { File dir = f.getParentFile(); if (dir != null && !dir.isDirectory() && !dir.mkdirs()) throw new IOException("cannot create " + dir); File tmp = new File(f.getPath() + ".tmp"); - Files.write(tmp.toPath(), text.getBytes(StandardCharsets.UTF_8)); + Files.write(tmp.toPath(), bytes); if (!tmp.renameTo(f)) { if (!f.delete() || !tmp.renameTo(f)) { tmp.delete(); throw new IOException("cannot write " + f); } } @@ -100,7 +118,9 @@ public static List list(File folder) { Map s = readState(new File(d, STATE)); long added; try { added = Long.parseLong(s.getOrDefault("added", "0")); } catch (NumberFormatException e) { added = 0; } - out.add(new Source(d.getName(), s.getOrDefault("name", d.getName()), s.getOrDefault("from", FROM_FILE), d, added, !"0".equals(s.get("enabled")))); + List atm = new ArrayList<>(); + for (String x : s.getOrDefault("atmosphere", "").split(",")) if (!x.trim().isEmpty()) atm.add(x.trim()); + out.add(new Source(d.getName(), s.getOrDefault("name", d.getName()), s.getOrDefault("from", FROM_FILE), d, added, !"0".equals(s.get("enabled")), atm)); } out.sort((x, y) -> x.added != y.added ? Long.compare(x.added, y.added) : x.id.compareToIgnoreCase(y.id)); return out; @@ -158,24 +178,55 @@ static String body(String text) { return t; } - /** The source that has this build's file with this text already (an import of the same file again), null when none */ - public static Source sameAs(File folder, String build, String text) { - String want = body(text); + /** The SHA-256 of an Atmosphère file's body (body): what sameAs compares */ + static String sum(String text) { return MncfBuild.sha256(body(text).getBytes(StandardCharsets.UTF_8)); } + + /** The source made from this Atmosphère file already (an import of the same file again), null when none */ + public static Source sameAs(File folder, String text) { + String want = sum(text); + for (Source s : list(folder)) if (s.atmosphere.contains(want)) return s; + return null; + } + + /** The source whose .mncf has these very bytes already, null when none */ + public static Source sameMncf(File folder, byte[] bytes) { + String want = MncfBuild.sha256(bytes); for (Source s : list(folder)) { - try { String t = s.text(build); if (t != null && body(t).equals(want)) return s; } catch (IOException ignored) { } + try { if (s.file().isFile() && MncfBuild.sha256(Files.readAllBytes(s.file().toPath())).equals(want)) return s; } catch (IOException ignored) { } } return null; } - /** A new source with these files (BID → text), on. Returns it */ - public static Source add(File folder, String name, String from, Map byBuild, long now) throws IOException { + /** + * A new source from Atmosphère files (BID → text) made one .mncf (MncfConvert) with what k knows; origin: the pick's name as the player had it. On. Returns + * it. IOException when the files cannot be converted or kept (nothing is left behind then) + */ + public static Source add(File folder, String name, String from, Map byBuild, long now, MncfConvert.Known k, String origin) throws IOException { + String text; + try { + text = MncfConvert.fromAtmosphere(byBuild, origin, k); + } catch (ConvertException e) { + throw new IOException("the cheats could not be converted (" + e.code() + ": " + e.getMessage() + ")", e); + } + List sums = new ArrayList<>(); + for (String t : byBuild.values()) sums.add(sum(t)); + return addFile(folder, name, from, text.getBytes(StandardCharsets.UTF_8), now, sums); + } + + /** A new source of an .mncf file, kept byte for byte (a signature stays good). On. Returns it */ + public static Source addMncf(File folder, String name, String from, byte[] mncf, long now) throws IOException { + return addFile(folder, name, from, mncf, now, new ArrayList()); + } + + private static Source addFile(File folder, String name, String from, byte[] mncf, long now, List sums) throws IOException { String n = uniqueName(list(folder), name), id = idFor(folder, n); File dir = new File(root(folder), id); if (!dir.mkdirs()) throw new IOException("cannot create " + dir); try { - for (Map.Entry e : byBuild.entrySet()) write(new File(dir, e.getKey().toUpperCase(Locale.ROOT) + ".txt"), e.getValue().replace("\r\n", "\n")); + write(new File(dir, MNCF), mncf); Map s = new LinkedHashMap<>(); s.put("name", n); s.put("from", from); s.put("added", String.valueOf(now)); s.put("enabled", "1"); + if (!sums.isEmpty()) s.put("atmosphere", String.join(",", sums)); writeState(new File(dir, STATE), s); } catch (IOException e) { deleteTree(dir); @@ -184,6 +235,38 @@ public static Source add(File folder, String name, String from, Map txt = s.txtFiles(); + if (txt.isEmpty() || s.file().isFile()) continue; + try { + Map byBuild = new LinkedHashMap<>(); + for (Map.Entry e : txt.entrySet()) byBuild.put(e.getKey(), new String(Files.readAllBytes(e.getValue().toPath()), StandardCharsets.UTF_8)); + String text = MncfConvert.fromAtmosphere(byBuild, s.name, k); + write(s.file(), text); + Map st = readState(new File(s.dir, STATE)); + List sums = new ArrayList<>(); + for (String t : byBuild.values()) sums.add(sum(t)); + st.put("atmosphere", String.join(",", sums)); + writeState(new File(s.dir, STATE), st); + for (File f : txt.values()) f.delete(); + n++; + } catch (IOException | ConvertException | RuntimeException e) { + new File(s.dir, MNCF).delete(); + } + } + return n; + } + /** A source switched on or off as a whole */ public static void enabled(File folder, String id, boolean on) throws IOException { File f = new File(new File(root(folder), id), STATE); @@ -209,101 +292,46 @@ static void deleteTree(File f) { } /** - * The files of upstream's earlier import (<folder>/imported/*.txt, each starting with "build <ID>") made into sources, one a file, by their names' - * order, then removed. Returns the new sources (empty: nothing to move) + * The files of upstream's earlier import (<folder>/imported/*.txt, each starting with "build <ID>") made into sources, one a file (each an .mncf, + * with what k knows), by their names' order, then removed. Returns the new sources (empty: nothing to move) */ - public static List migrate(File folder, long now) throws IOException { + public static List migrate(File folder, long now, MncfConvert.Known k) throws IOException { List out = new ArrayList<>(); File[] l = new File(folder, "imported").listFiles((d, n) -> n.toLowerCase(Locale.ROOT).endsWith(".txt")); if (l == null) return out; java.util.Arrays.sort(l, (x, y) -> x.getName().compareToIgnoreCase(y.getName())); - int k = 0; + int c = 0; for (File f : l) { String text = new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8); CheatFile.Parsed p = CheatFile.parse(text, -1); if (p.build == null) continue; Map files = new LinkedHashMap<>(); files.put(p.build, text); - out.add(add(folder, f.getName().replaceFirst("(?i)\\.txt$", ""), FROM_EARLIER, files, now + k++)); + String name = f.getName().replaceFirst("(?i)\\.txt$", ""); + out.add(add(folder, name, FROM_EARLIER, files, now + c++, k, f.getName())); if (!f.delete()) throw new IOException("cannot remove " + f); } new File(folder, "imported").delete(); return out; } - /** Sources just made (moved: an import of an export, CheatSources.migrate) whose file of this build another source has already: removed again. Returns how many stay */ - public static int dropDuplicates(File folder, List moved, String build) { + /** Sources just made (moved: an import of an export, CheatSources.migrate) made from a file another source was made from already: removed again. Returns how many stay */ + public static int dropDuplicates(File folder, List moved) { int stay = 0; Set ids = new HashSet<>(); for (Source m : moved) ids.add(m.id); for (Source m : moved) { boolean dup = false; - try { - String t = m.text(build); - if (t != null) for (Source o : list(folder)) { - if (o.id.equals(m.id) || ids.contains(o.id) && o.added > m.added) continue; // a later one of the same batch is not "already there" - String u = o.text(build); - if (u != null && body(u).equals(body(t))) { dup = true; break; } - } - } catch (IOException ignored) { } + for (Source o : list(folder)) { + if (o.id.equals(m.id) || ids.contains(o.id) && o.added > m.added) continue; // a later one of the same batch is not "already there" + for (String x : m.atmosphere) if (o.atmosphere.contains(x)) { dup = true; break; } + if (dup) break; + } if (dup) remove(folder, m.id); else stay++; } return stay; } - // ---- Export ---- - - /** - * The sources' files of this build as one .zip in upstream's export format (Cheats.exportZip / readZip): cheats/<source>.txt, each starting with a line - * "build <ID>", and toggles.json {"title_id", "build", "cheats" (the game's switch), "on" (the toggles' keys)}. Upstream's Import cheats… takes it back, - * and so does an import of the zip as a cheat file (CheatImport: a "build" line). Returns how many files went in - */ - public static int exportZip(java.io.OutputStream os, String titleId, String build, File folder, boolean master, Set on) throws IOException { - int n = 0; - try (java.util.zip.ZipOutputStream z = new java.util.zip.ZipOutputStream(os)) { - if (build != null) for (Source s : list(folder)) { - String t = s.text(build); - if (t == null) continue; - z.putNextEntry(new java.util.zip.ZipEntry("cheats/" + s.id + ".txt")); - z.write(withBuild(t, build).getBytes(StandardCharsets.UTF_8)); - z.closeEntry(); - n++; - } - StringBuilder j = new StringBuilder("{\"title_id\": ").append(json(titleId)).append(", \"build\": ").append(json(build == null ? "" : build)) - .append(", \"cheats\": ").append(master).append(", \"on\": ["); - int k = 0; - for (String key : on) j.append(k++ == 0 ? "" : ", ").append(json(key)); - j.append("]}\n"); - z.putNextEntry(new java.util.zip.ZipEntry("toggles.json")); - z.write(j.toString().getBytes(StandardCharsets.UTF_8)); - z.closeEntry(); - } - return n; - } - - /** A file's text with "build <ID>" as its first line (an earlier build line, and empty lines before it, left out) */ - static String withBuild(String text, String build) { - StringBuilder sb = new StringBuilder("build ").append(build).append('\n'); - boolean first = true; - for (String line : text.replace("\r\n", "\n").split("\n", -1)) { - if (first && line.trim().isEmpty()) continue; - if (first && line.trim().matches("(?i)build\\s+[0-9a-f]{16,}")) { first = false; continue; } - first = false; - sb.append(line).append('\n'); - } - return sb.toString().replaceAll("\n+$", "\n"); - } - - private static String json(String s) { - StringBuilder sb = new StringBuilder("\""); - for (char c : s.toCharArray()) { - if (c == '"' || c == '\\') sb.append('\\').append(c); - else if (c < 0x20) sb.append(String.format(Locale.ROOT, "\\u%04x", (int) c)); - else sb.append(c); - } - return sb.append('"').toString(); - } - // ---- The merged file ---- /** One source's file of the build, read, for the merge: its id, its name, whether it is on */ @@ -311,17 +339,27 @@ public static final class Block { public final String id, name; public final boolean enabled; public final CheatFile.Parsed parsed; - public Block(String id, String name, boolean enabled, CheatFile.Parsed parsed) { this.id = id; this.name = name; this.enabled = enabled; this.parsed = parsed; } + public final String error; // an .mncf that cannot be used at all: Appendix D's code; else null + public final boolean pending; // its file is not made ready for this build yet (blocks without make): no cheats listed until it is + public Block(String id, String name, boolean enabled, CheatFile.Parsed parsed) { this(id, name, enabled, parsed, null, false); } + Block(String id, String name, boolean enabled, CheatFile.Parsed parsed, String error, boolean pending) { + this.id = id; this.name = name; this.enabled = enabled; this.parsed = parsed; this.error = error; this.pending = pending; + } } - /** The merge's blocks of a game: the app's file (appText, null or empty: none) and each player's source that has a file of this build */ - public static List blocks(File folder, String appText, boolean appOn, String build, long textEnd) { + /** + * The merge's blocks of a game: the app's file (appText, null or empty: none) and each player's source, its .mncf made ready for the game's build (g). make: + * a file not made ready for it yet is made now (it reads the game's main: seconds for a large game); without, it is a pending block (MncfBuild.prepare makes it) + */ + public static List blocks(File folder, String appText, boolean appOn, MncfBuild.Game g, long textEnd, boolean make) { List out = new ArrayList<>(); if (appText != null && !appText.isEmpty()) out.add(new Block(APP, "Comes with the app", appOn, CheatFile.parse(appText, textEnd))); for (Source s : list(folder)) { + if (!s.file().isFile()) continue; // Atmosphère files not converted yet (upgrade): left out meanwhile try { - String t = s.text(build); - if (t != null) out.add(new Block(s.id, s.name, s.enabled, CheatFile.parse(t, textEnd))); + MncfBuild.Ready r = make ? MncfBuild.of(s.file(), g) : MncfBuild.kept(s.file(), g); + if (r == null) { out.add(new Block(s.id, s.name, s.enabled, new CheatFile.Parsed(), null, true)); continue; } + out.add(new Block(s.id, s.name, s.enabled, CheatFile.fromMncf(r, textEnd), r.error, false)); } catch (IOException ignored) { } // a file that cannot be read: its source has no cheats this time } return out; @@ -340,7 +378,33 @@ public static final class Merged { public final String text; public final List rows; public final int cheats, masters; // what the text holds - Merged(String text, List rows, int cheats, int masters) { this.text = text; this.rows = rows; this.cheats = cheats; this.masters = masters; } + public final List blocks; // every block merged, those without a row too (an .mncf whose cheats cannot work here, one not made ready yet) + Merged(String text, List rows, int cheats, int masters, List blocks) { this.text = text; this.rows = rows; this.cheats = cheats; this.masters = masters; this.blocks = blocks; } + + /** + * An .mncf cheat switched (Mistel's spec, section 7.8), its relations applied to on: switched on, the cheats it requires go on, and the ones it excludes, + * the ones that exclude it, and the others of its radio go off, with every cheat that requires one of those. Returns the other keys that changed (empty + * for an Atmosphère cheat, and when switched off) + */ + public Set related(Set on, String key, boolean x) { + Set changed = new java.util.LinkedHashSet<>(); + Row me = null; + for (Row r : rows) if (r.key.equals(key)) { me = r; break; } + if (me == null || me.cheat.mncf == null || !x) return changed; + Map byId = new LinkedHashMap<>(); + for (Row r : rows) if (r.block == me.block && r.cheat.mncf != null && !r.cheat.master) byId.put(r.cheat.mncf.id, r); + Set off = new HashSet<>(); + for (Row r : byId.values()) { + if (r == me) continue; + MncfBuild.Cheat c = r.cheat.mncf; + boolean clash = me.cheat.mncf.excludes.contains(c.id) || c.excludes.contains(me.cheat.mncf.id) || me.cheat.mncf.radio != null && me.cheat.mncf.radio.equals(c.radio); + if (clash) off.add(c.id); + } + for (Row r : byId.values()) if (r != me) for (String req : r.cheat.mncf.requires) if (off.contains(req)) off.add(r.cheat.mncf.id); + for (String id : off) { Row r = byId.get(id); if (r != null && on.remove(r.key)) changed.add(r.key); } + for (String req : me.cheat.mncf.requires) { Row r = byId.get(req); if (r != null && !off.contains(req) && on.add(r.key)) changed.add(r.key); } + return changed; + } /** The key of a block's cheat (by its key in its own file), null when it has none in the merge (Not supported) */ public String key(String blockId, String ownKey) { @@ -412,7 +476,7 @@ public static Merged merge(List blocks, Map val } if (open != null) sb.append("[--SectionEnd:").append(open).append("--]\n"); } - return new Merged(sb.toString(), rows, cheats, masters); + return new Merged(sb.toString(), rows, cheats, masters, blocks); } /** A group's section in the merged file: the group, with the source's name in front when more than one source is on; null for neither */ diff --git a/android/app/src/main/java/dev/peanuts/mods/CheatStatus.java b/android/app/src/main/java/dev/peanuts/mods/CheatStatus.java index 129584cd..b63ac8cb 100644 --- a/android/app/src/main/java/dev/peanuts/mods/CheatStatus.java +++ b/android/app/src/main/java/dev/peanuts/mods/CheatStatus.java @@ -77,7 +77,7 @@ public static String chip(Look l, CheatFile.Cheat c) { } /** What a row says while it has the focus (and its details): why it is not possible, else what it changes, and when it waits */ - public static String line(CheatFile.Cheat c, boolean bad, boolean inHost, String reason) { return line(c, bad, inHost, reason, c.value()); } + public static String line(CheatFile.Cheat c, boolean bad, boolean inHost, String reason) { return line(c, bad, inHost, reason, c.number != null ? c.number.own() : c.value()); } /** The same, a Value cheat writing number (the one set in the tab) */ public static String line(CheatFile.Cheat c, boolean bad, boolean inHost, String reason, long number) { @@ -91,6 +91,7 @@ public static String line(CheatFile.Cheat c, boolean bad, boolean inHost, String /** A refusal in the player's words (the host's detail goes to the log, not here) */ public static String why(String reason, CheatFile.Cheat c) { + if (c.reason() != null) return MncfWords.reason(c.reason(), c.mncf); // an .mncf cheat that cannot work here: why, before the game ran String token = reason == null ? "" : reason.contains(":") ? reason.substring(0, reason.indexOf(':')) : reason; switch (token) { case "rewritten": return "Peanuts rewrote this place of the game's code while building it, so this cheat cannot change it."; diff --git a/android/app/src/main/java/dev/peanuts/mods/CheatValues.java b/android/app/src/main/java/dev/peanuts/mods/CheatValues.java index 68e45b5f..ee3f6373 100644 --- a/android/app/src/main/java/dev/peanuts/mods/CheatValues.java +++ b/android/app/src/main/java/dev/peanuts/mods/CheatValues.java @@ -37,11 +37,14 @@ public static final class Kept { } } + /** Whether the cheat has a number the player can set: an Atmosphère Value cheat (plainValue) or an .mncf cheat with one whole-number value */ + public static boolean plain(CheatFile.Cheat c) { return c.number != null; } + /** - * Whether the cheat writes a plain number the player can set: a Value cheat whose number is not a float. A 4-byte number with its low 12 bits clear and an - * exponent between 2^-8 and 2^31 reads as a float (1.5 is 0x3FC00000) and keeps its words; a count rarely looks like that + * Whether an Atmosphère cheat writes a plain number the player can set: a Value cheat whose number is not a float. A 4-byte number with its low 12 bits + * clear and an exponent between 2^-8 and 2^31 reads as a float (1.5 is 0x3FC00000) and keeps its words; a count rarely looks like that */ - public static boolean plain(CheatFile.Cheat c) { + static boolean plainValue(CheatFile.Cheat c) { if (c.kind != CheatFile.Kind.VALUE || c.valueWord < 0) return false; int w = c.valueWidth; if (w != 1 && w != 2 && w != 4 && w != 8) return false; @@ -53,6 +56,40 @@ public static boolean plain(CheatFile.Cheat c) { return true; } + /** An Atmosphère Value cheat's number: its words at its place */ + static CheatFile.Number atmosphere(CheatFile.Cheat c) { + return new CheatFile.Number() { + @Override public long own() { return c.value(); } + @Override public long min() { return 0; } + @Override public long max() { return CheatValues.max(c.valueWidth); } + @Override public String unit() { return null; } + @Override public List lines(long v) { return CheatValues.lines(c.lines, c.valueWord, c.valueWidth, v); } + }; + } + + /** An .mncf cheat's one whole-number value (MncfBuild.number): its range and unit from the file, its code made again for a number (MncfBuild.Ready.lines) */ + static CheatFile.Number mncf(MncfBuild.Ready r, MncfBuild.Cheat m, List ownLines) { + io.github.davdxpx.mistel.mncf.ValueSpec v = m.value; + long own = ((java.lang.Number) v.defaultValue()).longValue(); + long[] range = range(v.type()); + long lo = v.min() == null ? range[0] : Math.max(range[0], v.min().longValue()), hi = v.max() == null ? range[1] : Math.min(range[1], v.max().longValue()); + return new CheatFile.Number() { + @Override public long own() { return own; } + @Override public long min() { return lo; } + @Override public long max() { return hi; } + @Override public String unit() { return v.unit(); } + @Override public List lines(long x) { return x == own ? ownLines : r.lines(m, Math.max(lo, Math.min(hi, x))); } + }; + } + + /** The numbers a whole-number type of the format holds (u64: up to a long's largest, the field's limit) */ + static long[] range(String type) { + boolean signed = type.startsWith("s"); + int bits = Integer.parseInt(type.substring(1)); + if (bits >= 64) return signed ? new long[] {Long.MIN_VALUE, Long.MAX_VALUE} : new long[] {0, Long.MAX_VALUE}; + return signed ? new long[] {-(1L << (bits - 1)), (1L << (bits - 1)) - 1} : new long[] {0, (1L << bits) - 1}; + } + /** The largest number a width holds (8 bytes: a long's largest, the field's limit) */ public static long max(int width) { return width >= 8 ? Long.MAX_VALUE : (1L << (8 * width)) - 1; } @@ -63,8 +100,11 @@ static long at(long[] words, int word, int width) { return width == 4 ? words[word] : words[word] & max(width); } - /** The cheat's lines with v as its number (c a Value cheat: its own place) */ - public static List lines(CheatFile.Cheat c, long v) { return lines(c.lines, c.valueWord, c.valueWidth, v); } + /** The cheat's lines with v as its number (c with a number: plain), its own lines when that number cannot be written */ + public static List lines(CheatFile.Cheat c, long v) { + List l = c.number == null ? null : c.number.lines(Math.max(c.number.min(), Math.min(v, c.number.max()))); + return l != null ? l : c.lines; + } /** lines with v at word (width bytes); the other words as written, the number's in eight upper-case hex digits */ static List lines(List lines, int word0, int width, long v) { @@ -90,28 +130,43 @@ static List lines(List lines, int word0, int width, long v) { private static String hex(long w) { return String.format(Locale.ROOT, "%08X", w & 0xFFFFFFFFL); } - /** The cheat's lines with the kept number, when the cheat still has the original number at its place; else null (the file's own lines stay) */ + /** + * The cheat's lines with the kept number, when the cheat still has the original number (an Atmosphère cheat: at its place; an .mncf one: as its value's + * default); else null (the file's own lines stay) + */ public static List apply(CheatFile.Cheat c, Kept k) { - if (k == null || at(c.words, k.word, k.width) != k.original) return null; - return lines(c.lines, k.word, k.width, k.number); + if (k == null) return null; + if (k.width != 0) { // by its words alone: a start reads the files without main's code size, so a Value cheat in main's data is not one by itself there + if (at(c.words, k.word, k.width) != k.original) return null; + return lines(c.lines, k.word, k.width, k.number); + } + if (!mncfValue(c) || k.original != c.number.own()) return null; + return c.number.lines(Math.max(c.number.min(), Math.min(k.number, c.number.max()))); } + /** Whether the cheat's number is an .mncf value (kept without a place in the words), not an Atmosphère Value's words */ + static boolean mncfValue(CheatFile.Cheat c) { return c.number != null && c.mncf != null && c.mncf.value != null; } + /** The number the cheat writes now: the kept one when it applies, else the file's */ public static long of(Map kept, String key, CheatFile.Cheat c) { Kept k = key == null ? null : kept.get(key.toLowerCase(Locale.ROOT)); - return k != null && apply(c, k) != null ? Math.min(k.number, max(k.width)) : c.value(); + if (c.number == null) return c.value(); + return k != null && apply(c, k) != null ? Math.max(c.number.min(), Math.min(k.number, c.number.max())) : c.number.own(); } - /** The merged file's text with the block of [key] holding c's lines for v; null when the file has no such block of c's length */ + /** The merged file's text with the block of [key] holding c's lines for v (every code line up to the next entry); null when the file has no such block */ public static String patch(String merged, String key, CheatFile.Cheat c, long v) { String[] l = merged.split("\n", -1); String head = "[" + key + "]"; for (int i = 0; i < l.length; i++) { if (!l[i].trim().equals(head)) continue; - if (i + c.lines.size() >= l.length) return null; - List put = lines(c, v); - for (int j = 0; j < put.size(); j++) l[i + 1 + j] = put.get(j); - return String.join("\n", l); + int end = i + 1; + while (end < l.length && CheatFile.codeLine(l[end])) end++; + StringBuilder sb = new StringBuilder(); + for (int j = 0; j <= i; j++) sb.append(l[j]).append('\n'); + for (String x : lines(c, v)) sb.append(x).append('\n'); + for (int j = end; j < l.length; j++) sb.append(l[j]).append(j + 1 < l.length ? "\n" : ""); + return sb.toString(); } return null; } @@ -131,8 +186,8 @@ public static Map read(File folder) { String[] t = line.split("\t"); if (t.length < 5 || t[0].isEmpty()) continue; try { - int width = Integer.parseInt(t[3].trim()); - if (width != 1 && width != 2 && width != 4 && width != 8) continue; + int width = Integer.parseInt(t[3].trim()); // 0: an .mncf cheat's value (no place in the words; original: the value's default) + if (width != 0 && width != 1 && width != 2 && width != 4 && width != 8) continue; out.put(t[0].toLowerCase(Locale.ROOT), new Kept(Long.parseLong(t[1].trim()), Integer.parseInt(t[2].trim()), width, Long.parseLong(t[4].trim()))); } catch (NumberFormatException ignored) { // a line this reader cannot read is left out @@ -141,12 +196,14 @@ public static Map read(File folder) { return out; } - /** Keeps v as the number of c (a Value cheat) under key; v equal to the file's own number forgets it */ + /** Keeps v as the number of c (a cheat with a number) under key; v equal to the file's own number forgets it */ public static void keep(File folder, String key, CheatFile.Cheat c, long v) throws IOException { Map all = read(folder); String k = key.toLowerCase(Locale.ROOT); - if (v == c.value()) all.remove(k); - else all.put(k, new Kept(Math.max(0, Math.min(v, max(c.valueWidth))), c.valueWord, c.valueWidth, c.value())); + long own = c.number != null ? c.number.own() : c.value(); + if (v == own) all.remove(k); + else if (mncfValue(c)) all.put(k, new Kept(Math.max(c.number.min(), Math.min(v, c.number.max())), -1, 0, own)); + else all.put(k, new Kept(Math.max(0, Math.min(v, max(c.valueWidth))), c.valueWord, c.valueWidth, own)); StringBuilder sb = new StringBuilder(); for (Map.Entry e : all.entrySet()) { Kept x = e.getValue(); diff --git a/android/app/src/main/java/dev/peanuts/mods/CheatsPage.java b/android/app/src/main/java/dev/peanuts/mods/CheatsPage.java index 0077d6ff..f7e69d25 100644 --- a/android/app/src/main/java/dev/peanuts/mods/CheatsPage.java +++ b/android/app/src/main/java/dev/peanuts/mods/CheatsPage.java @@ -41,8 +41,12 @@ * chips. A switch keeps the toggle for the game's next start (CheatsBridge.on: the toggles the launcher writes into <build>.enabled) and acts at once in a * running game through the in-game panel. A tap on a source opens its sheet: on or off as a whole, other versions, remove. *
    • Mods: today's Mods section (dev.peanuts.settings.ModsSection), each mod with "Next start" or "Needs a build".
    • - *
    • Add: a file (.zip, .txt) or a folder (CheatImportUi); a mod goes to the mod import.
    • + *
    • Add: a file (.zip, .txt, .mncf, .mncp) or a folder (CheatImportUi); a mod goes to the mod import. Export, beside Add on the Cheats tab while there are + * sources: the player's sources as .mncf or .mncp.
    • *
    + * Each source is an .mncf file (Mistel Native Cheat Format) made ready for the game's build (MncfBuild): a cheat that cannot work here is listed, off, with + * the reason in the player's words (MncfWords); a source signed by a key Peanuts trusts says who signed it, an unsigned one is as any other. A source not made + * ready for the build yet (after an update of the game) is made ready off the UI thread, and the page is built again then. * On the Thor the bottom screen explains the row the focus is on (BottomScreen.explain): a cheat's kind, what it changes, that it works at once, its source. * A, Y and X: switch, details, all off. Nothing here reads or writes a save. */ @@ -213,8 +217,9 @@ static final class Model { build = builds.isEmpty() ? null : builds.iterator().next(); version = build == null ? null : CheatsBridge.version(g.titleId, build); textEnd = CheatsBridge.textEnd(g.packDir); - CheatsBridge.wanted(c, g.titleId, CheatsBridge.master(c, g.titleId)); // the earlier state moved over once (the app's switch, upstream's imports) - merged = build == null ? null : CheatsBridge.merged(c, g.titleId, g.gameDir, g.packDir, build, textEnd); + CheatsBridge.wanted(c, g.titleId, CheatsBridge.master(c, g.titleId)); // the earlier state moved over once (the app's switch) + CheatsBridge.convert(c, g.titleId, g.name, g.packDir); // upstream's imports and an earlier version's Atmosphère sources made .mncf, with the pack's main + merged = build == null ? null : CheatsBridge.merged(c, g.titleId, g.gameDir, g.packDir, build, textEnd, false); // the kept ones (prepare makes the others) sources = CheatSources.list(folder); on = CheatsBridge.on(c, g.titleId); appHas = build != null && CheatsBridge.appText(g.packDir, build) != null; @@ -226,11 +231,15 @@ static final class Model { List blocks() { List out = new ArrayList<>(); if (merged != null) for (CheatSources.Row r : merged.rows) if (!out.contains(r.block)) out.add(r.block); + if (merged != null) for (CheatSources.Block b : merged.blocks) if (!out.contains(b) && (b.parsed.mncf != null || b.pending || b.error != null)) out.add(b); // an .mncf whose cheats cannot work here: listed with the reasons return out; } CheatSources.Block block(String id) { for (CheatSources.Block b : blocks()) if (b.id.equals(id)) return b; return null; } + /** Whether a source's file is not made ready for the build yet */ + boolean pending() { for (CheatSources.Block b : blocks()) if (b.pending) return true; return false; } + /** The cheats the game has now: the switchable ones of the sources that are on */ int cheats() { return merged == null ? 0 : merged.keys().size(); } @@ -286,6 +295,18 @@ private static void page(Activity a, LinearLayout content, Game g, boolean own) android.widget.Button add = PUi.button(a, "Add", PUi.Kind.PRIMARY, Feel.button(v -> CheatImportUi.add(a, g.titleId))); android.graphics.drawable.Drawable plus = Icons.get(a, "add", Icons.Ink.ON_BANANA); if (plus != null) { plus.setBounds(0, 0, PUi.dp(a, 20), PUi.dp(a, 20)); add.setCompoundDrawables(plus, null, null, null); add.setCompoundDrawablePadding(PUi.dp(a, 6)); add.setPadding(PUi.dp(a, 12), 0, PUi.dp(a, 16), 0); } + // Export beside Add, the other way a cheat file goes: the player's sources as .mncf (one) or .mncp (several), with what is on and the numbers set, or + // as a ZIP for other emulators (CheatImportUi.export: a dialog with both) + int sources = 0; + for (CheatSources.Source s : m.sources) if (s.file().isFile()) sources++; + int exportable = sources; + android.widget.Button export = !tab.equals(CHEATS) || sources == 0 ? null + : PUi.button(a, "Export", PUi.Kind.TONAL, Feel.button(v -> CheatImportUi.export(a, g, exportable))); + if (export != null) { + export.setContentDescription("Export the cheats"); + android.graphics.drawable.Drawable out = Icons.get(a, "pack_out", Icons.Ink.NORMAL); + if (out != null) { out.setBounds(0, 0, PUi.dp(a, 20), PUi.dp(a, 20)); export.setCompoundDrawables(out, null, null, null); export.setCompoundDrawablePadding(PUi.dp(a, 6)); export.setPadding(PUi.dp(a, 12), 0, PUi.dp(a, 16), 0); } + } LinearLayout head = PUi.row(a); head.setMinimumHeight(PUi.dp(a, 56)); @@ -303,14 +324,20 @@ private static void page(Activity a, LinearLayout content, Game g, boolean own) head.addView(titles, PUi.weight()); LinearLayout top = new LinearLayout(a); // the page's top, kept at the top while the rest scrolls (stick) top.setOrientation(LinearLayout.VERTICAL); - if (!own) { // the area's bar: Cheats | Mods, then Add + LinearLayout.LayoutParams el = PUi.wrap(); + el.leftMargin = PUi.dp(a, 10); + if (!own) { // the area's bar: Cheats | Mods, then Export and Add LinearLayout bar = PUi.row(a); bar.addView(seg, new LinearLayout.LayoutParams(PUi.dp(a, 240), ViewGroup.LayoutParams.WRAP_CONTENT)); bar.addView(PUi.spacer(a)); - bar.addView(add, PUi.wrap()); + if (export != null) bar.addView(export, PUi.wrap()); + LinearLayout.LayoutParams al = PUi.wrap(); + al.leftMargin = export != null ? PUi.dp(a, 10) : 0; + bar.addView(add, al); top.addView(bar); } else if (wide) { head.addView(seg, new LinearLayout.LayoutParams(PUi.dp(a, 240), ViewGroup.LayoutParams.WRAP_CONTENT)); + if (export != null) head.addView(export, el); LinearLayout.LayoutParams al = PUi.wrap(); al.leftMargin = PUi.dp(a, 10); head.addView(add, al); @@ -319,6 +346,7 @@ private static void page(Activity a, LinearLayout content, Game g, boolean own) top.addView(head); LinearLayout bar = PUi.row(a); bar.addView(seg, PUi.weight()); + if (export != null) bar.addView(export, el); LinearLayout.LayoutParams al = PUi.wrap(); al.leftMargin = PUi.dp(a, 10); bar.addView(add, al); @@ -393,6 +421,22 @@ private static boolean inside(View v, View parent) { return false; } + private static String preparing; // the title whose sources are being made ready for its build (off the UI thread) + + /** Sources not made ready for the build yet: made ready off the UI thread, then the page again (once a title at a time) */ + private static void prepare(Activity a, Model m) { + if (m.build == null || preparing != null || !m.pending()) return; + Game g = m.g; + preparing = g.titleId; + android.content.Context app = a.getApplicationContext(); + new Thread(() -> { + try { CheatsBridge.prepare(app, g.titleId, g.packDir, m.build); } + finally { + new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> { preparing = null; if (openFor != null && openFor.titleId.equals(g.titleId)) rebuild(); }); + } + }, "peanuts-cheats-ready").start(); + } + private static void cheats(Activity a, LinearLayout content, Model m) { Game g = m.g; LinearLayout first = PUi.add(content, PUi.listCard(a), 12); @@ -412,10 +456,11 @@ private static void cheats(Activity a, LinearLayout content, Model m) { if (m.appHas) { CheatSources.Block b = m.block(CheatSources.APP); any |= source(a, content, m, b, null, b != null ? b.name : "Comes with the app"); } for (CheatSources.Source s : m.sources) any |= source(a, content, m, m.block(s.id), s, s.name); for (CheatSources.Block b : blocks) if (b.id.startsWith("mod:")) any |= source(a, content, m, b, null, b.name); + prepare(a, m); if (!any) { LinearLayout card = PUi.add(content, PUi.listCard(a), 12); PUi.Setting none = new PUi.Setting(a, "", "No cheats yet", Feel.row(v -> CheatImportUi.add(a, g.titleId))) - .value("Add a zip, a text file or a folder with cheats for " + m.versionWords() + " (build " + shortBuild(m.build) + "). Peanuts never downloads any."); + .value("Add a Mistel cheat file (.mncf), or a zip, a text file or a folder with cheats for " + m.versionWords() + " (build " + shortBuild(m.build) + "). Peanuts never downloads any."); rowLook(none.view, "folder"); explainOnFocus(none.view, () -> BottomScreen.explain(a, null)); card.addView(none.view); @@ -428,22 +473,29 @@ private static boolean source(Activity a, LinearLayout content, Model m, CheatSo boolean app = s == null && b != null && b.id.equals(CheatSources.APP), mod = b != null && b.id.startsWith("mod:"); boolean enabled = s != null ? s.enabled : app ? m.appOn : true; Set otherBuilds = new LinkedHashSet<>(); - if (s != null) for (String bid : s.files().keySet()) if (!bid.equals(m.build)) otherBuilds.add(bid); + if (s != null) for (String bid : s.builds()) if (!bid.equals(m.build)) otherBuilds.add(bid); if (b == null && otherBuilds.isEmpty()) return false; - CheatFile.Parsed p = b == null ? null : b.parsed; + CheatFile.Parsed p = b == null || b.pending || b.error != null || forOther(b.parsed) ? null : b.parsed; int n = p == null ? 0 : p.switchable(); LinearLayout card = PUi.add(content, PUi.listCard(a), 16); + // a source not made ready for this build yet, or one that cannot be read, may name no other build: its line says what it is instead CharSequence line = p != null ? PUi.joined(count(n, "cheat") + " for " + m.versionWords(), shortBuild(m.build)) - : PUi.joined("For another version", shortBuild(otherBuilds.iterator().next())); + : b != null && b.pending ? PUi.joined("Cheats for " + m.versionWords(), shortBuild(m.build)) + : b != null && b.error != null ? "Cannot be read" + : otherBuilds.isEmpty() ? "For another version" : PUi.joined("For another version", shortBuild(otherBuilds.iterator().next())); PUi.Setting head = new PUi.Setting(a, "", name, Feel.row(v -> sourceSheet(a, m, b, s, name, otherBuilds))).value(line); rowLook(head.view, mod ? "mods" : "folder"); String from = s == null ? (app ? "Comes with the app" : "From a mod") : fromWords(s.from); head.view.addView(chip(a, enabled ? from : "Off", false), chipLp(a)); explainOnFocus(head.view, () -> explainSource(a, m, b, s, name, enabled, otherBuilds)); card.addView(head.view); + MncfBuild.Ready ready = b == null ? null : b.parsed.mncf; + if (ready != null && ready.verified()) card.addView(cardLine(a, "Signed by " + ready.signer + ": its file is as they made it.")); + if (b != null && b.pending) { card.addView(cardLine(a, "Looking up its cheats in " + m.versionWords() + ".")); return true; } + if (b != null && b.error != null) { card.addView(cardLine(a, "Its file cannot be read: it is damaged or of a newer kind. Remove it, or add a newer copy.")); return true; } if (p != null && !p.credits.isEmpty()) card.addView(cardLine(a, "Credit: " + CheatFile.credit(p))); - if (p != null && p.unsupported() > 0) card.addView(cardLine(a, p.unsupported() + " more " + (p.unsupported() == 1 ? "is" : "are") + " not supported here: listed, and off.")); + if (p != null && p.unsupported() > 0) card.addView(cardLine(a, p.unsupported() + " more " + (p.unsupported() == 1 ? "is" : "are") + (p.mncf != null ? " not possible here: listed with the reason, and off." : " not supported here: listed, and off."))); if (p != null && !p.masters.isEmpty() && enabled) { List ms = new ArrayList<>(); for (CheatFile.Cheat c : p.masters) ms.add(c.name); @@ -464,6 +516,13 @@ private static boolean source(Activity a, LinearLayout content, Model m, CheatSo return true; } + /** An .mncf block none of whose cheats is for this build (each refused as build-unknown): shown as a source for another version */ + static boolean forOther(CheatFile.Parsed p) { + if (p == null || p.mncf == null || p.cheats.isEmpty() && p.masters.isEmpty()) return p != null && p.mncf != null; + for (CheatFile.Cheat c : p.cheats) if (!"build-unknown".equals(c.reason())) return false; + return p.masters.isEmpty(); + } + static String fromWords(String from) { switch (from) { case CheatSources.FROM_ZIP: return "From your zip"; @@ -490,8 +549,7 @@ private static View cheatRow(Activity a, Model m, CheatSources.Block b, CheatFil col.addView(t); LinearLayout chips = PUi.row(a); chips.setPadding(0, PUi.dp(a, 4), 0, 0); - chips.addView(chip(a, c.kind.label, false)); - if (c.holdLabel() != null) { LinearLayout.LayoutParams lp = PUi.wrap(); lp.leftMargin = PUi.dp(a, 6); chips.addView(chip(a, c.holdLabel(), true), lp); } + chips(a, chips, c); col.addView(chips); row.addView(col, PUi.weight()); Switch sw = new Switch(a); @@ -504,8 +562,10 @@ private static View cheatRow(Activity a, Model m, CheatSources.Block b, CheatFil Runnable explain = () -> explainCheat(a, m, c, key, sw.isChecked(), source, from); sw.setOnCheckedChangeListener((v, x) -> { Feel.toggled(v, x); + Set others = m.merged.related(m.on, key, x); // an .mncf cheat's relations: what it needs on, what it cannot be on with off CheatsBridge.on(a, m.g.titleId, key, x); if (x) m.on.add(key); else m.on.remove(key); + if (!others.isEmpty()) { CheatsBridge.on(a, m.g.titleId, m.on); rebuild(); return; } explain.run(); }); row.setOnClickListener(v -> { if (can) sw.toggle(); else details(a, c, source, from); }); @@ -520,6 +580,16 @@ private static View cheatRow(Activity a, Model m, CheatSources.Block b, CheatFil return row; } + /** A cheat's chips: its kind ("Not possible here" for an .mncf cheat that cannot work here), its hold buttons, and what its file warns of */ + private static void chips(Context a, LinearLayout chips, CheatFile.Cheat c) { + chips.addView(chip(a, c.reason() != null ? "Not possible here" : c.kind.label, false)); + if (c.holdLabel() != null) { LinearLayout.LayoutParams lp = PUi.wrap(); lp.leftMargin = PUi.dp(a, 6); chips.addView(chip(a, c.holdLabel(), true), lp); } + if (c.mncf != null && c.reason() == null) for (String t : c.mncf.tags) { + String w = t.equals("may_crash") ? "May crash the game" : t.equals("touches_save") ? "Changes your save" : null; + if (w != null) { LinearLayout.LayoutParams lp = PUi.wrap(); lp.leftMargin = PUi.dp(a, 6); chips.addView(chip(a, w, false), lp); } + } + } + /** X: every cheat of the game off, for the next start and in a running game's panel */ private static void allOff(Activity a, Model m) { if (m.onCount() == 0) { Feel.refused(a); return; } @@ -534,8 +604,7 @@ private static void details(Activity a, CheatFile.Cheat c, String source, String LinearLayout box = new LinearLayout(a); box.setOrientation(LinearLayout.VERTICAL); LinearLayout chips = PUi.row(a); - chips.addView(chip(a, c.kind.label, false)); - if (c.holdLabel() != null) { LinearLayout.LayoutParams lp = PUi.wrap(); lp.leftMargin = PUi.dp(a, 6); chips.addView(chip(a, c.holdLabel(), true), lp); } + chips(a, chips, c); box.addView(chips); PUi.add(box, PUi.body(a, CheatFile.describe(c)), 12); PUi.add(box, PUi.small(a, "From " + source + (from.startsWith("From ") ? ", " + from.substring(5) : "") + "." + (c.group.isEmpty() ? "" : " In " + c.group + ".")), 8); @@ -560,14 +629,18 @@ private static void sourceSheet(Activity a, Model m, CheatSources.Block b, Cheat PUi.add(box, PUi.body(a, what + (app ? " They come with the app for this game." : " " + fromWords(s.from) + ".")), 0); if (p != null && !p.credits.isEmpty()) PUi.add(box, PUi.small(a, "Credit: " + CheatFile.credit(p)), 8); if (!otherBuilds.isEmpty()) { - PUi.add(box, PUi.section(a, "For another version"), 16); + PUi.add(box, PUi.section(a, "For other versions too"), 16); for (String bid : otherBuilds) { String v = CheatsBridge.version(m.g.titleId, bid); - int n = 0; - try { String text = s.text(bid); if (text != null) n = CheatFile.parse(text, -1).switchable(); } catch (IOException ignored) { } - PUi.add(box, PUi.small(a, PUi.joined(count(n, "cheat"), v != null ? v : null, "build " + bid)), 6); + PUi.add(box, PUi.small(a, v != null ? v + ", build " + bid : "Build " + bid), 6); } - PUi.add(box, PUi.small(a, "They start to work when the game is that version."), 6); + PUi.add(box, PUi.small(a, "Its cheats for those versions start to work when the game is one of them."), 6); + } + MncfBuild.Ready ready = b == null ? null : b.parsed.mncf; + if (ready != null && ready.file != null) { + Map origin = ready.file.origin(); + Object site = origin == null ? null : origin.get("site"), orig = origin == null ? null : origin.get("name"); + if (orig != null || site != null) PUi.add(box, PUi.small(a, "Added from " + (orig != null ? orig : site) + (orig != null && site != null ? ", from " + site : "") + "."), 8); } AlertDialog.Builder d = PUi.sheet(a, name, box).setNegativeButton("Close", null); d.setPositiveButton(on ? "Turn off" : "Turn on", Feel.confirm((x, w) -> { diff --git a/android/app/src/main/java/dev/peanuts/mods/MncfBuild.java b/android/app/src/main/java/dev/peanuts/mods/MncfBuild.java new file mode 100644 index 00000000..6b5b27a4 --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/mods/MncfBuild.java @@ -0,0 +1,610 @@ +package dev.peanuts.mods; + +import java.io.File; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import io.github.davdxpx.mistel.mncf.Atmosphere; +import io.github.davdxpx.mistel.mncf.AtmosphereException; +import io.github.davdxpx.mistel.mncf.Build; +import io.github.davdxpx.mistel.mncf.CheatResult; +import io.github.davdxpx.mistel.mncf.CodeModule; +import io.github.davdxpx.mistel.mncf.Converter; +import io.github.davdxpx.mistel.mncf.Evaluation; +import io.github.davdxpx.mistel.mncf.Evaluator; +import io.github.davdxpx.mistel.mncf.Mncf; +import io.github.davdxpx.mistel.mncf.MncfException; +import io.github.davdxpx.mistel.mncf.MncfFile; +import io.github.davdxpx.mistel.mncf.Module; +import io.github.davdxpx.mistel.mncf.Runtime; +import io.github.davdxpx.mistel.mncf.SignatureResult; +import io.github.davdxpx.mistel.mncf.TrustList; +import io.github.davdxpx.mistel.mncf.ValueSpec; + +/** + * One .mncf cheat file made ready for the build of the game that runs (Mistel's spec, sections 5, 6, 11.2): its cheats' states and reasons, and the Atmosphère + * code the host's cheat engine runs for them (Part A and B: the host reads one merged Atmosphère file). No Android classes: CheatLoaderJvmTest runs it. + *
      + *
    1. The file is read with Mistel's library (Mncf.load), its signature checked against the keys the app trusts ({@link #TRUST}: none yet).
    2. + *
    3. The build: the file's build whose main module is the one that runs, else a build of the running module's ID is added (cheats that find their place by a + * pattern still work then; per-build offsets and raw code of other builds do not).
    4. + *
    5. Each pattern is searched once in the game's own main (MncfMain) and its place written in as a fixed offset: the file "pinned" to this build. The pinned + * file, an .mncf itself, is kept with its states beside the source (build/<BID>.mncf and .tsv), so a later start or the in-game tab reads it without + * searching main again (section 6.3 allows it: a runtime MAY keep the result for later runs of the same build).
    6. + *
    7. Mistel's evaluator gives each cheat its state and reason for this runtime: guest reads and writes, code bytes, buttons; no display (monitors) and no + * code hooks (overrides become a stub patch). The parts of the core Atmosphère code cannot say ({@link #UNSUPPORTED}: toggle buttons, run once or for a + * time, several conditions, ...) are refused with runtime:unsupported:<part> until Peanuts runs Mistel's pass engine itself, and a patch or a stub + * over a place Peanuts' rewriter changed with runtime:rewritten (section 11.3).
    8. + *
    9. The cheats that can run become Atmosphère code (Mistel's Converter.toAtmosphere): their raw code for this build where the evaluator uses it, else code + * made from their operations.
    10. + *
    + */ +public final class MncfBuild { + private MncfBuild() {} + + /** The keys Peanuts trusts: Mistel's, once it has one (Mistel's docs/keys.toml is empty so far). An unsigned file loads as any other, without a mark */ + public static final TrustList TRUST = new TrustList(); + + /** The pinned files and their states: <source>/build/<BID>.mncf and <BID>.tsv; CACHE names the layout of the .tsv */ + static final String DIR = "build", CACHE = "mncf-build/1"; + + /** The capabilities of Peanuts' cheat engine (section 11.1): no display (the monitors wait for the pass engine), no code hooks (stubs are patches) */ + static final List CAPABILITIES = Collections.unmodifiableList(java.util.Arrays.asList("guest-read", "guest-write", "code-bytes", "buttons")); + + // Bases for the evaluator: the host's are not known before the game runs, and nothing here reads guest memory, so any that keep the places apart do + static final long MAIN_BASE = 0x8000000L, REGION_SIZE = 1L << 40; + + /** What the game is, for a file made ready */ + public static final class Game { + public final String titleId, build, version; // build: the running main's build ID, 16 hex digits upper case; version: its name ("2.0.2"), null unknown + public final File pack; // the pack: the game's own main (MncfMain), null for none + public Game(String titleId, String build, String version, File pack) { + this.titleId = titleId; this.build = build == null ? null : build.toUpperCase(Locale.ROOT); this.version = version; this.pack = pack; + } + } + + /** One cheat of the file for this build */ + public static final class Cheat { + public final int index; + public final String id, name, group, about, run; + public final List tags, requires, excludes; + public final String radio; + public final boolean master, isDefault; + public final String reason; // the spec's reason it is refused here (Appendix B, or runtime:), null when it can run + public final List lines; // its Atmosphère code for this build; empty when refused + public final ValueSpec value; // its one whole-number value the player sets (the in-game number field), else null + public final String valueKey; // "." + Cheat(int index, io.github.davdxpx.mistel.mncf.Cheat c, String reason, List lines, ValueSpec value) { + this.index = index; id = c.id(); name = c.name(); group = c.group() == null ? "" : c.group(); about = c.about(); run = c.run(); + tags = c.tags(); requires = c.requires(); excludes = c.excludes(); radio = c.radio(); master = c.isMaster(); isDefault = c.isDefault(); + this.reason = reason; this.lines = lines; this.value = value; valueKey = value == null ? null : c.id() + "." + value.id(); + } + public boolean refused() { return reason != null; } + } + + /** The file made ready: its cheats, or why it cannot be used at all */ + public static final class Ready { + public final String error; // Appendix D's code when the file cannot be used ("toml", "schema:cheat", ...), else null + public final MncfFile file; // the file as stored (its signature, authors, origin) + public final String signature, signer; // the signature's result (verified, unsigned, ...) and who signed it, by the trust list's name, null unless verified + public final String buildKey; // the file's build for the running one, null when the file has none and one was added + public final List cheats; + final String pinned; // the pinned file's text + final String key; // the build key in the pinned file + final Map raws; // which cheats run their raw code (the evaluator's "uses") + Ready(String error, MncfFile file, String signature, String signer, String buildKey, List cheats, String pinned, String key, Map raws) { + this.error = error; this.file = file; this.signature = signature; this.signer = signer; this.buildKey = buildKey; this.cheats = cheats; this.pinned = pinned; this.key = key; + this.raws = raws; + } + public boolean verified() { return SignatureResult.VERIFIED.equals(signature); } + + boolean usesRaw(Cheat c) { return Boolean.TRUE.equals(raws.get(c.id)); } + + /** The cheat's Atmosphère code with v as its value (the in-game number field); null when v does not fit or the code cannot be made */ + public List lines(Cheat c, long v) { + if (c.value == null || pinned == null || key == null) return null; + Map values = new HashMap<>(); + values.put(c.valueKey, v); + try { + return lower(pinned, key, values, Collections.singletonMap(c.id, Boolean.FALSE)).get(c.index); + } catch (MncfException | RuntimeException e) { + return null; + } + } + } + + // ---- Reading ---- + + static String sha256(byte[] b) { + try { + StringBuilder sb = new StringBuilder(); + for (byte x : MessageDigest.getInstance("SHA-256").digest(b)) sb.append(String.format(Locale.ROOT, "%02x", x & 0xFF)); + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + /** The file's build whose main module is the running one (section 5: the shorter ID a prefix of the longer, without case), null when none is */ + static String buildKey(MncfFile f, String build16) { + if (build16 == null) return null; + for (Build b : f.builds().values()) { + String main = b.modules().get("main"); + if (main == null) continue; + String a = main.toUpperCase(Locale.ROOT), r = build16.toUpperCase(Locale.ROOT); + if (a.startsWith(r) || r.startsWith(a)) return b.key(); + } + return null; + } + + /** The build IDs of main the file names (16 hex digits, upper case), in its order */ + public static List builds(MncfFile f) { + List out = new ArrayList<>(); + for (Build b : f.builds().values()) { + String main = b.modules().get("main"); + if (main != null && main.length() >= 16 && !out.contains(main.substring(0, 16).toUpperCase(Locale.ROOT))) out.add(main.substring(0, 16).toUpperCase(Locale.ROOT)); + } + return out; + } + + /** The version name of one of the file's builds by its main's build ID, null when it has none */ + public static String version(MncfFile f, String build16) { + String k = buildKey(f, build16); + Build b = k == null ? null : f.builds().get(k); + if (b == null) return null; + String v = b.version() != null && !b.version().isEmpty() ? b.version() : k, main = b.modules().get("main"); // the library gives the key when the file names no version + return main != null && main.equalsIgnoreCase(v) ? null : v; // a build named by its build ID has no version name + } + + /** + * A source file made ready for the game's build: from its kept pinned file when that is of these very bytes, else made now (and kept). One made while the + * pack had no main yet (a game not built yet) is kept too, so the page does not look it up again and again, and made again once the pack has its main + */ + public static Ready of(File source, Game g) throws IOException { + byte[] bytes = Files.readAllBytes(source.toPath()); + File dir = new File(source.getParentFile(), DIR); + String sha = sha256(bytes); + Ready kept = g.build == null ? null : kept(dir, g.build, sha, bytes, hasMain(g)); + if (kept != null) return kept; + CodeModule main = g.pack == null ? null : MncfMain.of(g.pack); + List changed = g.pack == null ? Collections.emptyList() : MncfMain.changed(g.pack); + Ready r = make(bytes, g, main, changed); + if (r.error == null && g.build != null) keep(dir, g.build, sha, r, main != null); + return r; + } + + /** A source file's kept pinned file for the game's build, when it is of these very bytes; null when it was not made yet (then {@link #of} makes it) */ + public static Ready kept(File source, Game g) throws IOException { + if (g.build == null) return null; + byte[] bytes = Files.readAllBytes(source.toPath()); + return kept(new File(source.getParentFile(), DIR), g.build, sha256(bytes), bytes, hasMain(g)); + } + + /** Whether the game's pack has its main now (MncfMain.has) */ + static boolean hasMain(Game g) { return g.pack != null && MncfMain.has(g.pack); } + + /** The bytes made ready (main: the game's own main, null when there is none; changed: the runs the rewriter changed) */ + public static Ready make(byte[] bytes, Game g, CodeModule main, List changed) { + MncfFile f; + try { + f = Mncf.load(bytes, TRUST); + } catch (MncfException e) { + return new Ready(e.code(), null, null, null, null, Collections.emptyList(), null, null, Collections.emptyMap()); + } + SignatureResult sig = f.signature(); + String signer = SignatureResult.VERIFIED.equals(sig.result()) && !sig.signers().isEmpty() ? sig.signers().get(0) : null; + String fileKey = buildKey(f, g.build); + Map doc = copy(f.doc()); + String key = fileKey; + if (key == null && g.build != null) key = addBuild(doc, g.build, g.version); + Module module = main == null ? Module.builder(g.build == null ? "0" : g.build).base(MAIN_BASE).size(REGION_SIZE).build() : main.toModule(MAIN_BASE); // no pack: places are not checked against an image + if (main != null) pin(doc, module); + String pinned = io.github.davdxpx.mistel.mncf.Writer.dumps(doc); + MncfFile p; + try { + p = Mncf.load(pinned.getBytes(StandardCharsets.UTF_8)); + } catch (MncfException e) { // the pinned file is the library's own writing of a file it read: not expected + return new Ready("pinned:" + e.code(), f, sig.result(), signer, fileKey, Collections.emptyList(), null, null, Collections.emptyMap()); + } + Runtime rt = runtime(g, module, changed); + Evaluation ev = Evaluator.evaluate(p, rt); + boolean bad = SignatureResult.INVALID.equals(sig.result()) || SignatureResult.REVOKED.equals(sig.result()); + Map reasons = new LinkedHashMap<>(); + Map raw = new HashMap<>(); + for (io.github.davdxpx.mistel.mncf.Cheat c : p.cheats()) { + CheatResult r = ev.cheat(c.id()); + String why = bad ? "signature" : r == null ? "invalid" : CheatResult.REFUSED.equals(r.state()) ? r.reason() : null; + if (main == null && ("pattern-not-found".equals(why) || "expect-mismatch".equals(why) || "outside".equals(why))) why = "runtime:no-main"; // no pack yet: nothing to search or compare + reasons.put(c.id(), why); + raw.put(c.id(), r != null && "raw".equals(r.uses())); + } + Map> lines = Collections.emptyMap(); + Map skipped = new HashMap<>(); + if (key != null) { + Map want = new LinkedHashMap<>(); + for (io.github.davdxpx.mistel.mncf.Cheat c : p.cheats()) if (reasons.get(c.id()) == null) want.put(c.id(), raw.get(c.id())); + try { + lines = lower(pinned, key, null, Collections.emptyMap(), want, skipped); + } catch (MncfException | RuntimeException e) { + for (String id : want.keySet()) skipped.put(id, ""); + } + } + List cheats = new ArrayList<>(); + for (io.github.davdxpx.mistel.mncf.Cheat c : p.cheats()) { + String why = reasons.get(c.id()); + List l = lines.get(c.index()); + if (why == null && key == null) why = "build-unknown"; + if (why == null && l == null) why = runtimeReason(skipped.get(c.id()), c); + cheats.add(new Cheat(c.index(), c, why, why == null ? l : Collections.emptyList(), Boolean.TRUE.equals(raw.get(c.id())) ? null : number(c))); + } + return new Ready(null, f, sig.result(), signer, fileKey, Collections.unmodifiableList(cheats), pinned, key, raw); + } + + /** + * The parts of the core (section 11.1, Mncf.FEATURES) Peanuts' cheat engine does not have yet, because the host runs Atmosphère code and these have no + * Atmosphère form: a cheat that uses one is refused with runtime:unsupported:<part> until Peanuts runs Mistel's pass engine itself. A single condition, + * hold and press buttons and an override with its expect do have one (a memory condition, a key block, a stub patch). Monitors are refused for the display + * capability Peanuts does not offer (capability-missing:display), so run.monitor is not listed + */ + static final List UNSUPPORTED = Collections.unmodifiableList(java.util.Arrays.asList("run.once", "run.timed", "toggle", "when.many", "match.any", + "trigger.enter", "interval")); + + /** + * The runtime the evaluator checks the cheats against: Peanuts' cheat engine on the Switch, the game that runs, its main (with its image for patterns), the + * parts it lacks, and the runs of main its rewriter changed (a patch or a stub over one is refused with runtime:rewritten, section 11.3) + */ + static Runtime runtime(Game g, Module main, List changed) { + Runtime.Builder b = Runtime.builder("switch").module("main", main).capabilities(CAPABILITIES).extensions(Mncf.KNOWN_EXTENSIONS).rawSyntaxes("atmosphere") + .unsupported(UNSUPPORTED); + if (g.titleId != null) b.gameId(g.titleId); + long base = 1L << 40; + for (String r : new String[] {"heap", "alias", "aslr"}) { b.region(r, base, REGION_SIZE); base += REGION_SIZE << 1; } + for (CodeModule.Run run : changed) b.rewritten("main", run.offset(), run.length()); + return b.build(); + } + + /** A cheat's one whole-number value the player sets: one value, an integer type, no choices and no flags (those wait for their own controls) */ + static ValueSpec number(io.github.davdxpx.mistel.mncf.Cheat c) { + if (c.values().size() != 1) return null; + ValueSpec v = c.values().values().iterator().next(); + if (!v.type().matches("[us](8|16|32|64)") || v.choices() != null || v.flags() != null) return null; + if (!(v.defaultValue() instanceof Long)) return null; // a default of 2^63 or more (a BigInteger) is past the field's numbers + return v; + } + + /** + * The reason of a cheat the evaluator lets run but Atmosphère code cannot say, from the converter's stable reason (Converter.Export.reasons(), spec + * section 15): the reader's own reasons as they are, runtime:unsupported:<part> for a part of the core that has no Atmosphère form in this shape (a + * condition on a pointer path, an action that also writes or holds; c names which run or which condition), capability-missing:display for a monitor, + * runtime:no-main for a pattern with no main to search, else runtime:<what> + */ + static String runtimeReason(String code, io.github.davdxpx.mistel.mncf.Cheat c) { + String k = code == null ? "" : code; + switch (k) { + case "atmosphere:run": return "runtime:unsupported:run." + (c != null && c.run().equals("timed") ? "timed" : "once"); + case "atmosphere:monitor": return "capability-missing:display"; + case "atmosphere:toggle": return "runtime:unsupported:toggle"; + case "atmosphere:condition": { + if (c != null) for (String part : Evaluator.uses(c)) if (part.equals("when.many") || part.equals("match.any") || part.equals("trigger.enter") || part.equals("interval")) return "runtime:unsupported:" + part; + return "runtime:unsupported:when"; + } + case "atmosphere:action": return "runtime:unsupported:run.action"; + case "atmosphere:override": return "runtime:unsupported:override"; + case "atmosphere:no-module": return "runtime:no-main"; + case "atmosphere:empty": return "invalid"; + case "": return "runtime:code"; + default: return k.startsWith("atmosphere:") ? "runtime:" + k.substring("atmosphere:".length()) : k; // module, region, address, too-long; the reader's reasons + } + } + + // ---- The pinned file ---- + + @SuppressWarnings("unchecked") + static Object copyAny(Object v) { + if (v instanceof Map) { + Map out = new LinkedHashMap<>(); + for (Map.Entry e : ((Map) v).entrySet()) out.put(e.getKey(), copyAny(e.getValue())); + return out; + } + if (v instanceof List) { + List out = new ArrayList<>(); + for (Object x : (List) v) out.add(copyAny(x)); + return out; + } + return v; + } + + @SuppressWarnings("unchecked") + static Map copy(Map doc) { return (Map) copyAny(doc); } + + /** A build of the running main added to the document; its key: the build ID, or that with a number when the file has that key already */ + @SuppressWarnings("unchecked") + static String addBuild(Map doc, String build16, String version) { + Map builds = (Map) doc.get("builds"); + if (builds == null) { + builds = new LinkedHashMap<>(); + Map d = new LinkedHashMap<>(); + for (Map.Entry e : doc.entrySet()) { // builds after game, as the layout writes them; the order of a map the writer orders itself + d.put(e.getKey(), e.getValue()); + } + d.put("builds", builds); + doc.clear(); + doc.putAll(d); + } + String key = build16; + for (int k = 2; builds.containsKey(key); k++) key = build16 + "-" + k; + Map b = new LinkedHashMap<>(); + if (version != null && !version.isEmpty() && !key.equals(version)) b.put("version", version); + Map modules = new LinkedHashMap<>(); + modules.put("main", build16); + b.put("modules", modules); + builds.put(key, b); + return key; + } + + static long longOf(Object o) { + if (o == null) return 0; + if (o instanceof Long || o instanceof Integer) return ((Number) o).longValue(); + if (o instanceof BigInteger) return ((BigInteger) o).longValue(); + String s = o.toString().trim(); + boolean neg = s.startsWith("-"); + if (neg) s = s.substring(1); + long v = s.startsWith("0x") || s.startsWith("0X") ? Long.parseUnsignedLong(s.substring(2), 16) : Long.parseLong(s); + return neg ? -v : v; + } + + /** Each location of main that finds its place by a pattern, given that place as a fixed offset where the pattern matches exactly once */ + @SuppressWarnings("unchecked") + static void pin(Map doc, Module main) { + Object cheats = doc.get("cheat"); + if (!(cheats instanceof List)) return; + Map> found = new HashMap<>(); + for (Object c : (List) cheats) { + if (!(c instanceof Map)) continue; + Map cheat = (Map) c; + for (String kind : new String[] {"patch", "write", "override", "read", "when"}) { + Object ops = cheat.get(kind); + if (!(ops instanceof List)) continue; + for (Object o : (List) ops) { + if (!(o instanceof Map)) continue; + Map op = (Map) o; + pinAt(op, kind.equals("override") ? "function" : "at", main, found); + if (kind.equals("when") && op.get("value") instanceof Map) pinAt((Map) op.get("value"), "at", main, found); + } + } + } + } + + @SuppressWarnings("unchecked") + private static void pinAt(Map op, String name, Module main, Map> found) { + Object a = op.get(name); + if (!(a instanceof Map)) return; + Map at = (Map) a; + if (!(at.get("find") instanceof String) || !"main".equals(at.get("module"))) return; + String find = (String) at.get("find"), section = at.get("section") instanceof String ? (String) at.get("section") : null; + List m; + try { + m = found.computeIfAbsent(find + "\n" + section, k -> Evaluator.findAll(main, find, section, 2)); + } catch (IllegalArgumentException e) { + return; // not a pattern: the evaluator refuses the cheat for it + } + if (m.size() != 1) return; // not found or more than once: left as it is, the evaluator says which + long off; + try { + off = m.get(0) + longOf(at.get("offset")); + } catch (NumberFormatException e) { + return; + } + if (off < 0) return; // before main: the evaluator's outside + Map to = new LinkedHashMap<>(); + to.put("module", "main"); + to.put("offset", off); + if (at.containsKey("path")) to.put("path", at.get("path")); + op.put(name, to); + } + + // ---- Atmosphère code ---- + + /** lower without a list of what it left out */ + static Map> lower(String pinned, String key, Map values, Map want) throws MncfException { + return lower(pinned, key, null, values, want, new HashMap()); + } + + /** + * The Atmosphère code of the cheats in want (id → whether it runs its raw code) for the build key (Converter.toAtmosphere), with the values set + * (cheat.value → number: the player's values, checked as the reader checks them; one a cheat cannot take leaves that cheat to its raw code for the build, + * or out); by the cheat's index. main: the build's main for the patterns and for checking each patch against expect, null for a file whose places are + * fixed already (the pinned file); with it a build the file does not name is written from the patterns. skipped gets the ones left out with the + * converter's stable reason (Export.reasons(), spec section 15; runtimeReason gives Peanuts' reason for it) + */ + static Map> lower(String text, String key, CodeModule main, Map values, Map want, Map skipped) throws MncfException { + io.github.davdxpx.mistel.mncf.Choices chosen = choices(values); + Map> out = new HashMap<>(); + for (Map part : parts(want)) { + MncfFile d = renamed(text, part.keySet()); + out.putAll(pick(d, Converter.toAtmosphere(d, key, main, "raw", chosen, cores(part)), skipped)); + } + return out; + } + + /** + * Every build a file names as Atmosphère code (Converter.toAtmosphereAll), as lower does for one: build key → the cheats' code by index. mains: the main of + * a build, by key, where Peanuts has it (patterns found, patches checked against expect); a build without one writes what is placed already and leaves + * a pattern out (atmosphere:no-module). reasons gets, by build key, the cheats left out with the converter's stable reason; a build that names no main + * module has no code and every cheat's reason is the build's (atmosphere:module) + */ + static Map>> lowerAll(String text, Map mains, Map values, Map want, + Map> reasons) throws MncfException { + io.github.davdxpx.mistel.mncf.Choices chosen = choices(values); + Map>> out = new LinkedHashMap<>(); + for (Map part : parts(want)) { + MncfFile d = renamed(text, part.keySet()); + for (Converter.BuildExport b : Converter.toAtmosphereAll(d, mains, "raw", chosen, cores(part))) { + Map why = reasons.computeIfAbsent(b.build(), k -> new LinkedHashMap()); + if (b.export() == null) { + for (String id : part.keySet()) why.put(id, b.reason()); + continue; + } + out.computeIfAbsent(b.build(), k -> new HashMap>()).putAll(pick(d, b.export(), why)); + } + } + return out; + } + + /** + * At most this many cheats are lowered together: the converter keeps Atmosphère's limit of 127 entries a file (spec section 15), and Peanuts' host + * takes more (CHEAT_MAX in dm/host/hle_cheats.c), so a source with more is lowered in parts. MncfExport keeps the limit for the whole ZIP file + */ + static final int LOWER_PART = 127; + + /** want in parts of at most LOWER_PART cheats, in its order */ + private static List> parts(Map want) { + List> out = new ArrayList<>(); + Map part = null; + for (Map.Entry e : want.entrySet()) { + if (part == null || part.size() >= LOWER_PART) out.add(part = new LinkedHashMap<>()); + part.put(e.getKey(), e.getValue()); + } + return out; + } + + /** The cheats of want that are made from their operations first (Converter's preferCheats; the others run their own raw code for the build first) */ + private static Map cores(Map want) { + Map out = new HashMap<>(); + for (Map.Entry e : want.entrySet()) if (!Boolean.TRUE.equals(e.getValue())) out.put(e.getKey(), "core"); + return out; + } + + /** Each cheat's code from the converter's export, by its index in the file (renamed's n<index>); skipped gets the others with their stable reason */ + private static Map> pick(MncfFile d, Converter.Export e, Map skipped) { + Map> lines = entries(e); + Map> out = new HashMap<>(); + for (io.github.davdxpx.mistel.mncf.Cheat c : d.cheats()) { + List l = lines.get(c.name()); + if (l == null || l.isEmpty()) { skipped.put(c.id(), e.reasons().getOrDefault(c.id(), "atmosphere:empty")); continue; } + out.put(Integer.parseInt(c.name().substring(1)), l); + } + return out; + } + + /** + * A file's text with only the cheats in keep, each named by its index in the file (n<index>), so the converter's entries are found again by name + * whatever a cheat's own name holds. Without what would join entries or tie cheats together, as neither matters for one cheat's code: groups (the + * converter's group entries), master (the converter puts every master into one entry; Peanuts' host and MncfExport.atmosphere keep them apart), + * requires, excludes and radio (they name cheats that may be left out here), presets and translations + */ + @SuppressWarnings("unchecked") + private static MncfFile renamed(String text, Set keep) throws MncfException { + MncfFile p = Mncf.load(text.getBytes(StandardCharsets.UTF_8)); + Map doc = copy(p.doc()); + List cheats = (List) doc.get("cheat"), kept = new ArrayList<>(); + int i = 0; + for (Object o : cheats) { + Map c = (Map) o; + int at = i++; + if (!keep.contains(c.get("id"))) continue; + c.put("name", "n" + at); + for (String k : new String[] {"group", "master", "requires", "excludes", "radio"}) c.remove(k); + kept.add(c); + } + doc.put("cheat", kept); + doc.remove("preset"); // a preset names values; the converter needs none of them + doc.remove("i18n"); + return Mncf.load(io.github.davdxpx.mistel.mncf.Writer.dumps(doc).getBytes(StandardCharsets.UTF_8)); + } + + /** The values set, as the player's choices */ + private static io.github.davdxpx.mistel.mncf.Choices choices(Map values) { + io.github.davdxpx.mistel.mncf.Choices.Builder cb = io.github.davdxpx.mistel.mncf.Choices.builder(); + for (Map.Entry v : values.entrySet()) cb.value(v.getKey(), v.getValue()); + return cb.build(); + } + + private static Map> entries(Converter.Export e) { + Map> out = new HashMap<>(); + if (e == null) return out; + try { + for (Atmosphere.Entry x : Atmosphere.parse(e.text())) out.put(x.name(), x.lines()); + } catch (AtmosphereException ex) { + return out; // the converter's own text: not expected + } + return out; + } + + // ---- Keeping it for the build ---- + + /** + * The kept pinned file of this build, when it was made from these very bytes, and with the game's main where the pack has it now (mainNow); null otherwise + * (then it is made again) + */ + static Ready kept(File dir, String build16, String sha, byte[] bytes, boolean mainNow) { + File tsv = new File(dir, build16 + ".tsv"), mncf = new File(dir, build16 + ".mncf"); + if (!tsv.isFile() || !mncf.isFile()) return null; + try { + String[] lines = new String(Files.readAllBytes(tsv.toPath()), StandardCharsets.UTF_8).split("\n"); + String[] h = lines[0].split("\t", -1); + if (h.length < 6 || !h[0].equals("# " + CACHE) || !h[1].equals(sha)) return null; + if (mainNow && h.length > 6 && h[6].equals(NO_MAIN)) return null; // made before the pack had its main: its patterns were not searched + MncfFile f = Mncf.load(bytes, TRUST); + String pinned = new String(Files.readAllBytes(mncf.toPath()), StandardCharsets.UTF_8); + MncfFile p = Mncf.load(pinned.getBytes(StandardCharsets.UTF_8)); + Map rows = new HashMap<>(); + for (int i = 1; i < lines.length; i++) { String[] r = lines[i].split("\t", -1); if (r.length >= 3) rows.put(r[0], r); } + String key = h[2].isEmpty() ? null : h[2]; + Map want = new LinkedHashMap<>(); + for (io.github.davdxpx.mistel.mncf.Cheat c : p.cheats()) { + String[] r = rows.get(c.id()); + if (r == null) return null; // a kept list of another file: made again + if (r[1].isEmpty()) want.put(c.id(), "raw".equals(r[2])); + } + Map skipped = new HashMap<>(); + Map> lines2 = key == null ? Collections.>emptyMap() : lower(pinned, key, null, Collections.emptyMap(), want, skipped); + List cheats = new ArrayList<>(); + Map raws = new HashMap<>(); + for (io.github.davdxpx.mistel.mncf.Cheat c : p.cheats()) { + String[] r = rows.get(c.id()); + String why = r[1].isEmpty() ? null : r[1]; + List l = lines2.get(c.index()); + if (why == null && l == null) why = runtimeReason(skipped.get(c.id()), c); + boolean raw = "raw".equals(r[2]); + cheats.add(new Cheat(c.index(), c, why, why == null ? l : Collections.emptyList(), raw ? null : number(c))); + raws.put(c.id(), raw); + } + return new Ready(null, f, f.signature().result(), h[4].isEmpty() ? null : h[4], h[3].isEmpty() ? null : h[3], Collections.unmodifiableList(cheats), pinned, key, raws); + } catch (IOException | MncfException | RuntimeException e) { + return null; + } + } + + /** Made without the game's main (the .tsv's last header field; "main" when it was read) */ + static final String NO_MAIN = "no-main"; + + /** + * The pinned file and its states kept for the build: "# mncf-build/1 \t sha \t key \t file's build key \t signer \t signature \t main or no-main", then + * id \t reason \t uses + */ + static void keep(File dir, String build16, String sha, Ready r, boolean withMain) { + try { + if (!dir.isDirectory() && !dir.mkdirs()) return; + StringBuilder sb = new StringBuilder("# ").append(CACHE).append('\t').append(sha).append('\t').append(r.key == null ? "" : r.key).append('\t') + .append(r.buildKey == null ? "" : r.buildKey).append('\t').append(r.signer == null ? "" : r.signer.replaceAll("[\t\r\n]", " ")).append('\t').append(r.signature).append('\t').append(withMain ? "main" : NO_MAIN).append('\n'); + for (Cheat c : r.cheats) sb.append(c.id).append('\t').append(c.reason == null ? "" : c.reason).append('\t').append(r.usesRaw(c) ? "raw" : "core").append('\n'); + CheatSources.write(new File(dir, build16 + ".mncf"), r.pinned); + CheatSources.write(new File(dir, build16 + ".tsv"), sb.toString()); + } catch (IOException | RuntimeException e) { + // not kept: the next reader makes it again + } + } +} diff --git a/android/app/src/main/java/dev/peanuts/mods/MncfConvert.java b/android/app/src/main/java/dev/peanuts/mods/MncfConvert.java new file mode 100644 index 00000000..9c73dc5d --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/mods/MncfConvert.java @@ -0,0 +1,88 @@ +package dev.peanuts.mods; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import io.github.davdxpx.mistel.mncf.CodeModule; +import io.github.davdxpx.mistel.mncf.ConvertException; +import io.github.davdxpx.mistel.mncf.Converter; +import io.github.davdxpx.mistel.mncf.Source; + +/** + * Every cheat file the player adds that is not .mncf becomes one (Mistel's spec, section 15), with everything that is known about it: one .mncf a source for + * all of its builds (an Atmosphère, Eden, Yuzu or Ryujinx file of each build ID, upstream's export, an earlier import), the game's ID and name, each build's + * version, where it came from (origin: the format and the zip's, folder's or file's name, the site its credits link to), and who made it: the people its credits + * name, else the player who adds it, else nobody. With the game's own main at hand (the pack: MncfMain) the converter fills each patch's expect from it and finds + * the places by patterns, so a cheat made for one build also works on a later one where its place is found; without it the cheats keep their offsets for their + * builds. The raw code of every cheat is kept word for word, so no cheat is lost. No Android classes: CheatLoaderJvmTest runs it. + */ +public final class MncfConvert { + private MncfConvert() {} + + /** What a conversion knows besides the files: the game, its builds' versions, its own main for the pack's build, who adds it */ + public static final class Known { + public final String titleId, gameName, author; + public final String build; // the pack's main build (16 hex, upper case), whose main is `main`; null without a pack + final Map versions; // build ID (16 hex) → its version name ("2.0.2"), as far as the app knows them + final MainSource main; + public Known(String titleId, String gameName, String author, String build, Map versions, MainSource main) { + this.titleId = titleId; this.gameName = gameName; this.author = author == null || author.trim().isEmpty() ? null : author.trim(); + this.build = build == null ? null : build.toUpperCase(Locale.ROOT); this.versions = versions == null ? Collections.emptyMap() : versions; this.main = main; + } + } + + /** Gives the game's own main of the pack's build when it is needed (read once: it is the size of the game's code) */ + public interface MainSource { + CodeModule main() throws IOException; + } + + /** A pack's main, read when first asked for; null when the pack has none */ + public static MainSource of(File pack) { + CodeModule[] kept = new CodeModule[1]; + boolean[] read = new boolean[1]; + return () -> { + if (!read[0]) { read[0] = true; kept[0] = pack == null ? null : MncfMain.of(pack); } + return kept[0]; + }; + } + + /** The name the origin keeps for a source's format: Atmosphère's code in each of its layouts (Eden, Yuzu and Ryujinx keep the same files) */ + static final String FORMAT = "atmosphere"; + + /** + * The Atmosphère files of one source (build ID → text) as one .mncf text. origin: the source's name as the player had it (a zip's, folder's or file's + * name), null when none. ConvertException when the files are not Atmosphère code the converter reads (its code() "atmosphere" or "source") + */ + public static String fromAtmosphere(Map byBuild, String origin, Known k) throws ConvertException, IOException { + List sources = new ArrayList<>(); + CodeModule main = null; + boolean mainAsked = false; + for (Map.Entry e : byBuild.entrySet()) { + String bid = e.getKey().toUpperCase(Locale.ROOT); + Source.Builder b = Source.builder(bid, CheatSources.body(e.getValue())); // lines that are not code, EdiZon's sections: Mistel's converter reads them + String v = k.versions.get(bid); + if (v != null && !v.isEmpty()) b.version(v); // two builds of one version name: the converter names them by their build IDs + if (k.build != null && k.build.equals(bid) && k.main != null) { + if (!mainAsked) { mainAsked = true; main = k.main.main(); } + if (main != null && sameBuild(main, bid)) b.module(main); + } + sources.add(b.build()); + } + Converter.Options o = Converter.Options.forGame(k.titleId); + if (k.gameName != null && !k.gameName.isEmpty()) o = o.gameName(k.gameName); + if (origin != null && !origin.trim().isEmpty()) o = o.origin(origin.trim()); + if (k.author != null) o = o.authors(Collections.singletonList(k.author)); + return Converter.fromAtmosphere(sources, o).text(); + } + + /** Whether the main read from the pack is of this build (the pack names its build ID; a pack of another version has another main) */ + static boolean sameBuild(CodeModule main, String bid16) { + String id = main.buildId(); + return id == null || id.toUpperCase(Locale.ROOT).startsWith(bid16.toUpperCase(Locale.ROOT)); + } +} diff --git a/android/app/src/main/java/dev/peanuts/mods/MncfExport.java b/android/app/src/main/java/dev/peanuts/mods/MncfExport.java new file mode 100644 index 00000000..4ec4826e --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/mods/MncfExport.java @@ -0,0 +1,463 @@ +package dev.peanuts.mods; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import io.github.davdxpx.mistel.mncf.CodeModule; +import io.github.davdxpx.mistel.mncf.Mncf; +import io.github.davdxpx.mistel.mncf.MncfException; +import io.github.davdxpx.mistel.mncf.MncfFile; +import io.github.davdxpx.mistel.mncf.SignatureResult; +import io.github.davdxpx.mistel.mncf.Writer; + +/** + * Export: the player's cheat sources of a game as Mistel Native Cheat Format files, so another device (or another app that reads .mncf) has the same cheats, + * switched as here. One source becomes one .mncf, several an .mncp pack with one .mncf a source (Mistel's spec, section 13; its manifest names each file's + * SHA-256). In each file the cheats switched on here are default = true and the others false, and a number set in the in-game tab is its value's default, so the + * import of the export on another device starts as this one is. A file nothing of that changes is written byte for byte as it was added (a signature stays + * good); a changed one is the library's writing of it (Writer: without signature lines). For other emulators, {@link #zip} writes the same sources as + * Atmosphère cheat files in Atmosphère's folders, one a build, and names what Atmosphère code cannot hold. No Android classes: CheatLoaderJvmTest runs it. + */ +public final class MncfExport { + private MncfExport() {} + + /** What an export is: its file name, the bytes, and how many sources and cheats went in */ + public static final class Out { + public final String fileName; + public final byte[] bytes; + public final int sources, cheats; + public final boolean pack; + Out(String fileName, byte[] bytes, int sources, int cheats, boolean pack) { this.fileName = fileName; this.bytes = bytes; this.sources = sources; this.cheats = cheats; this.pack = pack; } + } + + /** The name an export is offered under: "<game> cheats.mncf" or ".mncp", without characters a file name cannot have */ + public static String fileName(String gameName, boolean pack) { + String n = (gameName == null || gameName.trim().isEmpty() ? "Cheats" : gameName.trim() + " cheats").replaceAll("[\\\\/:*?\"<>|\\p{Cntrl}]", " ").replaceAll("\\s+", " ").trim(); + return n + (pack ? ".mncp" : ".mncf"); + } + + /** Whether the game has sources to export (an .mncf each) */ + public static boolean any(File folder) { + for (CheatSources.Source s : CheatSources.list(folder)) if (s.file().isFile()) return true; + return false; + } + + /** + * The export of the game's sources: merged gives each cheat's key (the toggles' and the kept numbers' key), on the keys switched on, kept the numbers set + * (CheatValues.read). Null when the game has no source. IOException when a source's file cannot be read + */ + public static Out make(File folder, String gameName, CheatSources.Merged merged, Set on, Map kept) throws IOException { + List sources = new ArrayList<>(); + for (CheatSources.Source s : CheatSources.list(folder)) if (s.file().isFile()) sources.add(s); + if (sources.isEmpty()) return null; + List names = new ArrayList<>(); + List files = new ArrayList<>(); + int cheats = 0; + for (CheatSources.Source s : sources) { + byte[] b = Files.readAllBytes(s.file().toPath()); + MncfFile f; + try { + f = Mncf.load(b); + } catch (MncfException e) { + files.add(b); // a file this app cannot use goes as it is: the other side may read it + names.add(s.id + ".mncf"); + continue; + } + for (io.github.davdxpx.mistel.mncf.Cheat c : f.cheats()) if (!c.isMaster()) cheats++; + files.add(withState(b, f, s.id, merged, on, kept)); + names.add(s.id + ".mncf"); + } + if (sources.size() == 1) return new Out(fileName(gameName, false), files.get(0), 1, cheats, false); + return new Out(fileName(gameName, true), pack(gameName, names, files), sources.size(), cheats, true); + } + + /** A source's file with the player's switches as defaults and the set numbers as its values' defaults; its own bytes when that changes nothing */ + @SuppressWarnings("unchecked") + static byte[] withState(byte[] own, MncfFile f, String sourceId, CheatSources.Merged merged, Set on, Map kept) { + Map byId = new HashMap<>(); + if (merged != null) for (CheatSources.Row r : merged.rows) if (r.block.id.equals(sourceId) && r.cheat.mncf != null) byId.put(r.cheat.mncf.id, r); + Map numbers = numbers(sourceId, merged, kept); + Map doc = MncfBuild.copy(f.doc()); + boolean changed = false; + for (Object o : (List) doc.get("cheat")) { + Map c = (Map) o; + CheatSources.Row r = byId.get(String.valueOf(c.get("id"))); + if (r == null || r.cheat.master) continue; // refused here, a master, or not in this build's merge: as the file has it + boolean want = on.contains(r.key), had = Boolean.TRUE.equals(c.get("default")); + if (want != had) { + if (want) c.put("default", true); else c.remove("default"); + changed = true; + } + Long n = r.cheat.mncf.valueKey == null ? null : numbers.get(r.cheat.mncf.valueKey); + if (n != null && c.get("values") instanceof Map) { + Object v = ((Map) c.get("values")).get(r.cheat.mncf.value.id()); + if (v instanceof Map) { ((Map) v).put("default", n); changed = true; } + } + } + return changed ? Writer.dumps(doc).getBytes(StandardCharsets.UTF_8) : own; + } + + /** The numbers set in the in-game tab of a source's cheats (CheatValues.read), inside their ranges: "<cheat id>.<value id>" → the number */ + static Map numbers(String sourceId, CheatSources.Merged merged, Map kept) { + Map out = new HashMap<>(); + if (merged == null || kept == null) return out; + for (CheatSources.Row r : merged.rows) { + if (!r.block.id.equals(sourceId) || r.cheat.mncf == null || r.cheat.number == null || r.cheat.mncf.valueKey == null) continue; + CheatValues.Kept k = kept.get(r.key.toLowerCase(Locale.ROOT)); + if (k != null && CheatValues.apply(r.cheat, k) != null) out.put(r.cheat.mncf.valueKey, Math.max(r.cheat.number.min(), Math.min(k.number, r.cheat.number.max()))); + } + return out; + } + + // ---- A ZIP for other emulators ---- + + /** At most this many entries beside the master in one Atmosphère file, group starts and ends counted (spec section 15; Atmosphère refuses more) */ + static final int ATMOSPHERE_MAX = 127; + + /** At most this many words of code in one entry, the master's too (spec section 15; Atmosphère refuses more) */ + static final int ATMOSPHERE_WORDS = 256; + + /** A file of this many bytes or more Atmosphère refuses (dmnt's text buffer, docs/reference/cheats.md) */ + static final int ATMOSPHERE_BYTES = 0x10000; + + /** The bytes of a name Atmosphère keeps (readable_name[0x40] with its terminator, docs/reference/cheats.md): a longer one is cut */ + static final int ATMOSPHERE_NAME = 63; + + /** A ZIP in Atmosphère's layout, and what went in and what could not */ + public static final class Zip { + public final String fileName; + public final byte[] bytes; + public final Map builds; // build ID (16 hex, upper case) → the cheats its file has; the running build first + public final Map versions; // build ID → its version name, where a file names one + public final int cheats; // the cheats in the ZIP, in one build's file at least + public final List left; // the cheats in no file: {name, why in the player's words}, in the sources' order + Zip(String fileName, byte[] bytes, Map builds, Map versions, int cheats, List left) { + this.fileName = fileName; this.bytes = bytes; this.builds = builds; this.versions = versions; this.cheats = cheats; this.left = left; + } + } + + /** The name a ZIP export is offered under: "<game> cheats.zip" */ + public static String zipName(String gameName) { return fileName(gameName, false).replaceFirst("\\.mncf$", ".zip"); } + + /** Where Atmosphère reads a build's cheats in the ZIP (Eden, Yuzu and Ryujinx read the same files) */ + public static String zipPath(String titleId, String build16) { + return "atmosphere/contents/" + titleId.toUpperCase(Locale.ROOT) + "/cheats/" + build16.toUpperCase(Locale.ROOT) + ".txt"; + } + + /** One cheat lowered for one build; key: "<source's place in the list>/<cheat id>" */ + private static final class Lowered { + final int source; + final String key, id, name, group; + final boolean master; + final List requires, lines; + Lowered(int source, MncfBuild.Cheat c, List lines) { + this.source = source; key = source + "/" + c.id; id = c.id; name = c.name; group = c.group; master = c.master; requires = c.requires; this.lines = lines; + } + } + + /** + * The game's sources as a ZIP for other emulators: one Atmosphère cheat file a build, at atmosphere/contents/<title ID>/cheats/<build ID>.txt, each + * source's cheats lowered by Mistel's converter for every build its file names (Converter.toAtmosphereAll). For the build that runs it gets the game's own + * main (MncfMain: the pack's main with its original words), so the patterns are found and every patch and override stub is checked against expect before + * it is written: a cheat whose place holds other code stays out, and the ZIP never writes over the wrong bytes. A build the game runs that the file does + * not name is written from the patterns with that main. Each cheat is its own code for the build where the file has it, else code made from its + * operations; one with a number set in the in-game tab is made from its operations with that number where it can be. Left out and named, with the + * converter's stable reason in the player's words: what Atmosphère code cannot say (a monitor, toggle buttons, a run once or for a time, several + * conditions), a pattern in a build whose main Peanuts does not have, what does not fit the game, and what goes past Atmosphère's limits. Masters become + * each file's one master code; groups are written as the spec writes them (section 15). Null when the game has no source + */ + public static Zip zip(File folder, String gameName, MncfBuild.Game g, CheatSources.Merged merged, Map kept) throws IOException { + List sources = new ArrayList<>(); + for (CheatSources.Source s : CheatSources.list(folder)) if (s.file().isFile()) sources.add(s); + if (sources.isEmpty()) return null; + CodeModule main = null; // the game's own main of the build that runs, read once for every source + if (g.pack != null && g.build != null) { + try { main = MncfMain.of(g.pack); } catch (IOException e) { main = null; } // a pack whose main does not fit together: its patterns stay out + if (main != null && !MncfConvert.sameBuild(main, g.build)) main = null; + } + Map> byBuild = new LinkedHashMap<>(); + if (g.build != null) byBuild.put(g.build, new ArrayList<>()); + Map versions = new LinkedHashMap<>(); + List left = new ArrayList<>(); + Map names = new LinkedHashMap<>(); // every cheat (not a master) by its key, in the sources' order + Map why = new HashMap<>(); // a cheat's key → why it is in no build + for (int si = 0; si < sources.size(); si++) { + CheatSources.Source s = sources.get(si); + byte[] bytes = Files.readAllBytes(s.file().toPath()); + MncfFile f; + try { + f = Mncf.load(bytes, MncfBuild.TRUST); + } catch (MncfException e) { + left.add(new String[] {s.name, "Its file cannot be read."}); + continue; + } + String sig = f.signature().result(); + boolean bad = SignatureResult.INVALID.equals(sig) || SignatureResult.REVOKED.equals(sig); + Map values = new HashMap<>(numbers(s.id, merged, kept)); + List all = new ArrayList<>(); + Map want = new LinkedHashMap<>(); // its own code first, or code made from its operations first where a number is set + for (io.github.davdxpx.mistel.mncf.Cheat c : f.cheats()) { + MncfBuild.Cheat x = new MncfBuild.Cheat(c.index(), c, null, Collections.emptyList(), MncfBuild.number(c)); + all.add(x); + want.put(c.id(), !(x.valueKey != null && values.containsKey(x.valueKey))); + if (!c.isMaster()) names.put(si + "/" + c.id(), c.name()); + if (bad) why.put(si + "/" + c.id(), MncfWords.reason("signature", null)); + } + if (bad) continue; + String own = new String(bytes, StandardCharsets.UTF_8), runKey = MncfBuild.buildKey(f, g.build); + Map mains = new HashMap<>(); + if (runKey != null && main != null) mains.put(runKey, main); + Map> reasons = new LinkedHashMap<>(); // build key → cheat id → the converter's reason + try { + for (Map.Entry>> e : MncfBuild.lowerAll(own, mains, values, want, reasons).entrySet()) { + String id = f.builds().get(e.getKey()).modules().get("main"), bid = id.substring(0, Math.min(16, id.length())).toUpperCase(Locale.ROOT); + add(byBuild.computeIfAbsent(bid, k -> new ArrayList<>()), si, all, e.getValue()); + String v = MncfBuild.version(f, bid); + if (v != null) versions.putIfAbsent(bid, v); + } + if (runKey == null && main != null) { // the build that runs, which the file does not name: from its patterns, with the game's main + Map sk = new LinkedHashMap<>(); + add(byBuild.get(g.build), si, all, MncfBuild.lower(own, g.build, main, values, want, sk)); + reasons.put(g.build, sk); + if (g.version != null) versions.putIfAbsent(g.build, g.version); + } + } catch (MncfException | RuntimeException e) { // the library's own writing of a file it read: not expected + for (MncfBuild.Cheat c : all) why.putIfAbsent(si + "/" + c.id, "An Atmosphère file cannot say what it does."); + continue; + } + // a cheat in no build: the reason of the build that runs, else of the file's first build + List> order = new ArrayList<>(); + Map run = reasons.get(runKey != null ? runKey : g.build); + if (run != null) order.add(run); + order.addAll(reasons.values()); + for (MncfBuild.Cheat c : all) { + for (Map r : order) if (r.containsKey(c.id)) { why.putIfAbsent(si + "/" + c.id, zipWords(r.get(c.id), c)); break; } + } + } + Map counts = new LinkedHashMap<>(); + Set in = new HashSet<>(); + Map past = new HashMap<>(); // a cheat's key → why a file it was lowered for could not hold it, the running build's first + ByteArrayOutputStream o = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(o)) { + for (Map.Entry> e : byBuild.entrySet()) { + Set here = new HashSet<>(); + String text = atmosphere(e.getValue(), sources, here, past); + if (here.isEmpty()) continue; + counts.put(e.getKey(), here.size()); + in.addAll(here); + z.putNextEntry(new ZipEntry(zipPath(g.titleId, e.getKey()))); + z.write(text.getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + } + } + for (Map.Entry e : names.entrySet()) { + if (in.contains(e.getKey())) continue; + left.add(new String[] {e.getValue(), past.containsKey(e.getKey()) ? past.get(e.getKey()) : why.getOrDefault(e.getKey(), "An Atmosphère file cannot say what it does.")}); + } + versions.keySet().retainAll(counts.keySet()); + return new Zip(zipName(gameName), o.toByteArray(), counts, versions, in.size(), left); + } + + /** Why the converter left a cheat out of an Atmosphère file, from its stable reason (Converter.Export.reasons(), spec section 15), in the player's words */ + static String zipWords(String code, MncfBuild.Cheat c) { + String k = code == null ? "" : code; + switch (k) { + case "atmosphere:no-module": return "Its place is found by the code around it, and Peanuts can look it up only in the version it has built."; + case "atmosphere:run": return "timed".equals(c == null ? null : c.run) ? "It runs for a set time, which an Atmosphère file cannot say." + : "It runs once when you turn it on, which an Atmosphère file cannot say."; + case "atmosphere:monitor": return "It shows values from the game, which an Atmosphère file cannot do."; + case "atmosphere:toggle": return "It is switched with a button combination, which an Atmosphère file cannot say."; + case "atmosphere:condition": return "It waits for the game in a way an Atmosphère file cannot say."; + case "atmosphere:action": return "It runs when you press its buttons in a way an Atmosphère file cannot say."; + case "atmosphere:override": return "It changes a function in a way an Atmosphère file cannot say."; + case "atmosphere:module": return "It changes a part of the game other than its main code, which an Atmosphère file cannot name."; + case "atmosphere:region": return "It writes a part of the game's memory an Atmosphère file cannot name."; + case "atmosphere:address": return "It writes a fixed address, which an Atmosphère file cannot name."; + case "atmosphere:empty": return "It has nothing to write."; + case "atmosphere:too-long": return "Its code is longer than one cheat in an Atmosphère file can be."; + case "atmosphere:too-many": return TOO_MANY; + default: return k.isEmpty() || k.startsWith("atmosphere:") ? "An Atmosphère file cannot say what it does." : MncfWords.reason(k, c); // the reader's reasons (Appendix B) + } + } + + private static void add(List to, int source, List cheats, Map> lines) { + for (MncfBuild.Cheat c : cheats) { + List code = lines.get(c.index); + if (code != null && !code.isEmpty()) to.add(new Lowered(source, c, code)); + } + } + + static final String TOO_MANY = "An Atmosphère file holds at most " + ATMOSPHERE_MAX + " cheats."; + static final String TOO_BIG = "An Atmosphère file can be at most 64 KB, and the cheats before this one fill it."; + static final String MASTER_TOO_LONG = "It needs a code that is always on, and that code does not fit in one Atmosphère file beside the others."; + + /** + * One build's Atmosphère file, within Atmosphère's limits (spec section 15), as Mistel's converter writes one source's file, for every source of the + * game together (the converter takes one file): the masters as its one master code, named by the first, of at most ATMOSPHERE_WORDS words (a + * master past that stays out, and with it the cheats of its source that require it), then each source's cheats in its order, at most ATMOSPHERE_MAX + * entries, the file under ATMOSPHERE_BYTES (past either, the rest stays out). A group starts with its name as an empty entry and ends with an entry of + * only 20000001 where a cheat in no group follows it, as Mistel's converter writes and reads them; where the group entries would leave cheats out, the + * file has no groups. A name an earlier source has already gets the source's name after it, as in the merged file; within one source the names stay as + * its file has them; every name is cut to the ATMOSPHERE_NAME bytes Atmosphère keeps. in gets the key of each cheat it has, past the key of each it could + * not hold with why (an earlier file's why is kept) + */ + static String atmosphere(List l, List sources, Set in, Map past) { + List masters = new ArrayList<>(), cheats = new ArrayList<>(); + Set outMasters = new HashSet<>(); // "/" of a master that does not fit + int words = 0; + for (Lowered x : l) { + if (!x.master) continue; + int w = words(x.lines); + if (words + w > ATMOSPHERE_WORDS) { outMasters.add(x.key); continue; } + words += w; + masters.add(x); + } + for (Lowered x : l) { + if (x.master) continue; + boolean needs = false; + for (String r : x.requires) needs |= outMasters.contains(x.source + "/" + r); + if (needs) past.putIfAbsent(x.key, MASTER_TOO_LONG); else cheats.add(x); + } + boolean groups = cheats.size() + count(marks(cheats, true)) <= ATMOSPHERE_MAX; + List mark = marks(cheats, groups); + StringBuilder sb = new StringBuilder(); + Map taken = new HashMap<>(); // a name in lower case → the source that has it + if (!masters.isEmpty()) { + String name = atm(masters.get(0).name); // the first master's name, as the converter names its one master entry (spec section 15) + if (name.isEmpty()) name = "Master code"; + sb.append('{').append(name).append("}\n"); + taken.put(name.toLowerCase(Locale.ROOT), -1); + for (Lowered x : masters) for (String line : x.lines) sb.append(line).append('\n'); + } + int entries = 0, bytes = utf8(sb); + String full = null; // why the file is full: then the rest stays out too + for (int i = 0; i < cheats.size(); i++) { + Lowered x = cheats.get(i); + String m = mark.get(i); + StringBuilder e = new StringBuilder(); + if (m != null) e.append(sb.length() > 0 ? "\n" : "").append(m); + String safe = atm(x.name); + e.append(sb.length() + e.length() > 0 ? "\n" : "").append('[').append(name(safe.isEmpty() ? "Cheat" : safe, x.source, sources.get(x.source).name, taken)).append("]\n"); + for (String line : x.lines) e.append(line).append('\n'); + int n = entries + (m == null ? 0 : 1) + 1, b = utf8(e); + if (full == null && n > ATMOSPHERE_MAX) full = TOO_MANY; + if (full == null && bytes + b >= ATMOSPHERE_BYTES) full = TOO_BIG; + if (full != null) { past.putIfAbsent(x.key, full); continue; } + sb.append(e); + entries = n; + bytes += b; + in.add(x.key); + } + return sb.toString(); + } + + /** + * The group entry before each cheat, null where it needs none: its group's name as an empty entry where a group starts (a group is its source's, so + * the next source starts its own), an entry of only 20000001 under the group's name where a cheat in no group follows one. All null without groups + */ + private static List marks(List cheats, boolean groups) { + List out = new ArrayList<>(); + String open = null; + int source = -1; + for (Lowered x : cheats) { + String g = groups && !x.group.isEmpty() ? atm(x.group) : null; + String m = null; + if (g != null && (x.source != source || !g.equals(open))) m = "[" + g + "]\n"; + else if (g == null && open != null) m = "[" + open + "]\n20000001\n"; + out.add(m); + open = g; + source = x.source; + } + return out; + } + + private static int count(List marks) { + int n = 0; + for (String m : marks) if (m != null) n++; + return n; + } + + /** The words of code in an entry's lines */ + private static int words(List lines) { + int n = 0; + for (String line : lines) for (String w : line.trim().split("\\s+")) if (!w.isEmpty()) n++; + return n; + } + + /** A cheat's name in the file: its own, or with its source's name when another source has it (taken: lower case → source); at most ATMOSPHERE_NAME bytes */ + private static String name(String base, int source, String sourceName, Map taken) { + Integer had = taken.get(base.toLowerCase(Locale.ROOT)); + if (had == null || had == source) { taken.put(base.toLowerCase(Locale.ROOT), source); return base; } + String n = fit(base, " (" + CheatSources.safe(sourceName) + ")"); + for (int k = 2; taken.containsKey(n.toLowerCase(Locale.ROOT)) && taken.get(n.toLowerCase(Locale.ROOT)) != source; k++) n = fit(base, " (" + CheatSources.safe(sourceName) + " " + k + ")"); + taken.put(n.toLowerCase(Locale.ROOT), source); + return n; + } + + /** A name as Atmosphère keeps it: without the characters that end a header, cut to ATMOSPHERE_NAME bytes */ + static String atm(String name) { return cut(CheatSources.safe(name), ATMOSPHERE_NAME); } + + /** name with suffix, the name cut so the whole has at most ATMOSPHERE_NAME bytes (the suffix cut too where it is longer alone) */ + private static String fit(String name, String suffix) { + String sfx = cut(suffix, ATMOSPHERE_NAME); + return cut(name, ATMOSPHERE_NAME - utf8(sfx)) + sfx; + } + + /** s cut to at most max UTF-8 bytes, between characters, trimmed */ + static String cut(String s, int max) { + if (utf8(s) <= max) return s; + int i = 0, b = 0; + while (i < s.length()) { + int cp = s.codePointAt(i), n = new String(Character.toChars(cp)).getBytes(StandardCharsets.UTF_8).length; + if (b + n > max) break; + b += n; + i += Character.charCount(cp); + } + return s.substring(0, i).trim(); + } + + private static int utf8(CharSequence s) { return s.toString().getBytes(StandardCharsets.UTF_8).length; } + + /** An .mncp: pack.toml (format, name, each file with its SHA-256) and the files, stored in a ZIP */ + static byte[] pack(String gameName, List names, List files) throws IOException { + StringBuilder m = new StringBuilder("format = \"mncf-pack/1\"\nname = ").append(toml(gameName == null || gameName.trim().isEmpty() ? "Cheats" : gameName.trim() + " cheats")).append('\n'); + for (int i = 0; i < names.size(); i++) m.append("\n[[file]]\npath = ").append(toml(names.get(i))).append("\nsha256 = \"").append(MncfBuild.sha256(files.get(i))).append("\"\n"); + ByteArrayOutputStream o = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(o)) { + z.putNextEntry(new ZipEntry("pack.toml")); + z.write(m.toString().getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + for (int i = 0; i < names.size(); i++) { + z.putNextEntry(new ZipEntry(names.get(i))); + z.write(files.get(i)); + z.closeEntry(); + } + } + return o.toByteArray(); + } + + /** A TOML basic string */ + static String toml(String s) { + StringBuilder sb = new StringBuilder("\""); + for (char c : s.toCharArray()) { + if (c == '"' || c == '\\') sb.append('\\').append(c); + else if (c < 0x20 || c == 0x7F) sb.append(String.format(Locale.ROOT, "\\u%04X", (int) c)); + else sb.append(c); + } + return sb.append('"').toString(); + } +} diff --git a/android/app/src/main/java/dev/peanuts/mods/MncfFacts.java b/android/app/src/main/java/dev/peanuts/mods/MncfFacts.java new file mode 100644 index 00000000..87d709a6 --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/mods/MncfFacts.java @@ -0,0 +1,69 @@ +package dev.peanuts.mods; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import io.github.davdxpx.mistel.mncf.Build; +import io.github.davdxpx.mistel.mncf.MncfFile; +import io.github.davdxpx.mistel.mncf.SignatureResult; + +/** + * What an .mncf file brings, counted from the file itself, for the Add dialog and the sheet after an import (CheatImportUi): its cheats, the versions it + * names, how many check the game's code before they change it (a patch or an override always names the original bytes), how many find their place by a pattern + * (so they keep working after a game update), the numbers a player can set, the cheats that say what they do, the ones kept only as the code they came as, and + * who signed it. No Android classes: CheatLoaderJvmTest counts a file. + */ +public final class MncfFacts { + public int cheats, checked, patterns, values, described, rawOnly; + public final List versions = new ArrayList<>(); + public String signer; // a key Peanuts trusts signed it: the name the trust list gives it; else null (an unsigned file is as any other) + + /** The facts of one file */ + public static MncfFacts of(MncfFile f) { MncfFacts x = new MncfFacts(); x.add(f); return x; } + + /** The facts of several files, added up (a pack) */ + public static MncfFacts of(List files) { MncfFacts x = new MncfFacts(); for (MncfFile f : files) x.add(f); return x; } + + void add(MncfFile f) { + for (Build b : f.builds().values()) { + String main = b.modules().get("main"), v = b.version() != null && !b.version().isEmpty() ? b.version() : b.key(); + if (v != null && !(main != null && main.equalsIgnoreCase(v)) && !versions.contains(v)) versions.add(v); // a build named by its ID has no version name + } + SignatureResult s = f.signature(); + if (signer == null && SignatureResult.VERIFIED.equals(s.result()) && !s.signers().isEmpty()) signer = s.signers().get(0); + for (io.github.davdxpx.mistel.mncf.Cheat c : f.cheats()) { + if (c.isMaster()) continue; + cheats++; + Map t = c.table(); + boolean code = t.get("patch") instanceof List || t.get("override") instanceof List, core = code || t.get("write") instanceof List || t.get("read") instanceof List; + if (code) checked++; + if (finds(t)) patterns++; + values += c.values().size(); + if (c.about() != null && !c.about().trim().isEmpty()) described++; + if (!core && t.get("raw") instanceof List) rawOnly++; + } + } + + /** Whether any place of the cheat is found by a pattern */ + @SuppressWarnings("unchecked") + static boolean finds(Map cheat) { + for (String kind : new String[] {"patch", "write", "override", "read", "when"}) { + Object ops = cheat.get(kind); + if (!(ops instanceof List)) continue; + for (Object o : (List) ops) { + if (!(o instanceof Map)) continue; + Object at = ((Map) o).get(kind.equals("override") ? "function" : "at"); + if (at instanceof Map && ((Map) at).get("find") != null) return true; + } + } + return false; + } + + /** "2.0.2", "1.0.0 and 2.0.2", "1.0.0, 1.1.0 and 2.0.2"; null when it names none */ + public String versionWords() { + if (versions.isEmpty()) return null; + if (versions.size() == 1) return versions.get(0); + return String.join(", ", versions.subList(0, versions.size() - 1)) + " and " + versions.get(versions.size() - 1); + } +} diff --git a/android/app/src/main/java/dev/peanuts/mods/MncfMain.java b/android/app/src/main/java/dev/peanuts/mods/MncfMain.java new file mode 100644 index 00000000..381e569a --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/mods/MncfMain.java @@ -0,0 +1,138 @@ +package dev.peanuts.mods; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import io.github.davdxpx.mistel.mncf.CodeModule; + +/** + * The game's own main module, as a pack holds it, for .mncf cheats (Mistel's spec, sections 6.3 and 7.4: patterns are searched in the original bytes and a + * patch's expect is compared with them). The pack has main as the rewriter left it (main.patched.bin: the image, then its patch area), the words it changed + * (main.changed.tsv: runs of offset and length in main's code) and what the game had there (main.orig.bin: those runs' original bytes, one after the other; + * dm/tools/patch_nso.py, dev.peanuts.pack.OrigFill). Put together they are the game's own image. A pack without main.orig.bin gives the rewritten image with the + * changed runs left out of every search and every expect (CodeModule's exclude), so nothing is read from a place the rewriter changed. The layout comes from + * main.fixups.tsv's header (TEXT_END, RO_OFF, DATA_OFF, PATCH_OFF, FILE_IMAGE_LEN, KEY_PAGE_OFF, BUILD_ID). No Android classes: CheatLoaderJvmTest runs it. + */ +public final class MncfMain { + private MncfMain() {} + + /** The largest image read (the arrays a JVM gives): a main larger than this has no patterns here */ + static final long MAX_IMAGE = Integer.MAX_VALUE - 64; + + /** main.fixups.tsv's header: "# NAME \t 0x..." lines, the names upper case */ + static Map header(File fixups) throws IOException { + Map out = new LinkedHashMap<>(); + for (String line : new String(Files.readAllBytes(fixups.toPath()), StandardCharsets.UTF_8).split("\n")) { + if (!line.startsWith("#")) continue; // the table's rows after the header + String[] w = line.substring(1).trim().split("\\s+"); + if (w.length >= 2) out.put(w[0].toUpperCase(Locale.ROOT), w[1].trim()); + } + return out; + } + + static long num(Map h, String key, long none) { + String v = h.get(key); + if (v == null) return none; + try { + boolean neg = v.startsWith("-"); + String t = neg ? v.substring(1) : v; + long n = t.startsWith("0x") || t.startsWith("0X") ? Long.parseUnsignedLong(t.substring(2), 16) : Long.parseLong(t); + return neg ? -n : n; + } catch (NumberFormatException e) { + return none; + } + } + + /** The build ID the pack's main was rewritten from (fixups' BUILD_ID, else changed.tsv's), upper case; null when neither names it */ + public static String buildId(File pack) { + try { + File f = new File(pack, "main.fixups.tsv"); + if (f.isFile()) { String b = header(f).get("BUILD_ID"); if (b != null && !b.isEmpty()) return b.toUpperCase(Locale.ROOT); } + File c = new File(pack, "main.changed.tsv"); + if (c.isFile()) { String b = header(c).get("BUILD_ID"); if (b != null && !b.isEmpty()) return b.toUpperCase(Locale.ROOT); } + } catch (IOException ignored) { } + return null; + } + + /** The runs main.changed.tsv lists (the words the rewriter changed), empty when the pack has none */ + public static List changed(File pack) throws IOException { + List out = new ArrayList<>(); + File f = new File(pack, "main.changed.tsv"); + if (!f.isFile()) return out; + for (String line : new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8).split("\n")) { + String t = line.endsWith("\r") ? line.substring(0, line.length() - 1) : line; + if (t.trim().isEmpty() || t.startsWith("#")) continue; + String[] c = t.split("\t"); + if (c.length < 2) throw new IOException("main.changed.tsv: a line that is not an offset and a length"); + try { + out.add(new CodeModule.Run(hex(c[0]), hex(c[1]))); + } catch (NumberFormatException e) { + throw new IOException("main.changed.tsv: a line that is not an offset and a length"); + } + } + return out; + } + + private static long hex(String s) { + String t = s.trim(); + if (t.startsWith("0x") || t.startsWith("0X")) t = t.substring(2); + return Long.parseUnsignedLong(t, 16); + } + + /** Whether the pack has a main image to read */ + public static boolean has(File pack) { + return pack != null && new File(pack, "main.patched.bin").isFile() && new File(pack, "main.fixups.tsv").isFile(); + } + + /** + * The game's own main of a pack: null when the pack has no image (not built yet, or another kind of pack). IOException when its files do not fit together + * (orig.bin shorter than the runs, a layout past the file's end) + */ + public static CodeModule of(File pack) throws IOException { + if (!has(pack)) return null; + Map h = header(new File(pack, "main.fixups.tsv")); + long text = num(h, "TEXT_END", -1), ro = num(h, "RO_OFF", -1), data = num(h, "DATA_OFF", -1), patch = num(h, "PATCH_OFF", 0), fileImage = num(h, "FILE_IMAGE_LEN", -1); + long key = num(h, "KEY_PAGE_OFF", -1); + if (text <= 0 || ro < text || data < ro) throw new IOException("main.fixups.tsv has no layout (TEXT_END, RO_OFF, DATA_OFF)"); + File bin = new File(pack, "main.patched.bin"); + long end = patch > 0 ? patch : fileImage; // the image's part of the file: up to the patch area after it, or FILE_IMAGE_LEN when the patch area lies before the base + if (end <= 0) end = bin.length(); + if (key > data && key < end) end = key; // the key page the loader puts after the data: not the game's + end = Math.min(end, bin.length()); + if (end <= data) throw new IOException("main.patched.bin ends before main's data"); + if (end > MAX_IMAGE) throw new IOException("main is larger than the app reads (" + end + " bytes)"); + byte[] image = new byte[(int) end]; + try (RandomAccessFile f = new RandomAccessFile(bin, "r")) { f.readFully(image); } + List runs = changed(pack), exclude = null; + File orig = new File(pack, "main.orig.bin"); + if (!runs.isEmpty()) { + if (orig.isFile()) { + long total = 0; + for (CodeModule.Run r : runs) total += r.length(); + if (orig.length() < total) throw new IOException("main.orig.bin is shorter than the runs main.changed.tsv lists"); + try (RandomAccessFile f = new RandomAccessFile(orig, "r")) { + for (CodeModule.Run r : runs) { + if (r.offset() < 0 || r.offset() + r.length() > end) throw new IOException("main.changed.tsv names a run past main's image"); + f.readFully(image, (int) r.offset(), (int) r.length()); + } + } + } else { + exclude = runs; // the rewritten words stay out of every search and expect + } + } + Map sections = new LinkedHashMap<>(); + sections.put("code", new long[] {0, Math.min((text + 0xFFF) & ~0xFFFL, ro)}); + sections.put("rodata", new long[] {ro, data}); + sections.put("data", new long[] {data, end}); + String id = h.get("BUILD_ID"); + return new CodeModule(image, sections, id == null || id.isEmpty() ? null : id.toUpperCase(Locale.ROOT), text, exclude); + } +} diff --git a/android/app/src/main/java/dev/peanuts/mods/MncfWords.java b/android/app/src/main/java/dev/peanuts/mods/MncfWords.java new file mode 100644 index 00000000..dda72608 --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/mods/MncfWords.java @@ -0,0 +1,75 @@ +package dev.peanuts.mods; + +import java.util.Locale; + +/** + * The reasons of Mistel's spec (Appendix B, and Peanuts' own runtime: reasons) in the player's words, for the page and the in-game tab: what stops the cheat + * here, in a sentence, without the format's terms (UI-RULES.md 5). The reason itself goes to the log. No Android classes: CheatLoaderJvmTest reads them. + */ +public final class MncfWords { + private MncfWords() {} + + /** Why a cheat cannot run here; c gives the names of the cheats a relation names (null: their ids are not looked up) */ + public static String reason(String reason, MncfBuild.Cheat c) { + String r = reason == null ? "" : reason, token = r.contains(":") ? r.substring(0, r.indexOf(':')) : r, detail = r.contains(":") ? r.substring(r.indexOf(':') + 1) : ""; + switch (token) { + case "pattern-not-found": return "Its place was not found in this version of the game."; + case "pattern-ambiguous": return "Its place was found more than once in this version of the game, so it is not clear which one it is."; + case "expect-mismatch": return "The game's code at its place is not what the cheat was made for: it is for another version."; + case "build-unknown": return "It was made for other versions of the game, not this one."; + case "outside": return "Its place lies outside the game."; + case "module-unknown": return "It changes a part of the game this version does not have."; + case "region-unknown": return "It writes a part of the game's memory Peanuts does not know."; + case "game-mismatch": return "It is for another game."; + case "signature": return "Its file was changed after it was signed, so none of its cheats run."; + case "value-out-of-range": return "Its number does not fit the place it is written to."; + case "requires": return "It needs another cheat of the file that cannot run here" + named(detail) + "."; + case "excludes": return "It can never be on together with a cheat it needs" + named(detail) + "."; + case "unknown-key": return "Its file has a part Peanuts does not know in this cheat (" + detail + ")."; + case "invalid": return detail.isEmpty() ? "It does nothing: it has no change to make." : "Its file has a mistake in this cheat (" + detail + ")."; + case "extension-missing": return "It uses a newer part of the cheat format (" + detail + ") that Peanuts does not read yet."; + case "capability-missing": + if (detail.equals("display")) return "It shows values from the game, which Peanuts cannot do yet."; + if (detail.equals("code-hook")) return "It changes a function in a way Peanuts cannot do yet."; + return "It needs something Peanuts cannot do yet (" + detail + ")."; + case "runtime": return runtime(detail); + default: return "It cannot run here (" + r + ")."; + } + } + + private static String named(String id) { return id.isEmpty() ? "" : " (" + id + ")"; } + + /** The runtime's reasons: runtime:unsupported:<part> and runtime:rewritten (section 11.1, 11.3), and Peanuts' own (MncfBuild.runtimeReason) */ + static String runtime(String why) { + String w = why.toLowerCase(Locale.ROOT); + if (w.startsWith("unsupported:")) return unsupported(w.substring("unsupported:".length())); + switch (w) { + case "rewritten": return "Peanuts rewrote this place of the game's code while building it, so this cheat cannot change it."; + case "no-main": return "Its place is found once the game is built."; + case "module": return "It changes a part of the game other than its main code, which Peanuts cannot do yet."; + case "region": return "It writes a part of the game's memory Peanuts cannot reach yet."; + case "address": return "It writes a fixed address, which the Switch does not have."; + case "too-long": return "Its code is longer than Peanuts can run yet."; + default: return "Peanuts cannot run it yet."; + } + } + + /** A part of the core Peanuts' cheat engine does not have yet (Mncf.FEATURES' keys) */ + static String unsupported(String part) { + switch (part) { + case "run.once": return "It runs once when you turn it on, which Peanuts cannot do yet."; + case "run.action": return "It runs each time you press its buttons, in a way Peanuts cannot do yet."; + case "run.timed": return "It runs for a set time, which Peanuts cannot do yet."; + case "run.monitor": return "It shows values from the game, which Peanuts cannot do yet."; + case "hold": return "It runs while you hold its buttons, in a way Peanuts cannot do yet."; + case "toggle": return "It is switched with a button combination, which Peanuts cannot do yet."; + case "press": return "It runs when you press its buttons, in a way Peanuts cannot do yet."; + case "when": return "It waits for the game to be in a certain state, in a way Peanuts cannot do yet."; + case "when.many": case "match.any": return "It waits for several things in the game at once, which Peanuts cannot do yet."; + case "trigger.enter": return "It runs at the moment the game gets to a certain state, which Peanuts cannot do yet."; + case "interval": return "It checks the game only now and then, which Peanuts cannot do yet."; + case "override": return "It changes a function in a way Peanuts cannot do yet."; + default: return "It uses a part of the cheat format Peanuts cannot run yet."; + } + } +} diff --git a/android/app/src/main/java/dev/peanuts/mods/ModsTab.java b/android/app/src/main/java/dev/peanuts/mods/ModsTab.java index 4850b8e2..b5944069 100644 --- a/android/app/src/main/java/dev/peanuts/mods/ModsTab.java +++ b/android/app/src/main/java/dev/peanuts/mods/ModsTab.java @@ -59,6 +59,8 @@ public interface Host { void close(); /** The panel's look over views added after the tab was built */ void style(View v); + /** A tab's own action in the menu's header, beside its name, with the controller's button for it (the quick menu's rail: InGamePanel) */ + default void action(String key, String label, Runnable run) {} } private static final int YELLOW = 0xFFFFD54F, ROW = 0xFF2D2E31, CHIP = 0xFF3A3B3E, TEXT = 0xFFE8EAED, QUIET = 0xFFB0B3B8, BAD_TEXT = 0xFFFF9670, BAD = 0xFF3D2016; @@ -99,18 +101,25 @@ static final class Shown { File folder; // the game's cheats folder (the merged file, values.tsv) String build; // the merged file's build: /.txt Map kept = new java.util.HashMap<>(); + CheatSources.Merged merged; // the merge the tab lists (an .mncf cheat's relations) long lastStep; // a held left / right: the steps grow (1, 10, 100, ...) int run; } // ---- Whether there is a tab, and which tab shows last ---- + /** What a tab of the quick menu shows (dev.nxnative.android.ModsPanel): both halves (one Mods tab, as before the quick menu), the cheats, the mods */ + public static final int BOTH = 0, CHEATS = 1, MODS = 2; + /** Whether the panel has a Mods tab for this game: Settings › Controls › Mods tab on, the game's Show in the game on, and cheats or mods to show */ - public static boolean wanted(Context c, String titleId, String gameDir, String packDir) { + public static boolean wanted(Context c, String titleId, String gameDir, String packDir) { return wanted(c, titleId, gameDir, packDir, BOTH); } + + /** The same for one half (CHEATS: cheats to show, MODS: mods to show) */ + public static boolean wanted(Context c, String titleId, String gameDir, String packDir, int part) { if (!PeanutsPrefs.modsTabAll(c) || !PeanutsPrefs.modsTab(c, titleId)) return false; try { - if (!model(c, titleId, gameDir, packDir).isEmpty()) return true; - return !mods(c, titleId, gameDir, packDir).isEmpty(); + if (part != MODS && !model(c, titleId, gameDir, packDir).isEmpty()) return true; + return part != CHEATS && !mods(c, titleId, gameDir, packDir).isEmpty(); } catch (RuntimeException e) { android.util.Log.w("peanuts", "mods tab: " + e); return false; @@ -136,12 +145,16 @@ static final class Group { Group(String heading) { this.heading = heading; } } - static List model(Context c, String titleId, String gameDir, String packDir) { + static List model(Context c, String titleId, String gameDir, String packDir) { return model(c, titleId, gameDir, packDir, null); } + + /** The same; merged[0] gets the merge (null: not wanted) */ + static List model(Context c, String titleId, String gameDir, String packDir, CheatSources.Merged[] merged) { List out = new ArrayList<>(); Set builds = CheatsBridge.builds(titleId, packDir); if (builds.isEmpty()) return out; String build = builds.iterator().next(); CheatSources.Merged m = CheatsBridge.merged(c, titleId, gameDir, packDir, build, CheatsBridge.textEnd(packDir)); + if (merged != null) merged[0] = m; List blocks = new ArrayList<>(); for (CheatSources.Row r : m.rows) if (r.block.enabled && !blocks.contains(r.block)) blocks.add(r.block); Map byHeading = new LinkedHashMap<>(); @@ -173,7 +186,10 @@ private static File modsRoot(Context c, String titleId, String gameDir, String p // ---- The tab ---- /** Builds the tab into the panel's box (ModsPanel.build) */ - public static void fill(Activity a, LinearLayout box, Host host) { + public static void fill(Activity a, LinearLayout box, Host host) { fill(a, box, host, BOTH); } + + /** The same for one half: the quick menu's Cheats tab (the search, All off and the cheats) or its Mods tab (the mods and Restart) */ + public static void fill(Activity a, LinearLayout box, Host host, int part) { left(); Shown s = new Shown(); s.a = a; s.host = host; s.box = box; @@ -182,12 +198,16 @@ public static void fill(Activity a, LinearLayout box, Host host) { List groups; List mods; try { - groups = model(a, s.titleId, gameDir, packDir); + CheatSources.Merged[] m = new CheatSources.Merged[1]; + groups = model(a, s.titleId, gameDir, packDir, m); + s.merged = m[0]; mods = mods(a, s.titleId, gameDir, packDir); } catch (RuntimeException e) { android.util.Log.w("peanuts", "mods tab: " + e); groups = new ArrayList<>(); mods = new ArrayList<>(); } + if (part == MODS) groups = new ArrayList<>(); + if (part == CHEATS) mods = new ArrayList<>(); Set on = CheatsBridge.on(a, s.titleId); s.folder = CheatsBridge.folder(a, s.titleId); Set builds = CheatsBridge.builds(s.titleId, packDir); @@ -196,7 +216,7 @@ public static void fill(Activity a, LinearLayout box, Host host) { int cheats = 0; for (Group g : groups) cheats += g.binds.size(); - // The top: search (from 15 cheats on) and All off + // The top: search (from 15 cheats on); All off is in the header, beside the tab's name (X) LinearLayout top = new LinearLayout(a); top.setOrientation(LinearLayout.HORIZONTAL); top.setGravity(Gravity.CENTER_VERTICAL); @@ -226,15 +246,9 @@ public static void fill(Activity a, LinearLayout box, Host host) { }); search.setOnFocusChangeListener(toFirstRow); top.addView(search, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); - } else top.addView(new View(a), new LinearLayout.LayoutParams(0, 1, 1)); - if (cheats > 0) { - Button all = new Button(a); - all.setText("All off"); - all.setOnClickListener(v -> allOff(s)); - all.setOnFocusChangeListener(toFirstRow); - top.addView(all); } - box.addView(top); + if (part != MODS && cheats > 0) host.action("X", "All off", () -> allOff(s)); + if (part != MODS && search != null) box.addView(top); // The cheats, by group s.list = new LinearLayout(a); @@ -248,12 +262,13 @@ public static void fill(Activity a, LinearLayout box, Host host) { s.binds.add(b); } } - if (cheats == 0) box.addView(note(a, "No cheats for this game: add them on the game's page, Mods & Cheats.")); + if (part == MODS) { /* the cheats are the Cheats tab's */ } + else if (cheats == 0) box.addView(note(a, "No cheats for this game: add them on the game's page, Mods & Cheats.")); else box.addView(note(a, "A switch acts at once and is kept for the next start. Cheated values are stored when the game saves.")); // The mods if (!mods.isEmpty()) { - box.addView(head(a, "Mods")); + if (part != MODS) box.addView(head(a, "Mods")); // the Mods tab has its name in the header for (ModStore.Mod m : mods) { View r = modRow(s, m, gameDir, packDir); if (s.firstMod == null) s.firstMod = r; @@ -262,7 +277,7 @@ public static void fill(Activity a, LinearLayout box, Host host) { } s.restart = restartBar(s); s.restart.setVisibility(modsChanged ? View.VISIBLE : View.GONE); - box.addView(s.restart); + if (part != CHEATS) box.addView(s.restart); box.addView(keys(a, cheats > 0)); if (search != null) { @@ -336,7 +351,7 @@ private static View row(Shown s, Bind b, boolean on) { b.sw.setOnCheckedChangeListener((v, x) -> { if (!s.updating) switched(s, b, x); }); r.setOnClickListener(v -> { if (b.sw.isEnabled()) b.sw.toggle(); else details(s, b); }); r.setOnLongClickListener(v -> { details(s, b); return true; }); - r.setOnFocusChangeListener((v, has) -> { b.desc.setText(line(b)); b.desc.setVisibility(has ? View.VISIBLE : View.GONE); }); + r.setOnFocusChangeListener((v, has) -> { b.desc.setText(line(b)); b.desc.setVisibility(has ? View.VISIBLE : View.GONE); if (has) inView(v); }); show(b); return r; } @@ -349,6 +364,7 @@ private static void switched(Shown s, Bind b, boolean on) { CheatsBridge.on(s.a, s.titleId, b.key, on); b.state = on ? "on" : "off"; b.reason = ""; + related(s, b, on); } else { s.updating = true; b.sw.setChecked(!on); @@ -440,7 +456,7 @@ static String line(Bind b) { if (b.field == null) return CheatStatus.line(b.cheat, bad(b), b.inHost, b.reason); String l = CheatStatus.line(b.cheat, bad(b), b.inHost, b.reason, b.number); if (bad(b)) return l; - if (changed(b)) l += " The file's own number is " + b.cheat.value() + "."; + if (changed(b)) l += " The file's own number is " + b.cheat.number.own() + "."; return b.later ? l + " The new number is in the game from the next start." : l; } @@ -489,7 +505,7 @@ private static View valueBar(Shown s, Bind b) { b.field.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); b.field.setGravity(Gravity.CENTER); b.field.setMaxLines(1); // not setSingleLine: its horizontal scrolling moves the foreground (the focus frame) out of sight - b.field.setMinWidth(Math.round(112 * dp)); + b.field.setMinWidth(Math.round(72 * dp)); b.field.setMinHeight(Math.round(36 * dp)); b.field.setPadding(Math.round(14 * dp), 0, Math.round(14 * dp), 0); GradientDrawable fb = new GradientDrawable(); @@ -510,27 +526,38 @@ private static View valueBar(Shown s, Bind b) { b.field.setOnFocusChangeListener((v, has) -> { b.desc.setText(has ? FIELD_LINE : line(b)); b.desc.setVisibility(has || b.row.isFocused() ? View.VISIBLE : View.GONE); + if (has) inView(v); }); b.apply = () -> applyNumber(s, b); shownNumber(b); bar.addView(stepper(c, "−", v -> step(s, b, -1))); - LinearLayout.LayoutParams fl = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + // The number takes the room between − and + (in a narrow menu it gets narrower, so + is never cut off); the file's own number goes under them + LinearLayout.LayoutParams fl = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1); fl.leftMargin = fl.rightMargin = Math.round(8 * dp); bar.addView(b.field, fl); bar.addView(stepper(c, "+", v -> step(s, b, 1))); + LinearLayout box = new LinearLayout(c); + box.setOrientation(LinearLayout.VERTICAL); + box.addView(bar); b.mark = new TextView(c); // the marker of a set number: the file's own beside it (Reset in the details brings it back) b.mark.setTextSize(11); b.mark.setTextColor(QUIET); b.mark.setMaxLines(1); b.mark.setEllipsize(TextUtils.TruncateAt.END); - b.mark.setPadding(Math.round(10 * dp), 0, 0, 0); - bar.addView(b.mark, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); + b.mark.setGravity(Gravity.CENTER_HORIZONTAL); + b.mark.setPadding(0, Math.round(2 * dp), 0, 0); + box.addView(b.mark, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); shownNumber(b); - return bar; + return box; + } + + /** The focused row or number whole on the screen once its line under the name has opened (the scroll to the focus ran before, on the shorter row) */ + private static void inView(View v) { + v.post(() -> v.requestRectangleOnScreen(new android.graphics.Rect(0, 0, v.getWidth(), v.getHeight()), false)); } /** Whether the number differs from the file's own (the player set it in the tab) */ - private static boolean changed(Bind b) { return b.field != null && b.number != b.cheat.value(); } + private static boolean changed(Bind b) { return b.field != null && b.number != b.cheat.number.own(); } /** A round − or + for touch (not focusable: the controller's left and right step the field) */ private static TextView stepper(Context c, String sign, View.OnClickListener click) { @@ -556,11 +583,12 @@ private static TextView stepper(Context c, String sign, View.OnClickListener cli /** The number, in yellow with the file's own beside it when it was set in the tab */ private static void shownNumber(Bind b) { boolean set = changed(b); - b.field.setText(Long.toString(b.number)); + String unit = b.cheat.number.unit(); + b.field.setText(unit == null || unit.isEmpty() ? Long.toString(b.number) : b.number + " " + unit); b.field.setTextColor(set ? YELLOW : TEXT); - b.field.setContentDescription(b.cheat.name + ", number " + b.number + (set ? ", the file has " + b.cheat.value() : "")); + b.field.setContentDescription(b.cheat.name + ", number " + b.number + (set ? ", the file has " + b.cheat.number.own() : "")); if (b.mark == null) return; - b.mark.setText("File: " + b.cheat.value()); + b.mark.setText("File: " + b.cheat.number.own()); b.mark.setVisibility(set ? View.VISIBLE : View.GONE); } @@ -571,14 +599,14 @@ private static void step(Shown s, Bind b, int dir) { s.lastStep = now; long size = 1; for (int i = 0; i < Math.min(s.run / 10, 9); i++) size *= 10; - long max = CheatValues.max(b.cheat.valueWidth); - long v = dir > 0 ? (b.number > max - size ? max : b.number + size) : Math.max(0, b.number - size); + long max = b.cheat.number.max(), min = b.cheat.number.min(); + long v = dir > 0 ? (b.number > max - size ? max : b.number + size) : (b.number < min + size ? min : b.number - size); setNumber(s, b, v, false); } /** The number shown at once; to the files and the host a moment after the last change (now: at once) */ private static void setNumber(Shown s, Bind b, long v, boolean now) { - b.number = Math.max(0, Math.min(v, CheatValues.max(b.cheat.valueWidth))); + b.number = Math.max(b.cheat.number.min(), Math.min(v, b.cheat.number.max())); shownNumber(b); s.box.removeCallbacks(b.apply); s.box.postDelayed(b.apply, now ? 0 : 500); @@ -617,20 +645,41 @@ private static void applyNumber(Shown s, Bind b) { }); } + /** + * An .mncf cheat switched on: what it needs on, what it cannot be on with off (CheatSources.Merged.related), in the host at once and kept for the next + * start, and their rows' switches with them + */ + private static void related(Shown s, Bind b, boolean on) { + if (s.merged == null || b.cheat.mncf == null) return; + Set all = CheatsBridge.on(s.a, s.titleId); + Set changed = s.merged.related(all, b.key, on); + if (changed.isEmpty()) return; + CheatsBridge.on(s.a, s.titleId, all); + for (Bind o : s.binds) { + if (o.key == null || !changed.contains(o.key)) continue; + boolean x = all.contains(o.key); + if (o.inHost) CheatsBridge.set(o.key, x); + s.updating = true; + o.sw.setChecked(x); + s.updating = false; + show(o); + } + } + /** A or a tap on the number: type one, in the app's dialog sheet */ private static void type(Shown s, Bind b) { AlertDialog.Builder db = dialog(s.a); Context c = db.getContext(); float dp = c.getResources().getDisplayMetrics().density; - long max = CheatValues.max(b.cheat.valueWidth); + long max = b.cheat.number.max(), min = b.cheat.number.min(); android.widget.FrameLayout box = new android.widget.FrameLayout(c); // as upstream's text dialog (TextInput): the field in the sheet's margins box.setPadding(Math.round(20 * dp), 0, Math.round(20 * dp), 0); EditText e = new EditText(c); - e.setHint("0 to " + max); // no message line: in landscape the keyboard leaves room for the title, the field and the buttons only - e.setInputType(InputType.TYPE_CLASS_NUMBER); + e.setHint(min + " to " + max); // no message line: in landscape the keyboard leaves room for the title, the field and the buttons only + e.setInputType(InputType.TYPE_CLASS_NUMBER | (min < 0 ? InputType.TYPE_NUMBER_FLAG_SIGNED : 0)); e.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_FLAG_NO_FULLSCREEN); e.setSingleLine(true); - e.setFilters(new android.text.InputFilter[] {new android.text.InputFilter.LengthFilter(Long.toString(max).length())}); + e.setFilters(new android.text.InputFilter[] {new android.text.InputFilter.LengthFilter(Math.max(Long.toString(max).length(), Long.toString(min).length()))}); e.setText(Long.toString(b.number)); e.setSelection(0, e.getText().length()); // typing replaces it box.addView(e); @@ -656,12 +705,14 @@ private static void type(Shown s, Bind b) { e.requestFocus(); } - /** The typed number, kept inside the cheat's width (a number too long for it is its largest) */ + /** The typed number, kept inside the cheat's range (a number too long for it is its largest, or its smallest) */ private static void typed(Shown s, Bind b, String text) { String t = text.trim(); - if (t.isEmpty() || !t.chars().allMatch(Character::isDigit)) return; + boolean neg = t.startsWith("-"); + String digits = neg ? t.substring(1) : t; + if (digits.isEmpty() || !digits.chars().allMatch(Character::isDigit)) return; long v; - try { v = Long.parseLong(t); } catch (NumberFormatException e) { v = Long.MAX_VALUE; } + try { v = Long.parseLong(t); } catch (NumberFormatException e) { v = neg ? Long.MIN_VALUE : Long.MAX_VALUE; } setNumber(s, b, v, true); } @@ -700,7 +751,7 @@ static void details(Shown s, Bind b) { sv.setFocusable(false); // as AlertDialog's own message: the controller's focus goes to the buttons sv.addView(box); db.setTitle(b.cheat.name).setView(sv).setNegativeButton("Close", null); - if (changed(b)) db.setNeutralButton("Reset", (x, w) -> setNumber(s, b, b.cheat.value(), true)); // the file's own number again (its kept one is forgotten) + if (changed(b)) db.setNeutralButton("Reset", (x, w) -> setNumber(s, b, b.cheat.number.own(), true)); // the file's own number again (its kept one is forgotten) AlertDialog d = db.create(); d.setOnKeyListener((di, k, e) -> { // B closes; A presses the focused button (Close first), or closes when none has the focus if (k != confirmKey && k != backKey) return false; diff --git a/android/app/src/main/java/dev/peanuts/ui/GameScreen.java b/android/app/src/main/java/dev/peanuts/ui/GameScreen.java index 8fb1468d..7e738055 100644 --- a/android/app/src/main/java/dev/peanuts/ui/GameScreen.java +++ b/android/app/src/main/java/dev/peanuts/ui/GameScreen.java @@ -35,6 +35,7 @@ public final class GameScreen extends Presentation { private BananaBackgroundView bg; private StartView start; private StatsView stats; + private android.view.View grip; // the in-game menu's grip on the Now playing page (the stats page has its own) private GameScreen(Activity game, Display d) { super(game, d, R.style.Theme_Banana); } @@ -112,6 +113,11 @@ private static void loadIcon(Activity game, String titleId) { stats = new StatsView(getContext()); stats.setVisibility(android.view.View.GONE); root.addView(stats, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + if (dev.peanuts.ingame.BottomMenu.on(getContext())) { // a swipe up from the bottom edge opens the in-game menu here; the grip shows where (the stats page has its own) + grip = dev.peanuts.ingame.BottomMenu.grip(getContext()); + root.addView(grip); + root.addView(dev.peanuts.ingame.BottomMenu.edge(getContext())); + } setContentView(root); } @@ -130,6 +136,7 @@ private void apply() { stats.setRunning(live); start.bind(name, icon); start.status(loading ? "Starting the companion" : "Now playing"); + if (grip != null) grip.setVisibility(!loading && !live ? android.view.View.VISIBLE : android.view.View.GONE); start.quiet(!loading); start.setAnimating(loading); bg.setRunning(loading); diff --git a/android/app/src/main/java/dev/peanuts/ui/LayoutChoice.java b/android/app/src/main/java/dev/peanuts/ui/LayoutChoice.java new file mode 100644 index 00000000..6b986d22 --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/ui/LayoutChoice.java @@ -0,0 +1,155 @@ +package dev.peanuts.ui; + +import android.app.Activity; +import android.graphics.Typeface; +import android.graphics.drawable.StateListDrawable; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import dev.nxnative.android.R; +import dev.peanuts.PeanutsPrefs; + +/** + * How the in-game menus look, picked once by the player: after the update, and for a new player after the first start's setup, Home's list shows the + * layouts as pictures (drawable/pil_layout_*.xml, made by design/peanuts-native/layouts/layouts.py) until one is picked. Two menus (the game menu at the + * left, the quick menu at the right), One menu at the right, and on a device with a second screen One menu on the bottom screen, which the focus starts on + * there. Later keeps the two menus and asks again at the next start. The menu's own settings change it later (Layout, dev.nxnative.android.InGamePanel). + */ +public final class LayoutChoice { + private LayoutChoice() {} + + private static boolean asked; // once a run of the app + + private static final int[] LAYOUTS = {PeanutsPrefs.LAYOUT_TWO, PeanutsPrefs.LAYOUT_RIGHT, PeanutsPrefs.LAYOUT_BOTTOM}; + private static final String[] PICTURES = {"pil_layout_two", "pil_layout_right", "pil_layout_bottom"}; // Peanuts' res (src/peanuts/res): by name + private static final String[] NAMES = {"Two menus", "One menu at the right", "One menu on the bottom screen"}; + private static final String[] LINES = { + "The game menu at the left, the settings at the right.", + "Everything in one place over the game.", + "The game in full view on top, the menu below."}; + + /** Home's list: the question while no layout is picked; then runs once it closes, or at once when it does not show */ + public static void offer(Activity a, Runnable then) { + if (asked || a.isFinishing() || !PeanutsPrefs.setupDone(a) || PeanutsPrefs.menuLayoutPicked(a)) { if (then != null) then.run(); return; } + asked = true; + boolean second = dev.peanuts.Companion.hasSecondDisplay(a); + int count = second ? 3 : 2; + float dp = a.getResources().getDisplayMetrics().density; + boolean wide = a.getResources().getDisplayMetrics().widthPixels > a.getResources().getDisplayMetrics().heightPixels; + + // A dialog of its own: Android's AlertDialog keeps its custom content to a part of a landscape screen, too short for the pictures and their lines + android.app.Dialog d = new android.app.Dialog(a); + d.requestWindowFeature(android.view.Window.FEATURE_NO_TITLE); + LinearLayout box = new LinearLayout(a); + box.setOrientation(LinearLayout.VERTICAL); + int pad = Math.round(22 * dp); + box.setPadding(pad, Math.round(20 * dp), pad, Math.round(10 * dp)); + box.setBackground(PUi.round(PUi.col(a, R.color.bn_card), 28 * dp, 0, 0)); + TextView title = PUi.text(a, "How should the in-game menus look?", 22, R.color.bn_text, 700); + box.addView(title); + TextView intro = PUi.text(a, "Pick how the menus look in a game. The menu's own settings change it later.", 14, R.color.bn_text_2, 400); + LinearLayout.LayoutParams ip = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ip.topMargin = Math.round(6 * dp); + box.addView(intro, ip); + LinearLayout cards = new LinearLayout(a); + cards.setOrientation(wide ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); + View[] made = new View[count]; + for (int i = 0; i < count; i++) { + int layout = LAYOUTS[i]; + View card = card(a, dp, i, second && layout == PeanutsPrefs.LAYOUT_BOTTOM); + card.setOnClickListener(v -> { + PeanutsPrefs.menuLayoutPick(a, layout); + d.dismiss(); + }); + LinearLayout.LayoutParams lp = wide ? new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f) + : new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + int gap = Math.round(6 * dp); + lp.setMargins(gap, Math.round(14 * dp), gap, 0); + cards.addView(card, lp); + made[i] = card; + } + ScrollView list = new ScrollView(a); // a short screen: the cards scroll between the title and Later + list.addView(cards); + box.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)); // the one to shrink + TextView later = PUi.text(a, "Later", 15, R.color.bn_accent, 700); + int lh = Math.round(16 * dp), lv = Math.round(10 * dp); + later.setPadding(lh, lv, lh, lv); + later.setBackground(PUi.ripple(a, PUi.round(android.graphics.Color.TRANSPARENT, 99 * dp, 0, 0))); + later.setFocusable(true); + later.setClickable(true); + later.setOnClickListener(v -> d.dismiss()); + LinearLayout.LayoutParams bp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + bp.gravity = android.view.Gravity.END; + bp.topMargin = Math.round(8 * dp); + box.addView(later, bp); + d.setContentView(box); + d.setOnDismissListener(x -> { if (then != null) then.run(); }); + if (d.getWindow() != null) { + d.getWindow().setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(android.graphics.Color.TRANSPARENT)); + int sw = a.getResources().getDisplayMetrics().widthPixels; + int w = wide ? Math.min(Math.round(sw * 0.92f), Math.round((count == 3 ? 900 : 640) * dp)) : Math.round(sw * 0.92f); + d.getWindow().setLayout(w, ViewGroup.LayoutParams.WRAP_CONTENT); + } + d.show(); + View first = made[second ? count - 1 : 0]; // two screens: the bottom screen's; else the first + boolean controller = padAttached(); // with a controller the frame shows at once where it starts + first.post(() -> { if (controller) first.requestFocusFromTouch(); else first.requestFocus(); }); + } + + private static boolean padAttached() { + for (int id : android.view.InputDevice.getDeviceIds()) { + android.view.InputDevice d = android.view.InputDevice.getDevice(id); + if (d != null && !d.isVirtual() && d.supportsSource(android.view.InputDevice.SOURCE_GAMEPAD)) return true; + } + return false; + } + + /** A layout's card: its picture, its name, what it does; the controller's focus as a frame in banana yellow, a touch's ripple */ + private static View card(Activity a, float dp, int i, boolean twoScreens) { + LinearLayout c = new LinearLayout(a); + c.setOrientation(LinearLayout.VERTICAL); + int p = Math.round(10 * dp); + c.setPadding(p, p, p, p); + float r = 18 * dp; + StateListDrawable frame = new StateListDrawable(); // over the card: the controller's focus as an outline, nothing else + frame.addState(new int[] {android.R.attr.state_focused}, PUi.round(android.graphics.Color.TRANSPARENT, r, PUi.col(a, R.color.bn_banana_deep), Math.round(3 * dp))); + frame.addState(new int[] {}, new android.graphics.drawable.ColorDrawable(android.graphics.Color.TRANSPARENT)); + c.setBackground(PUi.ripple(a, PUi.round(PUi.col(a, R.color.bn_tint), r, 0, 0))); + c.setForeground(frame); + c.setFocusable(true); + c.setClickable(true); + c.setDefaultFocusHighlightEnabled(false); + c.setContentDescription(NAMES[i]); + ImageView pic = new ImageView(a); + int id = a.getResources().getIdentifier(PICTURES[i], "drawable", a.getPackageName()); + if (id != 0) pic.setImageResource(id); + pic.setAdjustViewBounds(true); + pic.setMaxHeight(Math.round(108 * dp)); // the cards, their names and lines fit a handheld's screen under the title + pic.setScaleType(ImageView.ScaleType.FIT_CENTER); + android.widget.FrameLayout top = new android.widget.FrameLayout(a); // the picture, with the two screens' badge in its corner + top.addView(pic, new android.widget.FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + if (twoScreens) { + TextView tag = PUi.text(a, "For two screens", 12, R.color.bn_on_banana, 600); + int h = Math.round(8 * dp), v = Math.round(3 * dp); + tag.setPadding(h, v, h, v); + tag.setBackground(PUi.round(PUi.col(a, R.color.bn_banana), 99 * dp, 0, 0)); + top.addView(tag, new android.widget.FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, + android.view.Gravity.TOP | android.view.Gravity.START)); + } + c.addView(top, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + TextView name = PUi.text(a, NAMES[i], 15, R.color.bn_text, 700); + name.setTypeface(Typeface.create("sans-serif-medium", Typeface.BOLD)); + LinearLayout.LayoutParams np = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + np.topMargin = Math.round(8 * dp); + c.addView(name, np); + TextView line = PUi.text(a, LINES[i], 12.5f, R.color.bn_text_2, 400); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + lp.topMargin = Math.round(2 * dp); + c.addView(line, lp); + return c; + } +} diff --git a/android/app/src/main/java/dev/peanuts/ui/Library.java b/android/app/src/main/java/dev/peanuts/ui/Library.java index 52dbea4b..f35cd488 100644 --- a/android/app/src/main/java/dev/peanuts/ui/Library.java +++ b/android/app/src/main/java/dev/peanuts/ui/Library.java @@ -329,6 +329,7 @@ private static void plainText(View v) { */ @SuppressWarnings("unchecked") public static void fill(Activity a, LinearLayout box, List games, View ondeviceCard, Predicate shows, Function card, Consumer manage, Runnable refresh) { + box.post(() -> LayoutChoice.offer(a, null)); // how the in-game menus look, asked at the app's start until it is picked if (current == null || current.a != a) current = new Library(a); Library l = current; l.box = box; l.games = new ArrayList<>(games); l.ondeviceCard = ondeviceCard; gen++; diff --git a/android/app/src/main/java/dev/peanuts/ui/MenuFeel.java b/android/app/src/main/java/dev/peanuts/ui/MenuFeel.java new file mode 100644 index 00000000..342235f1 --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/ui/MenuFeel.java @@ -0,0 +1,122 @@ +package dev.peanuts.ui; + +import android.content.Context; +import android.media.AudioAttributes; +import android.media.AudioFormat; +import android.media.AudioTrack; +import android.os.SystemClock; +import android.view.View; + +/** + * How the in-game menus feel (dev.peanuts.ingame: the game menu, the quick menu, the bottom screen's menu), as a console's menus do: a fine tick of the + * motor for each step of the focus and a firmer one for a choice ({@link Haptics}, the launcher's words, its gaps and its respect for the system's touch + * feedback, battery saver and heat), and, when the player turns them on, soft menu sounds made here (a few milliseconds of a sine, no files). Two settings + * in the menu's own settings: Vibrate on each step (on) and Menu sounds (off), kept in the game's prefs file (its process writes it). Main thread only. + */ +public final class MenuFeel { + private MenuFeel() {} + + private static boolean ready, haptics = true, sounds; + private static long lastMove, lastOther; // a step's tick waits for neither a held direction nor the firmer word of the same press + + private static android.content.SharedPreferences prefs(Context c) { return c.getSharedPreferences("peanuts_panel", Context.MODE_PRIVATE); } + + public static boolean haptics(Context c) { return prefs(c).getBoolean("menu_haptics", true); } + public static boolean sounds(Context c) { return prefs(c).getBoolean("menu_sounds", false); } + public static void haptics(Context c, boolean on) { prefs(c).edit().putBoolean("menu_haptics", on).apply(); haptics = on; } + public static void sounds(Context c, boolean on) { prefs(c).edit().putBoolean("menu_sounds", on).apply(); sounds = on; if (on) Tone.warm(); } + + /** A menu opens: the settings read again (the app's haptics row, the system's touch feedback, battery saver, heat) */ + public static void refresh(Context c) { + Haptics.refresh(c); + haptics = haptics(c); + sounds = sounds(c); + ready = true; + if (sounds) Tone.warm(); + } + + private static void ready(View v) { if (!ready && v != null) refresh(v.getContext()); } + + /** The focus moved one step */ + public static void move(View v) { + ready(v); + long now = SystemClock.uptimeMillis(); + boolean held = now - lastMove < 90; // a held direction: no buzz and no rattle at the key repeat rate + lastMove = now; + if (held || now - lastOther < 150) return; // the focus a tab, an opening or a press put somewhere: that press has its word already + if (haptics) Haptics.play(v, Haptics.Word.TICK); + if (sounds) Tone.MOVE.play(); + } + + /** The focus cannot go further that way */ + public static void edge(View v) { ready(v); if (haptics) Haptics.play(v, Haptics.Word.EDGE); } + + /** A row pressed, a choice or a switch taken */ + public static void select(View v) { ready(v); lastOther = SystemClock.uptimeMillis(); if (haptics) Haptics.play(v, Haptics.Word.CLICK); if (sounds) Tone.SELECT.play(); } + + /** Another tab (the rail, L and R) */ + public static void tab(View v) { ready(v); lastOther = SystemClock.uptimeMillis(); if (haptics) Haptics.play(v, Haptics.Word.TICK); if (sounds) Tone.TAB.play(); } + + /** A menu opens */ + public static void open(View v) { if (v != null) refresh(v.getContext()); lastOther = SystemClock.uptimeMillis(); if (sounds) Tone.OPEN.play(); } + + /** A menu closes, or B goes one step back */ + public static void back(View v) { ready(v); if (sounds) Tone.BACK.play(); } + + /** + * The menu sounds: each a few milliseconds of a sine at a soft level with a quick fade, made once into its own static AudioTrack (a sonification, so it + * follows the system's own sound settings for those). Nothing is loaded until the setting is on. + */ + private enum Tone { + MOVE(new float[] {2093}, 14, 0.10f), + TAB(new float[] {1568}, 22, 0.12f), + SELECT(new float[] {1047, 1568}, 34, 0.13f), + OPEN(new float[] {784, 1175}, 40, 0.11f), + BACK(new float[] {1175, 784}, 34, 0.11f); + + private static final int RATE = 48000; + private final float[] notes; + private final int ms; + private final float level; + private AudioTrack track; + + Tone(float[] notes, int ms, float level) { this.notes = notes; this.ms = ms; this.level = level; } + + static void warm() { for (Tone t : values()) t.make(); } + + private void make() { + if (track != null) return; + int per = RATE * ms / 1000, n = per * notes.length; + short[] pcm = new short[n]; + for (int k = 0; k < notes.length; k++) { + for (int i = 0; i < per; i++) { + double t = (double) i / RATE, attack = Math.min(1.0, i / (RATE * 0.0015)), fade = Math.exp(-5.0 * i / per); + pcm[k * per + i] = (short) (Math.sin(2 * Math.PI * notes[k] * t) * attack * fade * level * Short.MAX_VALUE); + } + } + try { + track = new AudioTrack.Builder() + .setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build()) + .setAudioFormat(new AudioFormat.Builder().setEncoding(AudioFormat.ENCODING_PCM_16BIT).setSampleRate(RATE) + .setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build()) + .setTransferMode(AudioTrack.MODE_STATIC).setBufferSizeInBytes(n * 2).build(); + track.write(pcm, 0, n); + } catch (RuntimeException e) { + android.util.Log.w("peanuts", "menu sound " + this + ": " + e); + track = null; + } + } + + void play() { + make(); + AudioTrack t = track; + if (t == null) return; + try { + if (t.getPlayState() == AudioTrack.PLAYSTATE_PLAYING) t.stop(); + t.setPlaybackHeadPosition(0); + t.play(); + } catch (RuntimeException ignored) { /* a track the system took back: silence */ } + } + } +} diff --git a/android/app/src/main/java/dev/peanuts/ui/PanelPolish.java b/android/app/src/main/java/dev/peanuts/ui/PanelPolish.java index c63cb969..541317e6 100644 --- a/android/app/src/main/java/dev/peanuts/ui/PanelPolish.java +++ b/android/app/src/main/java/dev/peanuts/ui/PanelPolish.java @@ -20,14 +20,19 @@ * PEANUTS: a restyle of the in-game side panel's tabs, called from SidePanel.look() after a tab is built. It only changes looks, never behaviour and never removes a * view: short radio groups become segmented controls, the section headings (SidePanel.head: bold, 15 sp, an 18 dp top gap, no side padding) and the grey notes * (SidePanel.note: 12 sp, light grey, not bold) get one look each, and the all-caps default Buttons are rounded. A styled view is tagged, so a rebuilt tab - * (or a second call) is styled once. + * (or a second call) is styled once. In the quick menu (the canvas page "In-game menus") a heading is a section head in capitals in peanut tan, and a + * slider's label ("Size 100 %") reads as its name at the left and its value at the right. */ public final class PanelPolish { private PanelPolish() {} - private static final String DONE = "pn_polish"; + private static final String DONE = "pn_polish", INSET = "pn_inset"; + private static final int INSET_KEY = dev.nxnative.android.R.id.pn_inset; private static final int ACCENT = 0xFFFFD54F; // SidePanel.FOCUS, the selected tab's colour private static final int OUTLINE = 0xFF555555; + private static final int HEAD = 0xFFCDB48C; // peanut tan: the section heads (dev.peanuts.ingame.Look.TAN) + private static final int TRACK = 0xFF2D2E31, PEANUT = 0xFF4A3920, CREAM = 0xFFFFF1D2, QUIET = 0xFFB0B3B8; // a choice's track, its chosen part (the rail's block) + private static final java.util.regex.Pattern VALUED = java.util.regex.Pattern.compile("^(\\D+?)\\s+(\\d.*)$"); public static void apply(View root) { if (root == null) return; @@ -36,46 +41,214 @@ public static void apply(View root) { } private static void walk(View v, float dp, float sp) { + // The panel's yellow frame (SidePanel.focusMoved) alone shows the focus: no grey veil of the system's over a row, a choice or a switch + if (v.isFocusable()) v.setDefaultFocusHighlightEnabled(false); + if ((v instanceof CompoundButton || v instanceof android.widget.SeekBar) && v.getBackground() instanceof android.graphics.drawable.RippleDrawable) { + // The theme's borderless ripple of a switch, a radio or a slider: a light circle around the focused one, drawn on the sheet behind the rows. + // The frame shows the focus, and the switch, the choice or the thumb itself shows the change + v.setBackground(null); + } if (DONE.equals(v.getTag())) return; - if (v instanceof RadioGroup) segmented((RadioGroup) v, dp); + if (v instanceof RadioGroup) { + for (int i = 0; i < ((RadioGroup) v).getChildCount(); i++) ((RadioGroup) v).getChildAt(i).setDefaultFocusHighlightEnabled(false); + if (!segmented((RadioGroup) v, dp)) radios((RadioGroup) v, dp); + } + else if (v instanceof android.widget.CheckBox) switchLook((android.widget.CheckBox) v, dp); + else if (v instanceof android.widget.SeekBar) slider((android.widget.SeekBar) v); else if (v instanceof Button) button((Button) v, dp); else if (v instanceof TextView && !(v instanceof CompoundButton)) text((TextView) v, dp, sp); + if (v.isFocusable() && !(v instanceof android.widget.SeekBar) && !(v.getParent() instanceof RadioGroup) && v.getPaddingLeft() < Math.round(6 * dp)) inset(v, dp); if (v instanceof ViewGroup && !(v instanceof RadioGroup)) { ViewGroup g = (ViewGroup) v; for (int i = 0; i < g.getChildCount(); i++) walk(g.getChildAt(i), dp, sp); + for (int i = 0; i + 1 < g.getChildCount(); i++) valued(g, i, dp); } } - private static void segmented(RadioGroup g, float dp) { + /** + * A short choice (up to 4, labels up to 12 characters): one track, the panel's row grey, its parts side by side; the chosen one a peanut-brown block with + * its label in peanut cream (the rail's selected tab), the others in the quiet grey. The controller's yellow frame stays the focus alone. False: not short + */ + private static boolean segmented(RadioGroup g, float dp) { int n = g.getChildCount(); - if (n < 1 || n > 4) return; + if (n < 1 || n > 4) return false; for (int i = 0; i < n; i++) { View c = g.getChildAt(i); - if (!(c instanceof RadioButton) || String.valueOf(((RadioButton) c).getText()).length() > 12) return; + if (!(c instanceof RadioButton) || String.valueOf(((RadioButton) c).getText()).length() > 12) return false; } g.setOrientation(LinearLayout.HORIZONTAL); g.setTag(DONE); + int pad = Math.round(3 * dp); + g.setPadding(pad, pad, pad, pad); + g.setBackground(pill(TRACK, 0, dp, 12)); for (int i = 0; i < n; i++) { RadioButton b = (RadioButton) g.getChildAt(i); b.setButtonDrawable(null); b.setGravity(Gravity.CENTER); - b.setSingleLine(true); - b.setPadding(Math.round(6 * dp), 0, Math.round(6 * dp), 0); - b.setTextColor(new ColorStateList(new int[][] {{android.R.attr.state_checked}, {}}, new int[] {0xFF000000, 0xFFE8EAED})); + b.setMaxLines(1); // not setSingleLine: its horizontal scrolling moves the foreground (SidePanel's focus frame) out of sight + b.setMinHeight(Math.round(38 * dp)); + b.setPadding(Math.round(8 * dp), 0, Math.round(8 * dp), 0); + b.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + b.setTextColor(new ColorStateList(new int[][] {{android.R.attr.state_checked}, {-android.R.attr.state_enabled}, {}}, new int[] {CREAM, 0x66B0B3B8, QUIET})); StateListDrawable bg = new StateListDrawable(); - bg.addState(new int[] {android.R.attr.state_checked}, pill(ACCENT, 0, dp)); - bg.addState(new int[] {}, pill(Color.TRANSPARENT, OUTLINE, dp)); + bg.addState(new int[] {android.R.attr.state_checked}, pill(PEANUT, 0, dp, 9)); + bg.addState(new int[] {}, pill(Color.TRANSPARENT, 0, dp, 9)); b.setBackground(bg); RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f); - lp.setMargins(i == 0 ? 0 : Math.round(3 * dp), Math.round(2 * dp), i == n - 1 ? 0 : Math.round(3 * dp), Math.round(2 * dp)); + lp.setMargins(0, 0, 0, 0); b.setLayoutParams(lp); } + return true; + } + + /** + * The controller's focus came into a track of choices (Auto / On / Off, made by segmented) from outside it or from nothing (a menu opening), onto one that is not the chosen one: the + * chosen one, which the focus takes instead, as a console's menus land on the current value (Android picks the nearest by its position). Null when + * nothing is to change. A list of choices one under the other keeps its step to the next row + */ + public static View chosen(View old, View now) { + if (!(now instanceof RadioButton) || !(now.getParent() instanceof RadioGroup)) return null; + if (old != null) for (android.view.ViewParent o = old.getParent(); o != null; o = o.getParent()) if (o == now.getParent()) return null; // a step inside the track + View c = landing(now); + return c == now ? null : c; + } + + /** Where the focus lands for v: the chosen one of a track of choices when v is another of its choices, else v itself */ + public static View landing(View v) { + if (!(v instanceof RadioButton) || ((RadioButton) v).isChecked() || !(v.getParent() instanceof RadioGroup)) return v; + RadioGroup g = (RadioGroup) v.getParent(); + if (!DONE.equals(g.getTag()) || g.getOrientation() != LinearLayout.HORIZONTAL) return v; + View c = g.findViewById(g.getCheckedRadioButtonId()); + return c != null && c.getParent() == g && c.isEnabled() && c.isFocusable() ? c : v; + } + + /** + * A longer list of choices (the frame rate cap, Console mode): a still mark of the panel's own, a ring and, when chosen, a dot in its yellow (the free + * ones grey). SidePanel's focus frame lies on a choice's edge, which was its mark's and its text's: the list reaches 10 dp into the rows' side padding + * at both ends, each choice takes the row's width and its mark and text move 10 dp in, so the frame keeps clear of both as on the other rows and the + * marks stay under the headings + */ + private static void radios(RadioGroup g, float dp) { + if (DONE.equals(g.getTag())) return; + g.setTag(DONE); + int in = Math.round(10 * dp); + ViewGroup p = g.getParent() instanceof ViewGroup ? (ViewGroup) g.getParent() : null; + boolean room = p != null && p.getPaddingLeft() >= in && p.getPaddingRight() >= in && g.getOrientation() == LinearLayout.VERTICAL + && g.getLayoutParams() instanceof LinearLayout.LayoutParams; + if (room) { + p.setClipToPadding(false); + LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) g.getLayoutParams(); + lp.leftMargin -= in; + lp.rightMargin -= in; + lp.width = ViewGroup.LayoutParams.MATCH_PARENT; + g.setLayoutParams(lp); + } + for (int i = 0; i < g.getChildCount(); i++) { + if (!(g.getChildAt(i) instanceof RadioButton)) continue; + RadioButton b = (RadioButton) g.getChildAt(i); + b.setButtonTintList(null); + if (b.getBackground() instanceof android.graphics.drawable.RippleDrawable) b.setBackground(null); // the theme's grey circle on the focused mark: the frame shows the focus + b.setButtonDrawable(radioMark(dp, room ? in : 0)); // not the theme's animated mark: inside a wrapper its check animation stops before the dot + b.setMinHeight(Math.round(40 * dp)); // the row's height, which the theme's taller mark gave it + if (room) { + b.setPadding(b.getPaddingLeft(), b.getPaddingTop(), b.getPaddingRight() + in, b.getPaddingBottom()); + ViewGroup.LayoutParams blp = b.getLayoutParams(); + if (blp != null) { blp.width = ViewGroup.LayoutParams.MATCH_PARENT; b.setLayoutParams(blp); } + } + } + } + + /** A list choice's mark: a ring 18 dp across, a dot in it when chosen; the panel's yellow when chosen, grey when free, faint when it cannot be chosen */ + private static android.graphics.drawable.Drawable radioMark(float dp, int left) { + StateListDrawable s = new StateListDrawable(); + s.addState(new int[] {android.R.attr.state_checked, android.R.attr.state_enabled}, ring(dp, ACCENT, true)); + s.addState(new int[] {android.R.attr.state_checked}, ring(dp, 0x669AA0A6, true)); + s.addState(new int[] {-android.R.attr.state_enabled}, ring(dp, 0x669AA0A6, false)); + s.addState(new int[] {}, ring(dp, 0xFF9AA0A6, false)); + return new android.graphics.drawable.InsetDrawable(s, left + Math.round(3 * dp), 0, Math.round(12 * dp), 0); } - private static GradientDrawable pill(int fill, int stroke, float dp) { + private static android.graphics.drawable.Drawable ring(float dp, int color, boolean dot) { + int size = Math.round(18 * dp); + GradientDrawable r = new GradientDrawable(); + r.setShape(GradientDrawable.OVAL); + r.setStroke(Math.round(2 * dp), color); + r.setSize(size, size); + if (!dot) return r; + GradientDrawable d = new GradientDrawable(); + d.setShape(GradientDrawable.OVAL); + d.setColor(color); + android.graphics.drawable.LayerDrawable l = new android.graphics.drawable.LayerDrawable(new android.graphics.drawable.Drawable[] {r, d}); + int i = Math.round(5 * dp); + l.setLayerInset(1, i, i, i, i); + return l; + } + + /** A check box: its text over the row's width and a switch at its end, as the Mods tab's (track and thumb in the panel's yellow, grey when off) */ + private static void switchLook(android.widget.CheckBox b, float dp) { + if (DONE.equals(b.getTag())) return; + b.setTag(DONE); + b.setButtonDrawable(null); + StateListDrawable sw = new StateListDrawable(); + sw.addState(new int[] {android.R.attr.state_checked}, toggle(dp, true)); + sw.addState(new int[] {}, toggle(dp, false)); + b.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, sw, null); + b.setCompoundDrawablePadding(Math.round(12 * dp)); + b.setMinHeight(Math.round(44 * dp)); + if (b.getLayoutParams() instanceof LinearLayout.LayoutParams) b.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT; + b.setPaddingRelative(0, b.getPaddingTop(), 0, b.getPaddingBottom()); + inset(b, dp); + } + + /** + * A focusable row whose text starts at its edge (a switch, a list row such as Preset): SidePanel's focus frame lies on the row's edge and would cover + * its first letter. The row reaches 10 dp into the rows' side padding at both ends and its content moves 10 dp in, so the text stays under the + * headings and the frame keeps clear of it. Only where the parent has that padding (the panel's rows); once a row (its tag) + */ + private static void inset(View v, float dp) { + int in = Math.round(10 * dp); + if (INSET.equals(v.getTag(INSET_KEY)) || !(v.getParent() instanceof ViewGroup) || !(v.getLayoutParams() instanceof LinearLayout.LayoutParams)) return; + ViewGroup p = (ViewGroup) v.getParent(); + if (p.getPaddingLeft() < in || p.getPaddingRight() < in) return; + v.setTag(INSET_KEY, INSET); + p.setClipToPadding(false); + LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) v.getLayoutParams(); + lp.leftMargin -= in; + lp.rightMargin -= in; + v.setLayoutParams(lp); + v.setPadding(v.getPaddingLeft() + in, v.getPaddingTop(), v.getPaddingRight() + in, v.getPaddingBottom()); + } + + private static android.graphics.drawable.Drawable toggle(float dp, boolean on) { + GradientDrawable track = pill(on ? 0xAAFFD54F : 0xFF5F6368, 0, dp, 7); + GradientDrawable thumb = new GradientDrawable(); + thumb.setShape(GradientDrawable.OVAL); + thumb.setColor(on ? ACCENT : 0xFFBDC1C6); + android.graphics.drawable.LayerDrawable l = new android.graphics.drawable.LayerDrawable(new android.graphics.drawable.Drawable[] {track, thumb}); + int w = Math.round(38 * dp), h = Math.round(22 * dp); + l.setLayerSize(0, Math.round(34 * dp), Math.round(14 * dp)); + l.setLayerGravity(0, Gravity.CENTER); + l.setLayerSize(1, Math.round(20 * dp), Math.round(20 * dp)); + l.setLayerGravity(1, Gravity.CENTER_VERTICAL | (on ? Gravity.END : Gravity.START)); + l.setBounds(0, 0, w, h); + return new android.graphics.drawable.InsetDrawable(l, 0) { @Override public int getIntrinsicWidth() { return w; } @Override public int getIntrinsicHeight() { return h; } }; + } + + /** A slider: its played part and thumb in the panel's yellow over a grey track */ + private static void slider(android.widget.SeekBar s) { + if (DONE.equals(s.getTag())) return; + s.setTag(DONE); + s.setProgressTintList(ColorStateList.valueOf(ACCENT)); + s.setProgressBackgroundTintList(ColorStateList.valueOf(0xFF5F6368)); + s.setThumbTintList(ColorStateList.valueOf(ACCENT)); + } + + private static GradientDrawable pill(int fill, int stroke, float dp) { return pill(fill, stroke, dp, 8); } + + private static GradientDrawable pill(int fill, int stroke, float dp, float radius) { GradientDrawable d = new GradientDrawable(); d.setColor(fill); - d.setCornerRadius(8 * dp); + d.setCornerRadius(radius * dp); if (stroke != 0) d.setStroke(Math.round(dp), stroke); return d; } @@ -90,10 +263,12 @@ private static void text(TextView t, float dp, float sp) { if (bold && t.getPaddingLeft() == 0 && t.getPaddingTop() >= Math.round(12 * dp) && size >= 13 * sp) { float scale = size / (15 * sp); // the panel's text size setting scales every size; keep it t.setTag(DONE); - t.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); - t.setTextSize(TypedValue.COMPLEX_UNIT_PX, 13 * sp * scale); - t.setTextColor(0xFFC8C8C8); - t.setPadding(0, Math.round(20 * dp), 0, 0); + t.setTypeface(Typeface.DEFAULT_BOLD); + t.setTextSize(TypedValue.COMPLEX_UNIT_PX, 12 * sp * scale); + t.setAllCaps(true); + t.setLetterSpacing(0.08f); + t.setTextColor(HEAD); + t.setPadding(0, Math.round(20 * dp), 0, Math.round(2 * dp)); } else if (!bold && t.getCurrentTextColor() == Color.LTGRAY && size <= 13 * sp) { float scale = size / (12 * sp); t.setTag(DONE); @@ -103,6 +278,38 @@ private static void text(TextView t, float dp, float sp) { } } + /** + * A slider's label just above it, "Size 100 % (full)": its name at the left and its value at the right, in one row put where the label was. The label stays + * (hidden) and its text is still set by upstream's code; each change is split into the row again + */ + private static void valued(ViewGroup g, int i, float dp) { + View v = g.getChildAt(i), next = g.getChildAt(i + 1); + if (!(next instanceof android.widget.SeekBar) || !(v instanceof TextView) || v instanceof CompoundButton || v instanceof Button || v.getVisibility() != View.VISIBLE) return; + TextView label = (TextView) v; + java.util.regex.Matcher m = VALUED.matcher(String.valueOf(label.getText())); + if (!m.matches() || !(g instanceof LinearLayout) || ((LinearLayout) g).getOrientation() != LinearLayout.VERTICAL) return; + LinearLayout row = new LinearLayout(g.getContext()); + row.setOrientation(LinearLayout.HORIZONTAL); + row.setPadding(0, Math.round(6 * dp), 0, 0); + TextView name = new TextView(g.getContext()), value = new TextView(g.getContext()); + for (TextView t : new TextView[] {name, value}) { t.setTextSize(TypedValue.COMPLEX_UNIT_PX, label.getTextSize()); t.setTextColor(0xFFE8EAED); t.setSingleLine(true); } + value.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + row.addView(name, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); + row.addView(value, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + Runnable split = () -> { + java.util.regex.Matcher x = VALUED.matcher(String.valueOf(label.getText())); + if (x.matches()) { name.setText(x.group(1)); value.setText(x.group(2)); } else { name.setText(label.getText()); value.setText(""); } + }; + split.run(); + label.addTextChangedListener(new android.text.TextWatcher() { + @Override public void beforeTextChanged(CharSequence s, int a, int b, int c) {} + @Override public void onTextChanged(CharSequence s, int a, int b, int c) {} + @Override public void afterTextChanged(android.text.Editable e) { split.run(); } + }); + label.setVisibility(View.GONE); + g.addView(row, i); + } + /** True when v's parent is a LinearLayout whose children all have a layout weight (the tab bar's row of tabs) */ private static boolean inWeightedRow(View v) { if (!(v.getParent() instanceof LinearLayout)) return false; @@ -119,11 +326,15 @@ private static boolean inWeightedRow(View v) { private static void button(Button b, float dp) { if (!b.isAllCaps()) return; // the panel's list rows (SidePanel.row) already turned it off - TypedValue tv = new TypedValue(); - int fill = b.getContext().getTheme().resolveAttribute(android.R.attr.colorButtonNormal, tv, true) ? tv.data : 0xFF555555; + // A button of the panel's own (All off, Restart): a rounded chip in the rows' grey with its text in the panel's white, not the theme's raised grey block b.setTag(DONE); b.setAllCaps(false); b.setStateListAnimator(null); - b.setBackground(pill(fill, 0, dp)); + b.setBackground(pill(0xFF3A3B3E, 0, dp, 999)); + b.setTextColor(0xFFE8EAED); + b.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + b.setMinHeight(Math.round(38 * dp)); + b.setMinimumHeight(Math.round(38 * dp)); + b.setPadding(Math.round(18 * dp), 0, Math.round(18 * dp), 0); } } diff --git a/android/app/src/main/java/dev/peanuts/ui/StatsView.java b/android/app/src/main/java/dev/peanuts/ui/StatsView.java index 94f10b19..985e2d10 100644 --- a/android/app/src/main/java/dev/peanuts/ui/StatsView.java +++ b/android/app/src/main/java/dev/peanuts/ui/StatsView.java @@ -450,6 +450,7 @@ private void build() { tagLp.bottomMargin = -pad + PUi.dp(c, 2); // the tag (about 12 dp) fits in the padding (16 or 24 dp) under the card content.addView(buildTag, tagLp); addView(content, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + if (dev.peanuts.ingame.BottomMenu.on(getContext())) content.addView(dev.peanuts.ingame.BottomMenu.grip(getContext())); // the menu's grip: a swipe up opens it; it moves with the pixel shifter sheet = sheet(c); sheet.setVisibility(sheetOpen ? View.VISIBLE : View.GONE); addView(sheet, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/LICENSE b/android/app/src/main/java/io/github/davdxpx/mistel/LICENSE new file mode 100644 index 00000000..0170c8ea --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 davdxpx and the Mistel contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/MISTEL.sha256 b/android/app/src/main/java/io/github/davdxpx/mistel/MISTEL.sha256 new file mode 100644 index 00000000..9157e4be --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/MISTEL.sha256 @@ -0,0 +1,60 @@ +# mistel 76d283c633ce863407a632e9f9edcb555d03de24 format/lib/java/src/main/java/io/github/davdxpx/mistel/mncf and format/LICENSE, unchanged (peanuts/scripts/mncf-vendor.sh) +48e7544a51bc6320d1564225be02d84c3d5c88a7bf9cac4dd34afe68fb96a33a LICENSE +b6b32b3726955dce0dbbd4d49893351cfec6e8c76ddb60f507fa1f35708b6052 mncf/Arm64.java +15bb8a114a6866c839b97f91d03ed39cb51e016ba9eec3fbffec782154be2ed3 mncf/Atmosphere.java +be9b4e776413289de04207f800f2a7aa7d7e8c2878b6c98b595f41de21fb1f43 mncf/AtmosphereException.java +45ae082721b4867286fd740ea22babd63b1fde81e5b631bf7406c03cfa477742 mncf/Build.java +9e54f1761778367efdf41cd4ec135e9af95d81c5ffb7dcc28af8e81f03afb964 mncf/Change.java +a10fa1b793e35684cfa6113acf43d2c108736362adf49eb58bea47cd94c363c9 mncf/Cheat.java +8c91f8c960c3d938dde547ee616e89a995f6ae562e0b15bd930be26a7b867f79 mncf/CheatReport.java +10b17b1ef8f208ae8451cc0c57418e24494bfb21dd979d76d0143f7d3e767529 mncf/CheatResult.java +404008a53aec1923fba1a72b0171e3270f6ae802fc1d83e5d11ed7dab1cebfc7 mncf/CheatState.java +164d34f3467d4bc3d92fff05990b1da7b25007b0082a9c858b06f5adff532c4c mncf/Choices.java +6e6c21fad69904b259b9fe282632fd3a796e73cc97863350374fa2f476bb9b41 mncf/CodeModule.java +8a6a3443673894ff795bef8cdb313db010bc09f3bc6ebec6caac3da836e3e7ea mncf/CodeModuleException.java +5ed710a10520d11ee61530cc202bbdc84b3004e107aed78e7e1c48fd813edaba mncf/Conversion.java +6206fdae695675366c83c090b24344747aa96e9e0fe21d20a063b840f464bc7c mncf/ConversionReport.java +d64931ee300a1d4f1a71757a8bf296a9a8305fc7b4ad56f215ec3d309f87f56c mncf/ConvertException.java +7703a4fc3a28790815681d4e9f60c89624577fc0ede9ecd0bc667df3817d86e4 mncf/Converter.java +962762d42364361332028776822de0ef528cae281ca5546b9ddddc92a6c8fb61 mncf/Ed25519.java +0c1803c03315c3f9d37e33af0f79ec5c5c6ac625b007ae9b4d817d7b36aa91be mncf/Encode.java +55db57d56b15df1b34994cdcd85ed2dc17c853efe0ce71a77cd5335dd3dac1a6 mncf/Engine.java +5c50ec1472d0e6ec91a35d0242d73d999e127ff9634fff305b3d2bbe7a770b54 mncf/Evaluation.java +10a4a81916217d875137f1295a870848175290302d3fa5f6ed260d1f456d0d27 mncf/Evaluator.java +e95408bc95eac6603321a8147f57d72b5922587d6f811d0a54d451caf0d238f1 mncf/GuestMemory.java +98424b33c2d5b6e5ef81ecf06f48badd9abeff1805aa215384b13739dda23bce mncf/Lz4.java +2842b4006ef63ceb3ca216f3d91455f3b81488e13111cbf2963e68e31b2c1a5b mncf/Lz4Exception.java +3a6f51f04203c3a7d627c1b32a5ab60cfb5247c8bc37f9e0a4e01972e416389b mncf/Mncf.java +cf756e181b655d2ef2eea88133c7b12eef40ab76f60528234ed70a2c0f9a575a mncf/MncfException.java +d23366d9ad06277150c8ebeb00ed6fb80abc1ae794835960736cf4f5c9f55cb9 mncf/MncfFile.java +681daa3f169e9c0c6a812427c3b71975e2cf4ea8dea2b8ff4c01f09884741314 mncf/Model.java +6160d7115503536f0f5719e19e8e6797f87835a6c03bd111ac277d6431cdba6c mncf/Module.java +7f13eb10b25c233f977fec9e79367b9c1768d2be3a6a6383fceeedf4b5d2e4f4 mncf/Pack.java +3eec9c0d132ec58a2ebf02688c7120d900a737749d6a3d0a49c88d42330b9cb6 mncf/PackFile.java +baeb7a80d99d395f534893e6b469032c08e2cc33ae7d98f526f24012a43254f2 mncf/PackReader.java +d13e4b14e57e3f3689393c8285246dba3de37182ea329c84fefafaef78c9c94c mncf/Pass.java +95935d157be01a11ef2412c014985822903fcf36d925d706f4fa361881aefd80 mncf/Patch.java +b76e5f2816d6f81521879d03c18f71302fca5b7a43196f5b4fe74182b9745b3c mncf/PatchFile.java +724d5dec707f3880097b9308644289173df65cb6579965b5b0d9a5b0a3093895 mncf/PatchFileException.java +a6d3ee742c7c376dd9d0129cf2c5ce959238ea38af32c0d8d1df225c07ef1108 mncf/PatchSource.java +4b5c9345065f2968914950e4cd2ade70f9436b224f9da374904121e38ded1625 mncf/Patches.java +f5ad7e4ca683cf0f58d985f1b4c04ea099270ba44dbd565e30c481316dd3ebe9 mncf/Patterns.java +62ca82653bee0ea060db5778efc441a463f4eb84720eceae1b6a5052439dacdf mncf/Platform.java +3e53fe9abca1738fd868a72cedc53019887346975e5430826f019449fcb6813b mncf/Preset.java +d1c0192cbbecf7d112ec8afbe78c4f392fab652da797233491fdb51f9ef41262 mncf/Py.java +95aad3ae8b946e2f8d27d46f82419bd109c5e1ef3b1ca69edef10464d5b1b583 mncf/ResolvedOp.java +eec61dc351e12ac48ae8ba1cc9f2a3e0d6eb1f722b795ccc12cbaa2b9167f4e0 mncf/Runtime.java +3f6d8fd7c9c65aab40aab2ba13426ebad33bce739db353d93645fa7e4310c900 mncf/Schema.java +c6112d9290635fa5f71092e3869398a9f94f2cfa36cf934dfe1f99e2c0a17e68 mncf/Shown.java +f6134e01e783e5fc69808728b35f42036c77d385213a29988c6fb22daa4af55f mncf/SignatureResult.java +ad1e9be10b2c5a0d85cb1f8512346b6ec48b75e38824580511d943bf08201c33 mncf/Signatures.java +77ca418ad963b87831c51f3b42bfcd492f83d668719ba2b4b332f1bf2d01c0b3 mncf/Source.java +4b489e02bb6f45a111e9310714a4c7231a9a70cc289681adef3abed40111bf67 mncf/TrustList.java +7da36975a0cf10224a5db30e487d4e3a6ab28f0e790d7fb65cce16dc02be5f37 mncf/Utf8.java +6e31a1159f8c40103fd8836ba1fdb4d21b4e7c7c4a65f8162012c413af50bd54 mncf/ValueSpec.java +cc9139002a1bdfb46d064d1ceced92835f54a7d63dd3ca0017b42fe2462bb73a mncf/Values.java +bd58488d735b027205e1f1377eccfadefb6eb618926b6bd97a1eda4101071d10 mncf/Writer.java +526335b40c01885bedc710acaad7a5aaf922cb846063a744cc0879f35f40ae27 mncf/Zip.java +f92a609ed12785b766116551d22028e36a5c3c4384e131071a8c71e081ccdd0f mncf/toml/Toml.java +d66ecdbe25aa6b0ead59dd477b24c9587468a753b5fbd680fa4a2965cf9314fc mncf/toml/TomlDateTime.java +ecc463a530bcacadac01ad46970a945eda5330735576fe22c42d79df894b3463 mncf/toml/TomlException.java diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Arm64.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Arm64.java new file mode 100644 index 00000000..7c73bac9 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Arm64.java @@ -0,0 +1,125 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +/** + * What the converter needs to know about ARM64 instructions: which ones are relative to their + * own address, and which of their bytes change when the code moves in another build of the game. + */ +final class Arm64 { + + private Arm64() { + } + + /** The little-endian word at an offset, from the bytes that are there (fewer than 4 at the end). */ + static long word(byte[] data, int offset) { + long w = 0; + for (int i = 0; i < 4 && offset + i < data.length; i++) { + w |= (long) (data[offset + i] & 0xFF) << (8 * i); + } + return w; + } + + private static long signed(long value, int bits) { + return (value & (1L << (bits - 1))) != 0 ? value - (1L << bits) : value; + } + + /** + * The address a PC-relative instruction at pc refers to, or null for an instruction that is + * not PC-relative. + */ + static Long pcRelativeTarget(long w, long pc) { + if ((w & 0x7C000000L) == 0x14000000L) { // B, BL + return pc + 4 * signed(w & 0x3FFFFFF, 26); + } + if ((w & 0xFF000010L) == 0x54000000L || (w & 0x7E000000L) == 0x34000000L) { // B.cond, CBZ, CBNZ + return pc + 4 * signed((w >> 5) & 0x7FFFF, 19); + } + if ((w & 0x7E000000L) == 0x36000000L) { // TBZ, TBNZ + return pc + 4 * signed((w >> 5) & 0x3FFF, 14); + } + if ((w & 0x3B000000L) == 0x18000000L || (w & 0xFF000000L) == 0xD8000000L) { // LDR and PRFM (literal) + return pc + 4 * signed((w >> 5) & 0x7FFFF, 19); + } + if ((w & 0x1F000000L) == 0x10000000L) { // ADR, ADRP + long imm = signed(((w >> 5) & 0x7FFFF) << 2 | (w >> 29) & 3, 21); + if ((w & 0x80000000L) != 0) { + return (pc & ~0xFFFL) + (imm << 12); + } + return pc + imm; + } + return null; + } + + static boolean isAdrp(long w) { + return (w & 0x9F000000L) == 0x90000000L; + } + + /** The base register of an ADD (immediate) or of a load or store with an unsigned 12-bit offset, or -1. */ + private static int low12Base(long w) { + if ((w & 0x7F800000L) == 0x11000000L || (w & 0x3B000000L) == 0x39000000L) { + return (int) ((w >> 5) & 31); + } + return -1; + } + + /** + * The offsets in [start, end) whose bytes change when the code moves: the address fields of + * PC-relative instructions and the low 12 bits of the page offset that follow an ADRP. Code + * is read in words aligned to 4. + */ + static Set movingBytes(byte[] data, int start, int end) { + Set moving = new TreeSet<>(); + int first = Math.max(0, (start - 32) & ~3); + Map pages = new HashMap<>(); // register, set by an ADRP + for (int off = first; off < ((end + 3) & ~3); off += 4) { + if (off + 4 > data.length) { + break; + } + long w = word(data, off); + int[] fields = {}; + if (isAdrp(w) || (w & 0x9F000000L) == 0x10000000L) { + fields = new int[] {0, 1, 2, 3}; + } else if (pcRelativeTarget(w, off) != null) { + fields = new int[] {0, 1, 2}; + } else { + int base = low12Base(w); + if (base >= 0 && pages.containsKey(base)) { + fields = new int[] {1, 2}; + if ((w & 31) == base) { // add x8, x8, #lo or ldr x8, [x8, #lo]: x8 changed + pages.remove(base); + } + } + } + if (isAdrp(w)) { + pages.put((int) (w & 31), off); + } + for (int i : fields) { + if (start <= off + i && off + i < end) { + moving.add(off + i); + } + } + } + return moving; + } + + /** + * Whether bytes written at an offset hold a PC-relative instruction whose target lies + * outside them, so that the same bytes mean something else at another place. + */ + static boolean relativeOutside(byte[] data, long offset, int length) { + if (Math.floorMod(offset, 4) != 0) { + return false; + } + for (int i = 0; i < length - length % 4; i += 4) { + Long target = pcRelativeTarget(word(data, i), offset + i); + if (target != null && !(offset <= target && target < offset + length)) { + return true; + } + } + return false; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Atmosphere.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Atmosphere.java new file mode 100644 index 00000000..dcd9dad1 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Atmosphere.java @@ -0,0 +1,1071 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Atmosphère cheat files (the dmnt cheat code of the Switch): reading, decoding, understanding + * and writing. + * + *

    A file is a list of entries: [Name] or {Name} (the master entry) followed by opcodes, words + * of 8 hexadecimal digits. The converter reads an entry's opcodes the way the cheat machine runs + * them and finds the plain writes they make, with the button mask and the memory condition + * around them, wherever the code says that plainly. + */ +public final class Atmosphere { + + static final String[] REGIONS = {"main", "heap", "alias", "aslr"}; + static final long MASK64 = -1L; + private static final Pattern WORD = Pattern.compile("[0-9A-Fa-f]{8}"); + private static final int[] WIDTHS = {1, 2, 4, 8}; + private static final String[] KEY_NAMES = {"A", "B", "X", "Y", "LSTICK", "RSTICK", "L", "R", "ZL", "ZR", "PLUS", + "MINUS", "DLEFT", "DUP", "DRIGHT", "DDOWN", "LSTICK_LEFT", "LSTICK_UP", "LSTICK_RIGHT", "LSTICK_DOWN", + "RSTICK_LEFT", "RSTICK_UP", "RSTICK_RIGHT", "RSTICK_DOWN", "SL", "SR"}; + private static final Map CONDITIONS = new HashMap<>(); + private static final Map CONDITION_CODES = new HashMap<>(); + + static { + String[] ops = {">", ">=", "<", "<=", "==", "!="}; + for (int i = 0; i < ops.length; i++) { + CONDITIONS.put(i + 1, ops[i]); + CONDITION_CODES.put(ops[i], i + 1); + } + } + + private Atmosphere() { + } + + /** The bit of each button, in the order of KEY_NAMES. */ + private static long keyBit(int index) { + return 1L << index; + } + + static int regionCode(String region) { + for (int i = 0; i < REGIONS.length; i++) { + if (REGIONS[i].equals(region)) { + return i; + } + } + return -1; + } + + static boolean isConditionOp(String op) { + return CONDITION_CODES.containsKey(op); + } + + /** The opcodes do something the core operations of .mncf cannot say plainly. */ + static final class Unclear extends Exception { + private static final long serialVersionUID = 1L; + final String why; + /** Back to Atmosphère: the stable reason (spec, section 15); null otherwise. */ + final String code; + + Unclear(String why) { + this(why, null); + } + + Unclear(String why, String code) { + super(why, null, false, false); + this.why = why; + this.code = code; + } + } + + /** One entry of a file: its name, whether it is the master entry, its line and its code. Immutable. */ + public static final class Entry { + private final String name; + private final boolean master; + private final int line; + private final List lines; + private final long[] words; + private final List broken; + + Entry(String name, boolean master, int line, List lines, long[] words) { + this(name, master, line, lines, words, Collections.emptyList()); + } + + Entry(String name, boolean master, int line, List lines, long[] words, List broken) { + this.name = name; + this.master = master; + this.line = line; + this.lines = Collections.unmodifiableList(new ArrayList<>(lines)); + this.words = words.clone(); + this.broken = Collections.unmodifiableList(new ArrayList<>(broken)); + } + + /** Returns the name between the brackets, without spaces at its ends. */ + public String name() { + return name; + } + + /** Returns whether the entry is written {Name}: the master code that runs before the others. */ + public boolean master() { + return master; + } + + /** Returns the number of the line the entry's name is on, counted from 1. */ + public int line() { + return line; + } + + /** Returns the code lines as written, without spaces at their ends. */ + public List lines() { + return lines; + } + + /** Returns the code's words. */ + public long[] words() { + return words.clone(); + } + + long[] wordsShared() { + return words; + } + + /** + * Returns the lines that mix code words with other text, when the file was read with + * notes; the entry's code cannot be read then. Empty otherwise. + */ + public List broken() { + return broken; + } + + /** Returns the code lines, each followed by a line feed, or empty text when there is no code. */ + public String code() { + if (lines.isEmpty()) { + return ""; + } + return String.join("\n", lines) + "\n"; + } + } + + /** A line of a cheat file that is neither a name nor code, read leniently. */ + public static final class Note { + private final int line; + private final String text; + + /** Makes a note of a line, by its number counted from 1 and its text. */ + public Note(int line, String text) { + this.line = line; + this.text = text; + } + + /** Returns the number of the line, counted from 1. */ + public int line() { + return line; + } + + /** Returns the text of the line, without spaces at its ends and without a name before it. */ + public String text() { + return text; + } + + @java.lang.Override + public boolean equals(Object o) { + return o instanceof Note && ((Note) o).line == line && ((Note) o).text.equals(text); + } + + @java.lang.Override + public int hashCode() { + return line * 31 + text.hashCode(); + } + + @java.lang.Override + public String toString() { + return "(" + line + ", " + Py.repr(text) + ")"; + } + } + + /** + * Returns the entries of an Atmosphère cheat file. + * + * @throws AtmosphereException for a name without its closing bracket, a word that is not 8 + * hexadecimal digits, or code before the first name + */ + public static List parse(String text) throws AtmosphereException { + return parse(text, null); + } + + /** + * Returns the entries of an Atmosphère cheat file. Strictly, with null as notes, as + * Atmosphère reads a file, any line that is neither a name nor code is an error. With a list + * as notes, a line without any code word, or any line before the first name, goes into it + * instead, and a line that mixes code words with other text goes into its entry's + * {@link Entry#broken}. + * + * @throws AtmosphereException for a name without its closing bracket, and strictly also for a + * word that is not 8 hexadecimal digits or code before the first name + */ + public static List parse(String text, List notes) throws AtmosphereException { + int from = 0; + while (from < text.length() && text.charAt(from) == '\uFEFF') { + from++; + } + List raw = Py.splitLines(text.substring(from)); + List drafts = new ArrayList<>(); + Object[] current = null; + for (int n = 1; n <= raw.size(); n++) { + String line = Py.strip(raw.get(n - 1)); + while (!line.isEmpty()) { + char c = line.charAt(0); + if (c == '[' || c == '{') { + char close = c == '[' ? ']' : '}'; + int end = line.indexOf(close); + if (end < 0) { + throw new AtmosphereException("line " + n + ": the name has no closing " + close); + } + current = new Object[] {Py.strip(line.substring(1, end)), c == '{', n, new ArrayList(), + new ArrayList(), new ArrayList()}; + drafts.add(current); + line = Py.strip(line.substring(end + 1)); + continue; + } + List tokens = Py.splitSpace(line); + List bad = new ArrayList<>(); + for (String tok : tokens) { + if (!Py.matches(WORD, tok)) { + bad.add(tok); + } + } + if (!bad.isEmpty() && notes != null) { + if (bad.size() == tokens.size() || current == null) { + notes.add(new Note(n, line)); + } else { + broken(current).add(line); + } + line = ""; + continue; + } + if (!bad.isEmpty()) { + throw new AtmosphereException("line " + n + ": " + Py.repr(bad.get(0)) + + " is not a word of 8 hexadecimal digits"); + } + if (current == null) { + if (notes != null) { + notes.add(new Note(n, line)); + line = ""; + continue; + } + throw new AtmosphereException("line " + n + ": code before the first name"); + } + lines(current).add(line); + for (String tok : tokens) { + words(current).add(Long.parseLong(tok, 16)); + } + line = ""; + } + } + List entries = new ArrayList<>(); + for (Object[] d : drafts) { + List ws = words(d); + long[] w = new long[ws.size()]; + for (int i = 0; i < w.length; i++) { + w[i] = ws.get(i); + } + entries.add(new Entry((String) d[0], (Boolean) d[1], (Integer) d[2], lines(d), w, broken(d))); + } + return entries; + } + + @SuppressWarnings("unchecked") + private static List lines(Object[] draft) { + return (List) draft[3]; + } + + @SuppressWarnings("unchecked") + private static List words(Object[] draft) { + return (List) draft[4]; + } + + @SuppressWarnings("unchecked") + private static List broken(Object[] draft) { + return (List) draft[5]; + } + + // Opcodes + + /** One opcode: its kind, its words and its fields. A field may be null where the opcode has none. */ + static final class Op { + final String kind; + final long[] words; + final Map f; + + Op(String kind, long[] words, Map f) { + this.kind = kind; + this.words = words; + this.f = f; + } + + long get(String field) { + Long v = f.get(field); + return v == null ? 0 : v; + } + } + + /** The i-th hexadecimal digit of a word, from the left. */ + static long nib(long w, int i) { + return (w >> (28 - 4 * i)) & 0xF; + } + + private static Map fields(Object... namesAndValues) { + Map f = new LinkedHashMap<>(); + for (int i = 0; i < namesAndValues.length; i += 2) { + Object v = namesAndValues[i + 1]; + f.put((String) namesAndValues[i], v == null ? null : v instanceof Boolean + ? (((Boolean) v) ? 1L : 0L) : ((Number) v).longValue()); + } + return f; + } + + private static boolean isWidth(long width) { + for (int w : WIDTHS) { + if (w == width) { + return true; + } + } + return false; + } + + /** Reads words one opcode at a time. */ + private static final class Reader { + final long[] words; + int i; + + Reader(long[] words) { + this.words = words; + } + + long[] take(int n) throws Unclear { + if (i + n > words.length) { + throw new Unclear("the code ends inside an opcode"); + } + long[] got = Arrays.copyOfRange(words, i, i + n); + i += n; + return got; + } + } + + /** The opcodes in a list of words. */ + static List decode(long[] words) throws Unclear { + List ops = new ArrayList<>(); + Reader r = new Reader(words); + while (r.i < words.length) { + long w = words[r.i]; + long t = nib(w, 0); + if (t == 0x0) { + long width = nib(w, 1); + if (!isWidth(width)) { + throw new Unclear("a store of width " + width); + } + long[] ws = r.take(width == 8 ? 4 : 3); + long value = width == 8 ? ws[2] << 32 | ws[3] : ws[2]; + ops.add(new Op("store", ws, fields("width", width, "mem", nib(w, 2), "reg", nib(w, 3), + "offset", (w & 0xFF) << 32 | ws[1], "value", value))); + } else if (t == 0x1) { + long width = nib(w, 1); + if (!isWidth(width)) { + throw new Unclear("a condition of width " + width); + } + long[] ws = r.take(width == 8 ? 4 : 3); + long value = width == 8 ? ws[2] << 32 | ws[3] : ws[2]; + ops.add(new Op("begin-cond", ws, fields("width", width, "mem", nib(w, 2), "cond", nib(w, 3), + "use_reg", nib(w, 4), "reg", nib(w, 5), "offset", (w & 0xFF) << 32 | ws[1], "value", value))); + } else if (t == 0x2) { + ops.add(new Op("end-cond", r.take(1), fields("else", nib(w, 1) == 1))); + } else if (t == 0x3) { + if (nib(w, 1) == 0) { + ops.add(new Op("loop", r.take(2), fields("start", true, "reg", nib(w, 3)))); + } else { + ops.add(new Op("loop", r.take(1), fields("start", false, "reg", nib(w, 3)))); + } + } else if (t == 0x4) { + long[] ws = r.take(3); + ops.add(new Op("load-const", ws, fields("reg", nib(w, 3), "value", ws[1] << 32 | ws[2]))); + } else if (t == 0x5) { + long[] ws = r.take(2); + ops.add(new Op("load-mem", ws, fields("width", nib(w, 1), "mem", nib(w, 2), "reg", nib(w, 3), + "from", nib(w, 4), "oreg", nib(w, 5), "offset", (w & 0xFF) << 32 | ws[1]))); + } else if (t == 0x6) { + long[] ws = r.take(3); + ops.add(new Op("store-reg-imm", ws, fields("width", nib(w, 1), "reg", nib(w, 3), "inc", nib(w, 4), + "use_oreg", nib(w, 5), "oreg", nib(w, 6), "value", ws[1] << 32 | ws[2]))); + } else if (t == 0x7) { + long[] ws = r.take(2); + ops.add(new Op("arith", ws, fields("width", nib(w, 1), "reg", nib(w, 3), "op", nib(w, 4), + "value", ws[1]))); + } else if (t == 0x8) { + ops.add(new Op("keys", r.take(1), fields("mask", w & 0x0FFFFFFF))); + } else if (t == 0x9) { + long width = nib(w, 1); + if (nib(w, 5) == 1) { + long[] ws = r.take(width == 8 ? 3 : 2); + long value = width == 8 ? ws[1] << 32 | ws[2] : ws[1]; + ops.add(new Op("arith-reg", ws, fields("width", width, "op", nib(w, 2), "dst", nib(w, 3), + "src", nib(w, 4), "imm", value))); + } else { + ops.add(new Op("arith-reg", r.take(1), fields("width", width, "op", nib(w, 2), "dst", nib(w, 3), + "src", nib(w, 4), "src2", nib(w, 6)))); + } + } else if (t == 0xA) { + long kind = nib(w, 5); + long[] ws = r.take(kind == 2 || kind == 4 || kind == 5 ? 2 : 1); + Long imm = ws.length == 2 ? (w & 0xF) << 32 | ws[1] : null; + ops.add(new Op("store-reg", ws, fields("width", nib(w, 1), "src", nib(w, 2), "reg", nib(w, 3), + "inc", nib(w, 4), "kind", kind, "mem", nib(w, 6), "oreg", nib(w, 7), "imm", imm))); + } else if (t == 0xC) { + long sub = nib(w, 1); + if (sub == 0) { + long kind = nib(w, 5); + int n; + if (kind == 0 || kind == 2) { + n = 2; + } else if (kind == 1 || kind == 3 || kind == 5) { + n = 1; + } else if (kind == 4) { + n = nib(w, 2) == 8 ? 3 : 2; + } else { + throw new Unclear("a register condition of an unknown kind"); + } + ops.add(new Op("reg-cond", r.take(n), fields())); + } else if (sub == 4) { + long[] ws = r.take(3); + ops.add(new Op("keys", ws, fields("mask", ws[1] << 32 | ws[2], "repeat", nib(w, 2)))); + } else if (sub == 1 || sub == 2 || sub == 3) { + ops.add(new Op(sub == 1 ? "save" : sub == 2 ? "save-mask" : "static-reg", r.take(1), fields())); + } else { + throw new Unclear(String.format("code type C%X", sub)); + } + } else if (t == 0xF) { + long sub = nib(w, 2); + if (nib(w, 1) != 0xF || (sub != 0 && sub != 1)) { + throw new Unclear(String.format("code type %03X", w >> 20)); + } + ops.add(new Op(sub == 0 ? "pause" : "resume", r.take(1), fields())); + } else { + throw new Unclear(String.format("code type %X", t)); + } + } + return ops; + } + + // What the opcodes do + + /** A place the code writes: a region of Appendix A and an offset, maybe followed by a pointer path. */ + static final class Place { + final String region; + final long offset; + final long[] path; + + Place(String region, long offset, long[] path) { + this.region = region; + this.offset = offset; + this.path = path; + } + + Place(String region, long offset) { + this(region, offset, null); + } + + boolean hasPath() { + return path != null && path.length > 0; + } + + Place plus(long n) { + if (hasPath()) { + long[] p = path.clone(); + p[p.length - 1] = p[p.length - 1] + n; + return new Place(region, offset, p); + } + return new Place(region, offset + n); + } + + Place read() { + long[] p = path == null ? new long[1] : Arrays.copyOf(path, path.length + 1); + return new Place(region, offset, p); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Place)) { + return false; + } + Place p = (Place) o; + return region.equals(p.region) && offset == p.offset + && (path == null ? p.path == null : p.path != null && Arrays.equals(path, p.path)); + } + + @Override + public int hashCode() { + return region.hashCode() * 31 + Long.valueOf(offset).hashCode() * 7 + (path == null ? 0 : Arrays.hashCode(path)); + } + } + + /** A plain store: width bytes of value at a place. */ + static final class Store { + final Place place; + final int width; + final long value; + + Store(Place place, int width, long value) { + this.place = place; + this.width = width; + this.value = value; + } + + /** The value's bytes, little-endian, width of them. */ + byte[] data() { + byte[] out = new byte[width]; + for (int i = 0; i < width && i < 8; i++) { + out[i] = (byte) (value >>> (8 * i)); + } + return out; + } + } + + /** A memory condition around the stores. */ + static final class Cond { + final Place place; + final int width; + final String op; + final long value; + + Cond(Place place, int width, String op, long value) { + this.place = place; + this.width = width; + this.op = op; + this.value = value; + } + + List key() { + return Arrays.asList(place, width, op, value); + } + } + + /** What an entry does. */ + static final class Derived { + List stores = new ArrayList<>(); + long keys; + Cond condition; + List released; // the stores of an else branch of the button block + final Set reads = new HashSet<>(); // registers read before the entry wrote them + final Set writes = new HashSet<>(); // registers the entry writes + } + + /** What the entry does, as plain stores. */ + static Derived derive(Entry entry) throws Unclear { + return derive(entry.wordsShared()); + } + + static Derived derive(long[] words) throws Unclear { + List ops = decode(words); + Derived out = new Derived(); + List body = new ArrayList<>(ops); + if (!body.isEmpty() && body.get(0).kind.equals("keys")) { + if (body.get(0).get("repeat") != 0) { + throw new Unclear("a button block that repeats"); + } + out.keys = body.get(0).get("mask"); + body = new ArrayList<>(body.subList(1, body.size())); + if (body.isEmpty() || !body.get(body.size() - 1).kind.equals("end-cond")) { + throw new Unclear("a button block that does not end"); + } + body = new ArrayList<>(body.subList(0, body.size() - 1)); + int elseAt = -1; + for (int i = 0; i < body.size(); i++) { + Op op = body.get(i); + if (op.kind.equals("end-cond") && op.get("else") != 0 && depth(body.subList(0, i)) == 0) { + elseAt = i; + break; + } + } + if (elseAt >= 0) { + out.released = plain(body.subList(elseAt + 1, body.size()), out); + body = new ArrayList<>(body.subList(0, elseAt)); + } + } + if (!body.isEmpty() && body.get(0).kind.equals("begin-cond")) { + Op c = body.get(0); + if (c.get("use_reg") != 0 || c.get("mem") >= REGIONS.length || !CONDITIONS.containsKey((int) c.get("cond"))) { + throw new Unclear("a memory condition through a register"); + } + Op last = body.get(body.size() - 1); + if (!last.kind.equals("end-cond") || last.get("else") != 0) { + throw new Unclear("a memory condition that does not end plainly"); + } + out.condition = new Cond(new Place(REGIONS[(int) c.get("mem")], c.get("offset")), (int) c.get("width"), + CONDITIONS.get((int) c.get("cond")), c.get("value")); + body = new ArrayList<>(body.subList(1, body.size() - 1)); + } + out.stores = plain(body, out); + if (out.released != null) { + if (out.condition != null) { + throw new Unclear("a button block with an else branch and a condition"); + } + Set held = new HashSet<>(); + for (Store s : out.stores) { + for (int i = 0; i < s.width; i++) { + held.add(s.place.plus(i)); + } + } + for (Store s : out.released) { + for (int i = 0; i < s.width; i++) { + if (!held.contains(s.place.plus(i))) { + throw new Unclear("an else branch that writes places the button block does not"); + } + } + } + } + return out; + } + + private static int depth(List ops) { + int d = 0; + for (Op op : ops) { + if (op.kind.equals("begin-cond") || op.kind.equals("keys") || op.kind.equals("reg-cond")) { + d++; + } else if (op.kind.equals("end-cond") && op.get("else") == 0) { + d--; + } + } + return d; + } + + /** A register's value: a constant, or a place. */ + private static final class Val { + final Place place; + final long n; + + Val(Place place, long n) { + this.place = place; + this.n = n; + } + + static Val constant(long n) { + return new Val(null, n); + } + + boolean isConst() { + return place == null; + } + } + + /** The registers of one run of opcodes. */ + private static final class Regs { + final Map regs = new HashMap<>(); + final Derived out; + + Regs(Derived out) { + this.out = out; + } + + Val get(long r) { + if (!regs.containsKey(r)) { + if (!out.writes.contains(r)) { + out.reads.add(r); + } + return Val.constant(0); + } + return regs.get(r); + } + + void put(long r, Val v) { + regs.put(r, v); + out.writes.add(r); + } + } + + private static String region(long mem) { + return mem >= 0 && mem < REGIONS.length ? REGIONS[(int) mem] : null; + } + + /** The stores of a sequence of opcodes without blocks, following the registers. */ + private static List plain(List ops, Derived out) throws Unclear { + Regs regs = new Regs(out); + List stores = new ArrayList<>(); + for (Op op : ops) { + switch (op.kind) { + case "store": { + Val base = regs.get(op.get("reg")); + if (!base.isConst() || region(op.get("mem")) == null) { + throw new Unclear("a store whose offset register holds an address"); + } + stores.add(new Store(new Place(region(op.get("mem")), op.get("offset") + base.n), + (int) op.get("width"), op.get("value"))); + break; + } + case "load-const": + regs.put(op.get("reg"), Val.constant(op.get("value"))); + break; + case "load-mem": { + if (op.get("width") != 8) { + throw new Unclear("a load of a value that is not a pointer"); + } + if (op.get("from") == 0) { + if (region(op.get("mem")) == null) { + throw new Unclear("a load from an unknown region"); + } + regs.put(op.get("reg"), new Val(new Place(region(op.get("mem")), op.get("offset")).read(), 0)); + } else if (op.get("from") == 1) { + Val src = regs.get(op.get("reg")); + if (src.isConst()) { + throw new Unclear("a load from an address the code computed"); + } + regs.put(op.get("reg"), new Val(src.place.plus(op.get("offset")).read(), 0)); + } else { + throw new Unclear("a load through an offset register"); + } + break; + } + case "arith": { + long o = op.get("op"); + if (o != 0 && o != 1) { + throw new Unclear("arithmetic other than adding or subtracting"); + } + regs.put(op.get("reg"), add(regs.get(op.get("reg")), o == 0 ? op.get("value") : -op.get("value"))); + break; + } + case "arith-reg": { + Val src = regs.get(op.get("src")); + Val other = op.f.containsKey("imm") ? Val.constant(op.get("imm")) : regs.get(op.get("src2")); + long o = op.get("op"); + if (o == 9) { + regs.put(op.get("dst"), src); + } else if ((o == 0 || o == 1) && other.isConst()) { + regs.put(op.get("dst"), add(src, o == 0 ? other.n : -other.n)); + } else if (o == 0 && src.isConst()) { + regs.put(op.get("dst"), add(other, src.n)); + } else { + throw new Unclear("arithmetic on registers that the core operations cannot say"); + } + break; + } + case "store-reg-imm": { + Val target = regs.get(op.get("reg")); + if (op.get("use_oreg") != 0) { + target = add(target, constant(regs.get(op.get("oreg")))); + } + if (target.isConst()) { + throw new Unclear("a store to an address the code computed"); + } + if (!isWidth(op.get("width"))) { + throw new Unclear("a store of width " + op.get("width")); + } + stores.add(new Store(target.place, (int) op.get("width"), op.get("value"))); + if (op.get("inc") != 0) { + regs.put(op.get("reg"), add(regs.get(op.get("reg")), op.get("width"))); + } + break; + } + case "store-reg": { + Val value = regs.get(op.get("src")); + if (!value.isConst()) { + throw new Unclear("a store of a value the code computed"); + } + long k = op.get("kind"); + Val target; + if (k == 0) { + target = regs.get(op.get("reg")); + } else if (k == 1) { + target = add(regs.get(op.get("reg")), constant(regs.get(op.get("oreg")))); + } else if (k == 2) { + target = add(regs.get(op.get("reg")), op.get("imm")); + } else if ((k == 3 || k == 4 || k == 5) && region(op.get("mem")) != null) { + long off = (k == 3 || k == 5 ? constant(regs.get(op.get("oreg"))) : 0) + op.get("imm"); + target = new Val(new Place(region(op.get("mem")), off), 0); + } else { + throw new Unclear("a register store of an unknown kind"); + } + if (target.isConst()) { + throw new Unclear("a store to an address the code computed"); + } + if (!isWidth(op.get("width"))) { + throw new Unclear("a store of width " + op.get("width")); + } + stores.add(new Store(target.place, (int) op.get("width"), value.n)); + if (op.get("inc") != 0) { + regs.put(op.get("reg"), add(regs.get(op.get("reg")), op.get("width"))); + } + break; + } + default: + throw new Unclear(unclearKind(op.kind)); + } + } + return stores; + } + + private static String unclearKind(String kind) { + switch (kind) { + case "begin-cond": + return "a memory condition inside the code"; + case "end-cond": + return "a block inside the code"; + case "keys": + return "a button block inside the code"; + case "loop": + return "a loop"; + case "reg-cond": + return "a register condition"; + case "save": + case "save-mask": + return "saved registers"; + case "static-reg": + return "static registers"; + case "pause": + case "resume": + return "pausing the game"; + default: + return kind; + } + } + + private static long constant(Val v) throws Unclear { + if (!v.isConst()) { + throw new Unclear("an offset register that holds an address"); + } + return v.n; + } + + private static Val add(Val v, long n) { + if (v.isConst()) { + return Val.constant(v.n + n); + } + return new Val(v.place.plus(n), 0); + } + + /** Returns the buttons of a key mask joined by "+", or null when the mask is empty or has a bit without a name. */ + public static String keysToButtons(long mask) { + List names = new ArrayList<>(); + long sum = 0; + for (int i = 0; i < KEY_NAMES.length; i++) { + if ((mask & keyBit(i)) != 0) { + names.add(KEY_NAMES[i]); + sum += keyBit(i); + } + } + if (names.isEmpty() || sum != mask) { + return null; + } + return String.join("+", names); + } + + /** + * Returns the key mask of buttons joined by "+". + * + * @throws IllegalArgumentException for a button that has no Atmosphère key + */ + public static long buttonsToKeys(String text) { + try { + return keyMask(text); + } catch (Unclear u) { + throw new IllegalArgumentException(u.why); + } + } + + /** The key mask of buttons joined by "+"; Unclear for a name without an Atmosphère bit. */ + static long keyMask(String text) throws Unclear { + List names = Py.split(text, '+'); + for (String name : names) { + if (!Arrays.asList(KEY_NAMES).contains(name)) { + throw new Unclear("the buttons " + text + " have no Atmosph\u00E8re key mask"); + } + } + long mask = 0; + for (String name : names) { + mask += keyBit(Arrays.asList(KEY_NAMES).indexOf(name)); + } + return mask; + } + + /** Whether an entry has no code, or only ends of blocks: a heading such as [--- Items ---]. */ + static boolean isNoop(Entry entry) { + try { + for (Op op : decode(entry.wordsShared())) { + if (!op.kind.equals("end-cond")) { + return false; + } + } + return true; + } catch (Unclear u) { + return false; + } + } + + // Writing + + private static void valueWords(List words, int width, long value) { + if (width == 8) { + words.add((value >>> 32) & 0xFFFFFFFFL); + } + words.add(value & 0xFFFFFFFFL); + } + + /** The opcodes that write value at a place: a type 0 store, or for a pointer path the loads and a type 6 store. */ + static List storeWords(Place place, int width, long value) throws Unclear { + if ((place.offset >>> 40) != 0) { + throw new Unclear("an offset beyond the 40 bits of a store"); + } + long region = regionCode(place.region); + List words = new ArrayList<>(); + if (!place.hasPath()) { + words.add((long) width << 24 | region << 20 | (place.offset >>> 32) & 0xFF); + words.add(place.offset & 0xFFFFFFFFL); + valueWords(words, width, value); + return words; + } + long reg = 0xF; + words.add(0x58000000L | region << 20 | reg << 16 | (place.offset >>> 32) & 0xFF); + words.add(place.offset & 0xFFFFFFFFL); + long[] path = place.path; + for (int i = 0; i < path.length - 1; i++) { + words.addAll(addWords(reg, path[i], true)); + } + long last = path[path.length - 1]; + if (last != 0) { + words.addAll(addWords(reg, last, false)); + } + words.add(0x60000000L | (long) width << 24 | reg << 16); + words.add((value >>> 32) & 0xFFFFFFFFL); + words.add(value & 0xFFFFFFFFL); + return words; + } + + /** The opcodes that add a path step to the register, and with thenLoad read the pointer there. */ + private static List addWords(long reg, long step, boolean thenLoad) { + long signed = step; + List words = new ArrayList<>(); + if (thenLoad && signed >= 0 && signed < (1L << 40)) { + words.add(0x58001000L | reg << 16 | (signed >> 32) & 0xFF); + words.add(signed & 0xFFFFFFFFL); + return words; + } + long magnitude = Math.abs(signed); // Long.MIN_VALUE stays negative: a 64-bit add below + if (magnitude > 0 && magnitude < (1L << 32)) { + long op = signed > 0 ? 0 : 1; + words.add(0x78000000L | reg << 16 | op << 12); + words.add(magnitude); + } else if (signed != 0) { // a 64-bit add: type 9, register plus a value + words.add(0x98000100L | reg << 16 | reg << 12); + words.add((step >>> 32) & 0xFFFFFFFFL); + words.add(step & 0xFFFFFFFFL); + } + if (thenLoad) { + words.add(0x58001000L | reg << 16); + words.add(0L); + } + return words; + } + + /** The opcodes of a memory condition. */ + static List conditionWords(Place place, int width, String op, long value) throws Unclear { + if ((place.offset >>> 40) != 0) { + throw new Unclear("an offset beyond the 40 bits of a condition"); + } + long region = regionCode(place.region); + List words = new ArrayList<>(); + words.add(0x10000000L | (long) width << 24 | region << 20 | (long) CONDITION_CODES.get(op) << 16 + | (place.offset >>> 32) & 0xFF); + words.add(place.offset & 0xFFFFFFFFL); + valueWords(words, width, value); + return words; + } + + /** Code lines: one opcode per line, as cheat files write them. */ + static List formatWords(List words) throws Unclear { + long[] w = new long[words.size()]; + for (int i = 0; i < w.length; i++) { + w[i] = words.get(i); + } + List lines = new ArrayList<>(); + for (Op op : decode(w)) { + StringBuilder b = new StringBuilder(); + for (long x : op.words) { + if (b.length() > 0) { + b.append(' '); + } + b.append(String.format("%08X", x)); + } + lines.add(b.toString()); + } + return lines; + } + + /** One entry to write: its name, whether it is the master entry, and its code lines. */ + static final class Out { + final String name; + final boolean master; + final List lines; + + Out(String name, boolean master, List lines) { + this.name = name; + this.master = master; + this.lines = lines; + } + } + + /** The text of an Atmosphère cheat file. */ + static String writeFile(List entries) { + List out = new ArrayList<>(); + for (Out e : entries) { + out.add(e.master ? "{" + e.name + "}" : "[" + e.name + "]"); + out.addAll(e.lines); + out.add(""); + } + return String.join("\n", out); + } + + /** + * The registers an entry may write, for an entry that derive cannot read: all of them when + * its opcodes are not even known. + */ + static Set registersWritten(Entry entry) { + Set all = new LinkedHashSet<>(); + for (long r = 0; r < 16; r++) { + all.add(r); + } + List ops; + try { + ops = decode(entry.wordsShared()); + } catch (Unclear u) { + return all; + } + Set regs = new LinkedHashSet<>(); + for (Op op : ops) { + if (op.kind.equals("load-const") || op.kind.equals("load-mem") || op.kind.equals("arith") + || (op.kind.equals("loop") && op.get("start") != 0)) { + regs.add(op.get("reg")); + } else if (op.kind.equals("arith-reg")) { + regs.add(op.get("dst")); + } else if ((op.kind.equals("store-reg-imm") || op.kind.equals("store-reg")) && op.get("inc") != 0) { + regs.add(op.get("reg")); + } else if (op.kind.equals("save") || op.kind.equals("save-mask") || op.kind.equals("static-reg")) { + return all; + } + } + return regs; + } + + /** The offsets of every plain store into the main module in an entry, whatever blocks are around them. */ + static Set mainOffsets(Entry entry) { + Set out = new HashSet<>(); + try { + for (Op op : decode(entry.wordsShared())) { + if (op.kind.equals("store") && op.get("mem") == 0) { + out.add(op.get("offset")); + } + } + } catch (Unclear u) { + return new HashSet<>(); + } + return out; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/AtmosphereException.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/AtmosphereException.java new file mode 100644 index 00000000..f66b4d2e --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/AtmosphereException.java @@ -0,0 +1,15 @@ +package io.github.davdxpx.mistel.mncf; + +/** + * A file that is not an Atmosphère cheat file, or that holds no cheat with code. Its code is + * "atmosphere". + */ +public final class AtmosphereException extends ConvertException { + + private static final long serialVersionUID = 1L; + + /** Makes an exception with a message for people. */ + public AtmosphereException(String message) { + super("atmosphere", message); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Build.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Build.java new file mode 100644 index 00000000..c1cba799 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Build.java @@ -0,0 +1,34 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** One build of the game that a file knows (section 5). Immutable. */ +public final class Build { + + private final String key; + private final String version; + private final Map modules; + + Build(String key, String version, Map modules) { + this.key = key; + this.version = version; + this.modules = Collections.unmodifiableMap(new LinkedHashMap<>(modules)); + } + + /** Returns the key of the build in the file's builds table. */ + public String key() { + return key; + } + + /** Returns the version name shown to players; the key when the file gives none. */ + public String version() { + return version; + } + + /** Returns the identity of each module of the build, by module name, in file order. */ + public Map modules() { + return modules; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Change.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Change.java new file mode 100644 index 00000000..ab6f54c0 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Change.java @@ -0,0 +1,151 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * One change of a pass (section 11.5), as {@link Engine#tick} gives it. Fields that do not + * apply to the kind are null. Immutable. + * + *
      + *
    • {@code patch} and {@code restore} write {@link #bytes()} into code at {@link #address()}; + *
    • {@code hook} makes the function at the address do {@link #action()}, returning + * {@link #value()} for "return", and {@code unhook} lets it run as it was; + *
    • {@code write} writes the bytes into guest memory for {@link #cheat()}; + *
    • {@code raw} runs the cheat's raw entry ({@link #syntax()}, {@link #build()}, + * {@link #code()}) once. + *
    + */ +public final class Change { + + /** Write bytes into code. */ + public static final String PATCH = "patch"; + /** Put original bytes back into code. */ + public static final String RESTORE = "restore"; + /** Make a function return at once, with a value or without. */ + public static final String HOOK = "hook"; + /** Let a hooked function run as it was. */ + public static final String UNHOOK = "unhook"; + /** Write bytes into guest memory. */ + public static final String WRITE = "write"; + /** Run a raw entry once. */ + public static final String RAW = "raw"; + + private final String kind; + private final Long address; + private final byte[] bytes; + private final String cheat; + private final String action; + private final Object value; + private final String syntax; + private final String build; + private final String code; + + private Change(String kind, Long address, byte[] bytes, String cheat, String action, Object value, + String syntax, String build, String code) { + this.kind = kind; + this.address = address; + this.bytes = bytes == null ? null : bytes.clone(); + this.cheat = cheat; + this.action = action; + this.value = value; + this.syntax = syntax; + this.build = build; + this.code = code; + } + + static Change code(String kind, long address, byte[] bytes) { + return new Change(kind, address, bytes, null, null, null, null, null, null); + } + + static Change hook(long address, String action, Object value) { + return new Change(HOOK, address, null, null, action, value, null, null, null); + } + + static Change unhook(long address) { + return new Change(UNHOOK, address, null, null, null, null, null, null, null); + } + + static Change write(String cheat, long address, byte[] bytes) { + return new Change(WRITE, address, bytes, cheat, null, null, null, null, null); + } + + static Change raw(String cheat, Model.Raw r) { + return new Change(RAW, null, null, cheat, null, null, r.syntax, r.build, r.code); + } + + /** Returns patch, restore, hook, unhook, write or raw. */ + public String kind() { + return kind; + } + + /** Returns the address, an unsigned 64-bit number, or null for raw. */ + public Long address() { + return address; + } + + /** Returns a copy of the bytes to write, or null for hook, unhook and raw. */ + public byte[] bytes() { + return bytes == null ? null : bytes.clone(); + } + + /** Returns the cheat a write or raw entry is for, or null. */ + public String cheat() { + return cheat; + } + + /** Returns the action of a hook, return or skip, or null. */ + public String action() { + return action; + } + + /** Returns the whole number a hooked function returns, or null. */ + public Object value() { + return value; + } + + /** Returns the syntax of a raw entry, or null. */ + public String syntax() { + return syntax; + } + + /** Returns the build of a raw entry, or null. */ + public String build() { + return build; + } + + /** Returns the code of a raw entry, or null. */ + public String code() { + return code; + } + + /** + * Returns the fields that are set, by name, as the conformance suite writes them: bytes as + * upper-case hexadecimal pairs, the address as a number that is never negative. + */ + public Map toMap() { + Map out = new LinkedHashMap<>(); + out.put("kind", kind); + put(out, "address", address == null ? null : Values.unsigned(address)); + put(out, "bytes", bytes == null ? null : Values.hexBytes(bytes)); + put(out, "cheat", cheat); + put(out, "action", action); + put(out, "value", value); + put(out, "syntax", syntax); + put(out, "build", build); + put(out, "code", code); + return Collections.unmodifiableMap(out); + } + + private static void put(Map out, String key, Object v) { + if (v != null) { + out.put(key, v); + } + } + + @Override + public String toString() { + return toMap().toString(); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Cheat.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Cheat.java new file mode 100644 index 00000000..c81e1d7e --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Cheat.java @@ -0,0 +1,229 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * One cheat of a file, as it was read and checked (sections 7 to 9). Immutable. + * + *

    When {@link #problem()} is not null, the cheat breaks a rule of the format and is refused + * whatever the runtime; its fields after the one that broke the rule keep their defaults. + */ +public final class Cheat { + + private final int index; + private final String id; + private final Map table; + private final String problem; + private final String name; + private final String about; + private final String group; + private final List tags; + private final boolean defaultOn; + private final boolean master; + private final String run; + private final Number duration; + private final String hold; + private final String toggle; + private final String press; + private final List requires; + private final List excludes; + private final String radio; + private final String match; + private final String trigger; + private final long interval; + private final Map values; + private final List ops; + private final List coreOps; + private final List raw; + + /** The fields of a cheat while the schema fills them in. */ + static final class Draft { + int index; + String id; + Map table; + String problem; + String name; + String about; + String group; + List tags = new ArrayList<>(); + boolean defaultOn; + boolean master; + String run = "on"; + Number duration; + String hold; + String toggle; + String press; + List requires = new ArrayList<>(); + List excludes = new ArrayList<>(); + String radio; + String match = "all"; + String trigger = "while"; + long interval = 1; + Map values = new LinkedHashMap<>(); + List ops = new ArrayList<>(); + List raw = new ArrayList<>(); + } + + Cheat(Draft d) { + index = d.index; + id = d.id; + table = d.table; + problem = d.problem; + name = d.name; + about = d.about; + group = d.group; + tags = Collections.unmodifiableList(new ArrayList<>(d.tags)); + defaultOn = d.defaultOn; + master = d.master; + run = d.run; + duration = d.duration; + hold = d.hold; + toggle = d.toggle; + press = d.press; + requires = Collections.unmodifiableList(new ArrayList<>(d.requires)); + excludes = Collections.unmodifiableList(new ArrayList<>(d.excludes)); + radio = d.radio; + match = d.match; + trigger = d.trigger; + interval = d.interval; + values = Collections.unmodifiableMap(new LinkedHashMap<>(d.values)); + ops = Collections.unmodifiableList(new ArrayList<>(d.ops)); + List core = new ArrayList<>(); + for (Model.Op op : d.ops) { + if (!(op instanceof Model.Condition)) { + core.add(op); + } + } + coreOps = Collections.unmodifiableList(core); + raw = Collections.unmodifiableList(new ArrayList<>(d.raw)); + } + + /** Returns the position of the cheat in the file, counted from 0. */ + public int index() { + return index; + } + + /** Returns the cheat's id. */ + public String id() { + return id; + } + + /** Returns the cheat's table as the file wrote it, unmodifiable. */ + public Map table() { + return table; + } + + /** + * Returns why the cheat is refused whatever the runtime, or null: unknown-key:<key>, + * extension-missing:<name>, invalid:<key> or invalid. + */ + public String problem() { + return problem; + } + + /** Returns the name shown to players. */ + public String name() { + return name; + } + + /** Returns the description, or null. */ + public String about() { + return about; + } + + /** Returns the group path such as "Items/Money", or null. */ + public String group() { + return group; + } + + /** Returns the tags, such as touches_save. */ + public List tags() { + return tags; + } + + /** Returns whether the cheat is on unless the player switches it off. */ + public boolean isDefault() { + return defaultOn; + } + + /** Returns whether this is a master cheat, on only while a cheat that needs it is on. */ + public boolean isMaster() { + return master; + } + + /** Returns how the cheat runs: on, once, action, timed or monitor. */ + public String run() { + return run; + } + + /** Returns the seconds a timed cheat runs, or null. */ + public Number duration() { + return duration; + } + + /** Returns the buttons to hold, joined by "+", or null. */ + public String hold() { + return hold; + } + + /** Returns the buttons that switch the cheat, joined by "+", or null. */ + public String toggle() { + return toggle; + } + + /** Returns the buttons that start an action, joined by "+", or null. */ + public String press() { + return press; + } + + /** Returns the ids of the cheats this one needs. */ + public List requires() { + return requires; + } + + /** Returns the ids of the cheats that cannot be on with this one. */ + public List excludes() { + return excludes; + } + + /** Returns the radio group, in which only one cheat can be on, or null. */ + public String radio() { + return radio; + } + + /** Returns how conditions combine: all or any. */ + public String match() { + return match; + } + + /** Returns when conditions fire: while or enter. */ + public String trigger() { + return trigger; + } + + /** Returns every how many frames the cheat runs. */ + public long interval() { + return interval; + } + + /** Returns the values the player sets, by id, in file order. */ + public Map values() { + return values; + } + + List ops() { + return ops; + } + + List coreOps() { + return coreOps; + } + + List raw() { + return raw; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CheatReport.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CheatReport.java new file mode 100644 index 00000000..75f2388e --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CheatReport.java @@ -0,0 +1,88 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** What the converter made of one entry of one cheat file. Immutable. */ +public final class CheatReport { + + /** The cheat finds its places by patterns, so it fits other builds too. */ + public static final String PATTERN = "pattern"; + /** The cheat has core operations with offsets for this build. */ + public static final String BUILD = "build"; + /** The cheat keeps only its raw code; {@link #why()} says why. */ + public static final String RAW = "raw"; + /** The entry only puts back the original code, so it became no cheat. */ + public static final String RESTORE = "restore"; + /** The entry's code mixes words with other text, so it became no cheat; {@link #why()} names the lines. */ + public static final String UNREADABLE = "unreadable"; + + private final String id; + private final String name; + private final String build; + private final String outcome; + private final String why; + private final int patterns; + private final int fixed; + private final int values; + private final List notes; + + CheatReport(String id, String name, String build, String outcome, String why, int patterns, int fixed, int values, + List notes) { + this.id = id; + this.name = name; + this.build = build; + this.outcome = outcome; + this.why = why; + this.patterns = patterns; + this.fixed = fixed; + this.values = values; + this.notes = Collections.unmodifiableList(new ArrayList<>(notes)); + } + + /** Returns the id of the cheat in the new file, or empty text when the entry became no cheat. */ + public String id() { + return id; + } + + /** Returns the entry's name. */ + public String name() { + return name; + } + + /** Returns the key of the build the entry is for. */ + public String build() { + return build; + } + + /** Returns pattern, build, raw or restore. */ + public String outcome() { + return outcome; + } + + /** Returns why the cheat keeps only raw code or became no cheat; empty otherwise. */ + public String why() { + return why; + } + + /** Returns how many operations find their place by a pattern. */ + public int patterns() { + return patterns; + } + + /** Returns how many operations keep offsets for this build. */ + public int fixed() { + return fixed; + } + + /** Returns how many values the player sets the cheat got. */ + public int values() { + return values; + } + + /** Returns notes on single places. */ + public List notes() { + return notes; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CheatResult.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CheatResult.java new file mode 100644 index 00000000..b7b01fec --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CheatResult.java @@ -0,0 +1,65 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** What a cheat does in one runtime: its state, the reason, and its resolved operations. Immutable. */ +public final class CheatResult { + + /** The cheat is not switched on. */ + public static final String OFF = "off"; + /** The cheat is on and its operations apply. */ + public static final String ON = "on"; + /** The cheat is on but waits: for held buttons, or for a pointer path that cannot be followed yet. */ + public static final String WAITING = "waiting"; + /** The cheat cannot be used here; the reason says why. */ + public static final String REFUSED = "refused"; + + private final String id; + private final String state; + private final String reason; + private final String uses; + private final List ops; + + CheatResult(String id, String state, String reason, String uses, List ops) { + this.id = id; + this.state = state; + this.reason = reason; + this.uses = uses; + this.ops = Collections.unmodifiableList(new ArrayList<>(ops)); + } + + /** Returns the cheat's id. */ + public String id() { + return id; + } + + /** Returns off, on, waiting or refused. */ + public String state() { + return state; + } + + /** + * Returns why the cheat is refused or waits, such as capability-missing:code-hook or + * path-broken; empty when there is no reason. + */ + public String reason() { + return reason; + } + + /** Returns core when the cheat's own operations apply, raw when its raw code does, or empty when refused. */ + public String uses() { + return uses; + } + + /** Returns the resolved operations, in file order, or a single raw operation. Empty when refused. */ + public List ops() { + return ops; + } + + @Override + public String toString() { + return id + ": " + state + (reason.isEmpty() ? "" : " (" + reason + ")"); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CheatState.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CheatState.java new file mode 100644 index 00000000..0c4558d2 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CheatState.java @@ -0,0 +1,38 @@ +package io.github.davdxpx.mistel.mncf; + +/** A cheat's state between passes or after one, as the {@link Engine} gives it. Immutable. */ +public final class CheatState { + + private final String id; + private final String state; + private final String reason; + + CheatState(String id, String state, String reason) { + this.id = id; + this.state = state; + this.reason = reason; + } + + /** Returns the cheat's id. */ + public String id() { + return id; + } + + /** Returns off, on, waiting or refused, as {@link CheatResult} names them. */ + public String state() { + return state; + } + + /** + * Returns the reason: why the cheat is refused or waits, done for a cheat that switched + * itself off, or empty. + */ + public String reason() { + return reason; + } + + @Override + public String toString() { + return id + ": " + state + (reason.isEmpty() ? "" : " (" + reason + ")"); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Choices.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Choices.java new file mode 100644 index 00000000..d72682fd --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Choices.java @@ -0,0 +1,131 @@ +package io.github.davdxpx.mistel.mncf; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * What the player chose: cheats switched on or off against their default, and values by + * "cheat.value". Immutable once built. + * + *

    A value is a {@link Long} (or a smaller whole number type, which becomes a Long), a + * {@link BigInteger}, a {@link Double} or {@link Float}, or a {@link Boolean}. A chosen value + * that the player cannot choose refuses its cheat with value-out-of-range: one of another kind + * (a Boolean is the only value of type bool, a whole number the only value of an integer type), + * NaN, one too wide for its type, one outside min and max, or one that is not among the choices. + */ +public final class Choices { + + private static final Choices NONE = new Builder().build(); + + private final List on; + private final List off; + private final Map values; + + private Choices(Builder b) { + on = Collections.unmodifiableList(new ArrayList<>(b.on)); + off = Collections.unmodifiableList(new ArrayList<>(b.off)); + values = Collections.unmodifiableMap(new LinkedHashMap<>(b.values)); + } + + /** Returns choices that change nothing: every cheat as its default, every value its default. */ + public static Choices none() { + return NONE; + } + + /** Starts a set of choices. */ + public static Builder builder() { + return new Builder(); + } + + /** Builds {@link Choices}. */ + public static final class Builder { + private final List on = new ArrayList<>(); + private final List off = new ArrayList<>(); + private final Map values = new LinkedHashMap<>(); + + private Builder() { + } + + /** Switches cheats on. */ + public Builder on(String... ids) { + return on(Arrays.asList(ids)); + } + + /** Switches cheats on. */ + public Builder on(Collection ids) { + on.addAll(ids); + return this; + } + + /** Switches cheats off that are on by default. */ + public Builder off(String... ids) { + return off(Arrays.asList(ids)); + } + + /** Switches cheats off that are on by default. */ + public Builder off(Collection ids) { + off.addAll(ids); + return this; + } + + /** + * Sets a value the player chose. + * + * @param key the cheat's id and the value's id, joined by a dot: "money.count" + * @param value a whole number, a float or a Boolean + * @throws IllegalArgumentException for any other kind of value + */ + public Builder value(String key, Object value) { + values.put(key, number(value)); + return this; + } + + /** Sets a value the player chose from its 64 bits, read as an unsigned number (for u64). */ + public Builder unsignedValue(String key, long bits) { + values.put(key, Values.unsigned(bits)); + return this; + } + + /** Returns the choices. */ + public Choices build() { + return new Choices(this); + } + } + + static Object number(Object v) { + if (v instanceof Long || v instanceof Integer || v instanceof Short || v instanceof Byte) { + return ((Number) v).longValue(); + } + if (v instanceof BigInteger) { + return Values.normalize((BigInteger) v); + } + if (v instanceof Double || v instanceof Float) { + return ((Number) v).doubleValue(); + } + if (v instanceof Boolean) { + return v; + } + throw new IllegalArgumentException("a value is a whole number, a float or a Boolean, not " + v); + } + + /** Returns the ids of the cheats switched on. */ + public List on() { + return on; + } + + /** Returns the ids of the cheats switched off. */ + public List off() { + return off; + } + + /** Returns the values the player chose, by "cheat.value". */ + public Map values() { + return values; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CodeModule.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CodeModule.java new file mode 100644 index 00000000..10685321 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CodeModule.java @@ -0,0 +1,340 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * A code module for the converter: its image as loaded, its sections, its identity, and the runs + * of bytes that are not its own. Made from a Switch NSO file (with LZ4 segments or without) or + * from a plain image. Immutable. + * + *

    The excluded runs are bytes such as code a runtime rewrote: the converter takes no original + * bytes and no pattern from them. The module keeps the image array it is given without copying + * it; the caller must not change it afterwards. + */ +public final class CodeModule { + + private static final int PAGE = 0x1000; + private static final Pattern HEX = Pattern.compile("(0x)?([0-9A-Fa-f]{1,16})"); + + /** A run of bytes of a module: its offset and its length. */ + public static final class Run { + private final long offset; + private final long length; + + /** Makes a run; the offset and the length are unsigned 64-bit numbers. */ + public Run(long offset, long length) { + this.offset = offset; + this.length = length; + } + + /** Returns the offset of the run's first byte. */ + public long offset() { + return offset; + } + + /** Returns the number of bytes. */ + public long length() { + return length; + } + + @Override + public boolean equals(Object o) { + return o instanceof Run && ((Run) o).offset == offset && ((Run) o).length == length; + } + + @Override + public int hashCode() { + return Long.valueOf(offset).hashCode() * 31 + Long.valueOf(length).hashCode(); + } + + @Override + public String toString() { + return "(0x" + Long.toHexString(offset) + ", " + length + ")"; + } + } + + private final byte[] image; + private final Map sections; + private final String buildId; + private final Long textSize; + private final List exclude; + + /** + * Makes a module from its parts. + * + * @param image the module's bytes as loaded + * @param sections "code", "rodata" and "data" to their offsets from start up to but not + * including end, as arrays of two numbers, in the order the module has them + * @param buildId the Switch build ID in hexadecimal, or null + * @param textSize where the code itself ends, before the zero bytes up to the next page, or null + * @param exclude runs whose bytes are not the module's own, or null for none + */ + public CodeModule(byte[] image, Map sections, String buildId, Long textSize, List exclude) { + this.image = image; + Map copy = new LinkedHashMap<>(); + for (Map.Entry e : sections.entrySet()) { + copy.put(e.getKey(), new long[] {e.getValue()[0], e.getValue()[1]}); + } + this.sections = copy; + this.buildId = buildId; + this.textSize = textSize; + this.exclude = exclude == null ? Collections.emptyList() + : Collections.unmodifiableList(new ArrayList<>(exclude)); + } + + /** Returns the same module with other excluded runs. */ + public CodeModule withExclude(List runs) { + return new CodeModule(image, sections, buildId, textSize, runs); + } + + /** Returns the module's bytes as loaded; the array itself, which callers must not change. */ + public byte[] image() { + return image; + } + + /** Returns the names of the sections, in the module's order. */ + public List sectionNames() { + return Collections.unmodifiableList(new ArrayList<>(sections.keySet())); + } + + /** Returns the first offset of a section, or throws IllegalArgumentException when it has none of that name. */ + public long sectionStart(String name) { + return section(name)[0]; + } + + /** Returns the offset just after a section. */ + public long sectionEnd(String name) { + return section(name)[1]; + } + + private long[] section(String name) { + long[] r = sections.get(name); + if (r == null) { + throw new IllegalArgumentException("the module has no section " + name); + } + return r; + } + + /** Returns whether the module has a section of that name. */ + public boolean hasSection(String name) { + return sections.containsKey(name); + } + + /** Returns the Switch build ID in hexadecimal, or null. */ + public String buildId() { + return buildId; + } + + /** Returns where the code itself ends, or null when it is not known. */ + public Long textSize() { + return textSize; + } + + /** Returns the runs whose bytes are not the module's own. */ + public List exclude() { + return exclude; + } + + /** Returns the build ID as cheat files name it: its first 8 bytes, 16 upper-case hexadecimal digits. Or null. */ + public String shortId() { + if (buildId == null || buildId.isEmpty()) { + return null; + } + return buildId.substring(0, Math.min(16, buildId.length())).toUpperCase(Locale.ROOT); + } + + /** Returns the name of the first section that holds an offset, or null. */ + public String sectionOf(long offset) { + for (Map.Entry e : sections.entrySet()) { + if (e.getValue()[0] <= offset && offset < e.getValue()[1]) { + return e.getKey(); + } + } + return null; + } + + /** + * Returns whether any byte from offset on, length of them, lies in an excluded run. Offsets + * and lengths are unsigned 64-bit numbers. + */ + public boolean excluded(long offset, long length) { + for (Run r : exclude) { + if (belowSum(r.offset, offset, length) && belowSum(offset, r.offset, r.length)) { + return true; + } + } + return false; + } + + /** Whether x is below a + b, all unsigned, the sum taken without wrapping. */ + private static boolean belowSum(long x, long a, long b) { + long sum = a + b; + return Long.compareUnsigned(sum, a) < 0 || Long.compareUnsigned(x, sum) < 0; + } + + /** + * Returns the module as the evaluator reads it, loaded at a base address: named by its short + * build ID, or by the SHA-256 hash of its image when it has none. + */ + public Module toModule(long base) { + String id = shortId(); + if (id == null) { + StringBuilder b = new StringBuilder("sha256:"); + for (byte x : Signatures.sha256(image)) { + b.append(String.format("%02x", x & 0xFF)); + } + id = b.toString(); + } + Module.Builder m = Module.builder(id).base(base).image(image).size(image.length); + for (Map.Entry e : sections.entrySet()) { + m.section(e.getKey(), e.getValue()[0], e.getValue()[1]); + } + return m.build(); + } + + /** The module as the evaluator reads it at base 0, without an identity, for searching patterns. */ + Module toModuleWithoutId() { + Module.Builder m = Module.builder(null).image(image).size(image.length); + for (Map.Entry e : sections.entrySet()) { + m.section(e.getKey(), e.getValue()[0], e.getValue()[1]); + } + return m.build(); + } + + // Reading module files + + /** Returns the module the bytes of a file hold: an NSO, or else a plain image that is all code. */ + public static CodeModule fromBytes(byte[] data) throws CodeModuleException { + if (data.length >= 4 && data[0] == 'N' && data[1] == 'S' && data[2] == 'O' && data[3] == '0') { + return parseNso(data); + } + Map code = new LinkedHashMap<>(); + code.put("code", new long[] {0, data.length}); + return new CodeModule(data.clone(), code, null, null, null); + } + + private static long u32(byte[] b, int at) { + return (b[at] & 0xFFL) | (b[at + 1] & 0xFFL) << 8 | (b[at + 2] & 0xFFL) << 16 | (b[at + 3] & 0xFFL) << 24; + } + + private static long align(long n) { + return (n + PAGE - 1) & ~(long) (PAGE - 1); + } + + /** Returns the module an NSO file holds. */ + public static CodeModule parseNso(byte[] data) throws CodeModuleException { + if (data.length < 0x100 || data[0] != 'N' || data[1] != 'S' || data[2] != 'O' || data[3] != '0') { + throw new CodeModuleException("not an NSO file"); + } + long flags = u32(data, 0x0C); + long[] mems = new long[3]; + byte[][] segs = new byte[3][]; + for (int i = 0; i < 3; i++) { + int header = 0x10 + 0x10 * i; + long fileOff = u32(data, header); + long memOff = u32(data, header + 4); + long size = u32(data, header + 8); + long packed = u32(data, 0x60 + 4 * i); + boolean compressed = (flags & (1L << i)) != 0; + long stored = compressed ? packed : size; + if (fileOff + stored > data.length) { + throw new CodeModuleException("segment " + i + " lies past the end of the file"); + } + byte[] raw = java.util.Arrays.copyOfRange(data, (int) fileOff, (int) (fileOff + stored)); + if (compressed && size > Integer.MAX_VALUE - 8) { + throw new CodeModuleException("segment " + i + " is too large"); + } + mems[i] = memOff; + segs[i] = compressed ? Lz4.decompress(raw, (int) size) : raw; + } + long bss = u32(data, 0x3C); + if (!(mems[0] <= mems[1] && mems[1] <= mems[2])) { + throw new CodeModuleException("the segments are not in the order code, read-only data, data"); + } + long length = mems[2] + segs[2].length + bss; + if (length > Integer.MAX_VALUE - 8) { + throw new CodeModuleException("the module is too large"); + } + // Each segment goes in as Python's slice assignment puts it: a segment that runs past + // the end makes the image longer. + Bytes image = new Bytes((int) length); + for (int i = 0; i < 3; i++) { + image.assign(mems[i], segs[i]); + } + byte[] bytes = image.toArray(); + Map sections = new LinkedHashMap<>(); + sections.put("code", new long[] {mems[0], Math.min(align(mems[0] + segs[0].length), mems[1])}); + sections.put("rodata", new long[] {mems[1], Math.min(align(mems[1] + segs[1].length), mems[2])}); + sections.put("data", new long[] {mems[2], bytes.length}); + StringBuilder id = new StringBuilder(); + for (int i = 0x40; i < 0x60; i++) { + id.append(String.format("%02X", data[i] & 0xFF)); + } + return new CodeModule(bytes, sections, id.toString(), mems[0] + segs[0].length, null); + } + + /** A growable byte array with Python's slice assignment. */ + private static final class Bytes { + private byte[] buf; + private int size; + + Bytes(int size) { + this.buf = new byte[size]; + this.size = size; + } + + void assign(long at, byte[] seg) throws CodeModuleException { + int start = (int) Math.min(at, size); + int stop = (int) Math.min(at + seg.length, size); + long newSize = (long) size - (stop - start) + seg.length; + if (newSize > Integer.MAX_VALUE - 8) { + throw new CodeModuleException("the module is too large"); + } + byte[] out = newSize == size ? buf : new byte[(int) newSize]; + if (out != buf) { + System.arraycopy(buf, 0, out, 0, start); + System.arraycopy(buf, stop, out, start + seg.length, size - stop); + } + System.arraycopy(seg, 0, out, start, seg.length); + buf = out; + size = (int) newSize; + } + + byte[] toArray() { + return buf.length == size ? buf : java.util.Arrays.copyOf(buf, size); + } + } + + /** + * Returns runs from lines of two hexadecimal numbers separated by a tab, such as a list of + * the places a runtime rewrote: up to 16 digits each, maybe after 0x. Lines that are empty + * or start with # are skipped. + * + * @throws CodeModuleException for a line that is not an offset and a length + */ + public static List readRuns(String text) throws CodeModuleException { + List runs = new ArrayList<>(); + List lines = Py.splitLines(text); + for (int n = 1; n <= lines.size(); n++) { + String line = Py.strip(lines.get(n - 1)); + if (line.isEmpty() || line.startsWith("#")) { + continue; + } + List parts = Py.split(line, '\t'); + Matcher offset = parts.size() < 2 ? null : Py.match(HEX, Py.strip(parts.get(0))); + Matcher length = parts.size() < 2 ? null : Py.match(HEX, Py.strip(parts.get(1))); + if (offset == null || length == null) { + throw new CodeModuleException("line " + n + " is not an offset and a length"); + } + runs.add(new Run(Long.parseUnsignedLong(offset.group(2), 16), Long.parseUnsignedLong(length.group(2), 16))); + } + return runs; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CodeModuleException.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CodeModuleException.java new file mode 100644 index 00000000..530f5911 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/CodeModuleException.java @@ -0,0 +1,12 @@ +package io.github.davdxpx.mistel.mncf; + +/** The bytes of a code module, or a list of runs, cannot be read. */ +public class CodeModuleException extends Exception { + + private static final long serialVersionUID = 1L; + + /** Makes an exception with a message for people. */ + public CodeModuleException(String message) { + super(message); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Conversion.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Conversion.java new file mode 100644 index 00000000..c6e28012 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Conversion.java @@ -0,0 +1,32 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.Map; + +/** The result of converting cheat files: the new document, its text and the report. Immutable. */ +public final class Conversion { + + private final Map doc; + private final String text; + private final ConversionReport report; + + Conversion(Map doc, String text, ConversionReport report) { + this.doc = doc; + this.text = text; + this.report = report; + } + + /** Returns the new document as a map of TOML values, unmodifiable. */ + public Map doc() { + return doc; + } + + /** Returns the text of the new .mncf file. */ + public String text() { + return text; + } + + /** Returns what the converter made of each entry. */ + public ConversionReport report() { + return report; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ConversionReport.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ConversionReport.java new file mode 100644 index 00000000..2c9ef2a9 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ConversionReport.java @@ -0,0 +1,68 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * What the converter made of the cheat files: one report per entry, groups, credits, warnings, + * lines that are not code and entries that could not be read. Immutable. + */ +public final class ConversionReport { + + private final List cheats; + private final List groups; + private final List credits; + private final List warnings; + private final List notes; + private final List unreadable; + + ConversionReport(List cheats, List groups, List credits, List warnings, + List notes, List unreadable) { + this.cheats = Collections.unmodifiableList(new ArrayList<>(cheats)); + this.groups = Collections.unmodifiableList(new ArrayList<>(groups)); + this.credits = Collections.unmodifiableList(new ArrayList<>(credits)); + this.warnings = Collections.unmodifiableList(new ArrayList<>(warnings)); + this.notes = Collections.unmodifiableList(new ArrayList<>(notes)); + this.unreadable = Collections.unmodifiableList(new ArrayList<>(unreadable)); + } + + /** Returns a report for each entry with code, in the order of the files and their entries. */ + public List cheats() { + return cheats; + } + + /** Returns the names of the headings that became groups. */ + public List groups() { + return groups; + } + + /** Returns the entries that credit someone, as their names. */ + public List credits() { + return credits; + } + + /** Returns warnings, such as a module whose build ID is not the cheat file's. */ + public List warnings() { + return warnings; + } + + /** Returns the lines of the files that are neither names nor code, each once. */ + public List notes() { + return notes; + } + + /** Returns the names of the entries whose code mixes words with other text; they are left out. */ + public List unreadable() { + return unreadable; + } + + /** Returns the number of entries with this outcome. */ + public int count(String outcome) { + int n = 0; + for (CheatReport c : cheats) { + n += c.outcome().equals(outcome) ? 1 : 0; + } + return n; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ConvertException.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ConvertException.java new file mode 100644 index 00000000..c24062db --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ConvertException.java @@ -0,0 +1,30 @@ +package io.github.davdxpx.mistel.mncf; + +/** + * Cheat or patch files cannot become one .mncf file. {@link #code()} says why: "source" for + * sources that do not fit together, such as two files that name the same build, "patch" for a + * file that is no patch file ({@link PatchFileException}), or "atmosphere" for a file that is not + * an Atmosphère cheat file ({@link AtmosphereException}). + */ +public class ConvertException extends Exception { + + private static final long serialVersionUID = 1L; + + private final String code; + + /** Makes an exception with the code "source" and a message for people. */ + public ConvertException(String message) { + this("source", message); + } + + /** Makes an exception with a code and a message for people. */ + protected ConvertException(String code, String message) { + super(message); + this.code = code; + } + + /** Returns "source", "atmosphere" or "patch". */ + public String code() { + return code; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Converter.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Converter.java new file mode 100644 index 00000000..2ba8721a --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Converter.java @@ -0,0 +1,2171 @@ +package io.github.davdxpx.mistel.mncf; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Converts Atmosphère cheat files to .mncf, and .mncf back to Atmosphère for one build (section + * 15). + * + *

    Every cheat keeps its code as a raw/1 entry. Where the code is plain writes, it also gets + * core operations: a write into the main module's code becomes a patch, one into data or a + * region a write, a pointer chain a path, a button block hold, a memory condition when, a movz + * or fmov a value the player sets (arm64-imm/1). With the code module, patches get expect from + * it and a pattern instead of a fixed offset wherever the bytes mean the same at another place. + * Several files for builds of the same game become one file with all their builds. This + * library has no disassembler, so it writes no asm fields. + */ +public final class Converter { + + // The patterns have ASCII semantics, as Python's re.A gives them: \b, \w, \W and \s are + // written out, and so is matching ASCII letters in either case, because some regular + // expression engines fold the case of all of Unicode under CASE_INSENSITIVE. + private static final String WORD = "[A-Za-z0-9_]"; + private static final String NOT_WORD = "[^A-Za-z0-9_]"; + private static final String BOUND = "(?:(?<=" + WORD + ")(?!" + WORD + ")|(?|]"; + private static final Pattern DECORATION = Pattern.compile("^" + DECORATION_CHARS + "+|" + DECORATION_CHARS + "+" + END); + private static final Pattern NAME_END = Pattern.compile("[,!;|]"); + private static final Pattern NAME_SPLIT = Pattern.compile(SPACE + "+&" + SPACE + "+|" + SPACE + "+and" + SPACE + "+"); + private static final Pattern PLATFORM = Pattern.compile("([^\\n]+?)" + SPACE + "*(?:" + SPACE + "(?:" + + caseless("on|at|from") + ")" + SPACE + "|@|\\()" + SPACE + "*([^\\n]+?)\\)?"); + private static final Pattern SITE = Pattern.compile( + "(?:https?://)?(?:www\\.)?([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,})"); + private static final long[] GROUP_END = {0x20000001L}; + private static final Pattern EDIZON = Pattern.compile("^--" + SPACE + "*" + caseless("section") + SPACE + "*(" + + caseless("start|end") + ")" + SPACE + "*:" + SPACE + "*([^\\n]*?)" + SPACE + "*--" + END); + private static final Pattern NOT_A_NAME = Pattern.compile("(?:" + caseless("all credited|all credits?|everyone" + + "|everybody|unknown|anonymous|various|(the )?community|n/?a") + ")"); + + private Converter() { + } + + /** A pattern in which each ASCII letter matches in either case; an escaped character stays as it is. */ + private static String caseless(String pattern) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < pattern.length(); i++) { + char c = pattern.charAt(i); + if (c == '\\' && i + 1 < pattern.length()) { + b.append(c).append(pattern.charAt(++i)); + } else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { + b.append('[').append(Character.toLowerCase(c)).append(Character.toUpperCase(c)).append(']'); + } else { + b.append(c); + } + } + return b.toString(); + } + + /** What to write into a converted file besides the cheats. Immutable. */ + public static final class Options { + private final String gameId; + private String platform = "switch"; + private String gameName; + private String name; + private String origin; + private List authors; + private boolean values = true; + + private Options(String gameId) { + this.gameId = gameId; + } + + private Options copy() { + Options o = new Options(gameId); + o.platform = platform; + o.gameName = gameName; + o.name = name; + o.origin = origin; + o.authors = authors; + o.values = values; + return o; + } + + /** Starts options for a game: its ID on its platform. */ + public static Options forGame(String gameId) { + return new Options(gameId); + } + + /** Returns options with another platform; the default is "switch". */ + public Options platform(String p) { + Options o = copy(); + o.platform = p; + return o; + } + + /** Returns options with the game's name. */ + public Options gameName(String n) { + Options o = copy(); + o.gameName = n; + return o; + } + + /** Returns options with the file's name; the default is "<game name> cheats". */ + public Options name(String n) { + Options o = copy(); + o.name = n; + return o; + } + + /** Returns options with where the files came from, such as a ZIP or folder name. */ + public Options origin(String n) { + Options o = copy(); + o.origin = n; + return o; + } + + /** Returns options with the authors to name when the files credit nobody. */ + public Options authors(List names) { + Options o = copy(); + o.authors = names == null ? null : Collections.unmodifiableList(new ArrayList<>(names)); + return o; + } + + /** Returns options that turn movz and fmov patches into values the player sets, or not. The default is on. */ + public Options values(boolean on) { + Options o = copy(); + o.values = on; + return o; + } + } + + // Mutable state while converting + + private static final class Report { + final List cheats = new ArrayList<>(); + final List groups = new ArrayList<>(); + final List credits = new ArrayList<>(); + final List warnings = new ArrayList<>(); + final List notes = new ArrayList<>(); // lines of the sources that are neither names nor code + final List unreadable = new ArrayList<>(); // names of entries whose code could not be read + } + + private static final class Rep { + String id; + final String name; + final String build; + String outcome; + String why = ""; + int patterns; + int fixed; + int values; + List notes = new ArrayList<>(); + + Rep(String id, String name, String build, String outcome) { + this.id = id; + this.name = name; + this.build = build; + this.outcome = outcome; + } + + CheatReport done() { + return new CheatReport(id, name, build, outcome, why, patterns, fixed, values, notes); + } + } + + private static final class Item { + final String name; + final boolean master; + final String group; + final Atmosphere.Entry entry; + Atmosphere.Derived derived; + Atmosphere.Unclear unclear; + + Item(String name, boolean master, String group, Atmosphere.Entry entry) { + this.name = name; + this.master = master; + this.group = group; + this.entry = entry; + } + } + + private static final class Op { + final String kind; + final Map table; + + Op(String kind, Map table) { + this.kind = kind; + this.table = table; + } + } + + /** One converted cheat of one file, before cheats of several builds are merged. */ + private static final class CheatState { + final Item item; + final String key; + final Rep rep; + String hold; + String press; // buttons of a block that patches without an else branch: run = "action" + boolean needsMaster; + boolean defaultOn; // a patch of a patch file that is on by default + List ops = new ArrayList<>(); + Map values = new LinkedHashMap<>(); + final Map raw; // null for a patch of a patch file + + CheatState(Item item, String key, Rep rep) { + this.item = item; + this.key = key; + this.rep = rep; + if (item.entry == null) { + raw = null; + return; + } + raw = new LinkedHashMap<>(); + raw.put("syntax", "atmosphere"); + raw.put("build", key); + raw.put("code", item.entry.code()); + } + } + + private static Map table(Object... keysAndValues) { + Map t = new LinkedHashMap<>(); + for (int i = 0; i < keysAndValues.length; i += 2) { + t.put((String) keysAndValues[i], keysAndValues[i + 1]); + } + return t; + } + + /** Returns an id from a name: lower-case letters, digits and hyphens, not yet in taken, which it is added to. */ + static String slug(String name, Set taken) { + String base = stripChars(name.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]+", "-"), "-"); + if (base.isEmpty()) { + base = "cheat"; + } + if (!(base.charAt(0) >= 'a' && base.charAt(0) <= 'z')) { + base = "cheat-" + base; + } + base = base.substring(0, Math.min(48, base.length())); + while (base.endsWith("-")) { + base = base.substring(0, base.length() - 1); + } + String out = base; + int n = 2; + while (taken.contains(out)) { + out = base + "-" + n; + n++; + } + taken.add(out); + return out; + } + + /** Python's str.strip(chars): the text without those characters at both ends. */ + private static String stripChars(String s, String chars) { + int a = 0; + int b = s.length(); + while (a < b && chars.indexOf(s.charAt(a)) >= 0) { + a++; + } + while (b > a && chars.indexOf(s.charAt(b - 1)) >= 0) { + b--; + } + return s.substring(a, b); + } + + /** + * Returns the people that credit lines name: what follows "by" or "credits:", up to a comma + * or the end. A person named with the platform they posted on ("Ann on Some Forum", "Ann @ + * Some Forum") is written "Ann (Some Forum)". A credit such as "All Credited" or "everyone" + * names no person. + */ + public static List authorsOf(List credits) { + List names = new ArrayList<>(); + for (String line : credits) { + Matcher m = AUTHOR.matcher(line); + if (!m.find()) { + continue; + } + String text = m.group(1) != null ? m.group(1) : m.group(2); + Matcher cut = NAME_END.matcher(text); + text = Py.strip(cut.find() ? text.substring(0, cut.start()) : text); + for (String name : NAME_SPLIT.split(text, -1)) { + name = stripChars(name, " ."); + Matcher on = PLATFORM.matcher(name); + if (on.matches()) { + name = Py.strip(on.group(1)) + " (" + stripChars(on.group(2), " .()") + ")"; + } + if (!name.isEmpty() && !LINK.matcher(name).lookingAt() && !NOT_A_NAME.matcher(name).matches() + && !names.contains(name)) { + names.add(name); + } + } + } + return names; + } + + /** Returns the website the credit lines name, as a lower-case domain without www, or null. */ + public static String siteOf(List credits) { + for (String line : credits) { + Matcher m = SITE.matcher(line); + if (m.find()) { + return m.group(1).toLowerCase(Locale.ROOT); + } + } + return null; + } + + // One file + + private static List read(Source src, Report report, String key) throws AtmosphereException { + List items = new ArrayList<>(); + String group = null; + List notes = new ArrayList<>(); + for (Atmosphere.Entry e : Atmosphere.parse(src.text(), notes)) { + if (!e.broken().isEmpty()) { + report.unreadable.add(e.name()); + Rep rep = new Rep("", e.name(), key, CheatReport.UNREADABLE); + rep.why = "lines that mix code with other text: " + String.join("; ", e.broken()); + report.cheats.add(rep); + continue; + } + long[] words = e.wordsShared(); + Matcher section = words.length == 0 || Atmosphere.isNoop(e) ? EDIZON.matcher(e.name()) : null; + if (section != null && section.find()) { + if (section.group(1).toLowerCase(Locale.ROOT).equals("start")) { + String cleaned = Py.strip(DECORATION.matcher(section.group(2)).replaceAll("").replace('/', '-')); + group = cleaned.isEmpty() ? null : cleaned; + if (group != null && !report.groups.contains(group)) { + report.groups.add(group); + } + } else { + group = null; + } + continue; + } + if (words.length == 0 || Atmosphere.isNoop(e)) { + if (CREDIT_NAME.matcher(e.name()).find()) { + if (!report.credits.contains(e.name())) { + report.credits.add(e.name()); + } + } else if (Arrays.equals(words, GROUP_END)) { + group = null; + } else if (!e.master()) { + String cleaned = Py.strip(DECORATION.matcher(e.name()).replaceAll("").replace('/', '-')); + group = cleaned.isEmpty() ? null : cleaned; + if (group != null && !report.groups.contains(group)) { + report.groups.add(group); + } + } + continue; + } + items.add(new Item(e.name(), e.master(), group, e)); + } + for (Atmosphere.Note n : notes) { + if (!report.notes.contains(n.text())) { + report.notes.add(n.text()); + } + } + List mastersFirst = new ArrayList<>(items); + Collections.sort(mastersFirst, new Comparator() { + @Override + public int compare(Item a, Item b) { + return Boolean.compare(!a.master, !b.master); + } + }); + Set written = new HashSet<>(); + for (Item it : mastersFirst) { + Atmosphere.Derived d; + try { + d = Atmosphere.derive(it.entry); + } catch (Atmosphere.Unclear u) { + it.unclear = u; + written.addAll(Atmosphere.registersWritten(it.entry)); + continue; + } + Set both = new HashSet<>(d.reads); + both.retainAll(written); + if (!both.isEmpty()) { + it.unclear = new Atmosphere.Unclear("it reads a register that an earlier cheat sets"); + } else { + it.derived = d; + } + written.addAll(d.writes); + } + return items; + } + + private static byte[] slice(byte[] image, long offset, long width) { + if (Long.compareUnsigned(offset, image.length) >= 0) { + return new byte[0]; + } + long end = Math.min(image.length, offset + width); + return Arrays.copyOfRange(image, (int) offset, (int) end); + } + + /** The original bytes at a place of the main module: from the module, else from the file's own restore code. */ + private static byte[] original(CodeModule module, Map, byte[]> originals, long offset, int width) { + if (module != null && !module.excluded(offset, width)) { + return slice(module.image(), offset, width); + } + byte[] out = new byte[width]; + for (int i = 0; i < width; i++) { + boolean found = false; + for (Map.Entry, byte[]> e : originals.entrySet()) { + long off = e.getKey().get(0); + long w = e.getKey().get(1); + if (off <= offset + i && offset + i < off + w) { + out[i] = e.getValue()[(int) (offset + i - off)]; + found = true; + break; + } + } + if (!found) { + return null; + } + } + return out; + } + + private static boolean inCode(CodeModule module, long offset, long width) { + String a = module.sectionOf(offset); + String b = module.sectionOf(offset + width - 1); + return ("code".equals(a) || "rodata".equals(a)) && ("code".equals(b) || "rodata".equals(b)); + } + + private static boolean isMainPlain(Atmosphere.Store s) { + return s.place.region.equals("main") && !s.place.hasPath(); + } + + /** The entries that only put back original code, and the original bytes the file's code gives. */ + private static Set restores(List items, CodeModule module, Map, byte[]> originals) { + Set restore = Collections.newSetFromMap(new IdentityHashMap()); + for (Item it : items) { + Atmosphere.Derived d = it.derived; + if (d == null || d.stores.isEmpty()) { + continue; + } + if (d.released != null) { + for (Atmosphere.Store s : d.released) { + if (isMainPlain(s)) { + List k = Arrays.asList(s.place.offset, (long) s.width); + if (!originals.containsKey(k)) { + originals.put(k, s.data()); + } + } + } + } + boolean other = d.keys != 0 || d.condition != null; + for (Atmosphere.Store s : d.stores) { + other |= !isMainPlain(s); + } + if (other) { + continue; + } + boolean anyExcluded = false; + if (module != null) { + for (Atmosphere.Store s : d.stores) { + anyExcluded |= module.excluded(s.place.offset, s.width); + } + } + if (module != null && !anyExcluded) { + boolean all = true; + for (Atmosphere.Store s : d.stores) { + all &= inCode(module, s.place.offset, s.width) + && Arrays.equals(slice(module.image(), s.place.offset, s.width), s.data()); + } + if (all) { + restore.add(it); + } + continue; + } + if (RESTORE_NAME.matcher(it.name).find()) { + Set others = new HashSet<>(); + for (Item o : items) { + if (o != it) { + others.addAll(Atmosphere.mainOffsets(o.entry)); + } + } + boolean all = true; + for (Atmosphere.Store s : d.stores) { + all &= others.contains(s.place.offset); + } + if (all) { + restore.add(it); + for (Atmosphere.Store s : d.stores) { + originals.put(Arrays.asList(s.place.offset, (long) s.width), s.data()); + } + } + } + } + return restore; + } + + private static Map location(Atmosphere.Place place, String key) { + Map offsets = table(key, Values.unsigned(place.offset)); + Map loc = place.region.equals("main") ? table("module", "main", "offsets", offsets) + : table("region", place.region, "offsets", offsets); + if (place.hasPath()) { + List path = new ArrayList<>(); + for (long p : place.path) { + path.add(p); + } + loc.put("path", path); + } + return loc; + } + + private static List mergeRuns(List stores) { + List runs = new ArrayList<>(); + for (Atmosphere.Store s : stores) { + Object[] last = runs.isEmpty() ? null : runs.get(runs.size() - 1); + if (last != null && (Long) last[0] + ((ByteArrayOutputStream) last[1]).size() == s.place.offset) { + byte[] data = s.data(); + ((ByteArrayOutputStream) last[1]).write(data, 0, data.length); + } else { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + byte[] data = s.data(); + b.write(data, 0, data.length); + runs.add(new Object[] {s.place.offset, b}); + } + } + List out = new ArrayList<>(); + for (Object[] r : runs) { + out.add(new Object[] {r[0], ((ByteArrayOutputStream) r[1]).toByteArray()}); + } + return out; + } + + private static double fmovValue(int imm8) { + double sign = (imm8 & 0x80) != 0 ? -1.0 : 1.0; + int cd = (imm8 >> 4) & 3; + int e = (imm8 & 0x40) == 0 ? cd + 1 : cd - 3; + return sign * (16 + (imm8 & 15)) / 16 * Math.pow(2.0, e); + } + + private static long le32(byte[] data, int at) { + return (data[at] & 0xFFL) | (data[at + 1] & 0xFFL) << 8 | (data[at + 2] & 0xFFL) << 16 + | (data[at + 3] & 0xFFL) << 24; + } + + /** + * The encode table and the value's type for new bytes that are one movz, a movz and a movk, + * or one fmov with an immediate, else null. + */ + private static Object[] encodeOf(byte[] data) { + if (data.length != 4 && data.length != 8) { + return null; + } + long w0 = le32(data, 0); + if (data.length == 4 && (w0 & 0x7FE00000L) == 0x52800000L) { + return new Object[] {table("insn", "movz", "width", (w0 >> 31) != 0 ? 64L : 32L, "rd", w0 & 31, + "value", (w0 >> 5) & 0xFFFF), "u16"}; + } + if (data.length == 8) { + long w1 = le32(data, 4); + if ((w0 & 0x7FE00000L) == 0x52800000L && (w1 & 0x7FE00000L) == 0x72A00000L && w0 >> 31 == w1 >> 31 + && (w0 & 31) == (w1 & 31)) { + long lo = (w0 >> 5) & 0xFFFF; + long hi = (w1 >> 5) & 0xFFFF; + return new Object[] {table("insn", "movz-movk", "width", (w0 >> 31) != 0 ? 64L : 32L, "rd", w0 & 31, + "value", hi << 16 | lo), "u32"}; + } + return null; + } + if ((w0 & 0xFF201FE0L) == 0x1E201000L && ((w0 >> 22) & 3) <= 1) { + boolean isDouble = ((w0 >> 22) & 3) == 1; + return new Object[] {table("insn", "fmov", "width", isDouble ? 64L : 32L, "rd", w0 & 31, + "value", fmovValue((int) ((w0 >> 13) & 0xFF))), isDouble ? "f64" : "f32"}; + } + return null; + } + + /** An unsigned 64-bit number as a BigInteger. */ + private static BigInteger unsigned(long bits) { + BigInteger v = BigInteger.valueOf(bits & Long.MAX_VALUE); + return bits < 0 ? v.setBit(63) : v; + } + + private static List storesAndReleased(Atmosphere.Derived d) { + List out = new ArrayList<>(d.stores); + if (d.released != null) { + out.addAll(d.released); + } + return out; + } + + /** + * The main module byte ranges a master entry writes, as start and end, or null when it is not + * known what it writes. + */ + private static List masterRanges(Item master) { + List out = new ArrayList<>(); + if (master == null) { + return out; + } + if (master.unclear != null) { + return null; + } + for (Atmosphere.Store s : storesAndReleased(master.derived)) { + if (s.place.region.equals("main") && !s.place.hasPath()) { + BigInteger lo = unsigned(s.place.offset); + out.add(new BigInteger[] {lo, lo.add(BigInteger.valueOf(s.width))}); + } + } + return out; + } + + private static boolean inside(List ranges, BigInteger offset, long width) { + BigInteger end = offset.add(BigInteger.valueOf(width)); + for (BigInteger[] r : ranges) { + if (r[0].compareTo(end) < 0 && offset.compareTo(r[1]) < 0) { + return true; + } + } + return false; + } + + /** + * Whether a cheat depends on the master entry of its file: it reads registers the master + * sets, or it touches, reads through or branches into bytes the master writes. A cheat that + * stays raw code, or a master whose effect is not known, counts as dependent, as in + * Atmosphère, where the master always runs first. + */ + private static boolean depends(Item it, CheatState c, Item master, List ranges) { + if (master == null) { + return false; + } + if (ranges == null || it.unclear != null || c.ops.isEmpty()) { + return true; + } + Atmosphere.Derived d = it.derived; + for (Long r : d.reads) { + if (master.derived.writes.contains(r)) { + return true; + } + } + List places = new ArrayList<>(); + List widths = new ArrayList<>(); + for (Atmosphere.Store s : storesAndReleased(d)) { + places.add(s.place); + widths.add(s.width); + } + if (d.condition != null) { + places.add(d.condition.place); + widths.add(d.condition.width); + } + for (int k = 0; k < places.size(); k++) { + Atmosphere.Place place = places.get(k); + if (!place.region.equals("main")) { + continue; + } + if (inside(ranges, unsigned(place.offset), place.hasPath() ? 8 : widths.get(k))) { + return true; + } + } + for (Atmosphere.Store s : d.stores) { + if (s.place.region.equals("main") && !s.place.hasPath() && (s.place.offset & 3) == 0) { + byte[] data = s.data(); + for (int i = 0; i < data.length - data.length % 4; i += 4) { + long pc = s.place.offset + i; + Long target = Arm64.pcRelativeTarget(le32(data, i), pc); + if (target != null && inside(ranges, unsigned(s.place.offset).add(BigInteger.valueOf(i)) + .add(BigInteger.valueOf(target - pc)), 4)) { + return true; + } + } + } + } + return false; + } + + private static List convertOne(Source src, String key, Report report, boolean values) + throws AtmosphereException { + CodeModule module = src.module(); + List items = read(src, report, key); + Map, byte[]> originals = new LinkedHashMap<>(); + Set restore = restores(items, module, originals); + Item master = null; + for (Item it : items) { + if (it.master && !restore.contains(it)) { + master = it; + break; + } + } + List ranges = masterRanges(master); + List out = new ArrayList<>(); + for (Item it : items) { + Rep rep = new Rep("", it.name, key, CheatReport.RAW); + if (restore.contains(it)) { + rep.outcome = CheatReport.RESTORE; + rep.why = "it only puts back the original code"; + report.cheats.add(rep); + continue; + } + CheatState c = new CheatState(it, key, rep); + if (it.unclear != null) { + rep.why = it.unclear.why; + } else { + try { + core(c, it.derived, module, originals, values); + rep.outcome = rep.patterns > 0 && rep.fixed == 0 ? CheatReport.PATTERN : CheatReport.BUILD; + } catch (Atmosphere.Unclear u) { + c.ops = new ArrayList<>(); + c.values = new LinkedHashMap<>(); + c.hold = null; + c.press = null; + rep.why = u.why; + rep.outcome = CheatReport.RAW; + rep.patterns = 0; + rep.fixed = 0; + rep.values = 0; + rep.notes = new ArrayList<>(); + } + } + if (!it.master) { + c.needsMaster = depends(it, c, master, ranges); + } + out.add(c); + report.cheats.add(rep); + } + return out; + } + + private static String uType(int width) { + return "u" + (8 * width); + } + + private static void core(CheatState c, Atmosphere.Derived d, CodeModule module, Map, byte[]> originals, + boolean values) throws Atmosphere.Unclear { + Rep rep = c.rep; + String key = c.key; + String buttons = null; + if (d.keys != 0) { + buttons = Atmosphere.keysToButtons(d.keys); + if (buttons == null) { + throw new Atmosphere.Unclear("a button mask with bits that have no name"); + } + } + List code = new ArrayList<>(); + List ops = new ArrayList<>(); + for (Atmosphere.Store s : d.stores) { + if (isMainPlain(s)) { + if (module == null) { + if (original(null, originals, s.place.offset, s.width) == null) { + throw new Atmosphere.Unclear( + "a write into the main module: without the module, code and data look alike"); + } + code.add(s); + } else if (inCode(module, s.place.offset, s.width)) { + code.add(s); + } else if (module.sectionOf(s.place.offset) == null) { + throw new Atmosphere.Unclear("a write outside the main module"); + } else { + ops.add(new Op("write", table("at", location(s.place, key), "type", uType(s.width), + "value", Values.unsigned(s.value)))); + rep.fixed++; + } + } else { + ops.add(new Op("write", table("at", location(s.place, key), "type", uType(s.width), + "value", Values.unsigned(s.value)))); + rep.fixed++; + } + } + if (d.released != null) { + for (Atmosphere.Store s : d.released) { + if (!isMainPlain(s)) { + throw new Atmosphere.Unclear("it writes data when the buttons are released"); + } + byte[] o = original(module, originals, s.place.offset, s.width); + if (o == null || !Arrays.equals(o, s.data())) { + throw new Atmosphere.Unclear("the release branch writes other bytes than the original code"); + } + } + } + List> patches = new ArrayList<>(); + for (Object[] run : mergeRuns(code)) { + long off = (Long) run[0]; + byte[] data = (byte[]) run[1]; + byte[] expect = original(module, originals, off, data.length); + if (expect == null) { + throw new Atmosphere.Unclear("no original bytes for every byte it writes"); + } + if (Arrays.equals(expect, data)) { + rep.notes.add(String.format("main+0x%X already holds those bytes; the patch stays, as the source writes them", + off)); + } + patches.add(patch(c, off, data, expect, module, values, "main")); + } + if (patches.isEmpty() && ops.isEmpty()) { + throw new Atmosphere.Unclear("it writes only what is already there"); + } + if (buttons != null) { + if (d.released == null && !patches.isEmpty()) { + // Atmosphère patches at the press and leaves the patch when the buttons are let go: an action. + if (!ops.isEmpty()) { + throw new Atmosphere.Unclear("a button block without an else branch that patches code and writes data"); + } + c.press = buttons; + } else { + c.hold = buttons; + } + } + List all = new ArrayList<>(); + for (Map p : patches) { + all.add(new Op("patch", p)); + } + all.addAll(ops); + c.ops = all; + if (d.condition != null) { + Atmosphere.Cond cond = d.condition; + if (cond.place.region.equals("main") && module != null && inCode(module, cond.place.offset, cond.width)) { + throw new Atmosphere.Unclear("a condition on the code itself"); + } + c.ops.add(0, new Op("when", table("at", location(cond.place, key), "type", uType(cond.width), + "op", cond.op, "value", Values.unsigned(cond.value)))); + } + } + + private static Map patch(CheatState c, long off, byte[] data, byte[] expect, CodeModule module, + boolean values, String name) { + Rep rep = c.rep; + Map loc = null; + if (module != null) { + if (module.excluded(off, data.length)) { + rep.notes.add(String.format("%s+0x%X: the module's bytes there are not its own, so no pattern", name, off)); + } else if (Arm64.relativeOutside(data, off, data.length)) { + rep.notes.add(String.format("%s+0x%X: the new code branches or refers outside itself, so it fits this " + + "build only", name, off)); + } else if (module.textSize() != null && off >= module.textSize() && "code".equals(module.sectionOf(off))) { + rep.notes.add(String.format("%s+0x%X: code written after the end of the code, kept for this build", name, off)); + } else { + Patterns.Found p = Patterns.make(module, off, Math.min(4, data.length)); + if (p == null) { + rep.notes.add(String.format("%s+0x%X: no unique pattern of up to 64 bytes", name, off)); + } else { + loc = p.location(name); + if (!Arm64.movingBytes(module.image(), (int) off, (int) (off + expect.length)).isEmpty()) { + rep.notes.add(String.format("%s+0x%X: the original code refers to another place, so `expect` " + + "fits this build only", name, off)); + } + } + } + } + if (loc == null) { + loc = table("module", name, "offsets", table(c.key, Values.unsigned(off))); + rep.fixed++; + } else { + rep.patterns++; + } + Map t = table("at", loc, "expect", Values.hexBytes(expect)); + Object[] encoded = values ? encodeOf(data) : null; + if (encoded != null) { + @SuppressWarnings("unchecked") + Map enc = (Map) encoded[0]; + String vid = !c.values.containsKey("value") ? "value" : "value-" + (c.values.size() + 1); + c.values.put(vid, table("type", encoded[1], "default", enc.get("value"))); + Map e = new LinkedHashMap<>(enc); + e.put("value", "$" + vid); + t.put("encode", e); + rep.values++; + } else { + t.put("bytes", Values.hexBytes(data)); + } + return t; + } + + // Several files + + /** The operations without the offsets of their build: what must agree for two builds' cheats to be one. */ + private static List shape(List ops) { + List out = new ArrayList<>(); + for (Op op : ops) { + Map t = new LinkedHashMap<>(op.table); + @SuppressWarnings("unchecked") + Map at = t.containsKey("at") ? new LinkedHashMap<>((Map) t.get("at")) + : new LinkedHashMap(); + if (at.containsKey("offsets")) { + at.put("offsets", null); + } + t.put("at", at); + t.remove("asm"); + List keys = new ArrayList<>(t.keySet()); + Collections.sort(keys); + List items = new ArrayList<>(); + for (String k : keys) { + items.add(Arrays.asList(k, t.get(k))); + } + out.add(op.kind + " " + Py.repr(items)); + } + return out; + } + + private static boolean mergeable(CheatState a, CheatState b) { + return java.util.Objects.equals(a.hold, b.hold) && java.util.Objects.equals(a.press, b.press) + && a.needsMaster == b.needsMaster && sameValues(a.values, b.values) && shape(a.ops).equals(shape(b.ops)); + } + + /** Python's == for the value tables: numbers compare by value. */ + private static boolean sameValues(Object a, Object b) { + if (a instanceof Map && b instanceof Map) { + Map x = (Map) a; + Map y = (Map) b; + if (!x.keySet().equals(y.keySet())) { + return false; + } + for (Object k : x.keySet()) { + if (!sameValues(x.get(k), y.get(k))) { + return false; + } + } + return true; + } + if (a instanceof Number && b instanceof Number) { + return Values.same(a, b); + } + return java.util.Objects.equals(a, b); + } + + @SuppressWarnings("unchecked") + private static void mergeInto(CheatState a, CheatState b) { + for (int i = 0; i < Math.min(a.ops.size(), b.ops.size()); i++) { + Object at = a.ops.get(i).table.get("at"); + if (at instanceof Map && ((Map) at).containsKey("offsets")) { + Map offsets = (Map) ((Map) at).get("offsets"); + Map other = (Map) ((Map) b.ops.get(i).table.get("at")) + .get("offsets"); + offsets.putAll(other); + } + } + } + + /** Returns a conversion of one Atmosphère cheat file. */ + public static Conversion fromAtmosphere(Source source, Options options) throws ConvertException { + return fromAtmosphere(Collections.singletonList(source), options); + } + + /** + * Returns a conversion of one or more Atmosphère cheat files, each for one build of the same + * game. + * + *

    Two files with the same version name are named by their build IDs. + * + * @throws ConvertException with the code "atmosphere" when a file cannot be read, or none + * holds a cheat with code ({@link AtmosphereException}), or "source" when two files are + * for the same build ID or name the same build + */ + public static Conversion fromAtmosphere(List sources, Options options) throws ConvertException { + Report report = new Report(); + Map builds = new LinkedHashMap<>(); + List> perSource = new ArrayList<>(); + List buildIds = new ArrayList<>(); + List versions = new ArrayList<>(); + for (Source src : sources) { + buildIds.add(src.buildId().toUpperCase(Locale.ROOT)); + if (nonEmpty(src.version())) { + versions.add(src.version()); + } + } + if (new HashSet<>(buildIds).size() != buildIds.size()) { + throw new ConvertException("two files are for the same build ID"); + } + for (Source src : sources) { + String bid = src.buildId().toUpperCase(Locale.ROOT); + boolean shared = src.version() != null && Collections.frequency(versions, src.version()) > 1; + String named = shared ? bid : src.version(); + String key = nonEmpty(src.buildKey()) ? src.buildKey() : nonEmpty(named) ? named : bid; + if (builds.containsKey(key)) { + throw new ConvertException("two files name the build " + Py.repr(key)); + } + CodeModule m = src.module(); + String shortId = m == null ? null : m.shortId(); + if (shortId != null && !(shortId.startsWith(bid.substring(0, Math.min(16, bid.length()))) + || bid.startsWith(shortId))) { + report.warnings.add("the module of build " + key + " is " + shortId + ", its cheat file " + bid); + } + Map build = new LinkedHashMap<>(); + if (nonEmpty(src.version()) && !src.version().equals(key)) { + build.put("version", src.version()); + } + if (shared) { + report.warnings.add("builds " + bid + " and another one are both version " + src.version() + + ": named by their build IDs"); + } + build.put("modules", table("main", bid)); + builds.put(key, build); + perSource.add(convertOne(src, key, report, options.values)); + } + + // Cheats of several builds with the same name become one where they do the same; masters + // first, so that a cheat is only one cheat across builds whose masters are one cheat too. + List> merged = new ArrayList<>(); + Map> masterOf = new HashMap<>(); + for (boolean wantMaster : new boolean[] {true, false}) { + Map>> byName = new HashMap<>(); + for (List cheats : perSource) { + for (CheatState c : cheats) { + if (c.item.master != wantMaster) { + continue; + } + List target = null; + List> named = byName.get(c.item.name); + for (List g : named == null ? Collections.>emptyList() : named) { + boolean keyTaken = false; + for (CheatState x : g) { + keyTaken |= x.key.equals(c.key); + } + if (!keyTaken && mergeable(g.get(0), c) + && (wantMaster || masterOf.get(g.get(0).key) == masterOf.get(c.key))) { + target = g; + break; + } + } + if (target == null) { + target = new ArrayList<>(); + target.add(c); + merged.add(target); + if (named == null) { + named = new ArrayList<>(); + byName.put(c.item.name, named); + } + named.add(target); + } else { + target.add(c); + } + if (wantMaster) { + masterOf.put(c.key, target); + } + } + } + } + final Map order = new IdentityHashMap<>(); + for (List cheats : perSource) { + for (CheatState c : cheats) { + order.put(c, order.size()); + } + } + Collections.sort(merged, new Comparator>() { + @Override + public int compare(List a, List b) { + return Integer.compare(first(a), first(b)); + } + + private int first(List g) { + int min = Integer.MAX_VALUE; + for (CheatState c : g) { + min = Math.min(min, order.get(c)); + } + return min; + } + }); + + Set taken = new HashSet<>(); + Map, String> ids = new IdentityHashMap<>(); + for (List g : merged) { + ids.put(g, slug(g.get(0).item.name, taken)); + for (CheatState c : g) { + c.rep.id = ids.get(g); + } + } + List cheats = new ArrayList<>(); + for (List g : merged) { + CheatState first = g.get(0); + for (CheatState c : g.subList(1, g.size())) { + mergeInto(first, c); + } + Map t = table("id", ids.get(g), "name", first.item.name); + if (first.item.group != null && !first.item.group.isEmpty()) { + t.put("group", first.item.group); + } + if (first.item.master) { + t.put("master", true); + } else if (masterOf.get(first.key) != null && anyNeedsMaster(g)) { + t.put("requires", new ArrayList(Collections.singletonList(ids.get(masterOf.get(first.key))))); + } + if (first.press != null && !first.press.isEmpty()) { + t.put("run", "action"); + t.put("press", first.press); + } + if (first.hold != null && !first.hold.isEmpty()) { + t.put("hold", first.hold); + } + if (!first.values.isEmpty()) { + t.put("values", new LinkedHashMap<>(first.values)); + } + for (Op op : first.ops) { + if (!t.containsKey(op.kind)) { + t.put(op.kind, new ArrayList()); + } + @SuppressWarnings("unchecked") + List list = (List) t.get(op.kind); + list.add(op.table); + } + List raw = new ArrayList<>(); + for (CheatState c : g) { + raw.add(c.raw); + } + t.put("raw", raw); + cheats.add(t); + } + if (cheats.isEmpty()) { + throw new AtmosphereException("the file has no cheat with code"); + } + + Map doc = new LinkedHashMap<>(); + doc.put("format", "mncf/1"); + doc.put("name", nonEmpty(options.name) ? options.name + : nonEmpty(options.gameName) ? options.gameName + " cheats" : "Converted cheats"); + List found = authorsOf(report.credits); + if (!found.isEmpty() || (options.authors != null && !options.authors.isEmpty())) { + doc.put("authors", new ArrayList(!found.isEmpty() ? found : options.authors)); + } + List about = new ArrayList<>(); + if (!report.credits.isEmpty()) { + about.add("Credits in the source: " + String.join("; ", report.credits)); + } + if (!report.notes.isEmpty()) { + about.add("Lines in the source that are not cheat code: " + String.join("; ", report.notes)); + } + if (!report.unreadable.isEmpty()) { + about.add("Entries whose code could not be read, left out: " + String.join("; ", report.unreadable)); + } + if (!about.isEmpty()) { + doc.put("about", String.join("\n", about)); + } + Map origin = table("format", "atmosphere"); + if (nonEmpty(options.origin)) { + origin.put("name", options.origin); + } + String site = siteOf(report.credits); + if (site != null && !site.isEmpty()) { + origin.put("site", site); + } + doc.put("origin", origin); + List exts = new ArrayList<>(); + exts.add("raw/1"); + for (Object c : cheats) { + if (((Map) c).containsKey("values")) { + exts.add("arm64-imm/1"); + break; + } + } + doc.put("extensions", table("optional", exts)); + Map game = table("platform", options.platform, "id", options.gameId.toUpperCase(Locale.ROOT)); + if (nonEmpty(options.gameName)) { + game.put("name", options.gameName); + } + doc.put("game", game); + doc.put("builds", builds); + doc.put("cheat", cheats); + @SuppressWarnings("unchecked") + Map frozen = (Map) Values.freeze(doc); + List reports = new ArrayList<>(); + for (Rep r : report.cheats) { + reports.add(r.done()); + } + return new Conversion(frozen, Writer.dumps(frozen), + new ConversionReport(reports, report.groups, report.credits, report.warnings, report.notes, + report.unreadable)); + } + + private static boolean anyNeedsMaster(List g) { + for (CheatState c : g) { + if (c.needsMaster) { + return true; + } + } + return false; + } + + private static boolean nonEmpty(String s) { + return s != null && !s.isEmpty(); + } + + // Patch files: IPS, IPS32, IPSwitch + + private static final Pattern TITLE_ID = Pattern.compile("[0-9A-Fa-f]{16}"); + private static final List PATCH_FOLDERS = Arrays.asList("exefs", "exefs_patches", "atmosphere", "contents"); + + /** + * The patch set a file belongs to, from its path: the folder it is in + * ("exefs_patches/<set>/<build ID>.ips", or a mod's folder above "exefs/"), else its own + * name where that is no build ID, else "Patch". + */ + static String setName(String fileName) { + List parts = new ArrayList<>(); + for (String part : Py.split((fileName == null ? "" : fileName).replace('\\', '/'), '/')) { + if (!part.isEmpty()) { + parts.add(part); + } + } + if (parts.isEmpty()) { + return "Patch"; + } + for (int i = parts.size() - 2; i >= 0; i--) { + String folder = parts.get(i); + if (!PATCH_FOLDERS.contains(folder.toLowerCase(Locale.ROOT)) && !TITLE_ID.matcher(folder).matches()) { + return folder; + } + } + String last = parts.get(parts.size() - 1); + int dot = last.lastIndexOf('.'); + String stem = dot < 0 ? last : last.substring(0, dot); + return stem.isEmpty() || Patches.buildIdOf(last) != null ? "Patch" : stem; + } + + private static CheatState patchCheat(Item item, String key, Rep rep, List runs, CodeModule module, + String mname, boolean values) throws Atmosphere.Unclear { + CheatState c = new CheatState(item, key, rep); + for (Patches.Run run : runs) { + long off = run.offset(); + byte[] data = run.dataShared(); + List pieces = new ArrayList<>(); + long at = off; + while (at < off + data.length) { // one run for each section it crosses + String sec = module.sectionOf(at); + long stop = Math.min(off + data.length, sec != null ? module.sectionEnd(sec) : at + 1); + pieces.add(new Object[] {sec, at, Arrays.copyOfRange(data, (int) (at - off), (int) (stop - off))}); + at = stop; + } + for (Object[] piece : pieces) { + String sec = (String) piece[0]; + long where = (Long) piece[1]; + byte[] bytes = (byte[]) piece[2]; + if (sec == null) { + throw new Atmosphere.Unclear(String.format("%s+0x%X is in no section of the module", mname, where)); + } + if (module.excluded(where, bytes.length)) { + throw new Atmosphere.Unclear(String.format("%s+0x%X: the module's bytes there are not its own, so " + + "there is no `expect`", mname, where)); + } + byte[] expect = Arrays.copyOfRange(module.image(), (int) where, (int) where + bytes.length); + if (Arrays.equals(expect, bytes)) { + rep.notes.add(String.format("%s+0x%X already holds those bytes; the patch stays, as the source " + + "writes them", mname, where)); + } + if ("data".equals(sec)) { + c.ops.add(new Op("write", table("at", table("module", mname, "offsets", + table(key, Values.unsigned(where))), "type", "bytes", "value", Values.hexBytes(bytes), + "expect", Values.hexBytes(expect)))); + rep.fixed++; + } else { + c.ops.add(new Op("patch", patch(c, where, bytes, expect, module, values, mname))); + } + } + } + return c; + } + + /** Returns a conversion of one patch file. */ + public static Conversion fromPatches(PatchSource source, Options options) throws ConvertException { + return fromPatches(Collections.singletonList(source), options); + } + + /** + * Returns a conversion of patch files (IPS, IPS32 or IPSwitch text) of the same game, for one + * or more builds. + * + *

    Each IPS file becomes one cheat, named by its patch set, that is on by default, as a + * loader applies it whenever it is there. Each patch of an IPSwitch file becomes one cheat, + * named by its comment, on by default where it is @enabled. A write into code or read-only + * data becomes a patch, one into data a write that is made only while the place holds its + * original bytes, as a loader sets them only once. + * + * @throws ConvertException with the code "patch" for a file that is no patch file + * ({@link PatchFileException}), or "source" for a file without its module or build ID, + * a build with two build IDs for one module, or files of which no patch could be converted + */ + public static Conversion fromPatches(List sources, Options options) throws ConvertException { + Report report = new Report(); + Map> builds = new LinkedHashMap<>(); + List> perSource = new ArrayList<>(); + List formats = new ArrayList<>(); + List files = new ArrayList<>(); + List bids = new ArrayList<>(); + for (PatchSource src : sources) { + PatchFile f = Patches.read(src.dataShared()); + formats.add(f.format()); + String bid = f.buildId(); + if (!nonEmpty(bid)) { + bid = nonEmpty(src.fileName()) ? Patches.buildIdOf(src.fileName()) : null; + } + if (!nonEmpty(bid)) { + bid = nonEmpty(src.buildId()) ? Patches.trimBuildId(src.buildId()) : null; + } + if (!nonEmpty(bid)) { + bid = src.module() != null && nonEmpty(src.module().buildId()) + ? Patches.trimBuildId(src.module().buildId()) : null; + } + String what = nonEmpty(src.fileName()) ? src.fileName() : "a patch file"; + if (src.module() == null) { + throw new ConvertException(what + ": a patch needs the module it patches, for `expect`"); + } + if (!nonEmpty(bid)) { + throw new ConvertException(what + ": no build ID in the file, its name or the module"); + } + files.add(f); + bids.add(bid); + } + Map, Set> versions = new HashMap<>(); + for (int k = 0; k < sources.size(); k++) { + PatchSource src = sources.get(k); + if (nonEmpty(src.version())) { + List vkey = Arrays.asList(src.version(), src.moduleName()); + if (!versions.containsKey(vkey)) { + versions.put(vkey, new HashSet()); + } + versions.get(vkey).add(bids.get(k)); + } + } + for (int k = 0; k < sources.size(); k++) { + PatchSource src = sources.get(k); + PatchFile f = files.get(k); + String bid = bids.get(k); + Set same = versions.get(Arrays.asList(src.version(), src.moduleName())); + boolean shared = nonEmpty(src.version()) && same != null && same.size() > 1; + String named = shared ? bid : src.version(); + String key = nonEmpty(src.buildKey()) ? src.buildKey() : nonEmpty(named) ? named : bid; + CodeModule module = src.module(); + String mid = module.buildId(); + if (nonEmpty(mid)) { + String upper = mid.toUpperCase(Locale.ROOT); + if (!(upper.startsWith(bid) || bid.startsWith(upper))) { + report.warnings.add("the module of build " + key + " is " + upper + ", its patch file " + bid); + } + } + Map build = builds.get(key); + if (build == null) { + build = new LinkedHashMap<>(); + if (nonEmpty(src.version()) && !src.version().equals(key)) { + build.put("version", src.version()); + } + builds.put(key, build); + } + if (!build.containsKey("modules")) { + build.put("modules", new LinkedHashMap()); + } + @SuppressWarnings("unchecked") + Map mods = (Map) build.get("modules"); + if (mods.containsKey(src.moduleName()) && !bid.equals(mods.get(src.moduleName()))) { + throw new ConvertException("build " + Py.repr(key) + " has two build IDs for " + src.moduleName()); + } + mods.put(src.moduleName(), bid); + String set = nonEmpty(src.setName()) ? src.setName() : setName(src.fileName()); + for (PatchFile.Line line : f.notes()) { + if (!report.notes.contains(line.text())) { + report.notes.add(line.text()); + } + } + for (PatchFile.Line line : f.comments()) { + if (CREDIT_NAME.matcher(line.text()).find() && !report.credits.contains(line.text())) { + report.credits.add(line.text()); + } + } + int count = f.patches().size(); + String group = count > 1 ? set : null; + List out = new ArrayList<>(); + for (int i = 1; i <= count; i++) { + Patch p = f.patches().get(i - 1); + String own = nonEmpty(p.name()) && !CREDIT_NAME.matcher(p.name()).find() ? p.name() : ""; + String title = !own.isEmpty() ? own : count == 1 ? set : set + " " + i; + Rep rep = new Rep("", title, key, CheatReport.PATTERN); + Patches.ImageRuns written = Patches.imageRuns(p, module.image().length); + for (String d : written.dropped()) { + rep.notes.add("left out " + d); + } + CheatState c; + try { + if (written.runs().isEmpty()) { + throw new Atmosphere.Unclear("it writes nothing into the module"); + } + c = patchCheat(new Item(title, false, group, null), key, rep, written.runs(), module, + src.moduleName(), options.values); + } catch (Atmosphere.Unclear u) { + rep.outcome = CheatReport.UNREADABLE; + rep.why = u.why; + rep.patterns = 0; + rep.fixed = 0; + rep.values = 0; + rep.notes = new ArrayList<>(); + for (String d : written.dropped()) { + rep.notes.add("left out " + d); + } + report.unreadable.add(title + " (" + u.why + ")"); + report.cheats.add(rep); + continue; + } + c.defaultOn = p.enabled(); + rep.outcome = rep.patterns > 0 && rep.fixed == 0 ? CheatReport.PATTERN : CheatReport.BUILD; + out.add(c); + report.cheats.add(rep); + } + perSource.add(out); + } + + List> merged = new ArrayList<>(); + Map>> byName = new HashMap<>(); + for (List cheats : perSource) { + for (CheatState c : cheats) { + List target = null; + List> named = byName.get(c.item.name); + for (List g : named == null ? Collections.>emptyList() : named) { + boolean keyTaken = false; + for (CheatState x : g) { + keyTaken |= x.key.equals(c.key); + } + if (!keyTaken && mergeable(g.get(0), c) && g.get(0).defaultOn == c.defaultOn + && java.util.Objects.equals(g.get(0).item.group, c.item.group)) { + target = g; + break; + } + } + if (target == null) { + target = new ArrayList<>(); + target.add(c); + merged.add(target); + if (named == null) { + named = new ArrayList<>(); + byName.put(c.item.name, named); + } + named.add(target); + } else { + target.add(c); + } + } + } + Set taken = new HashSet<>(); + List cheats = new ArrayList<>(); + for (List g : merged) { + CheatState first = g.get(0); + String cid = slug(first.item.name, taken); + for (CheatState c : g) { + c.rep.id = cid; + if (c != first) { + mergeInto(first, c); + } + } + Map t = table("id", cid, "name", first.item.name); + if (nonEmpty(first.item.group)) { + t.put("group", first.item.group); + } + if (first.defaultOn) { + t.put("default", true); + } + if (!first.values.isEmpty()) { + t.put("values", new LinkedHashMap<>(first.values)); + } + for (Op op : first.ops) { + if (!t.containsKey(op.kind)) { + t.put(op.kind, new ArrayList()); + } + @SuppressWarnings("unchecked") + List list = (List) t.get(op.kind); + list.add(op.table); + } + cheats.add(t); + } + if (cheats.isEmpty()) { + throw new ConvertException("no patch of the files could be converted: " + String.join("; ", + report.unreadable.isEmpty() ? Collections.singletonList("none") : report.unreadable)); + } + + Map doc = new LinkedHashMap<>(); + doc.put("format", "mncf/1"); + doc.put("name", nonEmpty(options.name) ? options.name + : nonEmpty(options.gameName) ? options.gameName + " patches" : "Converted patches"); + List found = authorsOf(report.credits); + if (!found.isEmpty() || (options.authors != null && !options.authors.isEmpty())) { + doc.put("authors", new ArrayList(!found.isEmpty() ? found : options.authors)); + } + List about = new ArrayList<>(); + if (!report.credits.isEmpty()) { + about.add("Credits in the source: " + String.join("; ", report.credits)); + } + if (!report.notes.isEmpty()) { + about.add("Lines in the source that are not patches: " + String.join("; ", report.notes)); + } + if (!report.unreadable.isEmpty()) { + about.add("Patches that could not be converted, left out: " + String.join("; ", report.unreadable)); + } + if (!about.isEmpty()) { + doc.put("about", String.join("\n", about)); + } + Map origin = table("format", formats.get(0).equals("ips32") ? "ips" : formats.get(0)); + if (nonEmpty(options.origin)) { + origin.put("name", options.origin); + } + String site = siteOf(report.credits); + if (site != null && !site.isEmpty()) { + origin.put("site", site); + } + doc.put("origin", origin); + for (Object c : cheats) { + if (((Map) c).containsKey("values")) { + doc.put("extensions", table("optional", new ArrayList(Collections.singletonList("arm64-imm/1")))); + break; + } + } + Map game = table("platform", options.platform, "id", options.gameId.toUpperCase(Locale.ROOT)); + if (nonEmpty(options.gameName)) { + game.put("name", options.gameName); + } + doc.put("game", game); + doc.put("builds", builds); + doc.put("cheat", cheats); + @SuppressWarnings("unchecked") + Map frozen = (Map) Values.freeze(doc); + List reports = new ArrayList<>(); + for (Rep r : report.cheats) { + reports.add(r.done()); + } + return new Conversion(frozen, Writer.dumps(frozen), + new ConversionReport(reports, report.groups, report.credits, report.warnings, report.notes, + report.unreadable)); + } + + // Back to Atmosphere + + /** An Atmosphère cheat file made from a loaded file for one build, and what went into it. Immutable. */ + public static final class Export { + private final String fileName; + private final String text; + private final Map written; + private final Map skipped; + private final Map reasons; + + Export(String fileName, String text, Map written, Map skipped, + Map reasons) { + this.fileName = fileName; + this.text = text; + this.written = Collections.unmodifiableMap(new LinkedHashMap<>(written)); + this.skipped = Collections.unmodifiableMap(new LinkedHashMap<>(skipped)); + this.reasons = Collections.unmodifiableMap(new LinkedHashMap<>(reasons)); + } + + /** Returns the file name cheat files use: the build ID of the main module and ".txt". */ + public String fileName() { + return fileName; + } + + /** Returns the text of the cheat file. */ + public String text() { + return text; + } + + /** Returns the cheats written, by id: "raw" for their own raw code, "core" for code made from their operations. */ + public Map written() { + return written; + } + + /** Returns the cheats left out, by id, with why. */ + public Map skipped() { + return skipped; + } + + /** + * Returns the cheats left out, by id, with the stable reason (spec, section 15): the + * reader's reason for a cheat with a problem of its own, such as {@code build-unknown}, + * {@code pattern-not-found} or {@code expect-mismatch}, or {@code atmosphere:} for + * what Atmosphère cannot say. + */ + public Map reasons() { + return reasons; + } + } + + /** One build of a file as an Atmosphère cheat file, or the reason it cannot be one. Immutable. */ + public static final class BuildExport { + private final String build; + private final Export export; + private final String reason; + + BuildExport(String build, Export export, String reason) { + this.build = build; + this.export = export; + this.reason = reason; + } + + /** Returns the build key. */ + public String build() { + return build; + } + + /** Returns the cheat file, or null when the build cannot be one. */ + public Export export() { + return export; + } + + /** Returns null, or {@code atmosphere:module} for a build that names no main module. */ + public String reason() { + return reason; + } + } + + /** + * Returns every build of a loaded file as an Atmosphère cheat file, in the file's order, + * for an export in the Atmosphère layout. + * + * @param modules the main module of each build, by build key, for the cheats that find their + * place by a pattern; may be null or lack builds + * @param prefer "raw" or "core" + * @param choices the values the player chose; may be null + */ + public static List toAtmosphereAll(MncfFile f, Map modules, String prefer, + Choices choices) { + return toAtmosphereAll(f, modules, prefer, choices, null); + } + + /** + * Returns every build of a loaded file as an Atmosphère cheat file, as + * {@link #toAtmosphereAll(MncfFile, Map, String, Choices)} does, with raw or core chosen for + * single cheats. + * + * @param preferCheats "raw" or "core" by cheat id, where a cheat should differ from prefer; + * may be null + */ + public static List toAtmosphereAll(MncfFile f, Map modules, String prefer, + Choices choices, Map preferCheats) { + List out = new ArrayList<>(); + for (Map.Entry e : f.builds().entrySet()) { + if (!e.getValue().modules().containsKey("main")) { + out.add(new BuildExport(e.getKey(), null, "atmosphere:module")); + continue; + } + CodeModule module = modules == null ? null : modules.get(e.getKey()); + out.add(new BuildExport(e.getKey(), toAtmosphere(f, e.getKey(), module, prefer, choices, preferCheats), + null)); + } + return out; + } + + /** + * Returns the cheats of a loaded file as an Atmosphère cheat file for one build. Each cheat + * uses its raw code for the build when it has one and prefer is "raw"; otherwise code made + * from its operations, where they can be said in Atmosphère code. + * + * @param module the main module of the build, for operations that find their place by a + * pattern; may be null + * @param prefer "raw" or "core" + * @throws IllegalArgumentException when the file has no such build and no module is given, + * or the build names no main module + */ + public static Export toAtmosphere(MncfFile f, String buildKey, CodeModule module, String prefer) { + return toAtmosphere(f, buildKey, module, prefer, null); + } + + /** + * Returns the cheats of a loaded file as an Atmosphère cheat file for one build, as + * {@link #toAtmosphere(MncfFile, String, CodeModule, String)} does, with the values the player + * chose. A build the file does not name is written from its patterns, with the module of that + * build; the file name is then the module's build ID. + * + * @param choices the values the player chose, checked as the reader checks them: a cheat with + * a value it cannot take is written from its raw entry for the build, or else left out; + * null, or a value not chosen, writes the default + * @throws IllegalArgumentException when the file has no such build and no module is given, + * or the build names no main module + */ + public static Export toAtmosphere(MncfFile f, String buildKey, CodeModule module, String prefer, + Choices choices) { + return toAtmosphere(f, buildKey, module, prefer, choices, null); + } + + /** Entries of an Atmosphère file besides the master: dmnt holds 0x80, the first the master. */ + static final int ATM_ENTRIES = 127; + /** Words of one entry. */ + static final int ATM_WORDS = 0x100; + + private static int wordCount(List lines) { + int n = 0; + for (String line : lines) { + n += Py.splitSpace(line).size(); + } + return n; + } + + /** + * Returns the cheats of a loaded file as an Atmosphère cheat file for one build, as + * {@link #toAtmosphere(MncfFile, String, CodeModule, String, Choices)} does, with raw or core + * chosen for single cheats, such as one whose value the player set. The file keeps + * Atmosphère's limits: one master entry with the code of every master cheat, and up to 127 + * other entries of up to 256 words each; what does not fit is left out with + * {@code atmosphere:too-many} or {@code atmosphere:too-long}. + * + * @param preferCheats "raw" or "core" by cheat id, where a cheat should differ from prefer; + * may be null + * @throws IllegalArgumentException as the other forms do, or for a preference that is neither + * "raw" nor "core" + */ + public static Export toAtmosphere(MncfFile f, String buildKey, CodeModule module, String prefer, + Choices choices, Map preferCheats) { + Map modes = preferCheats == null ? Collections.emptyMap() : preferCheats; + List all = new ArrayList<>(); + all.add(prefer); + all.addAll(modes.values()); + for (String mode : all) { + if (!"raw".equals(mode) && !"core".equals(mode)) { + throw new IllegalArgumentException("prefer is \"raw\" or \"core\", not " + Py.repr(mode)); + } + } + Build build = f.builds().get(buildKey); + String mainId; + if (build != null) { + mainId = build.modules().get("main"); + if (mainId == null) { + throw new IllegalArgumentException("build " + Py.repr(buildKey) + " names no main module"); + } + } else if (module != null && nonEmpty(module.shortId())) { + mainId = module.shortId(); + } else { + throw new IllegalArgumentException("the file has no build " + Py.repr(buildKey) + + ", and no module of it is given"); + } + Choices chosen = choices != null ? choices : Choices.none(); + Map written = new LinkedHashMap<>(); + Map skipped = new LinkedHashMap<>(); + Map reasons = new LinkedHashMap<>(); + List entries = new ArrayList<>(); + String group = null; + String master = null; + List masterLines = new ArrayList<>(); + List cheats = new ArrayList<>(f.cheats()); + Collections.sort(cheats, new Comparator() { + @Override + public int compare(Cheat a, Cheat b) { + return Boolean.compare(!a.isMaster(), !b.isMaster()); + } + }); + for (Cheat c : cheats) { + if (c.problem() != null) { + skipped.put(c.id(), c.problem()); + reasons.put(c.id(), c.problem()); + continue; + } + Model.Raw raw = null; + for (Model.Raw r : c.raw()) { + if (r.build.equals(buildKey) && r.syntax.equals("atmosphere")) { + raw = r; + break; + } + } + List rawLines = null; + if (raw != null) { + rawLines = new ArrayList<>(); + for (String line : Py.splitLines(Py.strip(raw.code))) { + if (!Py.strip(line).isEmpty()) { + rawLines.add(Py.strip(line)); + } + } + } + List lines; + String how; + if (raw == null && c.ops().isEmpty()) { + skipped.put(c.id(), "only raw code, for other builds"); + reasons.put(c.id(), "build-unknown"); + continue; + } + String mode = modes.containsKey(c.id()) ? modes.get(c.id()) : prefer; + if (raw != null && "raw".equals(mode)) { + lines = rawLines; + how = "raw"; + } else { + try { + List words = coreWords(c, buildKey, module, chosen); + if (words.size() > ATM_WORDS) { + throw new Atmosphere.Unclear(words.size() + " words, more than an Atmosph\u00E8re entry holds", + "atmosphere:too-long"); + } + lines = Atmosphere.formatWords(words); + how = "core"; + } catch (Atmosphere.Unclear u) { + if (raw == null) { + skipped.put(c.id(), u.why); + reasons.put(c.id(), u.code != null ? u.code : "atmosphere:unclear"); + continue; + } + lines = rawLines; + how = "raw"; + } + } + if (wordCount(lines) > ATM_WORDS) { + skipped.put(c.id(), wordCount(lines) + " words, more than an Atmosph\u00E8re entry holds"); + reasons.put(c.id(), "atmosphere:too-long"); + continue; + } + if (c.isMaster()) { + // Atmosphère runs one master entry: the code of every master cheat goes into it, in file order. + if (wordCount(masterLines) + wordCount(lines) > ATM_WORDS) { + skipped.put(c.id(), "the master entry would hold more than 256 words"); + reasons.put(c.id(), "atmosphere:too-long"); + continue; + } + if (master == null) { + master = c.name(); + } + masterLines.addAll(lines); + written.put(c.id(), how); + continue; + } + // A new group starts with its name as an empty entry; a group is ended by an entry with only 20000001. + String cheatGroup = c.group() == null || c.group().isEmpty() ? null : c.group(); + List marks = new ArrayList<>(); + if (!java.util.Objects.equals(cheatGroup, group)) { + marks.add(cheatGroup != null ? new Atmosphere.Out(cheatGroup, false, Collections.emptyList()) + : new Atmosphere.Out(group, false, Collections.singletonList("20000001"))); + } + if (entries.size() + marks.size() + 1 > ATM_ENTRIES) { + skipped.put(c.id(), "more entries than an Atmosph\u00E8re file holds"); + reasons.put(c.id(), "atmosphere:too-many"); + continue; + } + entries.addAll(marks); + group = cheatGroup; + entries.add(new Atmosphere.Out(c.name(), false, lines)); + written.put(c.id(), how); + } + if (master != null) { + entries.add(0, new Atmosphere.Out(master, true, masterLines)); + } + String name = mainId.substring(0, Math.min(16, mainId.length())).toUpperCase(Locale.ROOT) + ".txt"; + return new Export(name, Atmosphere.writeFile(entries), written, skipped, reasons); + } + + private static long base(Model.Location loc, String buildKey, CodeModule module) throws Atmosphere.Unclear { + if (loc.kind.equals("module") || loc.kind.equals("region")) { + return loc.offset; + } + if (loc.kind.equals("module-builds") || loc.kind.equals("region-builds")) { + if (!loc.offsets.containsKey(buildKey)) { + throw new Atmosphere.Unclear("a location without an offset for this build", "build-unknown"); + } + return loc.offsets.get(buildKey); + } + if (loc.kind.equals("pattern")) { + if (module == null) { + throw new Atmosphere.Unclear("a pattern, and no module to search", "atmosphere:no-module"); + } + List found = Evaluator.findAll(module.toModuleWithoutId(), loc.find, loc.section, 2); + if (found.size() != 1) { + throw new Atmosphere.Unclear("a pattern that does not match exactly once in the module", + found.isEmpty() ? "pattern-not-found" : "pattern-ambiguous"); + } + return found.get(0) + loc.offset; + } + throw new Atmosphere.Unclear("an absolute address", "atmosphere:address"); + } + + private static Atmosphere.Place place(Model.Location loc, String buildKey, CodeModule module) throws Atmosphere.Unclear { + if (loc.module != null && !loc.module.equals("main")) { + throw new Atmosphere.Unclear("a module other than main", "atmosphere:module"); + } + String region = loc.module != null ? "main" : loc.region; + if (Atmosphere.regionCode(region) < 0) { + throw new Atmosphere.Unclear("the region " + (region == null ? "None" : region), "atmosphere:region"); + } + long[] path = loc.hasPath() ? loc.path.clone() : null; + return new Atmosphere.Place(region, base(loc, buildKey, module), path); + } + + private static List stores(Atmosphere.Place place, byte[] data) { + List out = new ArrayList<>(); + int i = 0; + while (i < data.length) { + int left = data.length - i; + int width = left >= 4 ? 4 : left >= 2 ? 2 : 1; + long v = 0; + for (int k = 0; k < width; k++) { + v |= (data[i + k] & 0xFFL) << (8 * k); + } + out.add(new Atmosphere.Store(place.plus(i), width, v)); + i += width; + } + return out; + } + + /** + * A value of the cheat: a number, the value the player chose, or the default. A chosen value + * that the player cannot choose makes the cheat unclear, as the reader refuses it + * (value-out-of-range). + */ + private static Object defaultOf(Cheat c, Object v, Choices chosen) throws Atmosphere.Unclear { + if (!(v instanceof Model.ValueRef)) { + return v; + } + Model.ValueRef ref = (Model.ValueRef) v; + if (!chosen.values().containsKey(c.id() + "." + ref.name)) { + return c.values().get(ref.name).defaultValue(); + } + Object value = Evaluator.chosenValue(c, ref, chosen); + if (value == null) { + throw new Atmosphere.Unclear("a chosen value the cheat cannot take", "value-out-of-range"); + } + return value; + } + + /** + * With the module, the bytes a patch or stub writes over must be expect, or data already: + * Atmosphère code writes without looking. Not where the module's bytes are not its own. + */ + /** + * With the module, a place in main lies inside it with every byte read or written there: for a + * pointer path, the pointer at its base. + */ + private static void checkInside(CodeModule module, Atmosphere.Place place, long length) throws Atmosphere.Unclear { + if (module != null && place.region.equals("main") + && place.offset + (place.hasPath() ? 8 : length) > module.image().length) { + throw new Atmosphere.Unclear("a place past the end of the module", "outside"); + } + } + + private static void checkModule(CodeModule module, Atmosphere.Place place, byte[] expect, byte[] data) + throws Atmosphere.Unclear { + if (module == null || place.hasPath() || !place.region.equals("main")) { + return; + } + byte[] image = module.image(); + if (place.offset + expect.length > image.length) { + throw new Atmosphere.Unclear("a place past the end of the module", "outside"); + } + byte[] here = Arrays.copyOfRange(image, (int) place.offset, (int) place.offset + expect.length); + if (!Arrays.equals(here, expect) && !Arrays.equals(here, data) + && !module.excluded(place.offset, expect.length)) { + throw new Atmosphere.Unclear("the module holds other bytes than `expect`", "expect-mismatch"); + } + } + + private static List coreWords(Cheat c, String buildKey, CodeModule module, Choices chosen) + throws Atmosphere.Unclear { + if (!c.run().equals("on") && !c.run().equals("action")) { + throw new Atmosphere.Unclear("run = \"" + c.run() + "\" has no Atmosph\u00E8re form", + c.run().equals("monitor") ? "atmosphere:monitor" : "atmosphere:run"); + } + if (c.toggle() != null) { + throw new Atmosphere.Unclear("toggle buttons have no Atmosph\u00E8re form", "atmosphere:toggle"); + } + List stores = new ArrayList<>(); + List restores = new ArrayList<>(); + List conds = new ArrayList<>(); + for (Model.Op op : c.ops()) { + if (op instanceof Model.Patch) { + Model.Patch p = (Model.Patch) op; + Atmosphere.Place place = place(p.at, buildKey, module); + checkInside(module, place, p.expect.length); + byte[] data; + if (p.encode != null) { + data = Encode.arm64Imm(p.encode.insn, p.encode.width, p.encode.rd, + defaultOf(c, p.encode.value, chosen)); + if (data == null) { + throw new Atmosphere.Unclear("a value its instruction cannot hold", "value-out-of-range"); + } + } else { + data = p.bytes; + } + checkModule(module, place, p.expect, data); + stores.addAll(stores(place, data)); + restores.addAll(stores(place, p.expect)); + } else if (op instanceof Model.Write) { + Model.Write w = (Model.Write) op; + Atmosphere.Place place = place(w.at, buildKey, module); + checkInside(module, place, + w.type.equals("bytes") ? ((byte[]) w.value).length : Values.typeSize(w.type)); + Object v = defaultOf(c, w.value, chosen); + if (v instanceof Boolean) { + v = ((Boolean) v) ? 1L : 0L; + } + byte[] data; + if (w.type.equals("bytes")) { + data = (byte[]) w.value; + } else { + if (!Values.fits(w.type, v)) { + throw new Atmosphere.Unclear("a value its write cannot hold", "value-out-of-range"); + } + data = Values.encode(w.type, v, false); + } + stores.addAll(stores(place, data)); + } else if (op instanceof Model.Override) { + Model.Override o = (Model.Override) op; + if (o.expect == null) { + throw new Atmosphere.Unclear("an override without expect", "atmosphere:override"); + } + Object v = defaultOf(c, o.value, chosen); + long bits = v == null ? 0 : Values.bits(v); + byte[] stub = Encode.arm64Stub(o.action, bits); + if (stub.length > o.expect.length) { + throw new Atmosphere.Unclear("an override whose stub is longer than expect", "atmosphere:override"); + } + Atmosphere.Place place = place(o.function, buildKey, module); + checkInside(module, place, stub.length); + checkModule(module, place, Arrays.copyOf(o.expect, stub.length), stub); + stores.addAll(stores(place, stub)); + restores.addAll(stores(place, Arrays.copyOf(o.expect, stub.length))); + } else if (op instanceof Model.Condition) { + conds.add((Model.Condition) op); + } else if (op instanceof Model.Read) { + throw new Atmosphere.Unclear("a monitor has no Atmosph\u00E8re form", "atmosphere:monitor"); + } + } + if (conds.size() > 1 || (!conds.isEmpty() && (!c.match().equals("all") || !c.trigger().equals("while") + || c.interval() != 1))) { + throw new Atmosphere.Unclear("conditions that Atmosph\u00E8re cannot say", "atmosphere:condition"); + } + List body = new ArrayList<>(); + for (Atmosphere.Store s : stores) { + body.addAll(Atmosphere.storeWords(s.place, s.width, s.value)); + } + if (!conds.isEmpty()) { + Model.Condition cond = conds.get(0); + Atmosphere.Place place = place(cond.at, buildKey, module); + checkInside(module, place, Arrays.asList("u8", "u16", "u32", "u64").contains(cond.type) + ? Values.typeSize(cond.type) : 1); + Object value = defaultOf(c, cond.value, chosen); + if (place.hasPath() || !Arrays.asList("u8", "u16", "u32", "u64").contains(cond.type) + || !Atmosphere.isConditionOp(cond.op) || !Values.isInt(value)) { + throw new Atmosphere.Unclear("a condition that Atmosph\u00E8re cannot say", "atmosphere:condition"); + } + List words = Atmosphere.conditionWords(place, Integer.parseInt(cond.type.substring(1)) / 8, cond.op, + Values.bits(value)); + words.addAll(body); + words.add(0x20000000L); + body = words; + } + List words; + if (c.run().equals("action")) { + boolean writes = false; + for (Model.Op op : c.ops()) { + writes |= op instanceof Model.Write; + } + if (c.hold() != null || writes) { + throw new Atmosphere.Unclear("an action with writes or hold has no Atmosph\u00E8re form", + "atmosphere:action"); + } + words = new ArrayList<>(); + words.add(0x80000000L | Atmosphere.keyMask(c.press())); + words.addAll(body); + words.add(0x20000000L); + } else if (c.hold() != null) { + words = new ArrayList<>(); + words.add(0x80000000L | Atmosphere.keyMask(c.hold())); + words.addAll(body); + if (!restores.isEmpty()) { + words.add(0x21000000L); + for (Atmosphere.Store s : restores) { + words.addAll(Atmosphere.storeWords(s.place, s.width, s.value)); + } + } + words.add(0x20000000L); + } else { + words = body; + } + if (words.isEmpty()) { + throw new Atmosphere.Unclear("nothing to write", "atmosphere:empty"); + } + return words; + } + + /** The names of an original file's entries, sorted by how a regenerated file has their code. Immutable. */ + public static final class Comparison { + private final List same; + private final List differ; + private final List missing; + + Comparison(List same, List differ, List missing) { + this.same = Collections.unmodifiableList(new ArrayList<>(same)); + this.differ = Collections.unmodifiableList(new ArrayList<>(differ)); + this.missing = Collections.unmodifiableList(new ArrayList<>(missing)); + } + + /** Returns the entries whose code the other file has the same. */ + public List same() { + return same; + } + + /** Returns the entries whose code the other file has otherwise. */ + public List differ() { + return differ; + } + + /** Returns the entries the other file lacks. */ + public List missing() { + return missing; + } + } + + /** + * Compares the entries with code of two Atmosphère cheat files, by name. Code is the same + * when its words are; with effects, also when it writes the same bytes at the same places + * under the same buttons and condition, and puts the same back on release. Both files are + * read as the converter reads them: lines that are not code are passed over, and an entry + * that mixes code with other text is left out. + * + * @throws AtmosphereException for a name without its closing bracket + */ + public static Comparison compare(String original, String regenerated, boolean effects) throws AtmosphereException { + Map, Atmosphere.Entry> a = entryTable(original); + Map, Atmosphere.Entry> b = entryTable(regenerated); + List same = new ArrayList<>(); + List differ = new ArrayList<>(); + List missing = new ArrayList<>(); + for (Map.Entry, Atmosphere.Entry> e : a.entrySet()) { + Atmosphere.Entry other = b.get(e.getKey()); + String name = (String) e.getKey().get(0); + if (other == null) { + missing.add(name); + } else if (Arrays.equals(other.wordsShared(), e.getValue().wordsShared())) { + same.add(name); + } else { + List mine = effects ? effect(e.getValue()) : null; + List theirs = effects ? effect(other) : null; + if (effects && theirs != null && theirs.equals(mine)) { + same.add(name); + } else { + differ.add(name); + } + } + } + return new Comparison(same, differ, missing); + } + + private static Map, Atmosphere.Entry> entryTable(String text) throws AtmosphereException { + Map, Atmosphere.Entry> out = new LinkedHashMap<>(); + for (Atmosphere.Entry e : Atmosphere.parse(text, new ArrayList())) { + if (e.wordsShared().length > 0 && !Atmosphere.isNoop(e) && e.broken().isEmpty()) { + out.put(Arrays.asList(e.name(), e.master()), e); + } + } + return out; + } + + private static List effect(Atmosphere.Entry entry) { + Atmosphere.Derived d; + try { + d = Atmosphere.derive(entry); + } catch (Atmosphere.Unclear u) { + return null; + } + Map written = new HashMap<>(); + for (Atmosphere.Store s : d.stores) { + byte[] data = s.data(); + for (int i = 0; i < data.length; i++) { + written.put(s.place.plus(i), data[i] & 0xFF); + } + } + Object cond = d.condition == null ? null : d.condition.key(); + return Arrays.asList(d.keys, cond, d.released != null, written); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Ed25519.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Ed25519.java new file mode 100644 index 00000000..b9fc49e9 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Ed25519.java @@ -0,0 +1,145 @@ +package io.github.davdxpx.mistel.mncf; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * Ed25519 signature verification (RFC 8032) in plain Java, so that the reader needs no security + * provider that a platform may lack. + * + *

    Verification checks [S]B = R + [k]A without the cofactor, refuses S >= L, and refuses + * encodings of y >= p and points that are not on the curve. It works on public data only, so + * it does not need to run in constant time. + */ +final class Ed25519 { + + private static final BigInteger P = BigInteger.ONE.shiftLeft(255).subtract(BigInteger.valueOf(19)); + private static final BigInteger TWO = BigInteger.valueOf(2); + private static final BigInteger L = + BigInteger.ONE.shiftLeft(252).add(new BigInteger("27742317777372353535851937790883648493")); + private static final BigInteger D = + BigInteger.valueOf(-121665).multiply(inv(BigInteger.valueOf(121666))).mod(P); + private static final BigInteger SQRT_M1 = + TWO.modPow(P.subtract(BigInteger.ONE).shiftRight(2), P); + private static final BigInteger[] NEUTRAL = {BigInteger.ZERO, BigInteger.ONE, BigInteger.ONE, BigInteger.ZERO}; + private static final BigInteger[] BASE; + + static { + BigInteger y = BigInteger.valueOf(4).multiply(inv(BigInteger.valueOf(5))).mod(P); + BigInteger x = recoverX(y, 0); + BASE = new BigInteger[] {x, y, BigInteger.ONE, x.multiply(y).mod(P)}; + } + + private Ed25519() { + } + + private static BigInteger inv(BigInteger x) { + return x.modPow(P.subtract(TWO), P); + } + + /** Points in extended coordinates (X, Y, Z, T) with x = X/Z, y = Y/Z and x * y = T/Z. */ + private static BigInteger[] add(BigInteger[] p, BigInteger[] q) { + BigInteger a = p[1].subtract(p[0]).multiply(q[1].subtract(q[0])).mod(P); + BigInteger b = p[1].add(p[0]).multiply(q[1].add(q[0])).mod(P); + BigInteger c = TWO.multiply(p[3]).multiply(q[3]).multiply(D).mod(P); + BigInteger d = TWO.multiply(p[2]).multiply(q[2]).mod(P); + BigInteger e = b.subtract(a); + BigInteger f = d.subtract(c); + BigInteger g = d.add(c); + BigInteger h = b.add(a); + return new BigInteger[] {e.multiply(f).mod(P), g.multiply(h).mod(P), f.multiply(g).mod(P), e.multiply(h).mod(P)}; + } + + private static BigInteger[] mul(BigInteger s, BigInteger[] p) { + BigInteger[] q = NEUTRAL; + BigInteger[] addend = p; + for (int i = 0; i < s.bitLength(); i++) { + if (s.testBit(i)) { + q = add(q, addend); + } + addend = add(addend, addend); + } + return q; + } + + private static boolean equal(BigInteger[] p, BigInteger[] q) { + return p[0].multiply(q[2]).subtract(q[0].multiply(p[2])).mod(P).signum() == 0 + && p[1].multiply(q[2]).subtract(q[1].multiply(p[2])).mod(P).signum() == 0; + } + + private static BigInteger recoverX(BigInteger y, int sign) { + if (y.compareTo(P) >= 0) { + return null; + } + BigInteger yy = y.multiply(y); + BigInteger x2 = yy.subtract(BigInteger.ONE).multiply(inv(D.multiply(yy).add(BigInteger.ONE))).mod(P); + if (x2.signum() == 0) { + return sign != 0 ? null : BigInteger.ZERO; + } + BigInteger x = x2.modPow(P.add(BigInteger.valueOf(3)).shiftRight(3), P); + if (x.multiply(x).subtract(x2).mod(P).signum() != 0) { + x = x.multiply(SQRT_M1).mod(P); + } + if (x.multiply(x).subtract(x2).mod(P).signum() != 0) { + return null; + } + if ((x.testBit(0) ? 1 : 0) != sign) { + x = P.subtract(x); + } + return x; + } + + private static BigInteger littleEndian(byte[] data, int from, int length) { + byte[] reversed = new byte[length]; + for (int i = 0; i < length; i++) { + reversed[i] = data[from + length - 1 - i]; + } + return new BigInteger(1, reversed); + } + + private static BigInteger[] decompress(byte[] data, int from) { + BigInteger y = littleEndian(data, from, 32); + int sign = y.testBit(255) ? 1 : 0; + y = y.clearBit(255); + BigInteger x = recoverX(y, sign); + if (x == null) { + return null; + } + return new BigInteger[] {x, y, BigInteger.ONE, x.multiply(y).mod(P)}; + } + + private static BigInteger hashInt(byte[]... parts) { + MessageDigest sha512; + try { + sha512 = MessageDigest.getInstance("SHA-512"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-512 is not available", e); + } + for (byte[] part : parts) { + sha512.update(part); + } + byte[] h = sha512.digest(); + return littleEndian(h, 0, h.length).mod(L); + } + + /** Whether signature is a valid signature of message by the 32-byte public key. */ + static boolean verify(byte[] publicKey, byte[] message, byte[] signature) { + if (publicKey.length != 32 || signature.length != 64) { + return false; + } + BigInteger[] a = decompress(publicKey, 0); + BigInteger[] r = decompress(signature, 0); + if (a == null || r == null) { + return false; + } + BigInteger s = littleEndian(signature, 32, 32); + if (s.compareTo(L) >= 0) { + return false; + } + byte[] rBytes = new byte[32]; + System.arraycopy(signature, 0, rBytes, 0, 32); + BigInteger k = hashInt(rBytes, publicKey, message); + return equal(mul(s, BASE), add(r, mul(k, a))); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Encode.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Encode.java new file mode 100644 index 00000000..8744e713 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Encode.java @@ -0,0 +1,184 @@ +package io.github.davdxpx.mistel.mncf; + +import java.io.ByteArrayOutputStream; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Machine code the reader makes itself: the override stubs of section 7.5 and Appendix A, and + * the instructions of the {@code arm64-imm/1} extension. + */ +final class Encode { + + /** The instructions of {@code arm64-imm/1} and the number of bytes each one takes. */ + static final Map ARM64_IMM_INSNS; + + static { + Map insns = new LinkedHashMap<>(); + insns.put("movz", 4); + insns.put("movz-movk", 8); + insns.put("fmov", 4); + ARM64_IMM_INSNS = Collections.unmodifiableMap(insns); + } + + private static final long RET = 0xD65F03C0L; + + private Encode() { + } + + private static byte[] le32(long... words) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (long w : words) { + for (int i = 0; i < 4; i++) { + out.write((int) (w >>> (8 * i)) & 0xFF); + } + } + return out.toByteArray(); + } + + /** Whether Appendix A defines override stubs for this architecture. */ + static boolean hasStub(String arch) { + return "arm64".equals(arch) || "x86-64".equals(arch); + } + + /** + * The stub bytes for this architecture, or null where Appendix A defines none. + * + * @param value the 64 bits of the value "return" moves into the result register + */ + static byte[] stub(String arch, String action, long value) { + if ("arm64".equals(arch)) { + return arm64Stub(action, value); + } + if ("x86-64".equals(arch)) { + return x86Stub(action, value); + } + return null; + } + + /** The ARM64 stub: ret for "skip", the value moved into x0 and then ret for "return". */ + static byte[] arm64Stub(String action, long v) { + if (action.equals("skip")) { + return le32(RET); + } + if (Long.compareUnsigned(v, 0xFFFF) <= 0) { + return le32(0xD2800000L | v << 5, RET); // movz x0, #v + } + long inverted = ~v; + if (Long.compareUnsigned(inverted, 0xFFFF) <= 0) { + return le32(0x92800000L | inverted << 5, RET); // movn x0, #~v + } + long[] words = new long[5]; + int n = 0; + words[n++] = 0xD2800000L | (v & 0xFFFF) << 5; // movz x0, #(bits 0 to 15) + for (int hw = 1; hw <= 3; hw++) { + long chunk = (v >>> (16 * hw)) & 0xFFFF; + if (chunk != 0) { + words[n++] = 0xF2800000L | (long) hw << 21 | chunk << 5; // movk x0, #chunk, lsl #16*hw + } + } + long[] all = new long[n + 1]; + System.arraycopy(words, 0, all, 0, n); + all[n] = RET; + return le32(all); + } + + /** The x86-64 stub: ret for "skip", mov eax or rax and then ret for "return". */ + static byte[] x86Stub(String action, long v) { + if (action.equals("skip")) { + return new byte[] {(byte) 0xC3}; + } + if (Long.compareUnsigned(v, 0xFFFFFFFFL) <= 0) { + byte[] out = new byte[6]; + out[0] = (byte) 0xB8; + putLe(out, 1, v, 4); + out[5] = (byte) 0xC3; + return out; + } + if (v < 0 && v >= Integer.MIN_VALUE) { + byte[] out = new byte[8]; + out[0] = 0x48; + out[1] = (byte) 0xC7; + out[2] = (byte) 0xC0; + putLe(out, 3, v, 4); + out[7] = (byte) 0xC3; + return out; + } + byte[] out = new byte[11]; + out[0] = 0x48; + out[1] = (byte) 0xB8; + putLe(out, 2, v, 8); + out[10] = (byte) 0xC3; + return out; + } + + private static void putLe(byte[] out, int at, long v, int size) { + for (int i = 0; i < size; i++) { + out[at + i] = (byte) (v >>> (8 * i)); + } + } + + /** + * The 8-bit immediate of fmov for this value, or -1 if fmov cannot encode it exactly: a + * value of plus or minus (16 + m) / 16 times 2^e with m from 0 to 15 and e from -3 to 4. + */ + static int fmovImm8(Object value) { + if (!Values.isNumber(value)) { + return -1; + } + double v = Values.toDouble(value); + if (v == 0 || Double.isNaN(v) || Double.isInfinite(v)) { + return -1; + } + int sign = v < 0 ? 1 : 0; + double magnitude = Math.abs(v); + if (magnitude < Double.MIN_NORMAL) { + return -1; + } + int e = Math.getExponent(magnitude); // magnitude = f * 2^e, 1 <= f < 2 + double m16 = Math.scalb(magnitude, -e) * 16 - 16; // (f - 1) * 16 + if (e < -3 || e > 4 || m16 != Math.floor(m16) || m16 < 0 || m16 > 15) { + return -1; + } + int bcd = e >= 1 ? e - 1 : (0b100 | (e + 3)); // b = 0 for e in 1..4, b = 1 for e in -3..0 + return sign << 7 | bcd << 4 | (int) m16; + } + + /** The instruction bytes of an encode table of arm64-imm/1, or null if the value does not fit. */ + static byte[] arm64Imm(String insn, int width, int rd, Object value) { + long sf = width == 64 ? 1 : 0; + switch (insn) { + case "movz": { + if (!Values.isInt(value) || !inRange(value, 0xFFFFL)) { + return null; + } + long v = Values.bits(value); + return le32(sf << 31 | 0x52800000L | v << 5 | rd); + } + case "movz-movk": { + if (!Values.isInt(value) || !inRange(value, 0xFFFFFFFFL)) { + return null; + } + long v = Values.bits(value); + long lo = v & 0xFFFF; + long hi = v >>> 16; + return le32(sf << 31 | 0x52800000L | lo << 5 | rd, sf << 31 | 0x72A00000L | hi << 5 | rd); + } + case "fmov": { + int imm8 = fmovImm8(value); + if (imm8 < 0) { + return null; + } + long ftype = width == 64 ? 1 : 0; + return le32(0x1E201000L | ftype << 22 | (long) imm8 << 13 | rd); + } + default: + return null; + } + } + + private static boolean inRange(Object value, long max) { + return Values.compare(value, 0L) >= 0 && Values.compare(value, max) <= 0; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Engine.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Engine.java new file mode 100644 index 00000000..f2fa814d --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Engine.java @@ -0,0 +1,814 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +/** + * The cheats of a loaded file in one runtime, from pass to pass (sections 7.2, 7.3, 7.9, 11.3 + * and 11.5). Between passes the caller says what the player does; {@link #tick} runs one pass + * and returns the changes to make, every cheat's state and what the monitors read. + * + *

    {@code
    + * Engine engine = new Engine(file, runtime, Choices.builder().on("money").build(), 60);
    + * engine.switchCheat("speed", true);           // what the player does between passes
    + * engine.setValue("money.count", 5000);
    + * engine.hold("ZL");
    + * Pass pass = engine.tick(memory, null);        // one pass
    + * for (Change c : pass.changes()) {
    + *     // patch, restore, hook, unhook, write, raw: all code changes in one stop
    + * }
    + * engine.stop();                                // the changes that put back every place
    + * }
    + * + *

    The engine reads guest memory only through the reader it is given, and changes nothing + * itself. It is not thread-safe: one thread calls it. + */ +public final class Engine { + + private static final Comparator UNSIGNED = new Comparator() { + @Override + public int compare(Long a, Long b) { + return Long.compareUnsigned(a, b); + } + }; + + /** What the engine keeps for one cheat between passes. */ + private static final class Run { + String refused; + String state; + String reason; + long passes; + Double started; + boolean pressed; + boolean heldBefore; + Map last = new HashMap<>(); + boolean active; + /** Operation index to the address and bytes of an applied patch or stub. */ + Map covers = new HashMap<>(); + /** Operation index to the address, action and value of a hook. */ + Map hooks = new HashMap<>(); + + void restart() { + passes = 0; + started = null; + pressed = false; + heldBefore = false; + last = new HashMap<>(); + } + } + + /** What one cheat does in a pass. */ + private static final class Work { + boolean active; + boolean keep; + Map> places; + List out = new ArrayList<>(); + List shown; + boolean acted; + } + + /** Guest memory as one pass reads it: each place once. */ + private static final class Reads implements GuestMemory { + private final GuestMemory memory; + private final Map, byte[]> seen = new HashMap<>(); + + Reads(GuestMemory memory) { + this.memory = memory; + } + + @Override + public byte[] read(long address, int size) { + List key = Arrays.asList(address, (long) size); + if (!seen.containsKey(key)) { + byte[] raw = memory.read(address, size); + seen.put(key, raw == null ? null : raw.clone()); + } + return seen.get(key); + } + } + + private final MncfFile file; + private final Runtime runtime; + private final double rate; + private final String build; + private final Evaluation evaluation; + private final Map values = new LinkedHashMap<>(); + private final Map> cache = new HashMap<>(); + private final Map own; + private final Map runs = new LinkedHashMap<>(); + private List on; + private Set held; + private Set heldBefore; + private List> presses = new ArrayList<>(); + private long number; + private final TreeMap kept = new TreeMap<>(UNSIGNED); + private final TreeMap now = new TreeMap<>(UNSIGNED); + private TreeMap hooked = new TreeMap<>(UNSIGNED); + + /** + * Loads a file's cheats into an engine, as {@link Evaluator#evaluate} does. + * + * @param choices what the player chose before, or null + * @param rate the passes per second, for timed cheats when the caller gives no time + * @throws IllegalArgumentException if the rate is not above 0 + */ + public Engine(MncfFile file, Runtime runtime, Choices choices, double rate) { + if (!(rate > 0)) { + throw new IllegalArgumentException("rate is the number of passes per second, above 0"); + } + if (choices == null) { + choices = Choices.none(); + } + this.file = file; + this.runtime = runtime; + this.rate = rate; + values.putAll(choices.values()); + Evaluator.Loaded loaded = Evaluator.load(file, runtime, choices, cache); + this.evaluation = loaded.evaluation; + this.build = loaded.evaluation.build(); + this.own = new LinkedHashMap<>(loaded.own); + this.on = loaded.on; + for (CheatResult r : loaded.evaluation.cheats()) { + Run run = new Run(); + run.refused = r.state().equals(CheatResult.REFUSED) ? r.reason() : null; + run.state = r.state(); + run.reason = r.reason(); + runs.put(r.id(), run); + } + held = new HashSet<>(runtime.held()); + heldBefore = new HashSet<>(runtime.held()); + } + + /** Loads a file's cheats into an engine at 60 passes per second. */ + public Engine(MncfFile file, Runtime runtime, Choices choices) { + this(file, runtime, choices, 60); + } + + /** Returns the evaluation of the file when it was loaded. */ + public Evaluation evaluation() { + return evaluation; + } + + /** Returns the key of the build that runs, or null. */ + public String build() { + return build; + } + + // What the player does between passes + + /** + * Switches a cheat on or off as the player does (section 7.8). A master cheat is not a + * switch, and a refused cheat cannot be switched on: both stay as they are. + * + * @return whether the cheat is on afterwards + * @throws IllegalArgumentException if the file has no such cheat + */ + public boolean switchCheat(String id, boolean switchOn) { + Cheat c = cheat(id); + Run run = runs.get(id); + if (c.isMaster() || run.refused != null) { + return on.contains(id); + } + if (switchOn && !on.contains(id)) { + setOn(Evaluator.switchOn(file, on, id), null); + } else if (!switchOn && on.contains(id)) { + setOn(Evaluator.switchOff(file, on, id), null); + } + return on.contains(id); + } + + /** + * Sets a value the player chose. A value the player cannot choose refuses the cheat with + * value-out-of-range, until a value that fits is set. + * + * @param key the cheat's id and the value's id, joined by a dot: "money.count" + * @param value a whole number, a float or a Boolean + * @throws IllegalArgumentException if the cheat has no such value, or for another kind of value + */ + public void setValue(String key, Object value) { + int dot = key.indexOf('.'); + String id = dot < 0 ? key : key.substring(0, dot); + Cheat c = cheat(id); + if (dot < 0 || !c.values().containsKey(key.substring(dot + 1))) { + throw new IllegalArgumentException("cheat " + id + " has no value " + (dot < 0 ? "" : key.substring(dot + 1))); + } + values.put(key, Choices.number(value)); + Choices.Builder b = Choices.builder(); + for (Map.Entry e : values.entrySet()) { + b.value(e.getKey(), e.getValue()); + } + own.put(id, Evaluator.ownResult(file, c, runtime, build, b.build(), cache)); + refresh(); + } + + /** Sets the buttons the player holds now. */ + public void hold(Collection buttons) { + held = new HashSet<>(buttons); + } + + /** Sets the buttons the player holds now. */ + public void hold(String... buttons) { + hold(Arrays.asList(buttons)); + } + + /** + * Says that the player pressed these buttons together since the last pass, for a press + * shorter than a pass. + * + * @param buttons names joined by "+", such as "ZL+R" + */ + public void press(String buttons) { + presses.add(new HashSet<>(Py.split(buttons, '+'))); + } + + /** Says that the player pressed these buttons together since the last pass. */ + public void press(Collection buttons) { + presses.add(new HashSet<>(buttons)); + } + + // What the engine says + + /** Returns every cheat's state now, in file order. */ + public List states() { + List out = new ArrayList<>(); + for (Cheat c : file.cheats()) { + Run run = runs.get(c.id()); + out.add(new CheatState(c.id(), run.state, run.reason)); + } + return Collections.unmodifiableList(out); + } + + /** + * Returns a cheat's state now. + * + * @throws IllegalArgumentException if the file has no such cheat + */ + public CheatState state(String id) { + cheat(id); + Run run = runs.get(id); + return new CheatState(id, run.state, run.reason); + } + + // Passes + + /** + * Runs one pass and returns what to change. + * + * @param memory guest memory as it is at this pass, or null for the runtime's + * @param time the time of the pass in seconds, or null: then the passes before it divided by + * the rate. Give the time at every pass or at none. + */ + public Pass tick(GuestMemory memory, Double time) { + number++; + double t = time != null ? time : (number - 1) / rate; + Reads read = new Reads(memory != null ? memory : Evaluator.runtimeMemory(runtime)); + Set> pressed = pressed(); + heldBefore = new HashSet<>(held); + presses = new ArrayList<>(); + + for (Cheat c : file.cheats()) { + if (c.toggle() != null && !c.isMaster() && runs.get(c.id()).refused == null + && pressed.contains(buttons(c.toggle()))) { + switchCheat(c.id(), !on.contains(c.id())); + } + } + for (Cheat c : file.cheats()) { + Run run = runs.get(c.id()); + if (c.run().equals("timed") && on.contains(c.id())) { + if (run.started == null) { + run.started = t; + } + if (Values.lessOrEqual(c.duration(), t - run.started)) { + setOn(Evaluator.switchOff(file, on, c.id()), c.id()); + } + } + } + + Map work = new LinkedHashMap<>(); + for (Cheat c : file.cheats()) { + if (on.contains(c.id()) && runs.get(c.id()).refused == null) { + work.put(c.id(), work(c, read, pressed)); + } + } + Map, byte[]> checked = check(work, read); + for (Cheat c : file.cheats()) { + if (work.containsKey(c.id()) && (!on.contains(c.id()) || runs.get(c.id()).refused != null)) { + work.remove(c.id()); + } + } + List changes = code(work, checked); + Map> shown = new LinkedHashMap<>(); + for (Cheat c : file.cheats()) { + Work w = work.get(c.id()); + if (w == null) { + continue; + } + changes.addAll(w.out); + if (w.shown != null) { + shown.put(c.id(), w.shown); + } + } + for (Cheat c : file.cheats()) { + Work w = work.get(c.id()); + if (c.run().equals("once") && w != null && w.acted && on.contains(c.id())) { + setOn(Evaluator.switchOff(file, on, c.id()), c.id()); + } + } + return new Pass(number, changes, states(), shown); + } + + /** + * Switches every cheat off and returns the changes that put back every place the cheats + * changed, as before a file is loaded again or the game stops (section 11.3). + */ + public List stop() { + setOn(new ArrayList(), null); + return Collections.unmodifiableList(code(new LinkedHashMap(), + new HashMap, byte[]>())); + } + + // The parts of a pass + + private static Set buttons(String text) { + return new HashSet<>(Py.split(text, '+')); + } + + /** The button combinations of the file that were pressed since the last pass. */ + private Set> pressed() { + Set> combos = new LinkedHashSet<>(); + for (Cheat c : file.cheats()) { + for (String text : new String[] {c.toggle(), c.press()}) { + if (text != null) { + combos.add(buttons(text)); + } + } + } + Set> out = new HashSet<>(); + for (Set combo : combos) { + boolean now = held.containsAll(combo) && !heldBefore.containsAll(combo); + for (Set p : presses) { + now |= p.containsAll(combo); + } + if (now) { + out.add(combo); + } + } + return out; + } + + /** What a cheat that is on does in this pass, and its state after it. */ + private Work work(Cheat c, Reads read, Set> pressed) { + Run run = runs.get(c.id()); + Evaluator.Result result = own.get(c.id()); + run.passes++; + if (result.uses.equals("raw")) { + run.state = CheatResult.ON; + run.reason = ""; + Work w = new Work(); + w.out.add(Change.raw(c.id(), result.rawEntry)); + w.acted = true; + return w; + } + if ((run.passes - 1) % c.interval() != 0) { + Work w = new Work(); + w.active = run.active; + w.keep = true; + return w; + } + boolean pressing = c.run().equals("action") && pressed.contains(buttons(c.press())); + if (Evaluator.waitsForButtons(c, held, run.pressed || pressing)) { + return waiting(run, ""); + } + Platform plat = file.platform(); + Map> places = new HashMap<>(); + for (Evaluator.Plan p : result.plans) { + List ps = Evaluator.followAll(plat, p, read); + if (ps == null) { + return waiting(run, "path-broken"); + } + places.put(p.index, ps); + } + Map last = new HashMap<>(); + Boolean holds = test(c, result.plans, places, read, last); + if (holds == null) { + return waiting(run, "path-broken"); + } + boolean acts = holds && (c.trigger().equals("while") || !run.heldBefore) + && (!c.run().equals("action") || pressing); + List out = new ArrayList<>(); + List shown = null; + if (acts) { + boolean big = plat.bigEndian(); + for (Evaluator.Plan p : result.plans) { + long address = places.get(p.index).get(0).address; + if (p.kind.equals("write")) { + if (p.expect != null) { + byte[] there = read.read(address, p.expect.length); + if (there == null) { + return waiting(run, "path-broken"); + } + if (!Arrays.equals(there, p.expect)) { + continue; + } + } + out.add(Change.write(c.id(), address, p.data)); + } else if (p.kind.equals("read")) { + byte[] raw = read.read(address, Values.typeSize(p.type)); + if (raw == null) { + return waiting(run, "path-broken"); + } + if (shown == null) { + shown = new ArrayList<>(); + } + shown.add(new Shown(p.label, p.type, Values.decode(p.type, raw, big))); + } + } + } + run.heldBefore = holds; + run.last = last; + if (acts && c.run().equals("action")) { + run.pressed = true; + } + run.state = c.run().equals("action") && !run.pressed ? CheatResult.WAITING : CheatResult.ON; + run.reason = ""; + Work w = new Work(); + w.active = holds && (!c.run().equals("action") || run.pressed); + w.places = places; + w.out = out; + w.shown = shown; + w.acted = acts; + return w; + } + + private static Work waiting(Run run, String reason) { + run.state = CheatResult.WAITING; + run.reason = reason; + return new Work(); + } + + /** + * Whether the cheat's conditions hold now, with the bytes its changed conditions read put + * into last; null if a place cannot be read. Every condition is tested, so that the result + * does not depend on the order of the tests. + */ + private Boolean test(Cheat c, List plans, Map> places, Reads read, + Map last) { + boolean big = file.platform().bigEndian(); + Run run = runs.get(c.id()); + List results = new ArrayList<>(); + for (Evaluator.Plan p : plans) { + if (!p.kind.equals("when")) { + continue; + } + Model.Condition cond = (Model.Condition) p.op; + byte[] raw = read.read(places.get(p.index).get(0).address, Values.typeSize(p.type)); + if (raw == null) { + return null; + } + if (cond.op.equals("changed")) { + last.put(p.index, raw); + byte[] before = run.last.get(p.index); + results.add(before != null && !Arrays.equals(before, raw)); + continue; + } + Object v = p.value; + if (v instanceof Evaluator.Target) { + String type = ((Model.Place) cond.value).type; + byte[] other = read.read(places.get(p.index).get(1).address, Values.typeSize(type)); + if (other == null) { + return null; + } + v = Values.decode(type, other, big); + } + results.add(holds(cond.op, Values.decode(p.type, raw, big), v)); + } + if (results.isEmpty()) { + return true; + } + if (c.match().equals("all")) { + return !results.contains(false); + } + return results.contains(true); + } + + /** Whether a condition's operator holds between the value read and the value it compares with. */ + private static boolean holds(String op, Object a, Object v) { + if (v instanceof Boolean) { + v = ((Boolean) v) ? 1L : 0L; + } + switch (op) { + case "between": + Model.Between b = (Model.Between) v; + return Values.lessOrEqual(b.low, a) && Values.lessOrEqual(a, b.high); + case "==": + return Values.same(a, v); + case "!=": + return !Values.same(a, v); + case "<": + return Values.less(a, v); + case "<=": + return Values.lessOrEqual(a, v); + case ">": + return Values.less(v, a); + case ">=": + return Values.lessOrEqual(v, a); + case "&": + return Values.big(a).and(Values.big(v)).signum() != 0; + default: + return Values.big(a).and(Values.big(v)).signum() == 0; + } + } + + /** + * Checks expect for every patch and override stub that covers a place it did not cover in + * the pass before (section 7.4), and refuses the cheats where it differs. Returns the + * original bytes found, by cheat and operation. + */ + private Map, byte[]> check(Map work, Reads read) { + Map, byte[]> checked = new HashMap<>(); + List refused = new ArrayList<>(); + for (Cheat c : file.cheats()) { + Work w = work.get(c.id()); + if (w == null || !w.active || w.keep) { + continue; + } + Run run = runs.get(c.id()); + for (Evaluator.Plan p : own.get(c.id()).plans) { + if (!(p.kind.equals("patch") || p.kind.equals("override")) || p.data == null) { + continue; + } + long address = w.places.get(p.index).get(0).address; + Object[] cover = run.covers.get(p.index); + if (cover != null && (Long) cover[0] == address && ((byte[]) cover[1]).length == p.data.length) { + continue; + } + int n = p.expect.length; + byte[] there = null; + boolean all = true; + for (int i = 0; i < n; i++) { + all &= kept.containsKey(address + i); + } + if (!all) { + there = read.read(address, n); + if (there == null) { + refused.add(new String[] {c.id(), "outside"}); + break; + } + } + byte[] found = new byte[n]; + for (int i = 0; i < n; i++) { + Integer k = kept.get(address + i); + found[i] = k != null ? (byte) (int) k : there[i]; + } + if (!Arrays.equals(found, p.expect) && (p.kind.equals("override") || !Arrays.equals(found, p.data))) { + refused.add(new String[] {c.id(), "expect-mismatch"}); + break; + } + checked.put(Arrays.asList(c.id(), p.index), found); + } + } + for (String[] r : refused) { + own.put(r[0], Evaluator.refusedResult(r[0], r[1])); + } + if (!refused.isEmpty()) { + refresh(); + } + return checked; + } + + /** + * The code changes of a pass (section 11.5). Every code byte that a cheat that is active + * covers gets that cheat's byte, the last such cheat in file order winning; every other byte + * the engine changed gets its original back. A patch or stub is written whole when one of + * its bytes is not what it should be; the bytes no cheat covers any more are put back whole, + * in runs, except a run whose bytes all hold their originals already. + */ + private List code(Map work, Map, byte[]> checked) { + Map want = new HashMap<>(); + TreeMap hooks = new TreeMap<>(UNSIGNED); + Map newKept = new HashMap<>(); + Map newNow = new HashMap<>(); + List ranges = new ArrayList<>(); + for (Cheat c : file.cheats()) { + Work w = work.get(c.id()); + Run run = runs.get(c.id()); + if (w == null || !w.active) { + run.active = false; + run.covers = new HashMap<>(); + run.hooks = new HashMap<>(); + continue; + } + Map covers = new HashMap<>(); + Map hookedHere = new HashMap<>(); + for (Evaluator.Plan p : own.get(c.id()).plans) { + if (!(p.kind.equals("patch") || p.kind.equals("override"))) { + continue; + } + long address; + byte[] data; + if (w.keep) { + // Between two tests: as the last test left it. + if (p.data == null) { + Object[] h = run.hooks.get(p.index); + if (h != null) { + hooks.put((Long) h[0], new Object[] {h[1], h[2]}); + hookedHere.put(p.index, h); + } + continue; + } + Object[] cover = run.covers.get(p.index); + if (cover == null) { + continue; + } + address = (Long) cover[0]; + data = (byte[]) cover[1]; + } else { + address = w.places.get(p.index).get(0).address; + data = p.data; + } + if (data == null) { + hooks.put(address, new Object[] {p.action, p.value}); + hookedHere.put(p.index, new Object[] {address, p.action, p.value}); + continue; + } + byte[] found = checked.get(Arrays.asList(c.id(), p.index)); + for (int i = 0; i < data.length; i++) { + long a = address + i; + want.put(a, data[i] & 0xFF); + if (!kept.containsKey(a) && !newKept.containsKey(a)) { + newKept.put(a, p.expect[i] & 0xFF); + newNow.put(a, (found != null ? found[i] : p.expect[i]) & 0xFF); + } + } + covers.put(p.index, new Object[] {address, data}); + ranges.add(new long[] {address, data.length}); + } + run.active = true; + run.covers = covers; + run.hooks = hookedHere; + } + kept.putAll(newKept); + now.putAll(newNow); + + TreeMap marked = new TreeMap<>(UNSIGNED); + for (long[] range : ranges) { + boolean differs = false; + for (int i = 0; i < range[1]; i++) { + long a = range[0] + i; + differs |= !want.get(a).equals(now.get(a)); + } + if (differs) { + for (int i = 0; i < range[1]; i++) { + marked.put(range[0] + i, Change.PATCH); + } + } + } + for (Long a : kept.keySet()) { + if (!want.containsKey(a)) { + marked.put(a, Change.RESTORE); + } + } + List code = new ArrayList<>(); // address, order, change + long start = 0; + String kind = null; + java.io.ByteArrayOutputStream data = new java.io.ByteArrayOutputStream(); + boolean differs = false; + for (Map.Entry e : marked.entrySet()) { + long a = e.getKey(); + int target = e.getValue().equals(Change.PATCH) ? want.get(a) : kept.get(a); + if (kind != null && kind.equals(e.getValue()) && start + data.size() == a) { + data.write(target); + } else { + if (kind != null && differs) { + code.add(new Object[] {start, 0, Change.code(kind, start, data.toByteArray())}); + } + start = a; + kind = e.getValue(); + data = new java.io.ByteArrayOutputStream(); + data.write(target); + differs = false; + } + differs |= target != now.get(a); + } + if (kind != null && differs) { + code.add(new Object[] {start, 0, Change.code(kind, start, data.toByteArray())}); + } + for (Map.Entry e : marked.entrySet()) { + long a = e.getKey(); + if (e.getValue().equals(Change.PATCH)) { + now.put(a, want.get(a)); + } else { + kept.remove(a); + now.remove(a); + } + } + Set addresses = new TreeSet<>(UNSIGNED); + addresses.addAll(hooked.keySet()); + addresses.addAll(hooks.keySet()); + for (long a : addresses) { + Object[] h = hooks.get(a); + if (h != null) { + if (!sameHook(hooked.get(a), h)) { + code.add(new Object[] {a, 1, Change.hook(a, (String) h[0], h[1])}); + } + } else { + code.add(new Object[] {a, 1, Change.unhook(a)}); + } + } + hooked = hooks; + Collections.sort(code, new Comparator() { + @Override + public int compare(Object[] x, Object[] y) { + int c = Long.compareUnsigned((Long) x[0], (Long) y[0]); + return c != 0 ? c : Integer.compare((Integer) x[1], (Integer) y[1]); + } + }); + List out = new ArrayList<>(); + for (Object[] item : code) { + out.add((Change) item[2]); + } + return out; + } + + private static boolean sameHook(Object[] a, Object[] b) { + if (a == null || !Objects.equals(a[0], b[0])) { + return false; + } + if (a[1] == null || b[1] == null) { + return a[1] == null && b[1] == null; + } + return Values.same(a[1], b[1]); + } + + // Switching + + /** Makes these the cheats that are on, and gives the ones that changed their state. */ + private void setOn(List next, String done) { + Set before = new HashSet<>(on); + on = next; + for (Cheat c : file.cheats()) { + Run run = runs.get(c.id()); + if (run.refused != null) { + continue; + } + if (before.contains(c.id()) && !next.contains(c.id())) { + run.state = CheatResult.OFF; + run.reason = c.id().equals(done) ? "done" : ""; + } else if (!before.contains(c.id()) && next.contains(c.id())) { + run.restart(); + boolean waits = own.get(c.id()).uses.equals("core") && Evaluator.waitsForButtons(c, held, false); + run.state = waits ? CheatResult.WAITING : CheatResult.ON; + run.reason = ""; + } + } + } + + /** + * Gives every cheat the result of its relations after a cheat's own result changed, and + * switches off the cheats that are refused now. + */ + private void refresh() { + Map results = Evaluator.relations(file, own); + for (Cheat c : file.cheats()) { + Evaluator.Result r = results.get(c.id()); + Run run = runs.get(c.id()); + if (r.state.equals(CheatResult.REFUSED)) { + run.refused = r.reason; + run.state = CheatResult.REFUSED; + run.reason = r.reason; + } else if (run.refused != null) { + run.refused = null; + run.state = CheatResult.OFF; + run.reason = ""; + } + } + List next = on; + for (Cheat c : file.cheats()) { + if (next.contains(c.id()) && runs.get(c.id()).refused != null) { + next = Evaluator.switchOff(file, next, c.id()); + } + } + setOn(next, null); + } + + private Cheat cheat(String id) { + Cheat c = file.cheat(id); + if (c == null) { + throw new IllegalArgumentException("the file has no cheat " + id); + } + return c; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Evaluation.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Evaluation.java new file mode 100644 index 00000000..cef48427 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Evaluation.java @@ -0,0 +1,37 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** The build that runs and every cheat's result, as {@link Evaluator#evaluate} gives them. Immutable. */ +public final class Evaluation { + + private final String build; + private final List cheats; + + Evaluation(String build, List cheats) { + this.build = build; + this.cheats = Collections.unmodifiableList(new ArrayList<>(cheats)); + } + + /** Returns the key of the build that runs, or null when no build of the file matches. */ + public String build() { + return build; + } + + /** Returns the result of each cheat, in file order. */ + public List cheats() { + return cheats; + } + + /** Returns the result of the cheat with that id, or null. */ + public CheatResult cheat(String id) { + for (CheatResult c : cheats) { + if (c.id().equals(id)) { + return c; + } + } + return null; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Evaluator.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Evaluator.java new file mode 100644 index 00000000..0e7e0644 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Evaluator.java @@ -0,0 +1,1115 @@ +package io.github.davdxpx.mistel.mncf; + +import java.math.BigDecimal; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Identifies the build that runs and gives every cheat its state, reason and resolved + * operations (sections 5, 6, 11 and Appendix B). + */ +public final class Evaluator { + + private Evaluator() { + } + + /** A cheat cannot be used here, for the reason given. */ + private static final class Refused extends Exception { + private static final long serialVersionUID = 1L; + final String reason; + + Refused(String reason) { + super(reason, null, false, false); + this.reason = reason; + } + } + + /** + * The result of one cheat while the evaluation decides its state. A cheat whose own + * operations apply also has its planned operations; one that uses raw code, its entry. + */ + static final class Result { + final String id; + String state; + String reason; + final String uses; + final List ops; + boolean pathBroken; + List plans; + Model.Raw rawEntry; + + Result(String id, String state, String reason, String uses, List ops) { + this.id = id; + this.state = state; + this.reason = reason; + this.uses = uses; + this.ops = ops; + } + } + + /** A resolved place: its address and, for a place given in a module, the module and offset. */ + static final class Place { + final long address; + final String module; + final Long offset; + final Module inModule; + + Place(long address, String module, Long offset, Module inModule) { + this.address = address; + this.module = module; + this.offset = offset; + this.inModule = inModule; + } + } + + static final class SearchKey { + final Module module; + final int[] items; + final String section; + + SearchKey(Module module, int[] items, String section) { + this.module = module; + this.items = items; + this.section = section; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof SearchKey)) { + return false; + } + SearchKey k = (SearchKey) o; + return module == k.module && Arrays.equals(items, k.items) && Objects.equals(section, k.section); + } + + @Override + public int hashCode() { + return System.identityHashCode(module) * 31 + Arrays.hashCode(items) * 7 + Objects.hashCode(section); + } + } + + private static Result refused(String id, String reason) { + return new Result(id, CheatResult.REFUSED, reason, "", Collections.emptyList()); + } + + /** A cheat's own result when it is refused for the reason given. */ + static Result refusedResult(String id, String reason) { + return refused(id, reason); + } + + /** Returns the key of the build that runs, or null (section 5). */ + public static String identify(MncfFile f, Runtime rt) { + if (rt.build() != null) { + return f.builds().containsKey(rt.build()) ? rt.build() : null; + } + for (Build b : f.builds().values()) { + boolean all = true; + for (Map.Entry e : b.modules().entrySet()) { + Module m = rt.modules().get(e.getKey()); + if (m == null || m.id() == null || !f.platform().moduleIdMatches(e.getValue(), m.id())) { + all = false; + break; + } + } + if (all) { + return b.key(); + } + } + return null; + } + + /** Evaluates a file in a runtime with every cheat as its default. */ + public static Evaluation evaluate(MncfFile f, Runtime rt) { + return evaluate(f, rt, Choices.none()); + } + + /** Returns the build that runs and every cheat's state, reason and resolved operations. */ + public static Evaluation evaluate(MncfFile f, Runtime rt, Choices choices) { + return load(f, rt, choices == null ? Choices.none() : choices, new HashMap>()) + .evaluation; + } + + /** What loading a file gives: the evaluation, the cheats that are on, and each cheat's own result. */ + static final class Loaded { + final Evaluation evaluation; + final List on; + final Map own; + + Loaded(Evaluation evaluation, List on, Map own) { + this.evaluation = evaluation; + this.on = on; + this.own = own; + } + } + + /** + * Evaluates a file, and keeps the cheats that are on and each cheat's own result before its + * relations to other cheats were looked at. + */ + static Loaded load(MncfFile f, Runtime rt, Choices choices, Map> cache) { + String build = identify(f, rt); + Map own = new LinkedHashMap<>(); + for (Cheat c : f.cheats()) { + own.put(c.id(), ownResult(f, c, rt, build, choices, cache)); + } + Map results = relations(f, own); + List on = switchStates(f, results, choices, rt); + List out = new ArrayList<>(); + for (Cheat c : f.cheats()) { + Result r = results.get(c.id()); + out.add(new CheatResult(r.id, r.state, r.reason, r.uses, r.ops)); + } + return new Loaded(new Evaluation(build, out), on, own); + } + + /** A cheat's own result for the choices: refused with a reason, or its planned operations or raw entry. */ + static Result ownResult(MncfFile f, Cheat c, Runtime rt, String build, Choices choices, + Map> cache) { + String fileReason = fileReason(f, rt); + if (fileReason != null) { + return refused(c.id(), fileReason); + } + if (c.problem() != null) { + return refused(c.id(), c.problem()); + } + String arch = rt.arch() != null && !rt.arch().isEmpty() ? rt.arch() : f.platform().archs().get(0); + return cheat(f, c, rt, build, arch, choices, cache); + } + + private static String fileReason(MncfFile f, Runtime rt) { + if (!f.platform().name().equals(rt.platform()) + || (rt.gameId() != null && !Py.lower(rt.gameId()).equals(Py.lower(f.gameId())))) { + return "game-mismatch"; + } + String sig = f.signature().result(); + if (sig.equals(SignatureResult.INVALID) || sig.equals(SignatureResult.REVOKED)) { + return "signature"; + } + for (String name : f.requiredExtensions()) { + if (!rt.extensions().contains(name)) { + return "extension-missing:" + name; + } + } + return null; + } + + /** Whether the runtime applies this override by writing a stub over the function's first bytes. */ + private static boolean byBytes(Model.Override op, Runtime rt, String arch) { + return rt.capabilities().contains("code-bytes") && op.expect != null && Encode.hasStub(arch); + } + + /** Returns the parts of the core in {@link Mncf#FEATURES} that a cheat uses, in that order. */ + public static List uses(Cheat c) { + int conditions = 0; + boolean override = false; + for (Model.Op op : c.ops()) { + if (op instanceof Model.Condition) { + conditions++; + } + override |= op instanceof Model.Override; + } + Set used = new HashSet<>(); + if (!"on".equals(c.run())) { + used.add("run." + c.run()); + } + if (c.hold() != null) { + used.add("hold"); + } + if (c.toggle() != null) { + used.add("toggle"); + } + if (c.press() != null) { + used.add("press"); + } + if (conditions > 0) { + used.add("when"); + if (conditions > 1) { + used.add("when.many"); + } + if ("any".equals(c.match())) { + used.add("match.any"); + } + if ("enter".equals(c.trigger())) { + used.add("trigger.enter"); + } + if (c.interval() != 1) { + used.add("interval"); + } + } + if (override) { + used.add("override"); + } + List out = new ArrayList<>(); + for (String k : Mncf.FEATURES) { + if (used.contains(k)) { + out.add(k); + } + } + return out; + } + + private static Result cheat(MncfFile f, Cheat c, Runtime rt, String build, String arch, Choices choices, + Map> cache) { + for (String k : uses(c)) { + if (rt.unsupported().contains(k)) { + return refused(c.id(), "runtime:unsupported:" + k); + } + } + List buttonCaps = c.hold() != null || c.toggle() != null || c.press() != null + ? Collections.singletonList("buttons") : Collections.emptyList(); + List caps = new ArrayList<>(); + List exts = new ArrayList<>(); + for (Model.Op op : c.ops()) { + boolean path = op.location().hasPath(); + if (op instanceof Model.Condition && ((Model.Condition) op).value instanceof Model.Place) { + path |= ((Model.Place) ((Model.Condition) op).value).at.hasPath(); + } + if (path || op instanceof Model.Condition || op instanceof Model.Read) { + caps.add("guest-read"); + } + if (op instanceof Model.Write) { + caps.add("guest-write"); + } + if (op instanceof Model.Patch) { + caps.add("code-bytes"); + if (((Model.Patch) op).encode != null) { + exts.add("arm64-imm/1"); + } + } + if (op instanceof Model.Read) { + caps.add("display"); + } + if (op instanceof Model.Override && !byBytes((Model.Override) op, rt, arch)) { + caps.add("code-hook"); + } + } + caps.addAll(buttonCaps); + List missing = new ArrayList<>(); + for (String cap : Mncf.CAPABILITIES) { + if (caps.contains(cap) && !rt.capabilities().contains(cap)) { + missing.add(cap); + } + } + List missingExt = new ArrayList<>(); + for (String e : exts) { + if (!rt.extensions().contains(e)) { + missingExt.add(e); + } + } + boolean runsRaw = false; + if (rt.extensions().contains("raw/1")) { + for (Model.Raw r : c.raw()) { + runsRaw |= rt.rawSyntaxes().contains(r.syntax); + } + } + Model.Raw entry = null; + for (Model.Raw r : c.raw()) { + if (runsRaw && r.build.equals(build) && rt.rawSyntaxes().contains(r.syntax)) { + entry = r; + break; + } + } + List buttonsMissing = new ArrayList<>(); + for (String cap : buttonCaps) { + if (!rt.capabilities().contains(cap)) { + buttonsMissing.add(cap); + } + } + if (!c.coreOps().isEmpty()) { + if (missing.isEmpty() && missingExt.isEmpty()) { + return core(f, c, rt, build, arch, choices, cache); + } + if (entry != null && buttonsMissing.isEmpty()) { + return raw(c, entry); + } + return refused(c.id(), !missing.isEmpty() ? "capability-missing:" + missing.get(0) + : "extension-missing:" + missingExt.get(0)); + } + if (!runsRaw) { + return refused(c.id(), "extension-missing:raw/1"); + } + if (!buttonsMissing.isEmpty()) { + return refused(c.id(), "capability-missing:" + buttonsMissing.get(0)); + } + if (entry == null) { + return refused(c.id(), "build-unknown"); + } + return raw(c, entry); + } + + private static Result raw(Cheat c, Model.Raw r) { + ResolvedOp.Builder op = new ResolvedOp.Builder("raw"); + op.syntax = r.syntax; + op.build = r.build; + op.code = r.code; + Result result = new Result(c.id(), CheatResult.OFF, "", "raw", Collections.singletonList(op.done())); + result.rawEntry = r; + return result; + } + + /** + * The value the player chose, or the default. A chosen value that the player cannot choose + * refuses the cheat: not of the value's kind, NaN, too wide, outside min and max, or not + * among the choices. + */ + private static Object value(Cheat c, Model.ValueRef ref, Choices choices) throws Refused { + ValueSpec spec = c.values().get(ref.name); + String key = c.id() + "." + ref.name; + if (!choices.values().containsKey(key)) { + return spec.defaultValue(); + } + Object v = choices.values().get(key); + boolean ok; + if (spec.type().equals("bool")) { + ok = v instanceof Boolean; + } else if (Values.isFloatType(spec.type())) { + ok = Values.isNumber(v) && !Schema.isNan(v) && Values.fits(spec.type(), v); + } else { + ok = Values.isInt(v) && Values.fits(spec.type(), v); + } + if (!ok || !Schema.inSpec(spec, v)) { + throw new Refused("value-out-of-range"); + } + return v; + } + + /** + * The value the player chose, or the default, as {@link #value} gives it; null when the + * chosen value is not one the player can choose. + */ + static Object chosenValue(Cheat c, Model.ValueRef ref, Choices choices) { + try { + return value(c, ref, choices); + } catch (Refused r) { + return null; + } + } + + /** + * Resolves a cheat's operations for the runtime as it is now: plans them, then follows their + * pointer paths with the runtime's guest memory. + */ + private static Result core(MncfFile f, Cheat c, Runtime rt, String build, String arch, Choices choices, + Map> cache) { + List ops = new ArrayList<>(); + List plans = new ArrayList<>(); + boolean waiting = false; + GuestMemory memory = runtimeMemory(rt); + try { + int index = 0; + for (Model.Op op : c.ops()) { + Plan p = plan(f, c, index++, op, rt, build, arch, choices, cache); + plans.add(p); + List places = followAll(f.platform(), p, memory); + if (places == null) { + waiting = true; + ops.add(new ResolvedOp.Builder(p.kind).done()); + continue; + } + if (p.pathExpect) { + checkExpect(rt, places.get(0), p.expect, p.kind.equals("patch") ? p.data : null); + } + ops.add(p.resolved(places)); + } + } catch (Refused r) { + return refused(c.id(), r.reason); + } + Result result = new Result(c.id(), CheatResult.OFF, "", "core", ops); + result.pathBroken = waiting; + result.plans = Collections.unmodifiableList(plans); + return result; + } + + /** The runtime's reads as a {@link GuestMemory}. */ + static GuestMemory runtimeMemory(final Runtime rt) { + return new GuestMemory() { + @Override + public byte[] read(long address, int size) { + return rt.read(address, size); + } + }; + } + + /** + * A place an operation acts on before its pointer path is followed: the place of its base, + * the path, and how many bytes the operation reads or writes there. + */ + static final class Target { + final Place base; + final long[] path; + final int size; + + Target(Place base, long[] path, int size) { + this.base = base; + this.path = path; + this.size = size; + } + + boolean hasPath() { + return path != null && path.length > 0; + } + } + + /** + * One operation of a cheat, resolved as far as it can be without reading guest memory that + * changes. The targets are the operation's place and, for a condition that compares with + * another place, that place too. The data is what a patch, a write or an override stub + * writes; an override that the runtime hooks has none. A condition's value is a number, a + * Boolean, a Between, or the Target of the other place. + */ + static final class Plan { + final String kind; + final int index; + final Model.Op op; + final List targets; + byte[] data; + byte[] expect; + String type; + String action; + Object value; + String label; + boolean pathExpect; + + Plan(String kind, int index, Model.Op op, List targets) { + this.kind = kind; + this.index = index; + this.op = op; + this.targets = targets; + } + + ResolvedOp resolved(List places) { + Place p = places.get(0); + ResolvedOp.Builder out = new ResolvedOp.Builder(kind).place(p.address, p.module, p.offset); + if (kind.equals("patch")) { + out.expect = expect; + out.bytes = data; + } else if (kind.equals("write")) { + out.type = type; + out.expect = expect; + out.bytes = data; + } else if (kind.equals("override")) { + out.action = action; + out.value = value; + out.expect = expect; + out.bytes = data; + } else if (kind.equals("read")) { + out.type = type; + out.label = label; + } else { + Object v = value; + if (v instanceof Target) { + Map m = new LinkedHashMap<>(); + m.put("address", Values.unsigned(places.get(1).address)); + m.put("type", ((Model.Place) ((Model.Condition) op).value).type); + v = Collections.unmodifiableMap(m); + } else if (v instanceof Model.Between) { + v = ResolvedOp.pair(((Model.Between) v).low, ((Model.Between) v).high); + } + out.type = type; + out.op = ((Model.Condition) op).op; + out.value = v; + } + return out.done(); + } + } + + private static Plan plan(MncfFile f, Cheat c, int index, Model.Op op, Runtime rt, String build, String arch, + Choices choices, Map> cache) throws Refused { + boolean big = f.platform().bigEndian(); + if (op instanceof Model.Patch) { + Model.Patch p = (Model.Patch) op; + Target target = target(f, p.at, rt, build, p.expect.length, cache); + byte[] data; + if (p.encode != null) { + Model.Encoding e = p.encode; + Object v = e.value instanceof Model.ValueRef ? value(c, (Model.ValueRef) e.value, choices) : e.value; + data = Encode.arm64Imm(e.insn, e.width, e.rd, v); + if (data == null) { + throw new Refused("value-out-of-range"); + } + } else { + data = p.bytes; + } + if (!target.hasPath()) { + checkRewritten(rt, target.base, p.expect.length); + checkExpect(rt, target.base, p.expect, data); + } + Plan out = new Plan("patch", index, op, Collections.singletonList(target)); + out.data = data; + out.expect = p.expect; + out.pathExpect = target.hasPath(); + return out; + } + if (op instanceof Model.Write) { + Model.Write w = (Model.Write) op; + boolean isBytes = w.type.equals("bytes"); + int size = isBytes ? ((byte[]) w.value).length : Values.typeSize(w.type); + Target target = target(f, w.at, rt, build, size, cache); + byte[] data; + byte[] expect; + if (isBytes) { + data = (byte[]) w.value; + expect = (byte[]) w.expect; + } else { + Object v = w.value; + if (v instanceof Model.ValueRef) { + v = value(c, (Model.ValueRef) v, choices); + if (v instanceof Boolean) { + v = ((Boolean) v) ? 1L : 0L; + } + if (!Values.fits(w.type, v)) { + throw new Refused("value-out-of-range"); + } + } + data = Values.encode(w.type, v, big); + expect = w.expect != null ? Values.encode(w.type, w.expect, big) : null; + } + Plan out = new Plan("write", index, op, Collections.singletonList(target)); + out.data = data; + out.expect = expect; + out.type = w.type; + return out; + } + if (op instanceof Model.Override) { + Model.Override o = (Model.Override) op; + Object v = o.value; + if (v instanceof Model.ValueRef) { + v = whole(value(c, (Model.ValueRef) v, choices)); + } + boolean patches = byBytes(o, rt, arch); + byte[] stub = patches ? Encode.stub(arch, o.action, v == null ? 0 : Values.bits(v)) : null; + int size = o.expect != null ? o.expect.length : 4; + Target target = target(f, o.function, rt, build, size, cache); + if (patches) { + if (stub.length > o.expect.length) { + throw new Refused(o.value instanceof Model.ValueRef ? "value-out-of-range" : "invalid:override.expect"); + } + if (!target.hasPath()) { + checkRewritten(rt, target.base, stub.length); + checkExpect(rt, target.base, o.expect, null); + } + } + Plan out = new Plan("override", index, op, Collections.singletonList(target)); + out.data = stub; + out.expect = o.expect; + out.action = o.action; + out.value = v; + out.pathExpect = patches && target.hasPath(); + return out; + } + if (op instanceof Model.Read) { + Model.Read r = (Model.Read) op; + Target target = target(f, r.at, rt, build, Values.typeSize(r.type), cache); + Plan out = new Plan("read", index, op, Collections.singletonList(target)); + out.type = r.type; + out.label = r.label; + return out; + } + Model.Condition cond = (Model.Condition) op; + List targets = new ArrayList<>(); + targets.add(target(f, cond.at, rt, build, Values.typeSize(cond.type), cache)); + Object v = cond.value; + if (v instanceof Model.ValueRef) { + v = value(c, (Model.ValueRef) v, choices); + } else if (v instanceof Model.Place) { + Model.Place p = (Model.Place) v; + Target other = target(f, p.at, rt, build, Values.typeSize(p.type), cache); + targets.add(other); + v = other; + } + Plan out = new Plan("when", index, op, Collections.unmodifiableList(targets)); + out.type = cond.type; + out.value = v; + return out; + } + + /** A value as a whole number, as Python's int() makes one: a float loses its fraction. */ + private static Object whole(Object v) throws Refused { + if (v instanceof Boolean) { + return ((Boolean) v) ? 1L : 0L; + } + if (v instanceof Double) { + double d = (Double) v; + if (Double.isNaN(d) || Double.isInfinite(d)) { + throw new Refused("value-out-of-range"); + } + return Values.normalize(new BigDecimal(d).toBigInteger()); + } + return v; + } + + /** Whether size bytes from offset lie inside a range of the given length, all unsigned. */ + private static boolean inside(long offset, long need, long length) { + return Long.compareUnsigned(offset, length) <= 0 && Long.compareUnsigned(length - offset, need) >= 0; + } + + /** The place of a location's base (section 6.2), checked, and the pointer path that follows it. */ + private static Target target(MncfFile f, Model.Location loc, Runtime rt, String build, int size, + Map> cache) throws Refused { + Platform plat = f.platform(); + int pointer = plat.pointerSize(); + int need = loc.hasPath() ? pointer : size; + Place place; + if (loc.kind.equals("address")) { + place = new Place(loc.address, null, null, null); + if (rt.read(loc.address, need) == null) { + throw new Refused("outside"); + } + } else if (loc.kind.equals("module") || loc.kind.equals("module-builds") || loc.kind.equals("pattern")) { + Module m = rt.modules().get(loc.module); + if (m == null) { + throw new Refused("module-unknown"); + } + long off; + boolean negative = false; + if (loc.kind.equals("module")) { + off = loc.offset; + } else if (loc.kind.equals("module-builds")) { + if (build == null || !loc.offsets.containsKey(build)) { + throw new Refused("build-unknown"); + } + off = loc.offsets.get(build); + } else { + long found = search(m, loc, cache); + off = found + loc.offset; + negative = loc.offset < 0 && off < 0; + } + if (negative || (m.size() != null && !inside(off, need, m.size()))) { + throw new Refused("outside"); + } + place = new Place(m.base() + off, loc.module, off, m); + } else { + long[] r = rt.regionOrNull(loc.region); + if (r == null) { + throw new Refused("region-unknown"); + } + long off; + if (loc.kind.equals("region")) { + off = loc.offset; + } else { + if (build == null || !loc.offsets.containsKey(build)) { + throw new Refused("build-unknown"); + } + off = loc.offsets.get(build); + } + if (!inside(off, need, r[1])) { + throw new Refused("outside"); + } + place = new Place(r[0] + off, null, null, null); + } + return new Target(place, loc.hasPath() ? loc.path : null, size); + } + + /** + * The place a target names now: its base, or where its pointer path leads. Null where the + * path does not resolve at the moment: a null pointer, or a pointer or the place outside + * guest memory. + */ + static Place follow(Platform plat, Target target, GuestMemory memory) { + if (!target.hasPath()) { + return target.base; + } + int pointer = plat.pointerSize(); + long address = target.base.address; + long mask = pointer >= 8 ? -1L : (1L << (8 * pointer)) - 1; + for (long step : target.path) { + byte[] raw = memory.read(address, pointer); + if (raw == null || isZero(raw)) { + return null; + } + address = (number(raw, plat.bigEndian()) + step) & mask; + } + if (memory.read(address, target.size) == null) { + return null; + } + return new Place(address, null, null, null); + } + + /** The places of every target of a planned operation, or null if one of them does not resolve now. */ + static List followAll(Platform plat, Plan plan, GuestMemory memory) { + List places = new ArrayList<>(); + for (Target t : plan.targets) { + Place p = follow(plat, t, memory); + if (p == null) { + return null; + } + places.add(p); + } + return places; + } + + private static boolean isZero(byte[] raw) { + for (byte b : raw) { + if (b != 0) { + return false; + } + } + return true; + } + + private static long number(byte[] raw, boolean bigEndian) { + long v = 0; + int n = Math.min(raw.length, 8); + for (int i = 0; i < n; i++) { + int b = raw[bigEndian ? raw.length - 1 - i : i] & 0xFF; + v |= (long) b << (8 * i); + } + return v; + } + + private static long search(Module m, Model.Location loc, Map> cache) throws Refused { + SearchKey key = new SearchKey(m, loc.find, loc.section); + List found = cache.get(key); + if (found == null) { + found = findAll(m, loc.find, loc.section, 2); + cache.put(key, found); + } + if (found.isEmpty()) { + throw new Refused("pattern-not-found"); + } + if (found.size() > 1) { + throw new Refused("pattern-ambiguous"); + } + return found.get(0); + } + + /** + * Returns every module offset where a pattern matches, within the searched sections, up to + * a limit. Matches may overlap, and a match lies inside one section. Without a section, the + * code and rodata sections are searched, in that order. + * + * @param pattern a pattern such as "68 ?? 00 B9": at least four items, fixed bytes at both ends + * @param section code, rodata or data, or null for code and rodata + * @param limit the most matches to return, or 0 for all + * @throws IllegalArgumentException if the pattern is not valid + */ + public static List findAll(Module module, String pattern, String section, int limit) { + int[] items = Values.parsePattern(pattern); + if (items == null) { + throw new IllegalArgumentException("not a valid pattern: " + pattern); + } + return findAll(module, items, section, limit); + } + + static List findAll(Module m, int[] items, String section, int limit) { + List found = new ArrayList<>(); + // Sections that overlap count a place once. + Set seen = new HashSet<>(); + byte[] data = m.image(); + if (data == null) { + return found; + } + // The longest run of fixed bytes is searched for, with a Horspool skip table, and + // each place where it lies is then checked against the whole pattern. + int anchorAt = 0; + int anchorLength = 0; + for (int i = 0; i < items.length; ) { + if (items[i] < 0) { + i++; + continue; + } + int j = i; + while (j < items.length && items[j] >= 0) { + j++; + } + if (j - i > anchorLength) { + anchorAt = i; + anchorLength = j - i; + } + i = j; + } + byte[] anchor = new byte[anchorLength]; + for (int k = 0; k < anchorLength; k++) { + anchor[k] = (byte) items[anchorAt + k]; + } + int[] shift = new int[256]; + Arrays.fill(shift, anchorLength); + for (int k = 0; k < anchorLength - 1; k++) { + shift[anchor[k] & 0xFF] = anchorLength - 1 - k; + } + int lastAnchorByte = anchor[anchorLength - 1]; + int n = items.length; + for (long[] range : m.searchRanges(section)) { + long start = Math.max(0, Math.min(range[0], data.length)); + long end = Math.max(0, Math.min(range[1], data.length)); + if (end - start < n) { + continue; + } + int q = (int) start + anchorAt; + int last = (int) end - n + anchorAt; + while (q <= last) { + byte b = data[q + anchorLength - 1]; + if (b == lastAnchorByte && headMatches(data, q, anchor) && matches(data, q - anchorAt, items) + && seen.add(q - anchorAt)) { + found.add((long) (q - anchorAt)); + if (limit > 0 && found.size() >= limit) { + return found; + } + } + int next = q + shift[b & 0xFF]; + if (next < q) { + break; + } + q = next; + } + } + return found; + } + + /** Whether the run's bytes but its last, which the caller has checked, lie at the position. */ + private static boolean headMatches(byte[] data, int at, byte[] run) { + for (int k = 0; k < run.length - 1; k++) { + if (data[at + k] != run[k]) { + return false; + } + } + return true; + } + + private static boolean matches(byte[] data, int at, int[] items) { + for (int k = 0; k < items.length; k++) { + if (items[k] >= 0 && (data[at + k] & 0xFF) != items[k]) { + return false; + } + } + return true; + } + + /** Refuses a change over code the runtime rewrote for its own reasons (section 11.3). */ + private static void checkRewritten(Runtime rt, Place place, int length) throws Refused { + if (place.module != null && rt.wasRewritten(place.module, place.offset, length)) { + throw new Refused("runtime:rewritten"); + } + } + + private static void checkExpect(Runtime rt, Place place, byte[] expect, byte[] data) throws Refused { + byte[] actual; + if (place.inModule != null && place.inModule.image() != null) { + byte[] image = place.inModule.image(); + long start = place.offset; + if (Long.compareUnsigned(start, image.length) >= 0) { + actual = new byte[0]; + } else { + int s = (int) start; + int e = (int) Math.min(image.length, s + (long) expect.length); + actual = Arrays.copyOfRange(image, s, e); + } + } else { + actual = rt.read(place.address, expect.length); + if (actual == null) { + throw new Refused("outside"); + } + } + if (!Arrays.equals(actual, expect) && (data == null || !Arrays.equals(actual, data))) { + throw new Refused("expect-mismatch"); + } + } + + // Relations between cheats (section 9) + + /** The cheat and every cheat it requires, directly or not, in file order. */ + private static List closure(MncfFile f, String id) { + Set seen = new HashSet<>(); + Deque todo = new ArrayDeque<>(); + todo.push(id); + while (!todo.isEmpty()) { + String x = todo.pop(); + if (!seen.add(x)) { + continue; + } + for (String r : f.cheat(x).requires()) { + todo.push(r); + } + } + List out = new ArrayList<>(); + for (Cheat c : f.cheats()) { + if (seen.contains(c.id())) { + out.add(c.id()); + } + } + return out; + } + + /** The results after the relations between cheats (section 7.8), from each cheat's own result. */ + static Map relations(MncfFile f, Map own) { + Map results = new LinkedHashMap<>(own); + relate(f, results); + return results; + } + + private static void relate(MncfFile f, Map results) { + boolean changed = true; + while (changed) { + changed = false; + for (Cheat c : f.cheats()) { + if (results.get(c.id()).state.equals(CheatResult.REFUSED)) { + continue; + } + for (String req : c.requires()) { + if (results.get(req).state.equals(CheatResult.REFUSED)) { + results.put(c.id(), refused(c.id(), "requires:" + req)); + changed = true; + break; + } + } + } + } + for (Cheat c : f.cheats()) { + if (results.get(c.id()).state.equals(CheatResult.REFUSED)) { + continue; + } + String conflict = conflictIn(f, closure(f, c.id()), c.id()); + if (conflict != null) { + results.put(c.id(), refused(c.id(), "excludes:" + conflict)); + } + } + } + + /** A cheat of the group that can never be on together with the rest: what excludes:<id> names. */ + private static String conflictIn(MncfFile f, List group, String own) { + Set members = new HashSet<>(group); + for (String x : group) { + for (String y : f.cheat(x).excludes()) { + if (members.contains(y)) { + return !y.equals(own) ? y : x; + } + } + } + for (int i = 0; i < group.size(); i++) { + String radio = f.cheat(group.get(i)).radio(); + if (radio == null) { + continue; + } + for (int j = i + 1; j < group.size(); j++) { + String y = group.get(j); + if (radio.equals(f.cheat(y).radio())) { + return !y.equals(own) ? y : group.get(i); + } + } + } + return null; + } + + private static boolean conflicts(MncfFile f, String a, String b) { + Cheat ca = f.cheat(a); + Cheat cb = f.cheat(b); + return !a.equals(b) && (ca.excludes().contains(b) || cb.excludes().contains(a) + || (ca.radio() != null && ca.radio().equals(cb.radio()))); + } + + /** + * Switches on the cheats that are on when the file is loaded (section 11.2) and gives every + * cheat its state. Returns the cheats that are on. + */ + private static List switchStates(MncfFile f, Map results, Choices choices, Runtime rt) { + List on = new ArrayList<>(); + for (Cheat c : f.cheats()) { + if (!c.isMaster() && ((c.isDefault() && !choices.off().contains(c.id())) || choices.on().contains(c.id())) + && !results.get(c.id()).state.equals(CheatResult.REFUSED)) { + on = switchOn(f, on, c.id()); + } + } + for (Cheat c : f.cheats()) { + Result r = results.get(c.id()); + if (r.state.equals(CheatResult.REFUSED)) { + continue; + } + if (!on.contains(c.id())) { + r.state = CheatResult.OFF; + } else if (r.pathBroken) { + r.state = CheatResult.WAITING; + r.reason = "path-broken"; + } else if (r.uses.equals("core") && waitsForButtons(c, rt.held(), false)) { + r.state = CheatResult.WAITING; + } else { + r.state = CheatResult.ON; + } + } + return on; + } + + /** Whether a cheat that is on waits for buttons: held buttons it needs, or the first press of an action. */ + static boolean waitsForButtons(Cheat c, java.util.Collection held, boolean pressedOnce) { + if (c.hold() != null && !held.containsAll(Py.split(c.hold(), '+'))) { + return true; + } + return c.run().equals("action") && !pressedOnce; + } + + /** + * The cheats that are on after x is switched on (section 7.8): x and the cheats it requires + * are on, and every cheat that conflicts with one of them is off, with the cheats that + * require it. + */ + static List switchOn(MncfFile f, List on, String x) { + List group = closure(f, x); + List kept = new ArrayList<>(); + for (String y : on) { + boolean clash = false; + for (String g : group) { + clash |= conflicts(f, y, g); + } + if (!clash) { + kept.add(y); + } + } + List out = new ArrayList<>(dropUnmet(f, kept)); + for (String g : group) { + if (!out.contains(g)) { + out.add(g); + } + } + return dropMasters(f, out); + } + + /** + * The cheats that are on after x is switched off: without x, the cheats that require it, and + * the master cheats that nothing on needs any more. + */ + static List switchOff(MncfFile f, List on, String x) { + List kept = new ArrayList<>(on); + kept.remove(x); + return dropMasters(f, dropUnmet(f, kept)); + } + + private static List dropMasters(MncfFile f, List on) { + Set needed = new HashSet<>(); + for (String y : on) { + if (!f.cheat(y).isMaster()) { + needed.addAll(closure(f, y)); + } + } + List kept = new ArrayList<>(); + for (String y : on) { + if (needed.contains(y)) { + kept.add(y); + } + } + return kept; + } + + private static List dropUnmet(MncfFile f, List on) { + while (true) { + List kept = new ArrayList<>(); + for (String y : on) { + if (on.containsAll(f.cheat(y).requires())) { + kept.add(y); + } + } + if (kept.equals(on)) { + return on; + } + on = kept; + } + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/GuestMemory.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/GuestMemory.java new file mode 100644 index 00000000..69d1a93c --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/GuestMemory.java @@ -0,0 +1,17 @@ +package io.github.davdxpx.mistel.mncf; + +/** + * The guest memory of a running game, as the original console addressed it. A runtime gives it + * to the reader so that pointer paths, conditions and absolute addresses can be resolved. + */ +public interface GuestMemory { + + /** + * Returns the bytes of guest memory at an address. + * + * @param address the address, an unsigned 64-bit number + * @param size how many bytes to read, at least 1 + * @return exactly size bytes, or null when any of them lies outside guest memory + */ + byte[] read(long address, int size); +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Lz4.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Lz4.java new file mode 100644 index 00000000..7a8fc0e9 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Lz4.java @@ -0,0 +1,79 @@ +package io.github.davdxpx.mistel.mncf; + +/** LZ4 block decompression, as Switch code modules (NSO) use it for their segments. */ +final class Lz4 { + + private Lz4() { + } + + /** The size bytes that the LZ4 block src holds. */ + static byte[] decompress(byte[] src, int size) throws Lz4Exception { + byte[] dst = new byte[size]; + int n = 0; + int i = 0; + int end = src.length; + while (i < end) { + int token = src[i++] & 0xFF; + long lit = token >>> 4; + if (lit == 15) { + long[] r = length(src, i, lit); + i = (int) r[0]; + lit = r[1]; + } + if (i + lit > end) { + throw new Lz4Exception("the block ends inside literals"); + } + // A block that grows past its segment can never end at its size again. + if (n + lit > size) { + throw new Lz4Exception("the block is longer than its segment"); + } + System.arraycopy(src, i, dst, n, (int) lit); + n += (int) lit; + i += (int) lit; + if (i >= end) { + break; + } + if (i + 2 > end) { + throw new Lz4Exception("the block ends inside an offset"); + } + int off = (src[i] & 0xFF) | (src[i + 1] & 0xFF) << 8; + i += 2; + long match = token & 15; + if (match == 15) { + long[] r = length(src, i, match); + i = (int) r[0]; + match = r[1]; + } + match += 4; + int start = n - off; + if (off == 0 || start < 0) { + throw new Lz4Exception("a match points before the start"); + } + if (n + match > size) { + throw new Lz4Exception("the block is longer than its segment"); + } + for (int k = 0; k < match; k++) { + dst[n + k] = dst[start + k]; + } + n += (int) match; + } + if (n != size) { + throw new Lz4Exception("the block holds " + n + " bytes, the segment " + size); + } + return dst; + } + + /** Reads the bytes that extend a length: (the next position, the length). */ + private static long[] length(byte[] src, int i, long n) throws Lz4Exception { + while (true) { + if (i >= src.length) { + throw new Lz4Exception("the block ends inside a length"); + } + int b = src[i++] & 0xFF; + n += b; + if (b != 255) { + return new long[] {i, n}; + } + } + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Lz4Exception.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Lz4Exception.java new file mode 100644 index 00000000..a90318f4 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Lz4Exception.java @@ -0,0 +1,12 @@ +package io.github.davdxpx.mistel.mncf; + +/** An LZ4 block in a code module is broken or does not hold the size its segment gives. */ +public final class Lz4Exception extends CodeModuleException { + + private static final long serialVersionUID = 1L; + + /** Makes an exception with a message for people. */ + public Lz4Exception(String message) { + super(message); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Mncf.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Mncf.java new file mode 100644 index 00000000..8b30b149 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Mncf.java @@ -0,0 +1,130 @@ +package io.github.davdxpx.mistel.mncf; + +import io.github.davdxpx.mistel.mncf.toml.Toml; +import io.github.davdxpx.mistel.mncf.toml.TomlDateTime; +import io.github.davdxpx.mistel.mncf.toml.TomlException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +/** + * Reads the Mistel Native Cheat Format, version 1 ({@code mncf/1}). + * + *
    {@code
    + * MncfFile file = Mncf.load(bytes, trust);              // throws MncfException
    + * Runtime runtime = Runtime.builder("switch").module("main", module).build();
    + * Evaluation ev = Evaluator.evaluate(file, runtime, Choices.none());
    + * }
    + */ +public final class Mncf { + + /** The format version this reader reads. */ + public static final String FORMAT = "mncf/1"; + + /** The most bytes a file, and an entry of a pack, may have: 16 MiB. */ + public static final int MAX_FILE = 16 * 1024 * 1024; + + /** The extensions this reader knows, with their versions. */ + public static final List KNOWN_EXTENSIONS = Schema.KNOWN_EXTENSIONS; + + /** The capabilities a runtime can have (section 11), in the order reasons name them. */ + public static final List CAPABILITIES = + Values.list("guest-read", "guest-write", "code-bytes", "code-hook", "buttons", "display"); + + /** + * The parts of the core a runtime may not have yet (section 11.1), in the order they are + * checked. {@link Runtime.Builder#unsupported} takes them. + */ + public static final List FEATURES = Values.list("run.once", "run.action", "run.timed", + "run.monitor", "hold", "toggle", "press", "when", "when.many", "match.any", "trigger.enter", + "interval", "override"); + + private Mncf() { + } + + /** + * Reads and checks an .mncf file without trusted keys: a signed file is then "unknown-key". + * + * @throws MncfException when the file cannot be used at all + */ + public static MncfFile load(byte[] data) throws MncfException { + return load(data, null); + } + + /** + * Reads and checks an .mncf file and its signature lines. + * + * @param data the bytes of the file, at most {@link #MAX_FILE} of them + * @param trust the keys the reader trusts, or null for none + * @throws MncfException when the file cannot be used at all, with the code "size" for a + * file of more than {@link #MAX_FILE} bytes + */ + public static MncfFile load(byte[] data, TrustList trust) throws MncfException { + if (data.length > MAX_FILE) { + throw new MncfException("size", "the file has more than " + MAX_FILE + " bytes"); + } + byte[] copy = data.clone(); + String text = decode(copy); + Map doc = parseToml(text, "toml"); + SignatureResult signature = Signatures.check(copy, trust); + byte[] signed = Signatures.split(copy).signed; + MncfFile.Parts parts = Schema.buildFile(doc); + return new MncfFile(copy, signed, signature, parts); + } + + /** + * The text of a file's bytes, checked against section 2: UTF-8 without a byte order mark, + * LF line ends. + */ + static String decode(byte[] data) throws MncfException { + if (data.length >= 3 && (data[0] & 0xFF) == 0xEF && (data[1] & 0xFF) == 0xBB && (data[2] & 0xFF) == 0xBF) { + throw new MncfException("encoding", "the file starts with a byte order mark"); + } + String problem = Utf8.check(data); + if (problem != null) { + throw new MncfException("encoding", "the file is not UTF-8 (" + problem + ")"); + } + String text = new String(data, StandardCharsets.UTF_8); + if (text.indexOf('\r') >= 0) { + throw new MncfException("encoding", "the file has CR characters; line ends are LF only"); + } + return text; + } + + /** + * Parses TOML text for the format: a document without date or time values, nested at most + * {@link #MAX_DEPTH} levels (section 2). + */ + @SuppressWarnings("unchecked") + static Map parseToml(String text, String code) throws MncfException { + Map doc; + try { + doc = Toml.parse(text); + } catch (TomlException e) { + throw new MncfException(code, e.getMessage()); + } + checkDepthAndDates(doc, 0, code); + return (Map) Values.freeze(doc); + } + + /** How deep tables and arrays may nest: the root table is depth 0, each table or array one more. */ + static final int MAX_DEPTH = 128; + + private static void checkDepthAndDates(Object v, int depth, String code) throws MncfException { + if (depth > MAX_DEPTH) { + throw new MncfException(code, "arrays and tables nest deeper than " + MAX_DEPTH + " levels"); + } + if (v instanceof TomlDateTime) { + throw new MncfException(code, "the format has no date or time values"); + } + if (v instanceof Map) { + for (Object item : ((Map) v).values()) { + checkDepthAndDates(item, depth + 1, code); + } + } else if (v instanceof List) { + for (Object item : (List) v) { + checkDepthAndDates(item, depth + 1, code); + } + } + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/MncfException.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/MncfException.java new file mode 100644 index 00000000..4b7b575c --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/MncfException.java @@ -0,0 +1,30 @@ +package io.github.davdxpx.mistel.mncf; + +/** + * A file or a pack cannot be used at all. {@link #code()} is one of the codes of Appendix D, + * such as "encoding", "toml", "format", "schema:game.id" or "zip". + */ +public final class MncfException extends Exception { + + private static final long serialVersionUID = 1L; + + private final String code; + private final String detail; + + /** Makes an exception with its code and a message for people. */ + public MncfException(String code, String detail) { + super(code + ": " + detail); + this.code = code; + this.detail = detail; + } + + /** Returns the code of Appendix D. */ + public String code() { + return code; + } + + /** Returns what is wrong, in words, without the code. */ + public String detail() { + return detail; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/MncfFile.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/MncfFile.java new file mode 100644 index 00000000..fb0ab15f --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/MncfFile.java @@ -0,0 +1,204 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** An .mncf file after it was read and checked. Immutable; made by {@link Mncf#load}. */ +public final class MncfFile { + + private final byte[] data; + private final byte[] signed; + private final SignatureResult signature; + private final Map doc; + private final String name; + private final Platform platform; + private final String gameId; + private final String gameName; + private final List authors; + private final String about; + private final String fileVersion; + private final String language; + private final Map origin; + private final List required; + private final List optional; + private final Map builds; + private final Map> choices; + private final List cheats; + private final List presets; + private final Map i18n; + private final List warnings; + + /** The checked parts of a file while the schema fills them in. */ + static final class Parts { + Map doc; + String name; + Platform platform; + String gameId; + String gameName; + List authors = new ArrayList<>(); + String about; + String fileVersion; + String language = "en"; + Map origin; + List required = new ArrayList<>(); + List optional = new ArrayList<>(); + Map builds = new LinkedHashMap<>(); + Map> choices = new LinkedHashMap<>(); + List cheats = new ArrayList<>(); + List presets = new ArrayList<>(); + Map i18n = new LinkedHashMap<>(); + List warnings = new ArrayList<>(); + } + + MncfFile(byte[] data, byte[] signed, SignatureResult signature, Parts p) { + this.data = data.clone(); + this.signed = signed.clone(); + this.signature = signature; + this.doc = p.doc; + this.name = p.name; + this.platform = p.platform; + this.gameId = p.gameId; + this.gameName = p.gameName; + this.authors = Collections.unmodifiableList(new ArrayList<>(p.authors)); + this.about = p.about; + this.fileVersion = p.fileVersion; + this.language = p.language; + this.origin = p.origin; + this.required = Collections.unmodifiableList(new ArrayList<>(p.required)); + this.optional = Collections.unmodifiableList(new ArrayList<>(p.optional)); + this.builds = Collections.unmodifiableMap(new LinkedHashMap<>(p.builds)); + Map> lists = new LinkedHashMap<>(); + for (Map.Entry> e : p.choices.entrySet()) { + lists.put(e.getKey(), Collections.unmodifiableMap(new LinkedHashMap<>(e.getValue()))); + } + this.choices = Collections.unmodifiableMap(lists); + this.cheats = Collections.unmodifiableList(new ArrayList<>(p.cheats)); + this.presets = Collections.unmodifiableList(new ArrayList<>(p.presets)); + this.i18n = p.i18n; + this.warnings = Collections.unmodifiableList(new ArrayList<>(p.warnings)); + } + + /** Returns a copy of the file's bytes. */ + public byte[] data() { + return data.clone(); + } + + /** Returns a copy of the bytes the signature covers: the file up to its first signature line. */ + public byte[] signedBytes() { + return signed.clone(); + } + + /** Returns the result of checking the file's signature lines. */ + public SignatureResult signature() { + return signature; + } + + /** Returns the whole document as parsed TOML, unmodifiable. */ + public Map doc() { + return doc; + } + + /** Returns the file's name. */ + public String name() { + return name; + } + + /** Returns the platform of the game. */ + public Platform platform() { + return platform; + } + + /** Returns the game's ID on its platform. */ + public String gameId() { + return gameId; + } + + /** Returns the game's name, or null. */ + public String gameName() { + return gameName; + } + + /** Returns the authors. */ + public List authors() { + return authors; + } + + /** Returns the description, or null. */ + public String about() { + return about; + } + + /** Returns the file's own version, or null. */ + public String fileVersion() { + return fileVersion; + } + + /** Returns the language of the file's texts; "en" when the file names none. */ + public String language() { + return language; + } + + /** + * Returns the source a converter read the file from, unmodifiable: its "format", and maybe + * its "name" and the "site" it came from. Null when the file was not converted. + */ + public Map origin() { + return origin; + } + + /** Returns the extensions the file needs, with their versions. */ + public List requiredExtensions() { + return required; + } + + /** Returns the extensions the file can use, with their versions. */ + public List optionalExtensions() { + return optional; + } + + /** Returns the builds the file knows, by key, in file order. */ + public Map builds() { + return builds; + } + + /** Returns the named choice lists: for each list, the name of each number, in file order. */ + public Map> choices() { + return choices; + } + + /** Returns the cheats, in file order. */ + public List cheats() { + return cheats; + } + + /** Returns the cheat with that id, or null. */ + public Cheat cheat(String id) { + for (Cheat c : cheats) { + if (c.id().equals(id)) { + return c; + } + } + return null; + } + + /** Returns the presets that are valid, in file order. */ + public List presets() { + return presets; + } + + /** Returns the translations as the file wrote them, by language, unmodifiable. */ + public Map i18n() { + return i18n; + } + + /** + * Returns the warnings: unknown-key:<key> for a key outside a cheat that the format does + * not define, preset:<id> for a preset that was dropped, and i18n for a broken i18n table. + */ + public List warnings() { + return warnings; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Model.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Model.java new file mode 100644 index 00000000..223b4b23 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Model.java @@ -0,0 +1,182 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.Map; + +/** The checked operations of a cheat, as the evaluator reads them. Built once by {@link Schema}. */ +final class Model { + + private Model() { + } + + /** + * A place (section 6.2). The kind is module, module-builds, pattern, region, region-builds or + * address. Offsets, addresses and path steps hold 64 bits and are unsigned, except the offset + * of a pattern, which is signed. + */ + static final class Location { + String kind; + String module; + String region; + long address; + long offset; + Map offsets; + int[] find; + String section; + long[] path; + + boolean hasPath() { + return path != null && path.length > 0; + } + } + + /** A reference to a value the player sets: "$count". */ + static final class ValueRef { + final String name; + + ValueRef(String name) { + this.name = name; + } + } + + /** One operation of a cheat. */ + abstract static class Op { + /** The kind as resolved operations name it: patch, write, override, read or when. */ + abstract String kind(); + + /** The place the operation acts on. */ + abstract Location location(); + } + + /** The instruction of an encode table (arm64-imm/1). The value is a number or a ValueRef. */ + static final class Encoding { + String insn; + int width; + int rd; + Object value; + } + + static final class Patch extends Op { + Location at; + byte[] expect; + byte[] bytes; + Encoding encode; + Map asm; + + @java.lang.Override + String kind() { + return "patch"; + } + + @java.lang.Override + Location location() { + return at; + } + } + + /** A write. The value is bytes, a number or a ValueRef; expect is bytes, a number or null. */ + static final class Write extends Op { + Location at; + String type; + Object value; + Object expect; + + @java.lang.Override + String kind() { + return "write"; + } + + @java.lang.Override + Location location() { + return at; + } + } + + /** An override. The value is a whole number, a ValueRef, or null for "skip". */ + static final class Override extends Op { + Location function; + String action; + Object value; + byte[] expect; + + @java.lang.Override + String kind() { + return "override"; + } + + @java.lang.Override + Location location() { + return function; + } + } + + static final class Read extends Op { + Location at; + String type; + String label; + + @java.lang.Override + String kind() { + return "read"; + } + + @java.lang.Override + Location location() { + return at; + } + } + + /** + * A condition. The value is a number, a ValueRef, a Between, a Place, or null for "changed". + */ + static final class Condition extends Op { + Location at; + String type; + String op; + Object value; + + @java.lang.Override + String kind() { + return "when"; + } + + @java.lang.Override + Location location() { + return at; + } + } + + /** The two ends of a "between" condition. */ + static final class Between { + final Object low; + final Object high; + + Between(Object low, Object high) { + this.low = low; + this.high = high; + } + } + + /** Another place a condition compares with. */ + static final class Place { + final Location at; + final String type; + + Place(Location at, String type) { + this.at = at; + this.type = type; + } + } + + /** Raw code of an existing cheat format, for one build (raw/1). */ + static final class Raw { + final String syntax; + final String build; + final String code; + + Raw(String syntax, String build, String code) { + this.syntax = syntax; + this.build = build; + this.code = code; + } + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Module.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Module.java new file mode 100644 index 00000000..7805d1a5 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Module.java @@ -0,0 +1,152 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * A code module that runs: its identity, where it is loaded, and its bytes as the module file + * gave them. Immutable once built. + * + *

    Sections map "code", "rodata" and "data" to ranges of offsets. Without any, the whole + * module is code. The module keeps the image array it was given without copying it, so that a + * large module costs no second copy; the caller must not change the array afterwards. + */ +public final class Module { + + private final String id; + private final long base; + private final byte[] image; + private final Long size; + private final Map sections; + + private Module(Builder b) { + id = b.id; + base = b.base; + image = b.image; + size = b.size != null ? b.size : (image != null ? Long.valueOf(image.length) : null); + Map s = new LinkedHashMap<>(b.sections); + if (s.isEmpty() && size != null) { + s.put("code", new long[] {0, size}); + } + sections = Collections.unmodifiableMap(s); + } + + /** + * Starts a module. + * + * @param id the module's identity: a build ID for a Switch module, "sha256:" and the hash of + * the file elsewhere; null when it is not known + */ + public static Builder builder(String id) { + return new Builder(id); + } + + /** Builds a {@link Module}. */ + public static final class Builder { + private final String id; + private long base; + private byte[] image; + private Long size; + private final Map sections = new LinkedHashMap<>(); + + private Builder(String id) { + this.id = id; + } + + /** Sets the address the module is loaded at. The default is 0. */ + public Builder base(long address) { + this.base = address; + return this; + } + + /** Sets the module's bytes as its file gave them, which patterns are searched in. */ + public Builder image(byte[] bytes) { + this.image = bytes; + return this; + } + + /** Sets the module's size in bytes. The default is the size of the image. */ + public Builder size(long bytes) { + this.size = bytes; + return this; + } + + /** Adds a section, such as "code", "rodata" or "data", from start up to but not including end. */ + public Builder section(String name, long start, long end) { + sections.put(name, new long[] {start, end}); + return this; + } + + /** Returns the module. */ + public Module build() { + return new Module(this); + } + } + + /** Returns the module's identity, or null when it is not known. */ + public String id() { + return id; + } + + /** Returns the address the module is loaded at. */ + public long base() { + return base; + } + + /** Returns whether the module has its bytes. */ + public boolean hasImage() { + return image != null; + } + + /** Returns the module's size in bytes, or null when it is not known. */ + public Long size() { + return size; + } + + /** Returns the names of the module's sections. */ + public List sectionNames() { + return Collections.unmodifiableList(new ArrayList<>(sections.keySet())); + } + + /** Returns whether the module has a section of that name. */ + public boolean hasSection(String name) { + return sections.containsKey(name); + } + + /** Returns the first offset of a section. */ + public long sectionStart(String name) { + return section(name)[0]; + } + + /** Returns the offset just after a section. */ + public long sectionEnd(String name) { + return section(name)[1]; + } + + private long[] section(String name) { + long[] range = sections.get(name); + if (range == null) { + throw new IllegalArgumentException("the module has no section " + name); + } + return range; + } + + byte[] image() { + return image; + } + + /** The ranges a pattern is searched in: the named section, or code and rodata. */ + List searchRanges(String section) { + List ranges = new ArrayList<>(); + String[] names = section != null ? new String[] {section} : new String[] {"code", "rodata"}; + for (String n : names) { + if (sections.containsKey(n)) { + ranges.add(sections.get(n)); + } + } + return ranges; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Pack.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Pack.java new file mode 100644 index 00000000..cb77815b --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Pack.java @@ -0,0 +1,79 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** A pack after it was read (section 13): its manifest, signature and files. Immutable. */ +public final class Pack { + + private final String name; + private final SignatureResult signature; + private final List files; + private final List authors; + private final String about; + private final String fileVersion; + private final List warnings; + + Pack(String name, SignatureResult signature, List files, List authors, String about, + String fileVersion, List warnings) { + this.name = name; + this.signature = signature; + this.files = Collections.unmodifiableList(new ArrayList<>(files)); + this.authors = Collections.unmodifiableList(new ArrayList<>(authors)); + this.about = about; + this.fileVersion = fileVersion; + this.warnings = Collections.unmodifiableList(new ArrayList<>(warnings)); + } + + /** Returns the pack's name. */ + public String name() { + return name; + } + + /** Returns the result of checking the manifest's signature lines. */ + public SignatureResult signature() { + return signature; + } + + /** Returns the files the manifest lists, in its order. */ + public List files() { + return files; + } + + /** Returns the file the manifest lists under that path, or null. */ + public PackFile file(String path) { + for (PackFile f : files) { + if (f.path().equals(path)) { + return f; + } + } + return null; + } + + /** Returns the authors. */ + public List authors() { + return authors; + } + + /** Returns the description, or null. */ + public String about() { + return about; + } + + /** Returns the pack's own version, or null. */ + public String fileVersion() { + return fileVersion; + } + + /** Returns the warnings: unknown-key:<key> for each key of the manifest the format does not define. */ + public List warnings() { + return warnings; + } + + /** Returns whether a runtime may apply the pack's files at all: not when the manifest's signature is bad. */ + public boolean usable() { + String r = signature.result(); + return !r.equals(SignatureResult.INVALID) && !r.equals(SignatureResult.REVOKED); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PackFile.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PackFile.java new file mode 100644 index 00000000..12df5f6d --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PackFile.java @@ -0,0 +1,44 @@ +package io.github.davdxpx.mistel.mncf; + +/** One file that a pack's manifest lists, and whether the pack holds it as listed. Immutable. */ +public final class PackFile { + + /** The pack holds the file and its bytes match the manifest. */ + public static final String OK = "ok"; + /** The pack holds the file, but its bytes differ from the manifest; it must not be applied. */ + public static final String HASH = "hash"; + /** The manifest lists the file, but the pack does not hold it. */ + public static final String MISSING = "missing"; + + private final String path; + private final String sha256; + private final byte[] data; + private final String status; + + PackFile(String path, String sha256, byte[] data, String status) { + this.path = path; + this.sha256 = sha256; + this.data = data; + this.status = status; + } + + /** Returns the file's path in the pack. */ + public String path() { + return path; + } + + /** Returns the SHA-256 hash the manifest gives, in lower-case hexadecimal. */ + public String sha256() { + return sha256; + } + + /** Returns a copy of the file's bytes when the status is ok, else null. */ + public byte[] data() { + return data == null ? null : data.clone(); + } + + /** Returns ok, hash or missing. */ + public String status() { + return status; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PackReader.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PackReader.java new file mode 100644 index 00000000..d0ec3564 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PackReader.java @@ -0,0 +1,214 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** Reads packs (section 13): a ZIP file .mncp with a manifest pack.toml at its root. */ +public final class PackReader { + + private static final List PACK_KEYS = Values.list("format", "name", "authors", "about", "file_version", "file"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + /** The most entries, directories not counted, a pack may have. */ + public static final int MAX_ENTRIES = 4096; + + /** The most bytes a reader reads from one pack: the manifest and the files it lists, 256 MiB. */ + public static final long MAX_TOTAL = 256L * 1024 * 1024; + + private PackReader() { + } + + /** + * Returns whether a path can name a file in a pack: not empty, parts separated by "/", no + * empty part, no "." or "..", and no backslash. + */ + public static boolean isValidPath(String path) { + if (path.isEmpty() || path.indexOf('\\') >= 0) { + return false; + } + for (String part : Py.split(path, '/')) { + if (part.isEmpty() || part.equals(".") || part.equals("..")) { + return false; + } + } + return true; + } + + /** + * Reads a pack's bytes and checks its manifest and files. + * + * @param zip the bytes of the .mncp file + * @param trust the keys the reader trusts, or null for none + * @throws MncfException when the pack cannot be used at all: zip, manifest, format, + * schema:<key> or path:<path>, or size for a pack of more than + * {@link #MAX_ENTRIES} entries, an entry of more than {@link Mncf#MAX_FILE} bytes, or + * more than {@link #MAX_TOTAL} bytes to read + */ + public static Pack read(byte[] zip, TrustList trust) throws MncfException { + return read(zip, trust, MAX_TOTAL); + } + + /** Reads a pack with another limit for the bytes it reads, so that tests can reach it. */ + @SuppressWarnings("unchecked") + static Pack read(byte[] zip, TrustList trust, long maxTotal) throws MncfException { + Zip archive; + List names = new ArrayList<>(); + try { + archive = Zip.open(zip); + } catch (Zip.ZipError e) { + throw new MncfException("zip", "not a ZIP file (" + e.getMessage() + ")"); + } + for (Zip.Entry e : archive.entries()) { + if (!e.name.endsWith("/")) { + names.add(e.name); + } + } + if (names.size() > MAX_ENTRIES) { + throw new MncfException("size", "the pack has more than " + MAX_ENTRIES + " entries"); + } + long[] budget = {0, maxTotal}; + if (new HashSet<>(names).size() != names.size()) { + throw new MncfException("zip", "two entries have the same name"); + } + if (!names.contains("pack.toml")) { + throw new MncfException("manifest", "there is no pack.toml at the root"); + } + byte[] raw = read(archive, "pack.toml", budget); + String text; + try { + text = Mncf.decode(raw); + } catch (MncfException e) { + throw new MncfException("manifest", e.detail()); + } + Map doc = Mncf.parseToml(text, "manifest"); + if (doc.isEmpty() || !doc.keySet().iterator().next().equals("format") || !"mncf-pack/1".equals(doc.get("format"))) { + throw new MncfException("format", "`format = \"mncf-pack/1\"` must be the first key of pack.toml"); + } + List warnings = new ArrayList<>(); + for (String k : doc.keySet()) { + if (!PACK_KEYS.contains(k)) { + warnings.add("unknown-key:" + k); + } + } + Object name = doc.get("name"); + if (!(name instanceof String)) { + throw new MncfException("schema:name", "`name` must be a string"); + } + SignatureResult signature = Signatures.check(raw, trust); + String about = null; + String fileVersion = null; + for (String key : new String[] {"about", "file_version"}) { + if (doc.containsKey(key)) { + if (!(doc.get(key) instanceof String)) { + throw new MncfException("schema:" + key, "`" + key + "` must be a string"); + } + if (key.equals("about")) { + about = (String) doc.get(key); + } else { + fileVersion = (String) doc.get(key); + } + } + } + List authors = new ArrayList<>(); + if (doc.containsKey("authors")) { + Object a = doc.get("authors"); + boolean good = a instanceof List; + if (good) { + for (Object x : (List) a) { + good &= x instanceof String; + } + } + if (!good) { + throw new MncfException("schema:authors", "`authors` must be an array of strings"); + } + for (Object x : (List) a) { + authors.add((String) x); + } + } + Object entries = doc.get("file"); + boolean good = entries instanceof List && !((List) entries).isEmpty(); + if (good) { + for (Object e : (List) entries) { + good &= e instanceof Map; + } + } + if (!good) { + throw new MncfException("schema:file", "the manifest needs at least one [[file]]"); + } + Set seen = new HashSet<>(); + List files = new ArrayList<>(); + for (Object item : (List) entries) { + Map e = (Map) item; + Object path = e.get("path"); + Object digest = e.get("sha256"); + if (!(path instanceof String)) { + throw new MncfException("schema:file.path", "`path` must be a string"); + } + if (!isValidPath((String) path) || path.equals("pack.toml") || seen.contains(path)) { + throw new MncfException("path:" + path, Py.repr(path) + " is not a usable path in a pack"); + } + if (!Py.matches(SHA256, digest)) { + throw new MncfException("schema:file.sha256", path + ": `sha256` must be 64 lower-case hexadecimal digits"); + } + for (String k : e.keySet()) { + if (!k.equals("path") && !k.equals("sha256")) { + warnings.add("unknown-key:file." + k); + } + } + seen.add((String) path); + if (!names.contains(path)) { + files.add(new PackFile((String) path, (String) digest, null, PackFile.MISSING)); + continue; + } + byte[] data = read(archive, (String) path, budget); + if (!hex(Signatures.sha256(data)).equals(digest)) { + files.add(new PackFile((String) path, (String) digest, null, PackFile.HASH)); + } else { + files.add(new PackFile((String) path, (String) digest, data, PackFile.OK)); + } + } + return new Pack((String) name, signature, files, authors, about, fileVersion, warnings); + } + + /** + * The bytes of one entry: only a stored or deflated entry that is not encrypted, and none of + * more than {@link Mncf#MAX_FILE} bytes, whatever its header claims. + * + * @param budget the bytes read from the pack so far, and the most it may read; updated + */ + private static byte[] read(Zip archive, String name, long[] budget) throws MncfException { + Zip.Entry e = archive.entry(name); + if (!Zip.readable(e)) { + throw new MncfException("zip", name + ": neither stored nor deflated, or encrypted"); + } + if (Long.compareUnsigned(e.size, Mncf.MAX_FILE) > 0) { + throw new MncfException("size", name + ": more than " + Mncf.MAX_FILE + " bytes"); + } + byte[] data; + try { + data = archive.read(e, Mncf.MAX_FILE + 1); + } catch (Zip.ZipError ex) { + throw new MncfException("zip", name + " cannot be read (" + ex.getMessage() + ")"); + } + if (data.length > Mncf.MAX_FILE) { + throw new MncfException("size", name + ": more than " + Mncf.MAX_FILE + " bytes"); + } + budget[0] += data.length; + if (budget[0] > budget[1]) { + throw new MncfException("size", "the pack holds more than " + budget[1] + " bytes"); + } + return data; + } + + private static String hex(byte[] bytes) { + StringBuilder b = new StringBuilder(); + for (byte x : bytes) { + b.append(String.format("%02x", x & 0xFF)); + } + return b.toString(); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Pass.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Pass.java new file mode 100644 index 00000000..9ba5316a --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Pass.java @@ -0,0 +1,60 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * What one pass did (section 11.5): its number, its changes in the order to make them, every + * cheat's state after it in file order, and the values the monitors read, by cheat. Immutable. + */ +public final class Pass { + + private final long number; + private final List changes; + private final List cheats; + private final Map> shown; + + Pass(long number, List changes, List cheats, Map> shown) { + this.number = number; + this.changes = Collections.unmodifiableList(new ArrayList<>(changes)); + this.cheats = Collections.unmodifiableList(new ArrayList<>(cheats)); + Map> copy = new LinkedHashMap<>(); + for (Map.Entry> e : shown.entrySet()) { + copy.put(e.getKey(), Collections.unmodifiableList(new ArrayList<>(e.getValue()))); + } + this.shown = Collections.unmodifiableMap(copy); + } + + /** Returns the pass's number, from 1. */ + public long number() { + return number; + } + + /** Returns the changes: code changes first, in address order, then writes and raw entries. */ + public List changes() { + return changes; + } + + /** Returns every cheat's state after the pass, in file order. */ + public List cheats() { + return cheats; + } + + /** Returns the state of the cheat with that id, or null. */ + public CheatState cheat(String id) { + for (CheatState c : cheats) { + if (c.id().equals(id)) { + return c; + } + } + return null; + } + + /** Returns the values each monitor that worked in the pass read, in the order of its reads. */ + public Map> shown() { + return shown; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Patch.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Patch.java new file mode 100644 index 00000000..f1651ad6 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Patch.java @@ -0,0 +1,68 @@ +package io.github.davdxpx.mistel.mncf; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * One patch of a patch file: the records it writes, in file order. Each record's offset counts + * from the start of the module's NSO file, its 0x100-byte header first and then the image. + * Immutable. + */ +public final class Patch { + + /** One record of a patch: an offset and the bytes written there. Immutable. */ + public static final class Record { + private final BigInteger offset; + private final byte[] data; + + /** Makes a record of an offset, which may lie anywhere, and its bytes. */ + public Record(BigInteger offset, byte[] data) { + this.offset = offset; + this.data = data.clone(); + } + + /** + * Returns the offset from the start of the NSO file. It is a BigInteger because an + * IPSwitch file's offset_shift may move it anywhere, also below 0. + */ + public BigInteger offset() { + return offset; + } + + /** Returns the bytes. */ + public byte[] data() { + return data.clone(); + } + + byte[] dataShared() { + return data; + } + } + + private final String name; + private final boolean enabled; + private final List records; + + Patch(String name, boolean enabled, List records) { + this.name = name; + this.enabled = enabled; + this.records = Collections.unmodifiableList(new ArrayList<>(records)); + } + + /** Returns the comment that names the patch in an IPSwitch file; empty for an IPS file. */ + public String name() { + return name; + } + + /** Returns whether the patch is applied: @enabled in an IPSwitch file; an IPS file always is. */ + public boolean enabled() { + return enabled; + } + + /** Returns the records, in file order. */ + public List records() { + return records; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PatchFile.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PatchFile.java new file mode 100644 index 00000000..9ef77787 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PatchFile.java @@ -0,0 +1,85 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** A patch file as {@link Patches} reads it: its format, its patches and what else it says. Immutable. */ +public final class PatchFile { + + /** A line of an IPSwitch file, by its number counted from 1 and its text. Immutable. */ + public static final class Line { + private final int line; + private final String text; + + /** Makes a line of its number and text. */ + public Line(int line, String text) { + this.line = line; + this.text = text; + } + + /** Returns the number of the line, counted from 1. */ + public int line() { + return line; + } + + /** Returns the text. */ + public String text() { + return text; + } + + @java.lang.Override + public boolean equals(Object o) { + return o instanceof Line && ((Line) o).line == line && ((Line) o).text.equals(text); + } + + @java.lang.Override + public int hashCode() { + return line * 31 + text.hashCode(); + } + + @java.lang.Override + public String toString() { + return "(" + line + ", " + Py.repr(text) + ")"; + } + } + + private final String format; + private final List patches; + private final String buildId; + private final List notes; + private final List comments; + + PatchFile(String format, List patches, String buildId, List notes, List comments) { + this.format = format; + this.patches = Collections.unmodifiableList(new ArrayList<>(patches)); + this.buildId = buildId; + this.notes = Collections.unmodifiableList(new ArrayList<>(notes)); + this.comments = Collections.unmodifiableList(new ArrayList<>(comments)); + } + + /** Returns "ips", "ips32" or "pchtxt". */ + public String format() { + return format; + } + + /** Returns the patches: one for an IPS file, each patch of an IPSwitch file in order. */ + public List patches() { + return patches; + } + + /** Returns the build ID the file names itself (@nsobid-), in upper-case hexadecimal, or null. */ + public String buildId() { + return buildId; + } + + /** Returns forced comments (#) and the lines that are no patch, with what they say. */ + public List notes() { + return notes; + } + + /** Returns the other comments, for credits. */ + public List comments() { + return comments; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PatchFileException.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PatchFileException.java new file mode 100644 index 00000000..1afc7a83 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PatchFileException.java @@ -0,0 +1,12 @@ +package io.github.davdxpx.mistel.mncf; + +/** A file that is not a patch file of a format {@link Patches} reads. Its code is "patch". */ +public final class PatchFileException extends ConvertException { + + private static final long serialVersionUID = 1L; + + /** Makes an exception with a message for people. */ + public PatchFileException(String message) { + super("patch", message); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PatchSource.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PatchSource.java new file mode 100644 index 00000000..0df4ac04 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/PatchSource.java @@ -0,0 +1,144 @@ +package io.github.davdxpx.mistel.mncf; + +/** + * One patch file of a code module for the converter: its bytes, the module it patches, and what + * else is known. Immutable. + * + *

    A patch needs expect, which a patch file does not hold, so the module is required: the + * original bytes come from it. The build ID comes from the file itself (@nsobid-), else from its + * name ("<build ID>.ips"), else from {@link Builder#buildId}, else from the module. + */ +public final class PatchSource { + + private final byte[] data; + private final CodeModule module; + private final String fileName; + private final String setName; + private final String moduleName; + private final String buildId; + private final String version; + private final String buildKey; + + private PatchSource(Builder b) { + data = b.data; + module = b.module; + fileName = b.fileName; + setName = b.setName; + moduleName = b.moduleName; + buildId = b.buildId; + version = b.version; + buildKey = b.buildKey; + } + + /** Starts a source of the bytes of an IPS, IPS32 or IPSwitch file. */ + public static Builder builder(byte[] data) { + return new Builder(data); + } + + /** Builds a {@link PatchSource}. */ + public static final class Builder { + private final byte[] data; + private CodeModule module; + private String fileName; + private String setName; + private String moduleName = "main"; + private String buildId; + private String version; + private String buildKey; + + private Builder(byte[] data) { + this.data = data.clone(); + } + + /** Sets the module the file patches, for expect and patterns. */ + public Builder module(CodeModule module) { + this.module = module; + return this; + } + + /** Sets the file's name or path, such as "exefs_patches/60fps/<build ID>.ips". */ + public Builder fileName(String name) { + this.fileName = name; + return this; + } + + /** Sets the patch set: its folder in exefs_patches, or the mod's name. The default comes from the file name. */ + public Builder setName(String name) { + this.setName = name; + return this; + } + + /** Sets the module's name: main, the default, sdk, or subsdk0 to subsdk9. */ + public Builder moduleName(String name) { + this.moduleName = name; + return this; + } + + /** Sets the module's build ID, for a file whose text and name do not give it. */ + public Builder buildId(String id) { + this.buildId = id; + return this; + } + + /** Sets the version the player sees, which also names the build in the file. */ + public Builder version(String version) { + this.version = version; + return this; + } + + /** Sets the build's name in the file; the default is the version, else the build ID. */ + public Builder buildKey(String key) { + this.buildKey = key; + return this; + } + + /** Returns the source. */ + public PatchSource build() { + return new PatchSource(this); + } + } + + /** Returns the bytes of the file. */ + public byte[] data() { + return data.clone(); + } + + byte[] dataShared() { + return data; + } + + /** Returns the module the file patches, or null. */ + public CodeModule module() { + return module; + } + + /** Returns the file's name, or null. */ + public String fileName() { + return fileName; + } + + /** Returns the patch set's name, or null. */ + public String setName() { + return setName; + } + + /** Returns the module's name. */ + public String moduleName() { + return moduleName; + } + + /** Returns the build ID given, or null. */ + public String buildId() { + return buildId; + } + + /** Returns the version, or null. */ + public String version() { + return version; + } + + /** Returns the build's name in the file, or null. */ + public String buildKey() { + return buildKey; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Patches.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Patches.java new file mode 100644 index 00000000..913f2eef --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Patches.java @@ -0,0 +1,511 @@ +package io.github.davdxpx.mistel.mncf; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Pattern; + +/** + * Patch files of the Switch's code modules (section 15): IPS, IPS32 and IPSwitch text + * (.pchtxt), as Atmosphère's exefs_patches and the emulators load them. + */ +public final class Patches { + + /** What a patch file's offsets count before the module's image: the NSO file's header. */ + public static final int NSO_HEADER = 0x100; + + private static final Pattern HEX = Pattern.compile("[0-9A-Fa-f]+"); + private static final BigInteger HEADER = BigInteger.valueOf(NSO_HEADER); + + private Patches() { + } + + /** + * Reads the patch file in these bytes: IPS or IPS32 by their magic, else IPSwitch text in + * UTF-8, with or without a byte order mark. + * + * @throws PatchFileException for bytes that are neither + */ + public static PatchFile read(byte[] data) throws PatchFileException { + if (startsWith(data, "PATCH") || startsWith(data, "IPS32")) { + return readIps(data); + } + if (data.length >= 3 && (data[0] & 0xFF) == 0xEF && (data[1] & 0xFF) == 0xBB && (data[2] & 0xFF) == 0xBF) { + data = Arrays.copyOfRange(data, 3, data.length); + } + if (Utf8.check(data) != null) { + throw new PatchFileException("neither an IPS file nor IPSwitch text in UTF-8"); + } + return readPchtxt(new String(data, StandardCharsets.UTF_8)); + } + + private static boolean startsWith(byte[] data, String magic) { + if (data.length < magic.length()) { + return false; + } + for (int i = 0; i < magic.length(); i++) { + if (data[i] != (byte) magic.charAt(i)) { + return false; + } + } + return true; + } + + /** + * Reads an IPS or IPS32 file: PATCH or IPS32, then records up to EOF or EEOF. A record is an + * offset (3 or 4 bytes, big-endian), a size (2 bytes) and that many bytes; a size of 0 is a + * run: a count (2 bytes) and the byte it repeats. Whatever follows the end marker is ignored. + * + * @throws PatchFileException for a file without the magic, or one that ends too early + */ + public static PatchFile readIps(byte[] data) throws PatchFileException { + String format; + int width; + String end; + if (startsWith(data, "IPS32")) { + format = "ips32"; + width = 4; + end = "EEOF"; + } else if (startsWith(data, "PATCH")) { + format = "ips"; + width = 3; + end = "EOF"; + } else { + throw new PatchFileException("not an IPS file: it starts with neither PATCH nor IPS32"); + } + List records = new ArrayList<>(); + int i = 5; + while (true) { + if (startsAt(data, i, end)) { + return new PatchFile(format, Collections.singletonList(new Patch("", true, records)), null, + Collections.emptyList(), Collections.emptyList()); + } + if ((long) i + width + 2 > data.length) { + throw new PatchFileException(String.format("the file ends at 0x%X without %s", i, end)); + } + long offset = 0; + for (int k = 0; k < width; k++) { + offset = offset << 8 | (data[i + k] & 0xFF); + } + int size = (data[i + width] & 0xFF) << 8 | (data[i + width + 1] & 0xFF); + i += width + 2; + if (size == 0) { + if ((long) i + 3 > data.length) { + throw new PatchFileException(String.format("a run at 0x%X is cut off", i)); + } + int count = (data[i] & 0xFF) << 8 | (data[i + 1] & 0xFF); + byte value = data[i + 2]; + i += 3; + if (count > 0) { + byte[] run = new byte[count]; + Arrays.fill(run, value); + records.add(new Patch.Record(BigInteger.valueOf(offset), run)); + } + } else { + if ((long) i + size > data.length) { + throw new PatchFileException(String.format("a record at 0x%X claims %d bytes past the end of the " + + "file", i, size)); + } + records.add(new Patch.Record(BigInteger.valueOf(offset), Arrays.copyOfRange(data, i, i + size))); + i += size; + } + } + } + + private static boolean startsAt(byte[] data, int at, String marker) { + if ((long) at + marker.length() > data.length) { + return false; + } + for (int k = 0; k < marker.length(); k++) { + if (data[at + k] != (byte) marker.charAt(k)) { + return false; + } + } + return true; + } + + // IPSwitch text + + /** The index of the double quote that closes the string opening at start, or -1. */ + private static int stringEnd(String text, int start) { + int k = start + 1; + while (k < text.length()) { + char c = text.charAt(k); + if (c == '\\') { + k += 2; + } else if (c == '"') { + return k; + } else { + k++; + } + } + return -1; + } + + /** The line without a // comment that is not inside a string, and the comment, or null without one. */ + private static String[] uncomment(String line) { + int k = 0; + while (k < line.length()) { + char c = line.charAt(k); + if (c == '"') { + int end = stringEnd(line, k); + if (end < 0) { + return new String[] {line, null}; + } + k = end + 1; + } else if (line.startsWith("//", k)) { + return new String[] {line.substring(0, k), Py.strip(line.substring(k + 2))}; + } else { + k++; + } + } + return new String[] {line, null}; + } + + private static char escape(char c) { + switch (c) { + case 'n': + return '\n'; + case 't': + return '\t'; + case 'r': + return '\r'; + case '0': + return (char) 0; + case '\\': + case '"': + case '\'': + return c; + default: + return (char) 0xFFFF; + } + } + + private static byte[] string(String text) { + StringBuilder out = new StringBuilder(); + int k = 0; + while (k < text.length()) { + char c = text.charAt(k); + if (c == '\\' && k + 1 < text.length() && escape(text.charAt(k + 1)) != (char) 0xFFFF) { + out.append(escape(text.charAt(k + 1))); + k += 2; + } else { + out.append(c); + k++; + } + } + return out.toString().getBytes(StandardCharsets.UTF_8); + } + + /** + * The bytes of a patch line's value, or null: a string in double quotes, or hexadecimal + * digits in pairs, which @little-endian reverses. + */ + private static byte[] value(String text, boolean little) { + text = Py.strip(text); + if (text.startsWith("\"")) { + int end = stringEnd(text, 0); + return end > 0 && Py.strip(text.substring(end + 1)).isEmpty() ? string(text.substring(1, end)) : null; + } + String digits = String.join("", Py.splitSpace(text)); + if (digits.isEmpty() || digits.length() % 2 != 0 || !Py.matches(HEX, digits)) { + return null; + } + byte[] raw = new byte[digits.length() / 2]; + for (int i = 0; i < raw.length; i++) { + raw[i] = (byte) Integer.parseInt(digits.substring(2 * i, 2 * i + 2), 16); + } + if (little) { + for (int i = 0, j = raw.length - 1; i < j; i++, j--) { + byte t = raw[i]; + raw[i] = raw[j]; + raw[j] = t; + } + } + return raw; + } + + /** A patch of an IPSwitch file while it is read. */ + private static final class Draft { + final String name; + final boolean enabled; + final List records = new ArrayList<>(); + + Draft(String name, boolean enabled) { + this.name = name; + this.enabled = enabled; + } + } + + /** + * Reads IPSwitch text: directives, comments, and patches that @enabled or @disabled start and + * the next of them or @stop ends. The last comment on a line of its own before a patch names + * it. A patch line is an offset of 8 hexadecimal digits, a space and a value; @flag + * offset_shift adds to every offset after it. + * + * @throws PatchFileException for an @nsobid- without a build ID in hexadecimal, or an + * offset_shift without a number + */ + public static PatchFile readPchtxt(String text) throws PatchFileException { + List patches = new ArrayList<>(); + List notes = new ArrayList<>(); + List comments = new ArrayList<>(); + String buildId = null; + BigInteger shift = BigInteger.ZERO; + boolean little = false; + String last = ""; + Draft current = null; + List lines = Py.split(text.replace("\r\n", "\n"), '\n'); + for (int n = 1; n <= lines.size(); n++) { + String rawLine = lines.get(n - 1); + String[] parts = uncomment(rawLine); + String stripped = Py.strip(parts[0]); + String comment = parts[1]; + if (comment != null && !comment.isEmpty()) { + comments.add(new PatchFile.Line(n, comment)); + if (stripped.isEmpty()) { + last = comment; // a comment on a line of its own names the next patch; one after code does not + } + } + if (stripped.isEmpty()) { + continue; + } + String lower = stripped.toLowerCase(Locale.ROOT); + if (lower.startsWith("@stop")) { + break; + } + if (lower.startsWith("@nsobid-")) { + String bid = Py.strip(stripped.substring(8)); + if (!Py.matches(HEX, bid) || bid.length() > 64) { + throw new PatchFileException("line " + n + ": @nsobid- needs a build ID in hexadecimal"); + } + buildId = trimBuildId(bid); + } else if (lower.startsWith("@flag")) { + List words = Py.splitSpace(stripped); + if (words.size() >= 3 && words.get(1).toLowerCase(Locale.ROOT).equals("offset_shift")) { + BigInteger v = Py.parseIntAuto(words.get(2)); + if (v == null) { + throw new PatchFileException("line " + n + ": offset_shift needs a number"); + } + shift = v; + } + } else if (lower.startsWith("@little-endian")) { + little = true; + } else if (lower.startsWith("@big-endian")) { + little = false; + } else if (lower.startsWith("@enabled") || lower.startsWith("@disabled")) { + current = new Draft(last, lower.startsWith("@enabled")); + patches.add(current); + } else if (stripped.startsWith("#")) { + notes.add(new PatchFile.Line(n, Py.strip(stripped.substring(1)))); + } else { + String[] split = splitOnce(stripped); + byte[] value = split.length == 2 ? value(split[1], little) : null; + if (current == null || split[0].length() != 8 || !Py.matches(HEX, split[0]) || value == null) { + notes.add(new PatchFile.Line(n, Py.strip(rawLine))); + continue; + } + current.records.add(new Patch.Record(new BigInteger(split[0], 16).add(shift), value)); + } + } + List out = new ArrayList<>(); + for (Draft d : patches) { + out.add(new Patch(d.name, d.enabled, d.records)); + } + return new PatchFile("pchtxt", out, buildId, notes, comments); + } + + /** Python's str.split(None, 1) of a text without white space at its ends. */ + private static String[] splitOnce(String s) { + int i = 0; + while (i < s.length() && !Py.isSpace(s.charAt(i))) { + i++; + } + if (i == s.length()) { + return new String[] {s}; + } + int j = i; + while (j < s.length() && Py.isSpace(s.charAt(j))) { + j++; + } + return new String[] {s.substring(0, i), s.substring(j)}; + } + + // Build IDs + + /** The suffixes of patch file names, with each letter as Python's re.IGNORECASE matches it. */ + private static final String[][] SUFFIXES = {{".", "i", "p", "s"}, {".", "i", "p", "s", "3", "2"}, + {".", "p", "c", "h", "t", "x", "t"}}; + + private static boolean sameLetter(char c, String letter) { + char l = letter.charAt(0); + if (Character.toLowerCase(c) == l && c < 128) { + return true; + } + if (l == 'i') { + return c == 0x130 || c == 0x131; // capital I with a dot, small dotless i + } + if (l == 's') { + return c == 0x17F; // long s + } + return false; + } + + /** The file name without .ips, .ips32 or .pchtxt at its end, in any case. */ + private static String stem(String name) { + for (String[] suffix : SUFFIXES) { + int at = name.length() - suffix.length; + if (at < 0) { + continue; + } + boolean ok = true; + for (int k = 0; k < suffix.length && ok; k++) { + ok = sameLetter(name.charAt(at + k), suffix[k]); + } + if (ok) { + return name.substring(0, at); + } + } + return name; + } + + /** + * Returns the build ID that a patch file's name gives, "<build ID>.ips": an even number of + * hexadecimal digits, 16 to 64. The zero bytes at its end are left out, down to 16 digits. + * Null when the name is no build ID. + */ + public static String buildIdOf(String fileName) { + String name = fileName.replace('\\', '/'); + name = name.substring(name.lastIndexOf('/') + 1); + String stem = stem(name); + if (stem.length() < 16 || stem.length() > 64 || stem.length() % 2 != 0 || !Py.matches(HEX, stem)) { + return null; + } + return trimBuildId(stem); + } + + /** Returns a build ID in upper case, without the zero bytes at its end, down to 16 digits. */ + public static String trimBuildId(String text) { + String t = text.toUpperCase(Locale.ROOT); + while (t.codePointCount(0, t.length()) > 16 && t.endsWith("00")) { + t = t.substring(0, t.length() - 2); + } + return t; + } + + // Into a module + + /** A run of consecutive bytes a patch writes into a module's image. Immutable. */ + public static final class Run { + private final long offset; + private final byte[] data; + + Run(long offset, byte[] data) { + this.offset = offset; + this.data = data; + } + + /** Returns the offset in the image. */ + public long offset() { + return offset; + } + + /** Returns the bytes. */ + public byte[] data() { + return data.clone(); + } + + byte[] dataShared() { + return data; + } + } + + /** What a patch writes into a module's image, and what it leaves out. Immutable. */ + public static final class ImageRuns { + private final List runs; + private final List dropped; + + ImageRuns(List runs, List dropped) { + this.runs = Collections.unmodifiableList(new ArrayList<>(runs)); + this.dropped = Collections.unmodifiableList(new ArrayList<>(dropped)); + } + + /** Returns the runs of consecutive bytes, in order of offset. */ + public List runs() { + return runs; + } + + /** Returns what was left out, such as "0x10: 4 bytes in the NSO header". */ + public List dropped() { + return dropped; + } + } + + private static String bytes(BigInteger n) { + return n.equals(BigInteger.ONE) ? "1 byte" : n + " bytes"; + } + + private static String hex(BigInteger n) { + return (n.signum() < 0 ? "-0x" : "0x") + n.abs().toString(16).toUpperCase(Locale.ROOT); + } + + /** + * Returns the bytes a patch writes into a module's image of size bytes, as runs of + * consecutive bytes in order of offset, and what it left out. A later record wins over an + * earlier one at the same byte; the part of a record inside the NSO header or past the image + * is left out, as loaders do. + */ + public static ImageRuns imageRuns(Patch patch, long size) { + TreeMap written = new TreeMap<>(); + List dropped = new ArrayList<>(); + BigInteger big = BigInteger.valueOf(size); + for (Patch.Record r : patch.records()) { + byte[] data = r.dataShared(); + BigInteger start = r.offset().subtract(HEADER); + if (start.bitLength() < 62) { + long s = start.longValue(); + for (int k = 0; k < data.length; k++) { + long at = s + k; + if (at >= 0 && at < size) { + written.put(at, data[k]); + } + } + } + BigInteger length = BigInteger.valueOf(data.length); + if (start.signum() < 0) { + dropped.add(hex(r.offset()) + ": " + bytes(length.min(start.negate())) + " in the NSO header"); + } + if (start.add(length).compareTo(big) > 0) { + dropped.add(hex(r.offset()) + ": " + bytes(length.min(start.add(length).subtract(start.max(big)))) + + " past the module"); + } + } + List runs = new ArrayList<>(); + long runStart = -1; + ByteArrayOutputStream run = new ByteArrayOutputStream(); + for (Map.Entry e : written.entrySet()) { + long at = e.getKey(); + if (runStart >= 0 && runStart + run.size() == at) { + run.write(e.getValue()); + continue; + } + if (runStart >= 0) { + runs.add(new Run(runStart, run.toByteArray())); + } + runStart = at; + run.reset(); + run.write(e.getValue()); + } + if (runStart >= 0) { + runs.add(new Run(runStart, run.toByteArray())); + } + return new ImageRuns(runs, dropped); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Patterns.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Patterns.java new file mode 100644 index 00000000..ede68731 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Patterns.java @@ -0,0 +1,345 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * The shortest byte pattern that finds one place in a module exactly once (section 6.3). + * + *

    The bytes that change when the code moves in another build (branch and page offsets) become + * ??, so that a pattern keeps finding its place after an update as long as the code around it + * stays the same. + */ +final class Patterns { + + private static final int STEP = 4; + /** Candidates left after which a search looks at its last window first. */ + private static final int CROWD = 64; + + private Patterns() { + } + + /** A pattern: its items (-1 for ??), where it matches, and the place's offset from the match. */ + static final class Found { + final int[] items; + final long start; + final long place; + + Found(int[] items, long start, long place) { + this.items = items; + this.start = start; + this.place = place; + } + + String text() { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < items.length; i++) { + if (i > 0) { + b.append(' '); + } + b.append(items[i] < 0 ? "??" : String.format("%02X", items[i])); + } + return b.toString(); + } + + /** The location of the place: the module, the pattern, and the offset unless it is 0. */ + Map location(String module) { + Map loc = new LinkedHashMap<>(); + loc.put("module", module); + loc.put("find", text()); + if (place != 0) { + loc.put("offset", place); + } + return loc; + } + } + + /** The default search: code and read-only data, cut where the image ends. */ + private static List searchRanges(CodeModule m) { + long size = m.image().length; + List ranges = new ArrayList<>(); + for (String n : new String[] {"code", "rodata"}) { + if (m.hasSection(n)) { + ranges.add(new long[] {Math.min(m.sectionStart(n), size), Math.min(m.sectionEnd(n), size)}); + } + } + return ranges; + } + + /** The window's bytes, -1 where they move between builds or are not the module's own. */ + private static int[] items(CodeModule m, int start, int end, Set moving) { + int[] out = new int[end - start]; + byte[] image = m.image(); + for (int i = start; i < end; i++) { + out[i - start] = moving.contains(i) || m.excluded(i, 1) ? -1 : image[i] & 0xFF; + } + return out; + } + + /** A word of fixed bytes of the window: its distance from the place, its offset and its bytes. */ + private static final class Anchor { + final long distance; + final long start; + final byte[] piece; + + Anchor(long distance, long start, byte[] piece) { + this.distance = distance; + this.start = start; + this.piece = piece; + } + } + + /** The words of fixed bytes in the window, aligned as the place is, nearest the place first. */ + private static List anchors(int[] items, long base, long site) { + int first = (int) Math.floorMod(site - base, (long) STEP); + List words = new ArrayList<>(); + for (int i = first; i < items.length - STEP + 1; i += STEP) { + byte[] piece = new byte[STEP]; + boolean fixed = true; + for (int k = 0; k < STEP; k++) { + fixed &= items[i + k] >= 0; + piece[k] = (byte) items[i + k]; + } + if (fixed) { + words.add(new Anchor(Math.abs(base + i - site), base + i, piece)); + } + } + Collections.sort(words, new Comparator() { + @Override + public int compare(Anchor a, Anchor b) { + int c = Long.compare(a.distance, b.distance); + return c != 0 ? c : Long.compare(a.start, b.start); + } + }); + return words; + } + + /** Where the needle lies in the ranges, overlapping, or null when it lies there more than limit times. */ + private static List occurrences(byte[] image, byte[] needle, List ranges, int limit) { + int k = needle.length; + int[] shift = new int[256]; + Arrays.fill(shift, k); + for (int i = 0; i < k - 1; i++) { + shift[needle[i] & 0xFF] = k - 1 - i; + } + List found = new ArrayList<>(); + for (long[] r : ranges) { + int start = (int) Math.max(0, Math.min(r[0], image.length)); + int end = (int) Math.max(0, Math.min(r[1], image.length)); + // A Horspool scan: the shift after any window, a match too, never skips a place. + for (int at = start; at + k <= end; at += shift[image[at + k - 1] & 0xFF]) { + boolean same = true; + for (int i = k - 1; i >= 0 && same; i--) { + same = image[at + i] == needle[i]; + } + if (same) { + found.add((long) at); + if (found.size() > limit) { + return null; + } + } + } + } + return found; + } + + /** + * The shortest pattern that finds an offset exactly once and covers the first cover bytes of + * the place, or null when the place is not in code or read-only data, or no pattern up to 64 + * bytes is unique. + */ + static Found make(CodeModule m, long offset, int cover) { + int longest = 64; + int limit = 200000; + String section = m.sectionOf(offset); + if (!"code".equals(section) && !"rodata".equals(section)) { + return null; + } + long secStart = m.sectionStart(section); + long secEnd = Math.min(m.sectionEnd(section), m.image().length); + if (section.equals("code") && m.textSize() != null) { + if (offset >= m.textSize()) { + return null; // the zero bytes after the code: nothing there to find + } + secEnd = Math.min(secEnd, m.textSize()); + } + byte[] image = m.image(); + int lo = (int) Math.max(secStart, offset - longest); + int hi = (int) Math.min(secEnd, offset + longest); + Set moving = Arm64.movingBytes(image, lo, hi); + int[] window = items(m, lo, hi, moving); + cover = (int) Math.max(1, Math.min(cover, hi - offset)); + List ranges = searchRanges(m); + Found best = null; + List all = anchors(window, lo, offset); + for (Anchor a : all.subList(0, Math.min(3, all.size()))) { + List hits = occurrences(image, a.piece, ranges, limit); + if (hits == null) { + continue; + } + for (String order : new String[] {"forward", "backward", "both"}) { + Found found = grow(image, offset, cover, lo, hi, window, a.start, hits, ranges, order, longest); + if (found != null && (best == null || found.items.length < best.items.length + || (found.items.length == best.items.length && Math.abs(found.place) < Math.abs(best.place)))) { + best = found; + } + } + } + if (best == null) { + return null; + } + List check = Evaluator.findAll(m.toModuleWithoutId(), best.items, null, 2); + if (!check.equals(Collections.singletonList(best.start))) { + return null; + } + return best; + } + + private static Found grow(byte[] image, long offset, int cover, int lo, int hi, int[] window, long a0, + List hits, List ranges, String order, int longest) { + long start = Math.min(offset, a0); + if (offset % STEP == 0) { + start -= Math.floorMod(start, (long) STEP); + } + long end = Math.max(offset + cover, a0 + 1); + end = Math.min(hi, start + ((end - start + STEP - 1) / STEP) * STEP); + List alive = null; + long[] verified = null; // the module offsets of the pattern whose bytes every candidate was checked for + boolean lookedAhead = false; + int toggle = 0; + while (true) { + int[] items = slice(window, start - lo, end - lo); + if (items.length > 0 && items[0] >= 0 && items[items.length - 1] >= 0 + && start <= a0 && a0 < end && end - start >= 4) { + long shift = a0 - start; + if (alive == null) { + alive = new ArrayList<>(); + for (long h : hits) { + alive.add(h - shift); + } + } + boolean whole = items.length == end - start; + // The pattern only grows: a candidate needs checking only for the bytes added since it was checked. + int doneFrom = 0; + int doneTo = 0; + if (verified != null && whole) { + doneFrom = (int) (verified[0] - start); + doneTo = (int) (verified[1] - start); + } + List kept = new ArrayList<>(); + for (long q : alive) { + if (matches(image, q, items, ranges, doneFrom, doneTo)) { + kept.add(q); + } + } + alive = kept; + verified = whole ? new long[] {start, end} : null; + if (alive.size() == 1 && alive.get(0) == start) { + return new Found(items, start, offset - start); + } + if (alive.size() > CROWD && !lookedAhead) { + // Many candidates are left. Every later window lies inside the last one this order grows to, + // so where two candidates match that one, none of the windows before it can be unique. + lookedAhead = true; + long[] last = lastWindow(start, end, lo, hi, order, longest, toggle); + int[] lastItems = slice(window, last[0] - lo, last[1] - lo); + if (lastItems.length == last[1] - last[0]) { + int matching = 0; + for (long q : alive) { + if (matches(image, q - (start - last[0]), lastItems, ranges, 0, 0) && ++matching == 2) { + return null; + } + } + } + } + } + boolean growBack = start - STEP >= lo; + boolean growAhead = end + STEP <= hi; + if (end - start >= longest || !(growBack || growAhead)) { + return null; + } + boolean ahead; + if (order.equals("forward")) { + ahead = growAhead; + } else if (order.equals("backward")) { + ahead = !growBack; + } else { + ahead = growAhead && (toggle % 2 == 0 || !growBack); + toggle++; + } + if (ahead) { + end += STEP; + } else { + start -= STEP; + if (alive != null) { + List moved = new ArrayList<>(); + for (long q : alive) { + moved.add(q - STEP); + } + alive = moved; + } + } + } + } + + /** Python's list slice: indices below 0 count from the end, and both ends stay inside the list. */ + private static int[] slice(int[] list, long from, long to) { + int n = list.length; + long a = from < 0 ? Math.max(0, from + n) : Math.min(from, n); + long b = to < 0 ? Math.max(0, to + n) : Math.min(to, n); + return b <= a ? new int[0] : Arrays.copyOfRange(list, (int) a, (int) b); + } + + /** The window that growing from (start, end) in this order ends with. */ + private static long[] lastWindow(long start, long end, int lo, int hi, String order, int longest, int toggle) { + while (true) { + boolean growBack = start - STEP >= lo; + boolean growAhead = end + STEP <= hi; + if (end - start >= longest || !(growBack || growAhead)) { + return new long[] {start, end}; + } + boolean ahead; + if (order.equals("forward")) { + ahead = growAhead; + } else if (order.equals("backward")) { + ahead = !growBack; + } else { + ahead = growAhead && (toggle % 2 == 0 || !growBack); + toggle++; + } + if (ahead) { + end += STEP; + } else { + start -= STEP; + } + } + } + + /** Whether the pattern matches at q, inside the search ranges; the items from doneFrom to doneTo are known to. */ + private static boolean matches(byte[] image, long q, int[] items, List ranges, int doneFrom, int doneTo) { + int n = items.length; + boolean inside = false; + for (long[] r : ranges) { + inside |= r[0] <= q && q + n <= r[1]; + } + if (!inside || q < 0 || q + n > image.length) { + return false; + } + for (int i = 0; i < n; i++) { + if (i == doneFrom && doneTo > doneFrom) { + i = doneTo - 1; + continue; + } + if (items[i] >= 0 && (image[(int) q + i] & 0xFF) != items[i]) { + return false; + } + } + return true; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Platform.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Platform.java new file mode 100644 index 00000000..42c13cef --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Platform.java @@ -0,0 +1,164 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** One platform of Appendix A: what a reader needs to know about it. Immutable. */ +public final class Platform { + + private static final Pattern HEX_ID = Pattern.compile("[0-9A-Fa-f]{1,64}"); + private static final Pattern SHA256_ID = Pattern.compile("sha256:[0-9A-Fa-f]{64}"); + private static final Pattern PC_BUTTON = Pattern.compile("[A-Z0-9_]+"); + + private static final Map PLATFORMS; + + static { + List switchButtons = Arrays.asList(("A B X Y L R ZL ZR PLUS MINUS LSTICK RSTICK DUP DDOWN DLEFT DRIGHT " + + "LSTICK_UP LSTICK_DOWN LSTICK_LEFT LSTICK_RIGHT RSTICK_UP RSTICK_DOWN RSTICK_LEFT RSTICK_RIGHT SL SR") + .split(" ")); + List switch2Buttons = new ArrayList<>(switchButtons); + switch2Buttons.add("C"); + List n64Buttons = Arrays.asList("A B Z START L R CUP CDOWN CLEFT CRIGHT DUP DDOWN DLEFT DRIGHT".split(" ")); + List switchModules = new ArrayList<>(Arrays.asList("main", "sdk")); + for (int i = 0; i < 10; i++) { + switchModules.add("subsdk" + i); + } + List switchRegions = Arrays.asList("heap", "alias", "aslr"); + List none = Collections.emptyList(); + Map all = new LinkedHashMap<>(); + all.put("switch", new Platform("switch", Pattern.compile("[0-9A-Fa-f]{16}"), Arrays.asList("arm64"), + false, 8, switchModules, false, switchRegions, false, switchButtons)); + all.put("switch2", new Platform("switch2", Pattern.compile("[0-9A-Fa-f]{16}"), Arrays.asList("arm64"), + false, 8, switchModules, false, switchRegions, false, switch2Buttons)); + all.put("n64", new Platform("n64", Pattern.compile("[\\x21-\\x7E]{4}"), Arrays.asList("mips"), + true, 4, Arrays.asList("rom"), true, none, true, n64Buttons)); + all.put("pc", new Platform("pc", Pattern.compile("[a-z0-9-]+:" + Py.NOT_SPACE + "+"), + Arrays.asList("x86-64", "arm64"), false, 8, none, true, none, false, none)); + PLATFORMS = Collections.unmodifiableMap(all); + } + + private final String name; + private final Pattern gameId; + private final List archs; + private final boolean bigEndian; + private final int pointerSize; + private final List modules; + private final boolean sha256Ids; + private final List regions; + private final boolean addresses; + private final List buttons; + + private Platform(String name, Pattern gameId, List archs, boolean bigEndian, int pointerSize, + List modules, boolean sha256Ids, List regions, boolean addresses, List buttons) { + this.name = name; + this.gameId = gameId; + this.archs = Collections.unmodifiableList(new ArrayList<>(archs)); + this.bigEndian = bigEndian; + this.pointerSize = pointerSize; + this.modules = Collections.unmodifiableList(new ArrayList<>(modules)); + this.sha256Ids = sha256Ids; + this.regions = Collections.unmodifiableList(new ArrayList<>(regions)); + this.addresses = addresses; + this.buttons = Collections.unmodifiableList(new ArrayList<>(buttons)); + } + + /** Returns the platform of that name, or null when Appendix A has none. */ + public static Platform forName(String name) { + return PLATFORMS.get(name); + } + + /** Returns every platform of Appendix A, in the appendix's order. */ + public static List all() { + return Collections.unmodifiableList(new ArrayList<>(PLATFORMS.values())); + } + + /** Returns the platform's name, such as "switch". */ + public String name() { + return name; + } + + /** Returns the architectures a runtime of this platform can have; the first is the default. */ + public List archs() { + return archs; + } + + /** Returns whether numbers are stored big-endian; otherwise they are little-endian. */ + public boolean bigEndian() { + return bigEndian; + } + + /** Returns the size of a pointer in bytes. */ + public int pointerSize() { + return pointerSize; + } + + /** Returns the names a code module can have, or an empty list when any name is allowed. */ + public List modules() { + return modules; + } + + /** + * Returns how a module identity is written: "hex" for a build ID that matches by prefix, or + * "sha256" for the hash of the module file. + */ + public String moduleIdKind() { + return sha256Ids ? "sha256" : "hex"; + } + + /** Returns the names of the platform's memory regions. */ + public List regions() { + return regions; + } + + /** Returns whether {@code address} locations exist on this platform. */ + public boolean addresses() { + return addresses; + } + + /** Returns the button names, or an empty list when any upper-case name is allowed. */ + public List buttons() { + return buttons; + } + + /** Returns whether the text is a game ID of this platform. */ + public boolean isValidGameId(String id) { + return Py.matches(gameId, id); + } + + /** Returns whether the value is a module identity as a file writes it for this platform. */ + public boolean isValidModuleId(Object value) { + return Py.matches(sha256Ids ? SHA256_ID : HEX_ID, value); + } + + /** + * Returns whether a module identity from a file matches the identity of a module that runs + * (section 5): a build ID matches when one is a prefix of the other, a hash when both are + * the same. Case does not matter. + */ + public boolean moduleIdMatches(String listed, String running) { + String a = Py.lower(listed); + String b = Py.lower(running); + if (!sha256Ids) { + return a.length() <= b.length() ? b.startsWith(a) : a.startsWith(b); + } + return a.equals(b); + } + + /** Returns whether the name is a button of this platform. */ + public boolean isValidButton(String name) { + if (!buttons.isEmpty()) { + return buttons.contains(name); + } + return Py.matches(PC_BUTTON, name); + } + + @Override + public String toString() { + return name; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Preset.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Preset.java new file mode 100644 index 00000000..17d0269f --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Preset.java @@ -0,0 +1,47 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** A named set of cheats and values (section 10). Immutable. */ +public final class Preset { + + private final String id; + private final String name; + private final List cheats; + private final Map values; + + Preset(String id, String name, List cheats, Map values) { + this.id = id; + this.name = name; + this.cheats = Collections.unmodifiableList(new ArrayList<>(cheats)); + this.values = Collections.unmodifiableMap(new LinkedHashMap<>(values)); + } + + /** Returns the preset's id. */ + public String id() { + return id; + } + + /** Returns the name shown to players. */ + public String name() { + return name; + } + + /** Returns the ids of the cheats the preset switches on. */ + public List cheats() { + return cheats; + } + + /** + * Returns the values the preset sets, by "cheat.value", as numbers of the value's type: a + * Long, a BigInteger at 2^63 and above, a Double or a Boolean. Each one lies in its value's + * range, so it can go into {@link Choices} as it is. + */ + public Map values() { + return values; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Py.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Py.java new file mode 100644 index 00000000..fd170c65 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Py.java @@ -0,0 +1,455 @@ +package io.github.davdxpx.mistel.mncf; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The text rules of the Python reference reader that edge cases of the format depend on: which + * characters are white space, how int() reads a number, how a pattern anchored with ^ and $ + * matches, and how repr() writes a value. + */ +final class Py { + + /** The most decimal digits int() reads, as Python's default int_max_str_digits allows. */ + private static final int MAX_DECIMAL_DIGITS = 4300; + + private Py() { + } + + /** Whether the code point is white space as Python's str.isspace() and the \s of re see it. */ + static boolean isSpace(int c) { + return (c >= 0x09 && c <= 0x0D) || (c >= 0x1C && c <= 0x20) || c == 0x85 || c == 0xA0 + || c == 0x1680 || (c >= 0x2000 && c <= 0x200A) || c == 0x2028 || c == 0x2029 + || c == 0x202F || c == 0x205F || c == 0x3000; + } + + /** The regular expression class of every character that is not white space, as \S of re. */ + static final String NOT_SPACE = + "[^\\x09-\\x0D\\x1C-\\x20\\x{85}\\x{A0}\\x{1680}\\x{2000}-\\x{200A}\\x{2028}\\x{2029}" + + "\\x{202F}\\x{205F}\\x{3000}]"; + + /** The text without white space at both ends, as str.strip() gives it. */ + static String strip(String s) { + int start = 0; + int end = s.length(); + while (start < end && isSpace(s.charAt(start))) { + start++; + } + while (end > start && isSpace(s.charAt(end - 1))) { + end--; + } + return s.substring(start, end); + } + + /** The words of the text between runs of white space, as str.split() gives them. */ + static List splitSpace(String s) { + List words = new ArrayList<>(); + int i = 0; + while (i < s.length()) { + while (i < s.length() && isSpace(s.charAt(i))) { + i++; + } + int start = i; + while (i < s.length() && !isSpace(s.charAt(i))) { + i++; + } + if (i > start) { + words.add(s.substring(start, i)); + } + } + return words; + } + + /** + * The lines of the text, as str.splitlines() gives them: a line ends at a line feed, a + * carriage return, both together, or any other line boundary Python knows; no empty line + * follows a last line end. + */ + static List splitLines(String s) { + List lines = new ArrayList<>(); + int start = 0; + int i = 0; + while (i < s.length()) { + char c = s.charAt(i); + boolean end = c == '\n' || c == '\r' || c == 0x0B || c == 0x0C || (c >= 0x1C && c <= 0x1E) + || c == 0x85 || c == 0x2028 || c == 0x2029; + if (!end) { + i++; + continue; + } + lines.add(s.substring(start, i)); + i += c == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n' ? 2 : 1; + start = i; + } + if (start < s.length()) { + lines.add(s.substring(start)); + } + return lines; + } + + /** The parts of the text between each separator, empty parts included, as str.split(sep). */ + static List split(String s, char separator) { + List parts = new ArrayList<>(); + int start = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == separator) { + parts.add(s.substring(start, i)); + start = i + 1; + } + } + parts.add(s.substring(start)); + return parts; + } + + /** + * Matches the whole text, as Python's re.match does for a pattern between ^ and \Z. + * + * @return the matcher of the match, or null when the value is not text that matches + */ + static Matcher match(Pattern pattern, Object value) { + if (!(value instanceof String)) { + return null; + } + Matcher m = pattern.matcher((String) value); + return m.matches() ? m : null; + } + + /** Whether the value is text that matches the pattern, as {@link #match} decides. */ + static boolean matches(Pattern pattern, Object value) { + return match(pattern, value) != null; + } + + /** The text in lower case, as str.lower() gives it for the text this format uses. */ + static String lower(String s) { + return s.toLowerCase(Locale.ROOT); + } + + /** + * Reads a whole number as Python's int(text, base) does for base 10 or 16: white space at + * both ends, a sign, for base 16 an optional 0x prefix with one underscore after it, single + * underscores between digits, and decimal digits of any script. + * + * @return the number, or null where int() raises ValueError + */ + static BigInteger parseInt(String s, int base) { + StringBuilder t = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); ) { + int c = s.codePointAt(i); + i += Character.charCount(c); + if (c < 127) { + t.append((char) c); + } else if (isSpace(c)) { + t.append(' '); + } else if (Character.isDigit(c)) { + t.append((char) ('0' + Character.digit(c, 10))); + } else { + return null; + } + } + int n = t.length(); + int i = 0; + while (i < n && isAsciiSpace(t.charAt(i))) { + i++; + } + boolean negative = false; + if (i < n && (t.charAt(i) == '+' || t.charAt(i) == '-')) { + negative = t.charAt(i) == '-'; + i++; + } + if (base == 16 && i + 1 < n && t.charAt(i) == '0' && (t.charAt(i + 1) == 'x' || t.charAt(i + 1) == 'X')) { + i += 2; + if (i < n && t.charAt(i) == '_') { + i++; + } + } + if (i < n && t.charAt(i) == '_') { + return null; + } + StringBuilder digits = new StringBuilder(); + char previous = 0; + while (i < n) { + char c = t.charAt(i); + if (c == '_') { + if (previous == '_') { + return null; + } + } else if (Character.digit(c, base) >= 0 && c < 128) { + digits.append(c); + } else { + break; + } + previous = c; + i++; + } + if (previous == '_' || digits.length() == 0) { + return null; + } + if (base == 10 && digits.length() > MAX_DECIMAL_DIGITS) { + return null; + } + while (i < n && isAsciiSpace(t.charAt(i))) { + i++; + } + if (i != n) { + return null; + } + BigInteger value = new BigInteger(digits.toString(), base); + return negative ? value.negate() : value; + } + + /** + * Reads a whole number as Python's int(text, 0) does: as {@link #parseInt}, with the base + * from a prefix (0x, 0o or 0b, in either case), else decimal without leading zeros. + * + * @return the number, or null where int() raises ValueError + */ + static BigInteger parseIntAuto(String s) { + StringBuilder t = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); ) { + int c = s.codePointAt(i); + i += Character.charCount(c); + if (c < 127) { + t.append((char) c); + } else if (isSpace(c)) { + t.append(' '); + } else if (Character.isDigit(c)) { + t.append((char) ('0' + Character.digit(c, 10))); + } else { + return null; + } + } + int n = t.length(); + int i = 0; + while (i < n && isAsciiSpace(t.charAt(i))) { + i++; + } + int sign = i; + if (i < n && (t.charAt(i) == '+' || t.charAt(i) == '-')) { + i++; + } + int base = 10; + if (i + 1 < n && t.charAt(i) == '0') { + char p = Character.toLowerCase(t.charAt(i + 1)); + base = p == 'x' ? 16 : p == 'o' ? 8 : p == 'b' ? 2 : 10; + } + if (base != 10) { + int from = i + 2; + if (from < n && t.charAt(from) == '_') { + from++; + } + return parseDigits(t, sign, from, base); + } + BigInteger v = parseDigits(t, sign, i, 10); + if (v != null && i < n && t.charAt(i) == '0' && v.signum() != 0) { + return null; // a decimal number has no leading zeros, but 0, 00 and 0_0 are 0 + } + return v; + } + + /** + * The number of the text from an index on: digits of the base with single underscores + * between them, then white space, and the sign at the index given. Null when it is anything + * else. + */ + private static BigInteger parseDigits(CharSequence t, int sign, int from, int base) { + int n = t.length(); + boolean negative = sign < from && t.charAt(sign) == '-'; + int i = from; + if (i < n && t.charAt(i) == '_') { + return null; + } + StringBuilder digits = new StringBuilder(); + char previous = 0; + while (i < n) { + char c = t.charAt(i); + if (c == '_') { + if (previous == '_') { + return null; + } + } else if (Character.digit(c, base) >= 0 && c < 128) { + digits.append(c); + } else { + break; + } + previous = c; + i++; + } + if (previous == '_' || digits.length() == 0) { + return null; + } + if (base == 10 && digits.length() > MAX_DECIMAL_DIGITS) { + return null; + } + while (i < n && isAsciiSpace(t.charAt(i))) { + i++; + } + if (i != n) { + return null; + } + BigInteger value = new BigInteger(digits.toString(), base); + return negative ? value.negate() : value; + } + + private static boolean isAsciiSpace(char c) { + return c == ' ' || (c >= 0x09 && c <= 0x0D); + } + + // str() and repr() + + /** The value as Python's repr() writes it, for values a TOML document holds. */ + static String repr(Object v) { + if (v == null) { + return "None"; + } + if (v instanceof String) { + return stringRepr((String) v); + } + if (v instanceof Boolean) { + return ((Boolean) v) ? "True" : "False"; + } + if (v instanceof Double) { + return floatRepr((Double) v); + } + if (v instanceof Long || v instanceof BigInteger) { + return v.toString(); + } + if (v instanceof List) { + StringBuilder b = new StringBuilder("["); + for (Object item : (List) v) { + if (b.length() > 1) { + b.append(", "); + } + b.append(repr(item)); + } + return b.append(']').toString(); + } + if (v instanceof Map) { + StringBuilder b = new StringBuilder("{"); + for (Map.Entry e : ((Map) v).entrySet()) { + if (b.length() > 1) { + b.append(", "); + } + b.append(repr(e.getKey())).append(": ").append(repr(e.getValue())); + } + return b.append('}').toString(); + } + return String.valueOf(v); + } + + private static String stringRepr(String s) { + char quote = s.indexOf('\'') >= 0 && s.indexOf('"') < 0 ? '"' : '\''; + StringBuilder b = new StringBuilder().append(quote); + for (int i = 0; i < s.length(); ) { + int c = s.codePointAt(i); + i += Character.charCount(c); + if (c == quote || c == '\\') { + b.append('\\').append((char) c); + } else if (c == '\t') { + b.append("\\t"); + } else if (c == '\n') { + b.append("\\n"); + } else if (c == '\r') { + b.append("\\r"); + } else if (c < ' ' || c == 0x7F) { + b.append(String.format("\\x%02x", c)); + } else if (c < 0x7F || isPrintable(c)) { + b.appendCodePoint(c); + } else if (c <= 0xFF) { + b.append(String.format("\\x%02x", c)); + } else if (c <= 0xFFFF) { + b.append(String.format("\\u%04x", c)); + } else { + b.append(String.format("\\U%08x", c)); + } + } + return b.append(quote).toString(); + } + + private static boolean isPrintable(int c) { + switch (Character.getType(c)) { + case Character.CONTROL: + case Character.FORMAT: + case Character.SURROGATE: + case Character.PRIVATE_USE: + case Character.UNASSIGNED: + case Character.LINE_SEPARATOR: + case Character.PARAGRAPH_SEPARATOR: + case Character.SPACE_SEPARATOR: + return c == ' '; + default: + return true; + } + } + + /** The shortest text that reads back as the same double, as Python's repr() of a float. */ + static String floatRepr(double d) { + if (Double.isNaN(d)) { + return "nan"; + } + if (Double.isInfinite(d)) { + return d > 0 ? "inf" : "-inf"; + } + String sign = (Double.doubleToRawLongBits(d) < 0) ? "-" : ""; + if (d == 0) { + return sign + "0.0"; + } + double magnitude = Math.abs(d); + BigDecimal exact = new BigDecimal(magnitude); + BigDecimal best = null; + for (int precision = 1; precision <= 17 && best == null; precision++) { + BigDecimal down = exact.round(new MathContext(precision, RoundingMode.FLOOR)); + BigDecimal up = exact.round(new MathContext(precision, RoundingMode.CEILING)); + boolean downOk = Double.parseDouble(down.toString()) == magnitude; + boolean upOk = Double.parseDouble(up.toString()) == magnitude; + if (downOk && upOk) { + int c = exact.subtract(down).compareTo(up.subtract(exact)); + best = c < 0 ? down : c > 0 ? up : exact.round(new MathContext(precision, RoundingMode.HALF_EVEN)); + } else if (downOk) { + best = down; + } else if (upOk) { + best = up; + } + } + BigDecimal stripped = best.stripTrailingZeros(); + String digits = stripped.unscaledValue().toString(); + // The value is 0. times ten to the power point. + int point = digits.length() - stripped.scale(); + StringBuilder b = new StringBuilder(sign); + if (point <= -4 || point > 16) { + b.append(digits.charAt(0)); + if (digits.length() > 1) { + b.append('.').append(digits, 1, digits.length()); + } + int exponent = point - 1; + b.append('e').append(exponent < 0 ? '-' : '+'); + String e = Integer.toString(Math.abs(exponent)); + if (e.length() < 2) { + b.append('0'); + } + b.append(e); + } else if (point <= 0) { + b.append("0."); + for (int i = 0; i < -point; i++) { + b.append('0'); + } + b.append(digits); + } else if (point >= digits.length()) { + b.append(digits); + for (int i = digits.length(); i < point; i++) { + b.append('0'); + } + b.append(".0"); + } else { + b.append(digits, 0, point).append('.').append(digits, point, digits.length()); + } + return b.toString(); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ResolvedOp.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ResolvedOp.java new file mode 100644 index 00000000..02440c84 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ResolvedOp.java @@ -0,0 +1,197 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * One operation of a cheat, resolved for the runtime: where it acts and what it writes or + * compares. Fields that do not apply to the kind are null. Immutable. + * + *

    An operation whose pointer path cannot be followed yet has only its kind. + */ +public final class ResolvedOp { + + private final String kind; + private final Long address; + private final String module; + private final Long offset; + private final String type; + private final byte[] expect; + private final byte[] bytes; + private final String action; + private final Object value; + private final String op; + private final String label; + private final String syntax; + private final String build; + private final String code; + + private ResolvedOp(Builder b) { + kind = b.kind; + address = b.address; + module = b.module; + offset = b.offset; + type = b.type; + expect = b.expect == null ? null : b.expect.clone(); + bytes = b.bytes == null ? null : b.bytes.clone(); + action = b.action; + value = b.value; + op = b.op; + label = b.label; + syntax = b.syntax; + build = b.build; + code = b.code; + } + + /** The fields of a resolved operation while the evaluator fills them in. */ + static final class Builder { + final String kind; + Long address; + String module; + Long offset; + String type; + byte[] expect; + byte[] bytes; + String action; + Object value; + String op; + String label; + String syntax; + String build; + String code; + + Builder(String kind) { + this.kind = kind; + } + + Builder place(long address, String module, Long offset) { + this.address = address; + this.module = module; + this.offset = offset; + return this; + } + + ResolvedOp done() { + return new ResolvedOp(this); + } + } + + /** Returns patch, write, override, read, when or raw. */ + public String kind() { + return kind; + } + + /** Returns the address the operation acts on, an unsigned 64-bit number, or null. */ + public Long address() { + return address; + } + + /** Returns the module the address lies in, or null when it is not given as a module place. */ + public String module() { + return module; + } + + /** Returns the offset of the address in its module, unsigned, or null. */ + public Long offset() { + return offset; + } + + /** Returns the type of a write, read or condition, or null. */ + public String type() { + return type; + } + + /** Returns a copy of the bytes expected at the address before the operation, or null. */ + public byte[] expect() { + return expect == null ? null : expect.clone(); + } + + /** Returns a copy of the bytes to write: the patch, the value, or the override stub. Or null. */ + public byte[] bytes() { + return bytes == null ? null : bytes.clone(); + } + + /** Returns the action of an override: return or skip. Or null. */ + public String action() { + return action; + } + + /** + * Returns the value: for an override the whole number it returns; for a condition a number + * or Boolean, a list of the two ends of "between", or a map with the "address" and "type" + * of the other place. Or null. Whole numbers are Long, or BigInteger at 2^63 and above. + */ + public Object value() { + return value; + } + + /** Returns the comparison of a condition, such as "==" or "between". Or null. */ + public String op() { + return op; + } + + /** Returns the label of a read, or null. */ + public String label() { + return label; + } + + /** Returns the syntax of raw code, or null. */ + public String syntax() { + return syntax; + } + + /** Returns the build of raw code, or null. */ + public String build() { + return build; + } + + /** Returns the raw code, or null. */ + public String code() { + return code; + } + + /** + * Returns the fields that are set, by name, as the conformance suite writes them: bytes as + * upper-case hexadecimal pairs, the address and the offset as numbers that are never negative. + */ + public Map toMap() { + Map out = new LinkedHashMap<>(); + out.put("kind", kind); + put(out, "address", address == null ? null : Values.unsigned(address)); + put(out, "module", module); + put(out, "offset", offset == null ? null : Values.unsigned(offset)); + put(out, "type", type); + put(out, "expect", expect == null ? null : Values.hexBytes(expect)); + put(out, "bytes", bytes == null ? null : Values.hexBytes(bytes)); + put(out, "action", action); + put(out, "value", value); + put(out, "op", op); + put(out, "label", label); + put(out, "syntax", syntax); + put(out, "build", build); + put(out, "code", code); + return Collections.unmodifiableMap(out); + } + + private static void put(Map out, String key, Object v) { + if (v != null) { + out.put(key, v); + } + } + + /** A list of the two ends of a "between" condition, unmodifiable. */ + static List pair(Object low, Object high) { + List both = new ArrayList<>(); + both.add(low); + both.add(high); + return Collections.unmodifiableList(both); + } + + @Override + public String toString() { + return toMap().toString(); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Runtime.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Runtime.java new file mode 100644 index 00000000..dce1e52a --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Runtime.java @@ -0,0 +1,326 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * What the runtime that applies a file has and knows (section 11). A reader's caller fills it + * in with {@link #builder}. Immutable once built. + * + *

    Without a {@link GuestMemory}, the reader reads module bytes at their base address and + * nothing else. + */ +public final class Runtime { + + private final String platform; + private final String gameId; + private final String arch; + private final Map modules; + private final Map regions; + private final GuestMemory memory; + private final Set capabilities; + private final Set extensions; + private final Set rawSyntaxes; + private final String build; + private final Set held; + private final Set unsupported; + private final Map> rewritten; + + private Runtime(Builder b) { + platform = b.platform; + gameId = b.gameId; + arch = b.arch; + modules = Collections.unmodifiableMap(new LinkedHashMap<>(b.modules)); + regions = Collections.unmodifiableMap(new LinkedHashMap<>(b.regions)); + memory = b.memory; + capabilities = Collections.unmodifiableSet(new LinkedHashSet<>(b.capabilities)); + extensions = Collections.unmodifiableSet(new LinkedHashSet<>(b.extensions)); + rawSyntaxes = Collections.unmodifiableSet(new LinkedHashSet<>(b.rawSyntaxes)); + build = b.build; + held = Collections.unmodifiableSet(new LinkedHashSet<>(b.held)); + unsupported = Collections.unmodifiableSet(new LinkedHashSet<>(b.unsupported)); + Map> runs = new LinkedHashMap<>(); + for (Map.Entry> e : b.rewritten.entrySet()) { + runs.put(e.getKey(), Collections.unmodifiableList(new ArrayList<>(e.getValue()))); + } + rewritten = Collections.unmodifiableMap(runs); + } + + /** + * Starts a runtime of a platform of Appendix A, such as "switch". It has every capability, + * every extension this reader knows and the raw syntax "atmosphere" until told otherwise. + */ + public static Builder builder(String platform) { + return new Builder(platform); + } + + /** Builds a {@link Runtime}. */ + public static final class Builder { + private final String platform; + private String gameId; + private String arch; + private final Map modules = new LinkedHashMap<>(); + private final Map regions = new LinkedHashMap<>(); + private GuestMemory memory; + private Collection capabilities = Mncf.CAPABILITIES; + private Collection extensions = Mncf.KNOWN_EXTENSIONS; + private Collection rawSyntaxes = Collections.singletonList("atmosphere"); + private String build; + private Collection held = Collections.emptyList(); + private Collection unsupported = Collections.emptyList(); + private final Map> rewritten = new LinkedHashMap<>(); + + private Builder(String platform) { + this.platform = platform; + } + + /** Sets the ID of the game that runs; without it, any game ID of the platform matches. */ + public Builder gameId(String id) { + this.gameId = id; + return this; + } + + /** Sets the architecture; the default is the platform's first. */ + public Builder arch(String arch) { + this.arch = arch; + return this; + } + + /** Adds a code module that runs, under its name such as "main". */ + public Builder module(String name, Module module) { + modules.put(name, module); + return this; + } + + /** Adds a memory region, such as "heap", with its base address and size. */ + public Builder region(String name, long base, long size) { + regions.put(name, new long[] {base, size}); + return this; + } + + /** Sets the guest memory. */ + public Builder memory(GuestMemory memory) { + this.memory = memory; + return this; + } + + /** Sets the capabilities the runtime has, out of {@link Mncf#CAPABILITIES}. */ + public Builder capabilities(Collection names) { + this.capabilities = new ArrayList<>(names); + return this; + } + + /** Sets the capabilities the runtime has, out of {@link Mncf#CAPABILITIES}. */ + public Builder capabilities(String... names) { + return capabilities(Arrays.asList(names)); + } + + /** Sets the extensions the runtime supports, with their versions. */ + public Builder extensions(Collection names) { + this.extensions = new ArrayList<>(names); + return this; + } + + /** Sets the extensions the runtime supports, with their versions. */ + public Builder extensions(String... names) { + return extensions(Arrays.asList(names)); + } + + /** Sets the raw syntaxes the runtime can apply, such as "atmosphere". */ + public Builder rawSyntaxes(Collection names) { + this.rawSyntaxes = new ArrayList<>(names); + return this; + } + + /** Sets the raw syntaxes the runtime can apply, such as "atmosphere". */ + public Builder rawSyntaxes(String... names) { + return rawSyntaxes(Arrays.asList(names)); + } + + /** + * Names the build that runs, as a recompilation does that knows its build itself. The + * modules are then not compared. + */ + public Builder build(String key) { + this.build = key; + return this; + } + + /** Sets the buttons the player holds now. */ + public Builder held(Collection buttons) { + this.held = new ArrayList<>(buttons); + return this; + } + + /** Sets the buttons the player holds now. */ + public Builder held(String... buttons) { + return held(Arrays.asList(buttons)); + } + + /** + * Sets the parts of the core the runtime does not have yet, out of {@link Mncf#FEATURES}. + * A cheat that uses one is refused with "runtime:unsupported:" and the part. + */ + public Builder unsupported(Collection features) { + this.unsupported = new ArrayList<>(features); + return this; + } + + /** Sets the parts of the core the runtime does not have yet, out of {@link Mncf#FEATURES}. */ + public Builder unsupported(String... features) { + return unsupported(Arrays.asList(features)); + } + + /** + * Adds a run of code that the runtime rewrote for its own reasons, as an offset and a + * length in bytes in a module, both read as unsigned. A patch or a stub over it is refused + * with "runtime:rewritten". + */ + public Builder rewritten(String module, long offset, long length) { + List runs = rewritten.get(module); + if (runs == null) { + runs = new ArrayList<>(); + rewritten.put(module, runs); + } + runs.add(new long[] {offset, length}); + return this; + } + + /** Returns the runtime. */ + public Runtime build() { + return new Runtime(this); + } + } + + /** Returns the platform's name. */ + public String platform() { + return platform; + } + + /** Returns the ID of the game that runs, or null. */ + public String gameId() { + return gameId; + } + + /** Returns the architecture, or null for the platform's default. */ + public String arch() { + return arch; + } + + /** Returns the modules that run, by name. */ + public Map modules() { + return modules; + } + + /** Returns the names of the memory regions. */ + public Set regionNames() { + return regions.keySet(); + } + + /** Returns the base address of a region. */ + public long regionBase(String name) { + return region(name)[0]; + } + + /** Returns the size of a region in bytes. */ + public long regionSize(String name) { + return region(name)[1]; + } + + private long[] region(String name) { + long[] r = regions.get(name); + if (r == null) { + throw new IllegalArgumentException("the runtime has no region " + name); + } + return r; + } + + /** Returns the guest memory, or null. */ + public GuestMemory memory() { + return memory; + } + + /** Returns the capabilities. */ + public Set capabilities() { + return capabilities; + } + + /** Returns the extensions the runtime supports. */ + public Set extensions() { + return extensions; + } + + /** Returns the raw syntaxes the runtime can apply. */ + public Set rawSyntaxes() { + return rawSyntaxes; + } + + /** Returns the build the runtime names itself, or null. */ + public String build() { + return build; + } + + /** Returns the buttons held now. */ + public Set held() { + return held; + } + + /** Returns the parts of the core the runtime does not have yet. */ + public Set unsupported() { + return unsupported; + } + + /** + * Whether the runtime rewrote any byte of a module from an offset on for a length, all read + * as unsigned. + */ + public boolean wasRewritten(String module, long offset, long length) { + List runs = rewritten.get(module); + if (runs == null) { + return false; + } + for (long[] r : runs) { + if (below(r[0], offset, length) && below(offset, r[0], r[1])) { + return true; + } + } + return false; + } + + /** Whether a is less than b plus c, all unsigned, without overflow. */ + private static boolean below(long a, long b, long c) { + long sum = b + c; + return Long.compareUnsigned(sum, b) < 0 || Long.compareUnsigned(a, sum) < 0; + } + + long[] regionOrNull(String name) { + return regions.get(name); + } + + /** Bytes of guest memory, or without guest memory the bytes of a module, or null. */ + byte[] read(long address, int size) { + if (memory != null) { + return memory.read(address, size); + } + for (Module m : modules.values()) { + byte[] data = m.image(); + if (data == null || Long.compareUnsigned(address, m.base()) < 0) { + continue; + } + long offset = address - m.base(); + if (Long.compareUnsigned(offset, data.length) <= 0 && data.length - offset >= size) { + byte[] out = new byte[size]; + System.arraycopy(data, (int) offset, out, 0, size); + return out; + } + } + return null; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Schema.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Schema.java new file mode 100644 index 00000000..fc06c547 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Schema.java @@ -0,0 +1,1261 @@ +package io.github.davdxpx.mistel.mncf; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; + +/** + * Checks a parsed file against the spec and builds the model. + * + *

    Problems outside a cheat make the whole file unusable ({@link MncfException}) or, for keys + * the spec does not define, a warning. Problems inside a cheat turn only that cheat off: its + * problem becomes unknown-key:<key>, extension-missing:<name> or invalid:<key>, + * where <key> is the key's path from the cheat with its parts joined by dots. + */ +final class Schema { + + static final List KNOWN_EXTENSIONS = Values.list("raw/1", "arm64-imm/1"); + + private static final List FILE_KEYS = Values.list("format", "name", "authors", "about", "file_version", + "language", "origin", "extensions", "game", "builds", "cheat", "choices", "preset", "i18n"); + private static final List RUNS = Values.list("on", "once", "action", "timed", "monitor"); + private static final List OPS = + Values.list("==", "!=", "<", "<=", ">", ">=", "&", "!&", "between", "changed"); + private static final List SECTIONS = Values.list("code", "rodata", "data"); + private static final List ACTIONS = Values.list("return", "skip"); + private static final List OP_KEYS = Values.list("patch", "write", "override", "read", "when", "raw"); + private static final List WHOLE_VALUE_TYPES; + + static { + List types = new ArrayList<>(Values.INT_TYPES); + types.add("bool"); + WHOLE_VALUE_TYPES = Collections.unmodifiableList(types); + } + + /** A node of the key tree of a cheat, for finding keys the spec does not define. */ + private static final class Node { + static final int VALUE = 0; + static final int TABLE = 1; + static final int ARRAY = 2; + static final int MAP = 3; + + final int kind; + final Map children; + final Node element; + + private Node(int kind, Map children, Node element) { + this.kind = kind; + this.children = children; + this.element = element; + } + + static Node table(Object... keysAndNodes) { + Map children = new LinkedHashMap<>(); + for (int i = 0; i < keysAndNodes.length; i += 2) { + children.put((String) keysAndNodes[i], (Node) keysAndNodes[i + 1]); + } + return new Node(TABLE, children, null); + } + + static Node values(String... keys) { + Object[] pairs = new Object[2 * keys.length]; + for (int i = 0; i < keys.length; i++) { + pairs[2 * i] = keys[i]; + pairs[2 * i + 1] = new Node(VALUE, null, null); + } + return table(pairs); + } + + static Node arrayOf(Node table) { + return new Node(ARRAY, null, table); + } + + static Node mapOf(Node table) { + return new Node(MAP, null, table); + } + + Node with(Object... keysAndNodes) { + Map all = new LinkedHashMap<>(children); + all.putAll(table(keysAndNodes).children); + return new Node(TABLE, all, null); + } + } + + private static final Node VALUE = new Node(Node.VALUE, null, null); + private static final Node LOC = Node.values("module", "offset", "offsets", "find", "section", "region", "address", "path"); + private static final Node CHEAT_TREE = Node.values("id", "name", "about", "group", "tags", "default", "master", "run", + "duration", "hold", "toggle", "press", "requires", "excludes", "radio", "match", "trigger", "interval") + .with("values", Node.mapOf(Node.values("type", "min", "max", "step", "default", "unit", "display", "choices", + "flags")), + "patch", Node.arrayOf(Node.table("at", LOC, "expect", VALUE, "bytes", VALUE, + "asm", Node.values("expect", "bytes"), + "encode", Node.values("insn", "width", "rd", "value"))), + "write", Node.arrayOf(Node.table("at", LOC, "type", VALUE, "value", VALUE, "expect", VALUE)), + "override", Node.arrayOf(Node.table("function", LOC, "action", VALUE, "value", VALUE, "expect", VALUE)), + "read", Node.arrayOf(Node.table("at", LOC, "type", VALUE, "label", VALUE)), + "when", Node.arrayOf(Node.table("at", LOC, "type", VALUE, "op", VALUE, + "value", Node.table("at", LOC, "type", VALUE))), + "raw", Node.arrayOf(Node.values("syntax", "build", "code"))); + + /** A rule broken inside a cheat. */ + static final class Problem extends Exception { + private static final long serialVersionUID = 1L; + final String reason; + + Problem(String reason) { + super(reason, null, false, false); + this.reason = reason; + } + } + + private static Problem invalid(String path) { + return new Problem(path.isEmpty() ? "invalid" : "invalid:" + path); + } + + private Schema() { + } + + @SuppressWarnings("unchecked") + private static Map map(Object v) { + return (Map) v; + } + + @SuppressWarnings("unchecked") + private static List list(Object v) { + return (List) v; + } + + private static Object get(Map table, String key, Object fallback) { + return table.containsKey(key) ? table.get(key) : fallback; + } + + // The file + + /** The checked parts of a parsed file. */ + static MncfFile.Parts buildFile(Map doc) throws MncfException { + if (doc.isEmpty() || !doc.keySet().iterator().next().equals("format")) { + throw new MncfException("format", "`format` must be the first key of the file"); + } + if (!"mncf/1".equals(doc.get("format"))) { + throw new MncfException("format", "the format is " + Py.repr(doc.get("format")) + + ", this reader reads \"mncf/1\""); + } + MncfFile.Parts out = new MncfFile.Parts(); + List warnings = out.warnings; + for (String k : doc.keySet()) { + if (!FILE_KEYS.contains(k)) { + warnings.add("unknown-key:" + k); + } + } + out.doc = doc; + + out.name = reqStr(doc, "name"); + if (doc.containsKey("about")) { + out.about = reqStr(doc, "about"); + } + if (doc.containsKey("file_version")) { + out.fileVersion = reqStr(doc, "file_version"); + } + if (doc.containsKey("language")) { + out.language = reqStr(doc, "language"); + } + if (doc.containsKey("authors")) { + out.authors = strList(doc.get("authors"), "authors"); + } + if (doc.containsKey("origin")) { + Object o = doc.get("origin"); + if (!(o instanceof Map) || !(map(o).get("format") instanceof String) + || !(get(map(o), "name", "") instanceof String) || !(get(map(o), "site", "") instanceof String)) { + throw new MncfException("schema:origin", + "`origin` must be a table with a `format` string and maybe `name` and `site` strings"); + } + for (String k : map(o).keySet()) { + if (!k.equals("format") && !k.equals("name") && !k.equals("site")) { + warnings.add("unknown-key:origin." + k); + } + } + out.origin = map(o); + } + + List required = new ArrayList<>(); + List optional = new ArrayList<>(); + if (doc.containsKey("extensions")) { + Object ext = doc.get("extensions"); + if (!(ext instanceof Map)) { + throw new MncfException("schema:extensions", "`extensions` must be a table"); + } + Map e = map(ext); + for (String k : e.keySet()) { + if (!k.equals("required") && !k.equals("optional")) { + warnings.add("unknown-key:extensions." + k); + } + } + required = strList(get(e, "required", new ArrayList<>()), "extensions.required"); + optional = strList(get(e, "optional", new ArrayList<>()), "extensions.optional"); + List both = new ArrayList<>(required); + both.addAll(optional); + for (String name : both) { + if (!Py.matches(Values.EXTENSION, name)) { + throw new MncfException("schema:extensions", Py.repr(name) + + " is not an extension name with its version"); + } + } + } + out.required = required; + out.optional = optional; + + Object g = doc.get("game"); + if (!(g instanceof Map)) { + throw new MncfException("schema:game", "the `game` table is missing"); + } + Map game = map(g); + for (String k : game.keySet()) { + if (!k.equals("platform") && !k.equals("id") && !k.equals("name")) { + warnings.add("unknown-key:game." + k); + } + } + Object platName = game.get("platform"); + if (!(platName instanceof String)) { + throw new MncfException("schema:game.platform", "`game.platform` must be a string"); + } + Platform plat = Platform.forName((String) platName); + if (plat == null) { + throw new MncfException("platform", "the platform " + Py.repr(platName) + " is not in Appendix A"); + } + out.platform = plat; + Object gid = game.get("id"); + if (!(gid instanceof String) || !plat.isValidGameId((String) gid)) { + throw new MncfException("schema:game.id", "`game.id` is not a game ID of the " + platName + " platform"); + } + out.gameId = (String) gid; + if (game.containsKey("name")) { + if (!(game.get("name") instanceof String)) { + throw new MncfException("schema:game.name", "`game.name` must be a string"); + } + out.gameName = (String) game.get("name"); + } + + Object rawBuilds = get(doc, "builds", new LinkedHashMap()); + if (!(rawBuilds instanceof Map)) { + throw new MncfException("schema:builds", "`builds` must be a table"); + } + for (Map.Entry entry : map(rawBuilds).entrySet()) { + String key = entry.getKey(); + if (key.isEmpty() || !(entry.getValue() instanceof Map)) { + throw new MncfException("schema:builds", "build " + Py.repr(key) + + " must be a table with a non-empty key"); + } + Map b = map(entry.getValue()); + for (String k : b.keySet()) { + if (!k.equals("version") && !k.equals("modules")) { + warnings.add("unknown-key:builds." + key + "." + k); + } + } + Object mods = b.get("modules"); + if (!(mods instanceof Map) || map(mods).isEmpty()) { + throw new MncfException("schema:builds", "build " + Py.repr(key) + " needs a `modules` table"); + } + Map modules = new LinkedHashMap<>(); + for (Map.Entry m : map(mods).entrySet()) { + if ((!plat.modules().isEmpty() && !plat.modules().contains(m.getKey())) || m.getKey().isEmpty()) { + throw new MncfException("schema:builds", "build " + Py.repr(key) + ": " + Py.repr(m.getKey()) + + " is not a module of the " + platName + " platform"); + } + if (!plat.isValidModuleId(m.getValue())) { + throw new MncfException("schema:builds", "build " + Py.repr(key) + ": " + Py.repr(m.getValue()) + + " is not a module identity of " + platName); + } + modules.put(m.getKey(), (String) m.getValue()); + } + Object version = get(b, "version", key); + if (!(version instanceof String)) { + throw new MncfException("schema:builds", "build " + Py.repr(key) + ": `version` must be a string"); + } + out.builds.put(key, new Build(key, (String) version, modules)); + } + + Object rawChoices = get(doc, "choices", new LinkedHashMap()); + if (!(rawChoices instanceof Map)) { + throw new MncfException("schema:choices", "`choices` must be a table"); + } + for (Map.Entry entry : map(rawChoices).entrySet()) { + Map parsed = choiceList(entry.getValue()); + if (parsed == null) { + throw new MncfException("schema:choices", "choice list " + Py.repr(entry.getKey()) + + " must map whole numbers to names"); + } + out.choices.put(entry.getKey(), parsed); + } + + Object rawCheats = doc.get("cheat"); + if (!(rawCheats instanceof List) || list(rawCheats).isEmpty() || !allMaps(list(rawCheats))) { + throw new MncfException("schema:cheat", "the file needs at least one [[cheat]]"); + } + List ids = new ArrayList<>(); + List cheatTables = list(rawCheats); + for (int i = 0; i < cheatTables.size(); i++) { + Object cid = map(cheatTables.get(i)).get("id"); + if (!(cid instanceof String) || !Py.matches(Values.ID, cid)) { + throw new MncfException("schema:cheat.id", "cheat " + (i + 1) + " has no valid `id`"); + } + if (ids.contains(cid)) { + throw new MncfException("duplicate-id:" + cid, "two cheats have the id " + Py.repr(cid)); + } + ids.add((String) cid); + } + List listed = new ArrayList<>(required); + listed.addAll(optional); + Context ctx = new Context(plat, out.builds, out.choices, new HashSet<>(ids), listed); + for (int i = 0; i < cheatTables.size(); i++) { + out.cheats.add(checkCheat(i, map(cheatTables.get(i)), ctx)); + } + + Object rawPresets = get(doc, "preset", new ArrayList<>()); + if (!(rawPresets instanceof List)) { + throw new MncfException("schema:preset", "`preset` must be an array of tables"); + } + List presetTables = list(rawPresets); + List presetIds = new ArrayList<>(); + for (int i = 0; i < presetTables.size(); i++) { + Object p = presetTables.get(i); + Preset preset = preset(p, out.cheats, presetIds); + if (preset == null) { + Object pid = p instanceof Map ? map(p).get("id") : null; + warnings.add("preset:" + (pid instanceof String ? (String) pid : String.valueOf(i + 1))); + } else { + out.presets.add(preset); + presetIds.add(preset.id()); + } + } + + Object i18n = get(doc, "i18n", Collections.emptyMap()); + boolean good = i18n instanceof Map; + if (good) { + for (Object v : ((Map) i18n).values()) { + good &= v instanceof Map; + } + } + if (!good) { + warnings.add("i18n"); + i18n = Collections.emptyMap(); + } + out.i18n = map(i18n); + return out; + } + + private static boolean allMaps(List items) { + for (Object item : items) { + if (!(item instanceof Map)) { + return false; + } + } + return true; + } + + private static String reqStr(Map table, String key) throws MncfException { + Object v = table.get(key); + if (!(v instanceof String)) { + throw new MncfException("schema:" + key, "`" + key + "` must be a string"); + } + return (String) v; + } + + private static List strList(Object v, String key) throws MncfException { + if (!(v instanceof List)) { + throw new MncfException("schema:" + key, "`" + key + "` must be an array of strings"); + } + List out = new ArrayList<>(); + for (Object x : list(v)) { + if (!(x instanceof String)) { + throw new MncfException("schema:" + key, "`" + key + "` must be an array of strings"); + } + out.add((String) x); + } + return out; + } + + /** A key of a choice list as a number: up to 20 decimal digits, or 0x and up to 16 hexadecimal ones, maybe after a minus. */ + private static Number choiceKey(String k) { + Matcher m = Py.match(CHOICE_KEY, k); + if (m == null) { + return null; + } + BigInteger n = m.group(2) != null ? new BigInteger(m.group(2), 16) : new BigInteger(m.group(3)); + return Values.normalize(m.group(1).isEmpty() ? n : n.negate()); + } + + private static final java.util.regex.Pattern CHOICE_KEY = + java.util.regex.Pattern.compile("(-?)(?:0x([0-9A-Fa-f]{1,16})|([0-9]{1,20}))"); + + /** Whether a number is one a player can choose for this value: inside its range and among its choices. */ + static boolean inSpec(ValueSpec s, Object n) { + return !((s.min() != null && Values.less(n, s.min())) || (s.max() != null && Values.less(s.max(), n)) + || (s.choices() != null && !s.choices().containsKey(n))); + } + + private static Map choiceList(Object table) { + if (!(table instanceof Map) || map(table).isEmpty()) { + return null; + } + Map out = new LinkedHashMap<>(); + for (Map.Entry e : map(table).entrySet()) { + Number n = choiceKey(e.getKey()); + if (n == null || !(e.getValue() instanceof String)) { + return null; + } + out.put(n, (String) e.getValue()); + } + return out; + } + + private static Preset preset(Object p, List cheats, List seen) { + if (!(p instanceof Map)) { + return null; + } + Map t = map(p); + Object pid = t.get("id"); + Object name = t.get("name"); + Object ids = get(t, "cheats", new ArrayList<>()); + if (!(pid instanceof String) || !Py.matches(Values.ID, pid) || seen.contains(pid) || !(name instanceof String)) { + return null; + } + Map byId = new LinkedHashMap<>(); + for (Cheat c : cheats) { + byId.put(c.id(), c); + } + if (!(ids instanceof List)) { + return null; + } + List cheatIds = new ArrayList<>(); + for (Object x : list(ids)) { + if (!(x instanceof String) || !byId.containsKey(x)) { + return null; + } + cheatIds.add((String) x); + } + Object values = get(t, "values", new LinkedHashMap()); + if (!(values instanceof Map)) { + return null; + } + Map numbers = new LinkedHashMap<>(); + for (Map.Entry e : map(values).entrySet()) { + String k = e.getKey(); + int dot = k.indexOf('.'); + String cid = dot < 0 ? k : k.substring(0, dot); + String vid = dot < 0 ? "" : k.substring(dot + 1); + Cheat cheat = byId.get(cid); + ValueSpec spec = cheat != null ? cheat.values().get(vid) : null; + Object n = spec != null ? valueNumber(spec.type(), e.getValue()) : null; + if (n == null || !inSpec(spec, n)) { + return null; + } + numbers.put(k, n); + } + for (String k : t.keySet()) { + if (!k.equals("id") && !k.equals("name") && !k.equals("cheats") && !k.equals("values")) { + return null; + } + } + return new Preset((String) pid, (String) name, cheatIds, numbers); + } + + // One cheat + + private static final class Context { + final Platform platform; + final Map builds; + final Map> choices; + final Set ids; + final List listed; + final List unknownListed = new ArrayList<>(); + + Context(Platform platform, Map builds, Map> choices, Set ids, + List listed) { + this.platform = platform; + this.builds = builds; + this.choices = choices; + this.ids = ids; + this.listed = listed; + for (String e : listed) { + if (!KNOWN_EXTENSIONS.contains(e)) { + unknownListed.add(e); + } + } + } + } + + private static Cheat checkCheat(int index, Map table, Context ctx) { + Cheat.Draft c = new Cheat.Draft(); + c.index = index; + c.id = (String) table.get("id"); + c.table = table; + try { + checkKeys(table, CHEAT_TREE, Collections.emptyList(), ctx); + fillCheat(c, table, ctx); + } catch (Problem p) { + c.problem = p.reason; + } + return new Cheat(c); + } + + private static String extensionOf(List path) { + if (path.equals(Collections.singletonList("raw"))) { + return "raw/1"; + } + if (path.equals(Arrays.asList("patch", "encode"))) { + return "arm64-imm/1"; + } + return null; + } + + private static void checkKeys(Map table, Node tree, List path, Context ctx) throws Problem { + for (Map.Entry entry : table.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + List sub = new ArrayList<>(path); + sub.add(key); + String ext = extensionOf(sub); + if (!tree.children.containsKey(key) || (ext != null && !ctx.listed.contains(ext))) { + if (!ctx.unknownListed.isEmpty()) { + throw new Problem("extension-missing:" + ctx.unknownListed.get(0)); + } + throw new Problem("unknown-key:" + String.join(".", sub)); + } + Node node = tree.children.get(key); + if (node.kind == Node.TABLE) { + if (value instanceof Map) { + checkKeys(map(value), node, sub, ctx); + } + } else if (node.kind == Node.ARRAY) { + if (value instanceof List) { + for (Object item : list(value)) { + if (item instanceof Map) { + checkKeys(map(item), node.element, sub, ctx); + } + } + } + } else if (node.kind == Node.MAP) { + if (value instanceof Map) { + for (Map.Entry named : map(value).entrySet()) { + if (named.getValue() instanceof Map) { + List inner = new ArrayList<>(sub); + inner.add(named.getKey()); + checkKeys(map(named.getValue()), node.element, inner, ctx); + } + } + } + } + } + } + + private static void fillCheat(Cheat.Draft c, Map t, Context ctx) throws Problem { + Platform plat = ctx.platform; + c.name = string(t, "name", true); + c.about = string(t, "about", false); + if (t.containsKey("group")) { + Object g = t.get("group"); + if (!(g instanceof String) || ((String) g).isEmpty() || Py.split((String) g, '/').contains("")) { + throw invalid("group"); + } + c.group = (String) g; + } + if (t.containsKey("tags")) { + c.tags = stringList(t.get("tags"), "tags"); + } + c.defaultOn = bool(t, "default", false); + c.master = bool(t, "master", false); + Object run = get(t, "run", "on"); + if (!RUNS.contains(run)) { + throw invalid("run"); + } + c.run = (String) run; + if (t.containsKey("duration") || c.run.equals("timed")) { + Object d = t.get("duration"); + if (!c.run.equals("timed") || !Values.isNumber(d) || !finite(d) || Values.lessOrEqual(d, 0L)) { + throw invalid("duration"); + } + c.duration = (Number) d; + } + if (t.containsKey("hold")) { + c.hold = buttons(t.get("hold"), "hold", plat); + } + if (t.containsKey("toggle")) { + c.toggle = buttons(t.get("toggle"), "toggle", plat); + } + if (t.containsKey("press")) { + c.press = buttons(t.get("press"), "press", plat); + } + if (c.run.equals("action") != (c.press != null)) { + throw invalid("press"); + } + if (t.containsKey("requires")) { + c.requires = others(t.get("requires"), "requires", c, ctx); + } + if (t.containsKey("excludes")) { + c.excludes = others(t.get("excludes"), "excludes", c, ctx); + } + if (t.containsKey("radio")) { + Object r = t.get("radio"); + if (!(r instanceof String) || ((String) r).isEmpty()) { + throw invalid("radio"); + } + c.radio = (String) r; + } + Object match = get(t, "match", "all"); + if (!"all".equals(match) && !"any".equals(match)) { + throw invalid("match"); + } + c.match = (String) match; + Object trigger = get(t, "trigger", "while"); + if (!"while".equals(trigger) && !"enter".equals(trigger)) { + throw invalid("trigger"); + } + c.trigger = (String) trigger; + Object interval = get(t, "interval", 1L); + if (!Values.isInt(interval) || Values.less(interval, 1L)) { + throw invalid("interval"); + } + c.interval = ((Number) interval).longValue(); + + if (t.containsKey("values")) { + Object vs = t.get("values"); + if (!(vs instanceof Map)) { + throw invalid("values"); + } + for (Map.Entry e : map(vs).entrySet()) { + c.values.put(e.getKey(), valueSpec(e.getKey(), e.getValue(), ctx)); + } + } + + List ops = new ArrayList<>(); + for (Map.Entry e : t.entrySet()) { + String key = e.getKey(); + if (!OP_KEYS.contains(key)) { + continue; + } + Object value = e.getValue(); + if (!(value instanceof List) || !allMaps(list(value)) || list(value).isEmpty()) { + throw invalid(key); + } + for (Object item : list(value)) { + Map table = map(item); + switch (key) { + case "patch": + ops.add(patch(table, c, ctx)); + break; + case "write": + ops.add(write(table, c, ctx)); + break; + case "override": + ops.add(override(table, c, ctx)); + break; + case "read": + ops.add(read(table, ctx)); + break; + case "when": + ops.add(condition(table, c, ctx)); + break; + default: + c.raw.add(raw(table, ctx)); + break; + } + } + } + c.ops = ops; + boolean reads = false; + boolean changes = false; + boolean code = false; + boolean core = false; + for (Model.Op op : ops) { + reads |= op instanceof Model.Read; + changes |= op instanceof Model.Patch || op instanceof Model.Write || op instanceof Model.Override; + code |= op instanceof Model.Patch || op instanceof Model.Override; + core |= !(op instanceof Model.Condition); + } + if (c.run.equals("monitor")) { + if (changes || !reads) { + throw invalid("run"); + } + } else if (c.run.equals("once") && code) { + // A cheat that runs once is off right after its pass; code works only while a cheat is on. + throw invalid("run"); + } else if (reads) { + throw invalid("read"); + } + if (!core && c.raw.isEmpty()) { + throw invalid(""); + } + } + + private static String string(Map t, String key, boolean required) throws Problem { + if (!t.containsKey(key)) { + if (required) { + throw invalid(key); + } + return null; + } + if (!(t.get(key) instanceof String)) { + throw invalid(key); + } + return (String) t.get(key); + } + + private static List stringList(Object v, String path) throws Problem { + if (!(v instanceof List)) { + throw invalid(path); + } + List out = new ArrayList<>(); + for (Object x : list(v)) { + if (!(x instanceof String)) { + throw invalid(path); + } + out.add((String) x); + } + return out; + } + + private static List others(Object v, String path, Cheat.Draft c, Context ctx) throws Problem { + if (!(v instanceof List)) { + throw invalid(path); + } + List out = new ArrayList<>(); + for (Object x : list(v)) { + if (!(x instanceof String) || !ctx.ids.contains(x) || x.equals(c.id)) { + throw invalid(path); + } + out.add((String) x); + } + return out; + } + + private static boolean bool(Map t, String key, boolean fallback) throws Problem { + if (!t.containsKey(key)) { + return fallback; + } + if (!(t.get(key) instanceof Boolean)) { + throw invalid(key); + } + return (Boolean) t.get(key); + } + + private static String buttons(Object v, String path, Platform plat) throws Problem { + if (!(v instanceof String) || ((String) v).isEmpty()) { + throw invalid(path); + } + List names = Py.split((String) v, '+'); + for (String n : names) { + if (!plat.isValidButton(n)) { + throw invalid(path); + } + } + if (new HashSet<>(names).size() != names.size()) { + throw invalid(path); + } + return (String) v; + } + + static boolean isNan(Object v) { + return v instanceof Double && Double.isNaN((Double) v); + } + + private static boolean finite(Object v) { + return !(v instanceof Double) || (!Double.isNaN((Double) v) && !Double.isInfinite((Double) v)); + } + + /** A number of the file as a value of type t, or null if it is not one that fits. */ + static Object valueNumber(String t, Object v) { + if (t.equals("bool")) { + return v instanceof Boolean ? v : null; + } + if (Values.isIntType(t)) { + Number n = Values.integer(v); + return n != null && Values.fits(t, n) ? n : null; + } + if (Values.isFloatType(t)) { + return Values.isNumber(v) && !isNan(v) && Values.fits(t, v) ? v : null; + } + return null; + } + + private static ValueSpec valueSpec(String vid, Object specValue, Context ctx) throws Problem { + String path = "values." + vid; + if (!Py.matches(Values.ID, vid) || !(specValue instanceof Map)) { + throw invalid(path); + } + Map spec = map(specValue); + Object t = spec.get("type"); + if (!Values.VALUE_TYPES.contains(t)) { + throw invalid(path + ".type"); + } + String type = (String) t; + Number[] limits = new Number[3]; + String[] names = {"min", "max", "step"}; + for (int i = 0; i < 3; i++) { + String key = names[i]; + if (spec.containsKey(key)) { + if (type.equals("bool")) { + throw invalid(path + "." + key); + } + Object n = valueNumber(type, spec.get(key)); + if (n == null || (key.equals("step") && Values.lessOrEqual(n, 0L))) { + throw invalid(path + "." + key); + } + limits[i] = (Number) n; + } + } + Number min = limits[0]; + Number max = limits[1]; + if (min != null && max != null && Values.less(max, min)) { + throw invalid(path + ".max"); + } + String unit = null; + if (spec.containsKey("unit")) { + if (!(spec.get("unit") instanceof String)) { + throw invalid(path + ".unit"); + } + unit = (String) spec.get("unit"); + } + String display = "dec"; + if (spec.containsKey("display")) { + Object d = spec.get("display"); + if (!"dec".equals(d) && !"hex".equals(d)) { + throw invalid(path + ".display"); + } + display = (String) d; + } + Map choices = null; + if (spec.containsKey("choices")) { + Object ch = spec.get("choices"); + Map parsed = ch instanceof String ? ctx.choices.get(ch) : choiceList(ch); + boolean fit = parsed != null; + if (fit) { + for (Number k : parsed.keySet()) { + fit &= Values.fits(type, k); + } + } + if (!Values.isIntType(type) || !fit) { + throw invalid(path + ".choices"); + } + choices = parsed; + } + Map flags = null; + if (spec.containsKey("flags")) { + Object fl = spec.get("flags"); + Map parsed = fl instanceof Map ? choiceList(fl) : null; + boolean fit = parsed != null && Values.isIntType(type); + if (fit) { + long width = 8L * Values.typeSize(type); + for (Number b : parsed.keySet()) { + fit &= Values.compare(b, 0L) >= 0 && Values.compare(b, width) < 0; + } + } + if (!fit) { + throw invalid(path + ".flags"); + } + flags = parsed; + } + if (!spec.containsKey("default")) { + throw invalid(path + ".default"); + } + Object d = valueNumber(type, spec.get("default")); + if (d == null || (min != null && Values.less(d, min)) || (max != null && Values.less(max, d)) + || (choices != null && !choices.containsKey(d))) { + throw invalid(path + ".default"); + } + return new ValueSpec(vid, type, d, min, max, limits[2], unit, display, choices, flags); + } + + private static Model.ValueRef ref(Object v, Cheat.Draft c, String path, List kinds) throws Problem { + Matcher m = Py.match(Values.PLAYER_VALUE, v); + if (m == null) { + return null; + } + ValueSpec spec = c.values.get(m.group(1)); + if (spec == null || (kinds != null && !kinds.contains(spec.type()))) { + throw invalid(path); + } + return new Model.ValueRef(m.group(1)); + } + + /** A checked location (section 6.2). */ + private static Model.Location location(Object v, String path, Context ctx) throws Problem { + if (!(v instanceof Map)) { + throw invalid(path); + } + Map t = map(v); + List bases = new ArrayList<>(); + for (String k : new String[] {"module", "region", "address"}) { + if (t.containsKey(k)) { + bases.add(k); + } + } + if (bases.size() != 1) { + throw invalid(path); + } + String base = bases.get(0); + Model.Location loc = new Model.Location(); + loc.kind = base; + if (t.containsKey("path")) { + Object p = t.get("path"); + if (!(p instanceof List) || list(p).isEmpty()) { + throw invalid(path + ".path"); + } + List steps = list(p); + long[] out = new long[steps.size()]; + for (int i = 0; i < out.length; i++) { + Number n = Values.integer(steps.get(i)); + if (n == null) { + throw invalid(path + ".path"); + } + out[i] = n.longValue(); + } + loc.path = out; + } + if (base.equals("address")) { + if (!ctx.platform.addresses()) { + throw invalid(path + ".address"); + } + for (String k : new String[] {"offset", "offsets", "find", "section"}) { + if (t.containsKey(k)) { + throw invalid(path + "." + k); + } + } + Number a = Values.integer(t.get("address")); + if (a == null || Values.compare(a, 0L) < 0) { + throw invalid(path + ".address"); + } + loc.address = a.longValue(); + return loc; + } + Object name = t.get(base); + if (!(name instanceof String) || ((String) name).isEmpty()) { + throw invalid(path + "." + base); + } + if (base.equals("module")) { + loc.module = (String) name; + } else { + loc.region = (String) name; + } + if (t.containsKey("find")) { + if (!base.equals("module")) { + throw invalid(path + ".find"); + } + if (t.containsKey("offsets")) { + throw invalid(path + ".offsets"); + } + int[] pattern = Values.parsePattern(t.get("find")); + if (pattern == null) { + throw invalid(path + ".find"); + } + loc.kind = "pattern"; + loc.find = pattern; + if (t.containsKey("offset")) { + if (!Values.isInt(t.get("offset"))) { + throw invalid(path + ".offset"); + } + loc.offset = ((Number) t.get("offset")).longValue(); + } + if (t.containsKey("section")) { + if (!SECTIONS.contains(t.get("section"))) { + throw invalid(path + ".section"); + } + loc.section = (String) t.get("section"); + } + return loc; + } + if (t.containsKey("section")) { + throw invalid(path + ".section"); + } + if (t.containsKey("offset") == t.containsKey("offsets")) { + throw invalid(path); + } + if (t.containsKey("offset")) { + Number n = Values.integer(t.get("offset")); + if (n == null || Values.compare(n, 0L) < 0) { + throw invalid(path + ".offset"); + } + loc.offset = n.longValue(); + return loc; + } + Object offs = t.get("offsets"); + if (!(offs instanceof Map) || map(offs).isEmpty()) { + throw invalid(path + ".offsets"); + } + loc.offsets = new LinkedHashMap<>(); + for (Map.Entry e : map(offs).entrySet()) { + Number n = Values.integer(e.getValue()); + if (!ctx.builds.containsKey(e.getKey()) || n == null || Values.compare(n, 0L) < 0) { + throw invalid(path + ".offsets"); + } + loc.offsets.put(e.getKey(), n.longValue()); + } + loc.kind = base + "-builds"; + return loc; + } + + private static Model.Patch patch(Map t, Cheat.Draft c, Context ctx) throws Problem { + Model.Location at = location(t.get("at"), "patch.at", ctx); + byte[] expect = Values.parseBytes(t.get("expect")); + if (expect == null) { + throw invalid("patch.expect"); + } + if (t.containsKey("bytes") == t.containsKey("encode")) { + throw invalid("patch.bytes"); + } + Model.Patch p = new Model.Patch(); + p.at = at; + p.expect = expect; + if (t.containsKey("bytes")) { + p.bytes = Values.parseBytes(t.get("bytes")); + if (p.bytes == null) { + throw invalid("patch.bytes"); + } + if (p.bytes.length != expect.length) { + throw invalid("patch.expect"); + } + } else { + Object e = t.get("encode"); + if (!(e instanceof Map)) { + throw invalid("patch.encode"); + } + Map enc = map(e); + Object insn = enc.get("insn"); + Object width = enc.get("width"); + Object rd = enc.get("rd"); + Object value = enc.get("value"); + if (!(insn instanceof String) || !Encode.ARM64_IMM_INSNS.containsKey(insn)) { + throw invalid("patch.encode.insn"); + } + if (!Values.isInt(width) || !(Values.same(width, 32L) || Values.same(width, 64L))) { + throw invalid("patch.encode.width"); + } + if (!Values.isInt(rd) || Values.compare(rd, 0L) < 0 || Values.compare(rd, 31L) > 0) { + throw invalid("patch.encode.rd"); + } + int w = ((Number) width).intValue(); + int r = ((Number) rd).intValue(); + Model.ValueRef ref = ref(value, c, "patch.encode.value", Values.NUMBER_TYPES); + if (ref == null && (!Values.isNumber(value) || Encode.arm64Imm((String) insn, w, r, value) == null)) { + throw invalid("patch.encode.value"); + } + Model.Encoding encoding = new Model.Encoding(); + encoding.insn = (String) insn; + encoding.width = w; + encoding.rd = r; + encoding.value = ref != null ? ref : value; + p.encode = encoding; + if (expect.length != Encode.ARM64_IMM_INSNS.get(insn)) { + throw invalid("patch.expect"); + } + } + if (t.containsKey("asm")) { + Object a = t.get("asm"); + if (!(a instanceof Map) || !(get(map(a), "expect", "") instanceof String) + || !(get(map(a), "bytes", "") instanceof String)) { + throw invalid("patch.asm"); + } + p.asm = map(a); + } + return p; + } + + private static Model.Write write(Map t, Cheat.Draft c, Context ctx) throws Problem { + Model.Location at = location(t.get("at"), "write.at", ctx); + Object typ = t.get("type"); + if (!Values.WRITE_TYPES.contains(typ)) { + throw invalid("write.type"); + } + if (!t.containsKey("value")) { + throw invalid("write.value"); + } + Object v = t.get("value"); + Model.Write w = new Model.Write(); + w.at = at; + w.type = (String) typ; + if (typ.equals("bytes")) { + byte[] value = Values.parseBytes(v); + if (value == null) { + throw invalid("write.value"); + } + byte[] expect = null; + if (t.containsKey("expect")) { + expect = Values.parseBytes(t.get("expect")); + if (expect == null || expect.length != value.length) { + throw invalid("write.expect"); + } + } + w.value = value; + w.expect = expect; + return w; + } + Model.ValueRef ref = ref(v, c, "write.value", Values.VALUE_TYPES); + if (ref != null && Values.isIntType(typ) && Values.isFloatType(c.values.get(ref.name).type())) { + throw invalid("write.value"); + } + Object value = ref != null ? ref : valueNumber(w.type, v); + if (value == null) { + throw invalid("write.value"); + } + w.value = value; + if (t.containsKey("expect")) { + w.expect = valueNumber(w.type, t.get("expect")); + if (w.expect == null) { + throw invalid("write.expect"); + } + } + return w; + } + + private static Model.Override override(Map t, Cheat.Draft c, Context ctx) throws Problem { + Model.Location fn = location(t.get("function"), "override.function", ctx); + Object action = t.get("action"); + if (!ACTIONS.contains(action)) { + throw invalid("override.action"); + } + Model.Override o = new Model.Override(); + o.function = fn; + o.action = (String) action; + if (action.equals("return")) { + if (!t.containsKey("value")) { + throw invalid("override.value"); + } + Model.ValueRef ref = ref(t.get("value"), c, "override.value", WHOLE_VALUE_TYPES); + Number n = ref == null ? Values.integer(t.get("value")) : null; + if (ref == null && (n == null || !Values.inLongOrU64(Values.big(n)))) { + throw invalid("override.value"); + } + o.value = ref != null ? ref : n; + } else if (t.containsKey("value")) { + throw invalid("override.value"); + } + if (t.containsKey("expect")) { + o.expect = Values.parseBytes(t.get("expect")); + if (o.expect == null) { + throw invalid("override.expect"); + } + } + return o; + } + + private static Model.Read read(Map t, Context ctx) throws Problem { + Model.Location at = location(t.get("at"), "read.at", ctx); + Object typ = t.get("type"); + if (!Values.NUMBER_TYPES.contains(typ)) { + throw invalid("read.type"); + } + Model.Read r = new Model.Read(); + r.at = at; + r.type = (String) typ; + if (t.containsKey("label")) { + if (!(t.get("label") instanceof String)) { + throw invalid("read.label"); + } + r.label = (String) t.get("label"); + } + return r; + } + + private static Model.Condition condition(Map t, Cheat.Draft c, Context ctx) throws Problem { + Model.Location at = location(t.get("at"), "when.at", ctx); + Object typ = t.get("type"); + if (!Values.NUMBER_TYPES.contains(typ)) { + throw invalid("when.type"); + } + Object op = t.get("op"); + if (!OPS.contains(op)) { + throw invalid("when.op"); + } + if ((op.equals("&") || op.equals("!&")) && !Values.isIntType(typ)) { + throw invalid("when.type"); + } + Model.Condition cond = new Model.Condition(); + cond.at = at; + cond.type = (String) typ; + cond.op = (String) op; + if (op.equals("changed")) { + if (t.containsKey("value")) { + throw invalid("when.value"); + } + return cond; + } + if (!t.containsKey("value")) { + throw invalid("when.value"); + } + Object v = t.get("value"); + if (op.equals("between")) { + if (!(v instanceof List) || list(v).size() != 2) { + throw invalid("when.value"); + } + Object low = valueNumber(cond.type, list(v).get(0)); + Object high = valueNumber(cond.type, list(v).get(1)); + if (low == null || high == null || Values.less(high, low)) { + throw invalid("when.value"); + } + cond.value = new Model.Between(low, high); + return cond; + } + if (v instanceof Map) { + Map other = map(v); + Object otherType = other.get("type"); + if (!other.containsKey("at")) { + throw invalid("when.value.at"); + } + Model.Location placeAt = location(other.get("at"), "when.value.at", ctx); + if (!Values.NUMBER_TYPES.contains(otherType) || (bits(cond.op) && !Values.isIntType(otherType))) { + throw invalid("when.value.type"); + } + cond.value = new Model.Place(placeAt, (String) otherType); + return cond; + } + Model.ValueRef ref = ref(v, c, "when.value", bits(cond.op) ? WHOLE_VALUE_TYPES : Values.VALUE_TYPES); + cond.value = ref != null ? ref : valueNumber(cond.type, v); + if (cond.value == null) { + throw invalid("when.value"); + } + return cond; + } + + /** Whether a condition's operator tests bits, so that what it compares with is a whole number. */ + private static boolean bits(String op) { + return op.equals("&") || op.equals("!&"); + } + + private static Model.Raw raw(Map t, Context ctx) throws Problem { + Object syntax = t.get("syntax"); + Object build = t.get("build"); + Object code = t.get("code"); + if (!(syntax instanceof String) || ((String) syntax).isEmpty()) { + throw invalid("raw.syntax"); + } + if (!(build instanceof String) || !ctx.builds.containsKey(build)) { + throw invalid("raw.build"); + } + if (!(code instanceof String) || Py.strip((String) code).isEmpty()) { + throw invalid("raw.code"); + } + if (syntax.equals("atmosphere")) { + for (String token : Py.splitSpace((String) code)) { + if (token.codePointCount(0, token.length()) != 8 || !isHex(token)) { + throw invalid("raw.code"); + } + } + } + return new Model.Raw((String) syntax, (String) build, (String) code); + } + + private static boolean isHex(String token) { + for (int i = 0; i < token.length(); i++) { + if ("0123456789abcdefABCDEF".indexOf(token.charAt(i)) < 0) { + return false; + } + } + return true; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Shown.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Shown.java new file mode 100644 index 00000000..f445395a --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Shown.java @@ -0,0 +1,53 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** A value a monitor read in a pass (section 7.7). Immutable. */ +public final class Shown { + + private final String label; + private final String type; + private final Object value; + + Shown(String label, String type, Object value) { + this.label = label; + this.type = type; + this.value = value; + } + + /** Returns the read's label, or null. */ + public String label() { + return label; + } + + /** Returns the type the value was read as. */ + public String type() { + return type; + } + + /** + * Returns the value: a Long, a BigInteger for a u64 of 2^63 or more, or a Double for f32 + * and f64. + */ + public Object value() { + return value; + } + + /** Returns the fields that are set, by name, as the conformance suite writes them. */ + public Map toMap() { + Map out = new LinkedHashMap<>(); + out.put("type", type); + out.put("value", value); + if (label != null) { + out.put("label", label); + } + return Collections.unmodifiableMap(out); + } + + @Override + public String toString() { + return toMap().toString(); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/SignatureResult.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/SignatureResult.java new file mode 100644 index 00000000..6cca1ee7 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/SignatureResult.java @@ -0,0 +1,50 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** The result of section 12 for a file or a pack manifest. Immutable. */ +public final class SignatureResult { + + /** A trusted key signed it, and no signature line is bad. */ + public static final String VERIFIED = "verified"; + /** It has no signature line. */ + public static final String UNSIGNED = "unsigned"; + /** It is signed, but by no key the reader knows. */ + public static final String UNKNOWN_KEY = "unknown-key"; + /** A signature line is malformed or does not match. A runtime must not apply it. */ + public static final String INVALID = "invalid"; + /** A revoked key signed it. A runtime must not apply it. */ + public static final String REVOKED = "revoked"; + + private final String result; + private final List signers; + private final List keyIds; + + SignatureResult(String result, List signers, List keyIds) { + this.result = result; + this.signers = Collections.unmodifiableList(new ArrayList<>(signers)); + this.keyIds = Collections.unmodifiableList(new ArrayList<>(keyIds)); + } + + /** Returns verified, unsigned, unknown-key, invalid or revoked. */ + public String result() { + return result; + } + + /** Returns the names of the trusted keys that signed it, when the result is verified. */ + public List signers() { + return signers; + } + + /** Returns the key id of every well-formed signature line, in file order. */ + public List keyIds() { + return keyIds; + } + + @Override + public String toString() { + return result + (signers.isEmpty() ? "" : " " + signers); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Signatures.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Signatures.java new file mode 100644 index 00000000..d4453bb0 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Signatures.java @@ -0,0 +1,173 @@ +package io.github.davdxpx.mistel.mncf; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Signature lines and trust (section 12). */ +public final class Signatures { + + private static final byte[] PREFIX = "# mncf-signature: ".getBytes(StandardCharsets.US_ASCII); + private static final Pattern LINE = + Pattern.compile("# mncf-signature: (ed25519) ([0-9a-f]{16}) ([A-Za-z0-9+/]{86}==)"); + private static final Pattern ANY_LINE = Pattern.compile("# mncf-signature: ([a-z0-9-]+) .*", Pattern.DOTALL); + + private Signatures() { + } + + /** + * Returns the key id of a 32-byte public key: the first 16 hexadecimal digits of its SHA-256 + * hash, in lower case. + */ + public static String keyId(byte[] publicKey) { + byte[] hash = sha256(publicKey); + StringBuilder b = new StringBuilder(); + for (int i = 0; i < 8; i++) { + b.append(String.format("%02x", hash[i] & 0xFF)); + } + return b.toString(); + } + + static byte[] sha256(byte[] data) { + try { + return MessageDigest.getInstance("SHA-256").digest(data); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is not available", e); + } + } + + /** The parts of a file: the signed bytes, the lines from the first signature line on, and whether all are signature lines. */ + static final class Split { + final byte[] signed; + final List lines; + final boolean clean; + + Split(byte[] signed, List lines, boolean clean) { + this.signed = signed; + this.lines = lines; + this.clean = clean; + } + } + + static Split split(byte[] data) { + int start = startsWith(data, 0) ? 0 : -1; + if (start < 0) { + for (int i = 0; i < data.length; i++) { + if (data[i] == '\n' && startsWith(data, i + 1)) { + start = i + 1; + break; + } + } + } + if (start < 0) { + return new Split(data, new ArrayList(), true); + } + List lines = new ArrayList<>(); + int from = start; + for (int i = start; i <= data.length; i++) { + if (i == data.length || data[i] == '\n') { + lines.add(Arrays.copyOfRange(data, from, i)); + from = i + 1; + } + } + if (!lines.isEmpty() && lines.get(lines.size() - 1).length == 0) { + lines.remove(lines.size() - 1); + } + boolean clean = true; + for (byte[] line : lines) { + clean &= startsWith(line, 0); + } + return new Split(Arrays.copyOf(data, start), lines, clean); + } + + private static boolean startsWith(byte[] data, int at) { + if (data.length - at < PREFIX.length) { + return false; + } + for (int i = 0; i < PREFIX.length; i++) { + if (data[at + i] != PREFIX[i]) { + return false; + } + } + return true; + } + + /** + * Returns the bytes a signature covers: everything before the first line that starts with + * "# mncf-signature: ", or all of the data when there is none. + */ + public static byte[] signedBytes(byte[] data) { + return split(data).signed.clone(); + } + + /** + * Checks the signature lines of a file's or a pack manifest's bytes against the trust list. + * When lines disagree, invalid wins over revoked, revoked over verified, and verified over + * unknown-key. + * + * @param trust the trusted keys, or null for none + */ + public static SignatureResult check(byte[] data, TrustList trust) { + if (trust == null) { + trust = new TrustList(); + } + Split split = split(data); + List none = new ArrayList<>(); + if (split.lines.isEmpty()) { + return new SignatureResult(SignatureResult.UNSIGNED, none, none); + } + if (!split.clean) { + return new SignatureResult(SignatureResult.INVALID, none, none); + } + List results = new ArrayList<>(); + List signers = new ArrayList<>(); + List keyIds = new ArrayList<>(); + for (byte[] raw : split.lines) { + // A signature line is ASCII; any other byte keeps it from matching, as in a bytes pattern. + String line = new String(raw, StandardCharsets.ISO_8859_1); + Matcher m = LINE.matcher(line); + if (!m.matches()) { + Matcher other = ANY_LINE.matcher(line); + if (other.matches() && !other.group(1).equals("ed25519")) { + results.add(SignatureResult.UNKNOWN_KEY); // an algorithm this reader does not know + } else { + results.add(SignatureResult.INVALID); + } + continue; + } + String kid = m.group(2); + String sig64 = m.group(3); + byte[] sig = Base64.getDecoder().decode(sig64); + keyIds.add(kid); + if (!Base64.getEncoder().encodeToString(sig).equals(sig64)) { + results.add(SignatureResult.INVALID); + } else if (trust.isRevoked(kid)) { + results.add(SignatureResult.REVOKED); + } else if (!trust.keys(kid).isEmpty()) { + List good = new ArrayList<>(); + for (TrustList.Key key : trust.keys(kid)) { + if (Ed25519.verify(key.publicKey, split.signed, sig)) { + good.add(key.name); + } + } + results.add(good.isEmpty() ? SignatureResult.INVALID : SignatureResult.VERIFIED); + signers.addAll(good); + } else { + results.add(SignatureResult.UNKNOWN_KEY); + } + } + for (String result : new String[] {SignatureResult.INVALID, SignatureResult.REVOKED, + SignatureResult.VERIFIED, SignatureResult.UNKNOWN_KEY}) { + if (results.contains(result)) { + return new SignatureResult(result, result.equals(SignatureResult.VERIFIED) ? signers : none, keyIds); + } + } + return new SignatureResult(SignatureResult.UNSIGNED, none, none); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Source.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Source.java new file mode 100644 index 00000000..40243694 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Source.java @@ -0,0 +1,94 @@ +package io.github.davdxpx.mistel.mncf; + +/** + * One Atmosphère cheat file for the converter: the build ID of the main module it is for, its + * text, and what else is known about its build. Immutable. + */ +public final class Source { + + private final String buildId; + private final String text; + private final String version; + private final CodeModule module; + private final String buildKey; + + private Source(Builder b) { + buildId = b.buildId; + text = b.text; + version = b.version; + module = b.module; + buildKey = b.buildKey; + } + + /** + * Starts a source. + * + * @param buildId the build ID of the main module, in hexadecimal, as cheat files name it + * @param text the text of the cheat file + */ + public static Builder builder(String buildId, String text) { + return new Builder(buildId, text); + } + + /** Builds a {@link Source}. */ + public static final class Builder { + private final String buildId; + private final String text; + private String version; + private CodeModule module; + private String buildKey; + + private Builder(String buildId, String text) { + this.buildId = buildId; + this.text = text; + } + + /** Sets the version the player sees, which also names the build in the file. */ + public Builder version(String version) { + this.version = version; + return this; + } + + /** Sets the main module of the build, for expect and patterns. */ + public Builder module(CodeModule module) { + this.module = module; + return this; + } + + /** Sets the build's name in the file; the default is the version, else the build ID. */ + public Builder buildKey(String key) { + this.buildKey = key; + return this; + } + + /** Returns the source. */ + public Source build() { + return new Source(this); + } + } + + /** Returns the build ID of the main module. */ + public String buildId() { + return buildId; + } + + /** Returns the text of the cheat file. */ + public String text() { + return text; + } + + /** Returns the version the player sees, or null. */ + public String version() { + return version; + } + + /** Returns the main module, or null. */ + public CodeModule module() { + return module; + } + + /** Returns the build's name in the file, or null for the default. */ + public String buildKey() { + return buildKey; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/TrustList.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/TrustList.java new file mode 100644 index 00000000..98912d28 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/TrustList.java @@ -0,0 +1,149 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * The keys a reader trusts, by name, and the key ids it no longer trusts (section 12). A caller + * fills it in before reading files; reading does not change it. + */ +public final class TrustList { + + private final Map> keys = new LinkedHashMap<>(); + private final Set revoked = new LinkedHashSet<>(); + + /** A trusted public key and the name it is shown with. */ + static final class Key { + final String name; + final byte[] publicKey; + + Key(String name, byte[] publicKey) { + this.name = name; + this.publicKey = publicKey; + } + } + + /** + * Trusts a public key under a name. A key may be trusted under several names. + * + * @param publicKey the 32 bytes of an Ed25519 public key + * @return this list + * @throws IllegalArgumentException if the key is not 32 bytes + */ + public TrustList trust(String name, byte[] publicKey) { + if (publicKey.length != 32) { + throw new IllegalArgumentException("an Ed25519 public key is 32 bytes"); + } + String kid = Signatures.keyId(publicKey); + List list = keys.get(kid); + if (list == null) { + list = new ArrayList<>(); + keys.put(kid, list); + } + list.add(new Key(name, publicKey.clone())); + return this; + } + + /** + * Stops trusting a key id: a signature by it makes a file "revoked". + * + * @param keyId the 16 hexadecimal digits of the key id, in any case + * @return this list + */ + public TrustList revoke(String keyId) { + revoked.add(Py.lower(keyId)); + return this; + } + + /** Returns the key ids this list no longer trusts, in lower case. */ + public Set revoked() { + return Collections.unmodifiableSet(new LinkedHashSet<>(revoked)); + } + + boolean isRevoked(String keyId) { + return revoked.contains(keyId); + } + + List keys(String keyId) { + List list = keys.get(keyId); + return list == null ? Collections.emptyList() : list; + } + + private static final Pattern KEY_ID = Pattern.compile("[0-9a-f]{16}"); + + /** + * Returns the trust list a trust list file holds ({@code format = "mncf-keys/1"}, section + * 12): its keys in file order, and its revoked key ids. + * + * @throws MncfException with the code toml for text that is not TOML of the format, format + * when {@code format = "mncf-keys/1"} is not the first key, schema:key for a key without + * a name, without a public key of 32 bytes in canonical base64, or with an id that is not + * the public key's, and schema:revoked for a revoked id that is not 16 lower-case + * hexadecimal digits + */ + @SuppressWarnings("unchecked") + public static TrustList fromToml(String text) throws MncfException { + Map doc = Mncf.parseToml(text, "toml"); + if (doc.isEmpty() || !doc.keySet().iterator().next().equals("format") || !"mncf-keys/1".equals(doc.get("format"))) { + throw new MncfException("format", "`format = \"mncf-keys/1\"` must be the first key of a trust list"); + } + TrustList trust = new TrustList(); + Object keys = doc.containsKey("key") ? doc.get("key") : Collections.emptyList(); + Object revoked = doc.containsKey("revoked") ? doc.get("revoked") : Collections.emptyList(); + if (!isTableArrayOrEmpty(keys)) { + throw new MncfException("schema:key", "`key` must be an array of tables"); + } + for (Object item : (List) keys) { + Map k = (Map) item; + Object name = k.get("name"); + Object pub = k.get("public"); + byte[] raw = new byte[0]; + if (pub instanceof String) { + try { + raw = Base64.getDecoder().decode((String) pub); + } catch (IllegalArgumentException e) { + raw = new byte[0]; + } + } + if (!(name instanceof String) || ((String) name).isEmpty() || raw.length != 32 + || !Base64.getEncoder().encodeToString(raw).equals(pub)) { + throw new MncfException("schema:key", "a key needs a `name` and a `public` key of 32 bytes in base64"); + } + if (k.containsKey("id") && !Signatures.keyId(raw).equals(k.get("id"))) { + throw new MncfException("schema:key", "the key id of " + Py.repr(name) + " is " + Signatures.keyId(raw) + + ", not " + Py.repr(k.get("id"))); + } + trust.trust((String) name, raw); + } + if (!isTableArrayOrEmpty(revoked)) { + throw new MncfException("schema:revoked", "`revoked` must be an array of tables"); + } + for (Object item : (List) revoked) { + Object kid = ((Map) item).get("id"); + if (!Py.matches(KEY_ID, kid)) { + throw new MncfException("schema:revoked", "a revoked key needs an `id` of 16 lower-case hexadecimal digits"); + } + trust.revoke((String) kid); + } + return trust; + } + + private static boolean isTableArrayOrEmpty(Object v) { + if (!(v instanceof List)) { + return false; + } + for (Object x : (List) v) { + if (!(x instanceof Map)) { + return false; + } + } + return true; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Utf8.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Utf8.java new file mode 100644 index 00000000..bf6f0b7d --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Utf8.java @@ -0,0 +1,58 @@ +package io.github.davdxpx.mistel.mncf; + +/** + * A strict UTF-8 check (RFC 3629): no overlong forms, no surrogates, nothing above U+10FFFF. + * Written out here so that the result does not depend on a platform's decoder. + */ +final class Utf8 { + + private Utf8() { + } + + /** Returns null when the bytes are UTF-8, else what is wrong and at which byte, as Python says it. */ + static String check(byte[] data) { + int i = 0; + while (i < data.length) { + int b = data[i] & 0xFF; + if (b < 0x80) { + i++; + continue; + } + int need; + int low = 0x80; + int high = 0xBF; + if (b >= 0xC2 && b <= 0xDF) { + need = 1; + } else if (b >= 0xE0 && b <= 0xEF) { + need = 2; + if (b == 0xE0) { + low = 0xA0; + } else if (b == 0xED) { + high = 0x9F; + } + } else if (b >= 0xF0 && b <= 0xF4) { + need = 3; + if (b == 0xF0) { + low = 0x90; + } else if (b == 0xF4) { + high = 0x8F; + } + } else { + return "invalid start byte at byte " + i; + } + for (int k = 1; k <= need; k++) { + if (i + k >= data.length) { + return "unexpected end of data at byte " + i; + } + int c = data[i + k] & 0xFF; + int lo = k == 1 ? low : 0x80; + int hi = k == 1 ? high : 0xBF; + if (c < lo || c > hi) { + return "invalid continuation byte at byte " + i; + } + } + i += need + 1; + } + return null; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ValueSpec.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ValueSpec.java new file mode 100644 index 00000000..1954038b --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/ValueSpec.java @@ -0,0 +1,91 @@ +package io.github.davdxpx.mistel.mncf; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A value the player sets (section 8): its type, range and default. Immutable. + * + *

    Numbers are a {@link Long}, or a {@link java.math.BigInteger} for a u64 value of 2^63 or + * more, a {@link Double} for a float, and a {@link Boolean} for type bool. For any whole number, + * {@link Number#longValue()} gives its 64 bits. A float type may have whole numbers as its + * limits and default, as the file wrote them. + */ +public final class ValueSpec { + + private final String id; + private final String type; + private final Object defaultValue; + private final Number min; + private final Number max; + private final Number step; + private final String unit; + private final String display; + private final Map choices; + private final Map flags; + + ValueSpec(String id, String type, Object defaultValue, Number min, Number max, Number step, String unit, + String display, Map choices, Map flags) { + this.id = id; + this.type = type; + this.defaultValue = defaultValue; + this.min = min; + this.max = max; + this.step = step; + this.unit = unit; + this.display = display; + this.choices = choices == null ? null : Collections.unmodifiableMap(new LinkedHashMap<>(choices)); + this.flags = flags == null ? null : Collections.unmodifiableMap(new LinkedHashMap<>(flags)); + } + + /** Returns the value's id within its cheat. */ + public String id() { + return id; + } + + /** Returns the type: u8 to u64, s8 to s64, f32, f64 or bool. */ + public String type() { + return type; + } + + /** Returns the default value: a number, or a Boolean for type bool. */ + public Object defaultValue() { + return defaultValue; + } + + /** Returns the smallest value allowed, or null. */ + public Number min() { + return min; + } + + /** Returns the largest value allowed, or null. */ + public Number max() { + return max; + } + + /** Returns the step between values, or null. */ + public Number step() { + return step; + } + + /** Returns the unit shown after the value, or null. */ + public String unit() { + return unit; + } + + /** Returns how the value is shown: "dec" or "hex". */ + public String display() { + return display; + } + + /** Returns the named choices by their number, in file order, or null when the value has none. */ + public Map choices() { + return choices; + } + + /** Returns the named bit flags by bit number, in file order, or null when the value has none. */ + public Map flags() { + return flags; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Values.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Values.java new file mode 100644 index 00000000..826f3a99 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Values.java @@ -0,0 +1,384 @@ +package io.github.davdxpx.mistel.mncf; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Scalars of the format: integers that may be written as strings, bytes strings, patterns and + * typed values, and how numbers compare and fit. + * + *

    A number is a {@link Long}, a {@link BigInteger} only where the integer does not fit in a + * long (a u64 value of 2^63 or more), a {@link Double}, or a {@link Boolean} where a value of + * type bool is meant. Numbers compare exactly, also an integer with a float, as Python does. + */ +final class Values { + + static final Pattern ID = Pattern.compile("[a-z][a-z0-9-]*"); + static final Pattern BYTES = Pattern.compile("[0-9A-Fa-f]{2}( [0-9A-Fa-f]{2})*"); + static final Pattern PATTERN = Pattern.compile("([0-9A-Fa-f]{2}|\\?\\?)( ([0-9A-Fa-f]{2}|\\?\\?))*"); + static final Pattern BIG_INT = Pattern.compile("0x([0-9A-Fa-f]{1,16})"); + static final Pattern EXTENSION = Pattern.compile("(x-)?[a-z0-9][a-z0-9-]*/[0-9]+"); + static final Pattern PLAYER_VALUE = Pattern.compile("\\$([a-z][a-z0-9-]*)"); + + static final List INT_TYPES = list("u8", "u16", "u32", "u64", "s8", "s16", "s32", "s64"); + static final List FLOAT_TYPES = list("f32", "f64"); + static final List NUMBER_TYPES = join(INT_TYPES, FLOAT_TYPES); + static final List WRITE_TYPES = join(NUMBER_TYPES, list("bytes")); + static final List VALUE_TYPES = join(NUMBER_TYPES, list("bool")); + + private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE); + private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE); + private static final BigInteger U64_END = BigInteger.ONE.shiftLeft(64); + + private Values() { + } + + static List list(String... items) { + return Collections.unmodifiableList(Arrays.asList(items)); + } + + private static List join(List a, List b) { + List all = new ArrayList<>(a); + all.addAll(b); + return Collections.unmodifiableList(all); + } + + /** Whether the value is a whole number, not a bool: Python's type(v) is int. */ + static boolean isInt(Object v) { + return v instanceof Long || v instanceof BigInteger; + } + + /** Whether the value is a whole or a floating point number, not a bool. */ + static boolean isNumber(Object v) { + return isInt(v) || v instanceof Double; + } + + /** The number with the smallest type that holds it: a Long where it fits, else the BigInteger. */ + static Number normalize(BigInteger v) { + return v.bitLength() < 64 ? (Number) v.longValue() : v; + } + + /** A whole number or a bool as a BigInteger, a bool being 0 or 1. */ + static BigInteger big(Object v) { + if (v instanceof Long) { + return BigInteger.valueOf((Long) v); + } + if (v instanceof Boolean) { + return ((Boolean) v) ? BigInteger.ONE : BigInteger.ZERO; + } + return (BigInteger) v; + } + + /** The low 64 bits of a whole number or a bool. */ + static long bits(Object v) { + if (v instanceof Boolean) { + return ((Boolean) v) ? 1 : 0; + } + return ((Number) v).longValue(); + } + + /** An unsigned 64-bit number as a number: a Long below 2^63, else a BigInteger. */ + static Number unsigned(long bits) { + return bits >= 0 ? (Number) bits : new BigInteger(Long.toUnsignedString(bits)); + } + + /** + * An integer of the file: a TOML integer, or a string such as "0xFFFFFFFF80000000" with up + * to 16 hexadecimal digits. Null if it is neither. + */ + static Number integer(Object v) { + if (v instanceof Long) { + return (Long) v; + } + Matcher m = Py.match(BIG_INT, v); + if (m == null) { + return null; + } + return normalize(new BigInteger(m.group(1), 16)); + } + + /** A bytes string as bytes, or null if it is not one. */ + static byte[] parseBytes(Object text) { + Matcher m = Py.match(BYTES, text); + if (m == null) { + return null; + } + String s = m.group(); + byte[] out = new byte[(s.length() + 1) / 3]; + for (int i = 0; i < out.length; i++) { + out[i] = (byte) Integer.parseInt(s.substring(3 * i, 3 * i + 2), 16); + } + return out; + } + + /** + * A pattern as byte values, with -1 for each ??, or null if it is not a valid pattern: at + * least four items, the first and the last a fixed byte. + */ + static int[] parsePattern(Object text) { + Matcher m = Py.match(PATTERN, text); + if (m == null) { + return null; + } + List items = Py.split(m.group(), ' '); + int[] out = new int[items.size()]; + for (int i = 0; i < out.length; i++) { + String t = items.get(i); + out[i] = t.equals("??") ? -1 : Integer.parseInt(t, 16); + } + if (out.length < 4 || out[0] < 0 || out[out.length - 1] < 0) { + return null; + } + return out; + } + + /** Bytes in the file's notation: upper-case pairs separated by single spaces. */ + static String hexBytes(byte[] data) { + StringBuilder b = new StringBuilder(data.length * 3); + for (int i = 0; i < data.length; i++) { + if (i > 0) { + b.append(' '); + } + b.append(Character.toUpperCase(Character.forDigit((data[i] >> 4) & 0xF, 16))); + b.append(Character.toUpperCase(Character.forDigit(data[i] & 0xF, 16))); + } + return b.toString(); + } + + static boolean isIntType(Object t) { + return INT_TYPES.contains(t); + } + + static boolean isFloatType(Object t) { + return FLOAT_TYPES.contains(t); + } + + /** The size in bytes of a number type or bool, or 0 for any other name. */ + static int typeSize(String t) { + switch (t) { + case "u8": + case "s8": + case "bool": + return 1; + case "u16": + case "s16": + return 2; + case "u32": + case "s32": + case "f32": + return 4; + case "u64": + case "s64": + case "f64": + return 8; + default: + return 0; + } + } + + private static boolean signed(String t) { + return t.charAt(0) == 's'; + } + + /** Whether the number v can be stored as type t. */ + static boolean fits(String t, Object v) { + if (t.equals("bool")) { + if (v instanceof Boolean) { + return true; + } + if (!isInt(v)) { + return false; + } + BigInteger n = big(v); + return n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE); + } + if (isIntType(t)) { + if (!isInt(v)) { + return false; + } + int width = 8 * typeSize(t); + BigInteger n = big(v); + BigInteger low = signed(t) ? BigInteger.ONE.shiftLeft(width - 1).negate() : BigInteger.ZERO; + BigInteger high = (signed(t) ? BigInteger.ONE.shiftLeft(width - 1) : BigInteger.ONE.shiftLeft(width)) + .subtract(BigInteger.ONE); + return n.compareTo(low) >= 0 && n.compareTo(high) <= 0; + } + if (isFloatType(t)) { + if (!isNumber(v)) { + return false; + } + if (t.equals("f32") && v instanceof Double) { + double d = (Double) v; + // A finite value that rounds to an infinite float is too big, as struct.pack says. + return !(Float.isInfinite((float) d) && !Double.isInfinite(d) && !Double.isNaN(d)); + } + return true; + } + return false; + } + + /** The number as a double, rounded to the nearest one as Python's float() does. */ + static double toDouble(Object v) { + if (v instanceof Double) { + return (Double) v; + } + if (v instanceof Long) { + return (double) (Long) v; + } + if (v instanceof Boolean) { + return ((Boolean) v) ? 1 : 0; + } + BigInteger n = (BigInteger) v; + if (n.signum() > 0 && n.bitLength() == 64) { + long bits = n.longValue(); + // Halve with the lowest bit kept as a sticky bit, so that the rounding stays exact. + return (double) ((bits >>> 1) | (bits & 1)) * 2.0; + } + return Double.parseDouble(n.toString()); + } + + /** + * The number that the bytes hold as a number type, in the platform's byte order: a Long, a + * BigInteger for a u64 of 2^63 or more, or a Double for f32 and f64. + */ + static Object decode(String t, byte[] raw, boolean bigEndian) { + long bits = 0; + int size = raw.length; + for (int i = 0; i < size; i++) { + int b = raw[bigEndian ? i : size - 1 - i] & 0xFF; + bits = (bits << 8) | b; + } + if (t.equals("f32")) { + return (double) Float.intBitsToFloat((int) bits); + } + if (t.equals("f64")) { + return Double.longBitsToDouble(bits); + } + if (signed(t)) { + int shift = 64 - 8 * size; + return (bits << shift) >> shift; + } + return unsigned(bits); + } + + /** The bytes of the number v as type t, in the platform's byte order. */ + static byte[] encode(String t, Object v, boolean bigEndian) { + int size = typeSize(t); + long bits; + if (t.equals("bool")) { + return new byte[] {(byte) (truthy(v) ? 1 : 0)}; + } else if (t.equals("f32")) { + bits = Float.floatToRawIntBits((float) toDouble(v)) & 0xFFFFFFFFL; + } else if (t.equals("f64")) { + bits = Double.doubleToRawLongBits(toDouble(v)); + } else { + bits = bits(v); + } + byte[] out = new byte[size]; + for (int i = 0; i < size; i++) { + byte b = (byte) (bits >>> (8 * i)); + out[bigEndian ? size - 1 - i : i] = b; + } + return out; + } + + private static boolean truthy(Object v) { + if (v instanceof Boolean) { + return (Boolean) v; + } + if (v instanceof Double) { + return (Double) v != 0; + } + return big(v).signum() != 0; + } + + /** + * Compares two numbers as Python does: exactly, also between a whole number and a float, a + * bool counting as 0 or 1. + * + * @return a negative number, zero or a positive number, or null when either is NaN + */ + static Integer compare(Object a, Object b) { + if (a instanceof Double || b instanceof Double) { + double x = a instanceof Double ? (Double) a : 0; + double y = b instanceof Double ? (Double) b : 0; + if (Double.isNaN(x) || Double.isNaN(y)) { + return null; + } + if (a instanceof Double && b instanceof Double) { + return x < y ? -1 : x > y ? 1 : 0; + } + if (a instanceof Double && Double.isInfinite(x)) { + return x > 0 ? 1 : -1; + } + if (b instanceof Double && Double.isInfinite(y)) { + return y > 0 ? -1 : 1; + } + return exact(a).compareTo(exact(b)); + } + return big(a).compareTo(big(b)); + } + + private static BigDecimal exact(Object v) { + return v instanceof Double ? new BigDecimal((Double) v) : new BigDecimal(big(v)); + } + + /** Python's a < b for numbers: false when either is NaN. */ + static boolean less(Object a, Object b) { + Integer c = compare(a, b); + return c != null && c < 0; + } + + /** Python's a <= b for numbers: false when either is NaN. */ + static boolean lessOrEqual(Object a, Object b) { + Integer c = compare(a, b); + return c != null && c <= 0; + } + + /** Python's a == b for numbers. */ + static boolean same(Object a, Object b) { + Integer c = compare(a, b); + return c != null && c == 0; + } + + /** Whether the whole number lies in the signed or unsigned 64-bit range. */ + static boolean inLongOrU64(BigInteger n) { + return n.compareTo(LONG_MIN) >= 0 && n.compareTo(U64_END) < 0; + } + + /** Whether the whole number fits in a long. */ + static boolean inLong(BigInteger n) { + return n.compareTo(LONG_MIN) >= 0 && n.compareTo(LONG_MAX) <= 0; + } + + /** + * A copy of a parsed document in which every table and array is unmodifiable, so that it can + * be handed to callers. + */ + @SuppressWarnings("unchecked") + static Object freeze(Object v) { + if (v instanceof Map) { + Map copy = new LinkedHashMap<>(); + for (Map.Entry e : ((Map) v).entrySet()) { + copy.put(e.getKey(), freeze(e.getValue())); + } + return Collections.unmodifiableMap(copy); + } + if (v instanceof List) { + List copy = new ArrayList<>(); + for (Object item : (List) v) { + copy.add(freeze(item)); + } + return Collections.unmodifiableList(copy); + } + return v; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Writer.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Writer.java new file mode 100644 index 00000000..e878bc62 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Writer.java @@ -0,0 +1,400 @@ +package io.github.davdxpx.mistel.mncf; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Writes .mncf text: any document as {@link Mncf#load} reads it (a map of TOML values), in one + * fixed layout. + * + *

    The layout follows the spec's examples: the file's own keys, then [game], the builds, the + * choice lists, every cheat with its values and operations as indented sub-tables, the presets + * and the translations. Keys come in the order the spec lists them, and keys it does not define + * after them in their own order. Locations, offsets, addresses and path steps are written in + * hexadecimal, other whole numbers in decimal up to 0xFFFF and in hexadecimal above. Writing a + * file that was read gives the same file again, without its signature lines. + * + *

    A document holds maps, lists, strings, whole numbers (Long, or BigInteger at 2^63 and + * above), doubles and booleans. A float is written as the shortest text that reads back as the + * same double, as Python's repr() writes it. + */ +public final class Writer { + + private static final List TOP = + Values.list("format", "name", "authors", "about", "file_version", "language", "origin", "extensions"); + private static final List TABLES = Values.list("game", "builds", "choices", "cheat", "preset", "i18n"); + private static final List GAME = Values.list("platform", "id", "name"); + private static final List BUILD = Values.list("version", "modules"); + private static final List CHEAT = Values.list("id", "name", "about", "group", "tags", "default", "master", + "run", "duration", "hold", "toggle", "press", "requires", "excludes", "radio", "match", "trigger", + "interval"); + private static final List VALUE = + Values.list("type", "min", "max", "step", "default", "unit", "display", "choices", "flags"); + private static final List PRESET = Values.list("id", "name", "cheats", "values"); + private static final Map> OPS = new HashMap<>(); + private static final Map> INLINE = new HashMap<>(); + private static final List HEX_KEYS = Values.list("offset", "address", "path", "offsets"); + private static final List MULTILINE = Values.list("code", "about"); + private static final Pattern BARE = Pattern.compile("[A-Za-z0-9_-]+"); + private static final String INDENT = " "; + private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE); + + static { + OPS.put("patch", Values.list("at", "expect", "bytes", "encode", "asm")); + OPS.put("write", Values.list("at", "type", "value", "expect")); + OPS.put("override", Values.list("function", "action", "value", "expect")); + OPS.put("read", Values.list("at", "type", "label")); + OPS.put("when", Values.list("at", "type", "op", "value")); + OPS.put("raw", Values.list("syntax", "build", "code")); + List location = Values.list("module", "region", "address", "find", "offset", "offsets", "section", "path"); + INLINE.put("at", location); + INLINE.put("function", location); + INLINE.put("value", Values.list("at", "type")); + INLINE.put("encode", Values.list("insn", "width", "rd", "value")); + INLINE.put("asm", Values.list("expect", "bytes")); + INLINE.put("origin", Values.list("format", "name", "site")); + INLINE.put("extensions", Values.list("required", "optional")); + INLINE.put("modules", Collections.emptyList()); + } + + private Writer() { + } + + /** Returns the text of a loaded file, in this layout, without its signature lines. */ + public static String write(MncfFile f) { + return dumps(f.doc()); + } + + /** + * Returns the text of a document. A key of the layout's own tables (game, builds, choices, + * cheat, preset, i18n) whose value does not have the shape the layout writes is written as + * a plain value, with the file's own keys. + * + * @throws IllegalArgumentException for a value that has no TOML form + */ + public static String dumps(Map doc) { + List out = new ArrayList<>(); + for (String k : ordered(doc, TOP)) { + Object v = doc.get(k); + if (TABLES.contains(k) ? !shaped(k, v) + : !(v instanceof Map && !INLINE.containsKey(k)) && !isTableArray(v)) { + out.add(valueLine(k, v, "")); + } + } + Map shaped = new HashMap<>(); + for (String k : TABLES) { + if (doc.containsKey(k) && shaped(k, doc.get(k))) { + shaped.put(k, doc.get(k)); + } + } + if (shaped.containsKey("game")) { + Map game = map(shaped.get("game")); + out.add(""); + out.add("[game]"); + for (String k : ordered(game, GAME)) { + out.add(valueLine(k, game.get(k), "")); + } + } + if (shaped.containsKey("builds")) { + for (Map.Entry b : map(shaped.get("builds")).entrySet()) { + out.add(""); + out.add("[builds." + key(b.getKey()) + "]"); + Map build = map(b.getValue()); + for (String k : ordered(build, BUILD)) { + out.add(valueLine(k, build.get(k), "")); + } + } + } + if (shaped.containsKey("choices")) { + for (Map.Entry c : map(shaped.get("choices")).entrySet()) { + out.add(""); + out.add("[choices." + key(c.getKey()) + "]"); + for (Map.Entry e : map(c.getValue()).entrySet()) { + out.add(valueLine(e.getKey(), e.getValue(), "")); + } + } + } + if (shaped.containsKey("cheat")) { + for (Object c : (List) shaped.get("cheat")) { + cheat(out, map(c)); + } + } + if (shaped.containsKey("preset")) { + for (Object p : (List) shaped.get("preset")) { + Map preset = map(p); + out.add(""); + out.add("[[preset]]"); + for (String k : ordered(preset, PRESET)) { + out.add(valueLine(k, preset.get(k), "")); + } + } + } + if (shaped.containsKey("i18n")) { + section(out, "i18n", map(shaped.get("i18n")), false); + } + for (Map.Entry e : doc.entrySet()) { + String k = e.getKey(); + Object v = e.getValue(); + if (TOP.contains(k) || TABLES.contains(k)) { + continue; + } + if (v instanceof Map && !INLINE.containsKey(k)) { + section(out, key(k), map(v), false); + } else if (isTableArray(v)) { + for (Object item : (List) v) { + section(out, key(k), map(item), true); + } + } + } + while (!out.isEmpty() && out.get(0).isEmpty()) { + out.remove(0); + } + return String.join("\n", out) + "\n"; + } + + private static void cheat(List out, Map c) { + out.add(""); + out.add("[[cheat]]"); + List subs = new ArrayList<>(); + for (String k : ordered(c, CHEAT)) { + Object v = c.get(k); + if ((k.equals("values") && isTableOfTables(v)) || isTableArray(v)) { + subs.add(k); + } else { + out.add(valueLine(k, v, "")); + } + } + for (String k : subs) { + Object v = c.get(k); + if (k.equals("values") && !isTableArray(v)) { + for (Map.Entry e : map(v).entrySet()) { + out.add(""); + out.add(INDENT + "[cheat.values." + key(e.getKey()) + "]"); + Map spec = map(e.getValue()); + for (String x : ordered(spec, VALUE)) { + out.add(valueLine(x, spec.get(x), INDENT)); + } + } + continue; + } + List order = OPS.containsKey(k) ? OPS.get(k) : Collections.emptyList(); + for (Object item : (List) v) { + Map t = map(item); + out.add(""); + out.add(INDENT + "[[cheat." + key(k) + "]]"); + for (String x : ordered(t, order)) { + out.add(valueLine(x, t.get(x), INDENT)); + } + } + } + } + + /** + * A table the layout does not know, under its header: its values, then its tables and arrays + * of tables as sections of their own. The header is left out for a table that has only + * tables and arrays of tables, unless it is an element of an array. + */ + private static void section(List out, String path, Map table, boolean array) { + List values = new ArrayList<>(); + List subs = new ArrayList<>(); + for (Map.Entry e : table.entrySet()) { + if (!(e.getValue() instanceof Map) && !isTableArray(e.getValue())) { + values.add(e.getKey()); + } else { + subs.add(e.getKey()); + } + } + if (!values.isEmpty() || subs.isEmpty() || array) { + out.add(""); + out.add(array ? "[[" + path + "]]" : "[" + path + "]"); + for (String k : values) { + out.add(valueLine(k, table.get(k), "")); + } + } + for (String k : subs) { + Object v = table.get(k); + if (v instanceof Map) { + section(out, path + "." + key(k), map(v), false); + } else { + for (Object item : (List) v) { + section(out, path + "." + key(k), map(item), true); + } + } + } + } + + /** Whether the value is a table that holds tables only, and at least one. */ + private static boolean isTableOfTables(Object v) { + if (!(v instanceof Map) || ((Map) v).isEmpty()) { + return false; + } + for (Object x : ((Map) v).values()) { + if (!(x instanceof Map)) { + return false; + } + } + return true; + } + + private static String valueLine(String k, Object v, String indent) { + if (MULTILINE.contains(k) && v instanceof String && ((String) v).indexOf('\n') >= 0) { + return indent + key(k) + " = " + multiline((String) v); + } + return indent + key(k) + " = " + scalar(v, k, false); + } + + private static List ordered(Map table, List order) { + List keys = new ArrayList<>(); + for (String k : order) { + if (table.containsKey(k)) { + keys.add(k); + } + } + for (String k : table.keySet()) { + if (!order.contains(k)) { + keys.add(k); + } + } + return keys; + } + + private static boolean isTableArray(Object v) { + if (!(v instanceof List) || ((List) v).isEmpty()) { + return false; + } + for (Object x : (List) v) { + if (!(x instanceof Map)) { + return false; + } + } + return true; + } + + /** + * Whether a top-level table of the layout has the shape the layout writes: cheat and preset + * an array of tables, builds and choices a table of tables, game and i18n a table. + */ + private static boolean shaped(String k, Object v) { + if (k.equals("cheat") || k.equals("preset")) { + return isTableArray(v); + } + if (k.equals("builds") || k.equals("choices")) { + if (!(v instanceof Map)) { + return false; + } + for (Object x : ((Map) v).values()) { + if (!(x instanceof Map)) { + return false; + } + } + return true; + } + return v instanceof Map; + } + + @SuppressWarnings("unchecked") + private static Map map(Object v) { + return (Map) v; + } + + // Values + + /** A key: bare where it can be, else a string. */ + static String key(String k) { + return Py.matches(BARE, k) ? k : string(k); + } + + /** A basic string. */ + static String string(String s) { + StringBuilder out = new StringBuilder("\""); + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (ch == '"' || ch == '\\') { + out.append('\\').append(ch); + } else if (ch == '\n') { + out.append("\\n"); + } else if (ch == '\t') { + out.append("\\t"); + } else if (ch < 0x20 || ch == 0x7F) { + out.append(String.format("\\u%04X", (int) ch)); + } else { + out.append(ch); + } + } + return out.append('"').toString(); + } + + /** A multi-line basic string, or a basic string where it holds other control characters. */ + static String multiline(String s) { + String body = s.replace("\\", "\\\\").replace("\"\"\"", "\"\"\\\""); + for (int i = 0; i < body.length(); i++) { + char ch = body.charAt(i); + if (ch < 0x20 && ch != '\n' && ch != '\t') { + return string(s); + } + } + return s.endsWith("\n") ? "\"\"\"\n" + body + "\"\"\"" : "\"\"\"\n" + body + "\\\n\"\"\""; + } + + private static String integer(Object n, boolean hex) { + BigInteger v = Values.big(n); + if (v.compareTo(LONG_MAX) > 0) { + return "\"0x" + v.toString(16).toUpperCase(java.util.Locale.ROOT) + "\""; + } + if (v.signum() < 0 || (!hex && v.compareTo(BigInteger.valueOf(0xFFFF)) <= 0)) { + return v.toString(); + } + return "0x" + v.toString(16).toUpperCase(java.util.Locale.ROOT); + } + + private static String number(double v) { + if (Double.isNaN(v)) { + return "nan"; + } + if (Double.isInfinite(v)) { + return v > 0 ? "inf" : "-inf"; + } + String text = Py.floatRepr(v); + return text.indexOf('.') >= 0 || text.indexOf('e') >= 0 || text.indexOf('n') >= 0 ? text : text + ".0"; + } + + /** A value, inline tables and arrays included. */ + static String scalar(Object v, String k, boolean hex) { + if (v instanceof Boolean) { + return ((Boolean) v) ? "true" : "false"; + } + if (v instanceof Long || v instanceof BigInteger || v instanceof Integer || v instanceof Short + || v instanceof Byte) { + return integer(v instanceof BigInteger ? v : (Object) ((Number) v).longValue(), hex || HEX_KEYS.contains(k)); + } + if (v instanceof Double || v instanceof Float) { + return number(((Number) v).doubleValue()); + } + if (v instanceof String) { + return string((String) v); + } + if (v instanceof List) { + List parts = new ArrayList<>(); + for (Object x : (List) v) { + parts.add(scalar(x, k, hex || HEX_KEYS.contains(k))); + } + return "[" + String.join(", ", parts) + "]"; + } + if (v instanceof Map) { + Map m = map(v); + List order = INLINE.containsKey(k) ? INLINE.get(k) : Collections.emptyList(); + boolean innerHex = HEX_KEYS.contains(k); + List parts = new ArrayList<>(); + for (String x : ordered(m, order)) { + parts.add(key(x) + " = " + scalar(m.get(x), x, innerHex)); + } + return parts.isEmpty() ? "{}" : "{ " + String.join(", ", parts) + " }"; + } + throw new IllegalArgumentException("no TOML form for " + (v == null ? "null" : v.getClass().getSimpleName())); + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Zip.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Zip.java new file mode 100644 index 00000000..44e3fdd1 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/Zip.java @@ -0,0 +1,391 @@ +package io.github.davdxpx.mistel.mncf; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.CRC32; +import java.util.zip.DataFormatException; +import java.util.zip.Inflater; + +/** + * A ZIP archive in memory, read through its central directory as the reference reader's ZIP + * module reads it: the end record is searched for in the last 64 KiB, data before the archive + * is allowed, and names are UTF-8 when the entry says so and code page 437 otherwise. An entry's + * name is its raw name; the reader does not shorten it or take another from an extra field. + * Stored and deflated entries that are not encrypted can be read; their CRC-32 is checked. + */ +final class Zip { + + /** The archive cannot be read. */ + static final class ZipError extends Exception { + private static final long serialVersionUID = 1L; + + ZipError(String message) { + super(message); + } + } + + /** One entry of the central directory. */ + static final class Entry { + String name; + String originalName; + int flags; + int method; + long crc; + long compressedSize; + long size; + long headerOffset; + /** Where the next entry's local header starts, or the central directory. */ + long endOffset; + } + + private static final int END_SIZE = 22; + private static final int END64_SIZE = 56; + private static final int LOCATOR_SIZE = 20; + private static final int CENTRAL_SIZE = 46; + private static final int LOCAL_SIZE = 30; + private static final int MAX_COMMENT = 0xFFFF; + private static final int MAX_EXTRACT_VERSION = 63; + + /** The characters of code page 437 from 0x80 to 0xFF; the bytes below are ASCII. */ + private static final String CP437_HIGH = + "\u00C7\u00FC\u00E9\u00E2\u00E4\u00E0\u00E5\u00E7\u00EA\u00EB\u00E8\u00EF\u00EE\u00EC\u00C4\u00C5" + + "\u00C9\u00E6\u00C6\u00F4\u00F6\u00F2\u00FB\u00F9\u00FF\u00D6\u00DC\u00A2\u00A3\u00A5\u20A7\u0192" + + "\u00E1\u00ED\u00F3\u00FA\u00F1\u00D1\u00AA\u00BA\u00BF\u2310\u00AC\u00BD\u00BC\u00A1\u00AB\u00BB" + + "\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510" + + "\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567" + + "\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580" + + "\u03B1\u00DF\u0393\u03C0\u03A3\u03C3\u00B5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229" + + "\u2261\u00B1\u2265\u2264\u2320\u2321\u00F7\u2248\u00B0\u2219\u00B7\u221A\u207F\u00B2\u25A0\u00A0"; + + private final byte[] data; + private final List entries; + private final Map byName; + + private Zip(byte[] data, List entries) { + this.data = data; + this.entries = Collections.unmodifiableList(entries); + Map names = new LinkedHashMap<>(); + for (Entry e : entries) { + names.put(e.name, e); + } + this.byName = names; + } + + List entries() { + return entries; + } + + Entry entry(String name) { + return byName.get(name); + } + + // Little-endian fields + + private static int u16(byte[] b, long at) { + int i = (int) at; + return (b[i] & 0xFF) | (b[i + 1] & 0xFF) << 8; + } + + private static long u32(byte[] b, long at) { + return u16(b, at) | (long) u16(b, at + 2) << 16; + } + + private static long u64(byte[] b, long at) { + return u32(b, at) | u32(b, at + 4) << 32; + } + + private static boolean signature(byte[] b, long at, int third, int fourth) { + int i = (int) at; + return b[i] == 'P' && b[i + 1] == 'K' && b[i + 2] == third && b[i + 3] == fourth; + } + + /** The bytes from a position, at most length of them, fewer where the data ends. */ + private static byte[] slice(byte[] b, long from, long length) { + if (from < 0 || from >= b.length || length <= 0) { + return new byte[0]; + } + long end = Math.min(b.length, from + length); + return Arrays.copyOfRange(b, (int) from, (int) end); + } + + /** Reads the central directory of an archive. */ + static Zip open(byte[] data) throws ZipError { + long[] end = endRecord(data); + if (end == null) { + throw new ZipError("File is not a zip file"); + } + long sizeCd = end[0]; + long offsetCd = end[1]; + long location = end[2]; + boolean zip64 = end[3] != 0; + long concat = location - sizeCd - offsetCd; + if (zip64) { + concat -= END64_SIZE + LOCATOR_SIZE; + } + long startDir = offsetCd + concat; + if (startDir < 0 || sizeCd < 0) { + throw new ZipError("Bad offset for central directory"); + } + byte[] cd = slice(data, startDir, sizeCd); + List entries = new ArrayList<>(); + long total = 0; + int pos = 0; + while (total < sizeCd) { + if (cd.length - pos < CENTRAL_SIZE) { + throw new ZipError("Truncated central directory"); + } + if (!signature(cd, pos, 1, 2)) { + throw new ZipError("Bad magic number for central directory"); + } + int extractVersion = cd[pos + 6] & 0xFF; + int flags = u16(cd, pos + 8); + int method = u16(cd, pos + 10); + long crc = u32(cd, pos + 16); + long compressedSize = u32(cd, pos + 20); + long size = u32(cd, pos + 24); + int nameLength = u16(cd, pos + 28); + int extraLength = u16(cd, pos + 30); + int commentLength = u16(cd, pos + 32); + long headerOffset = u32(cd, pos + 42); + int at = pos + CENTRAL_SIZE; + byte[] rawName = slice(cd, at, nameLength); + at += rawName.length; + byte[] extra = slice(cd, at, extraLength); + at += extra.length; + at += slice(cd, at, commentLength).length; + pos = at; + Entry e = new Entry(); + e.originalName = name(rawName, flags); + e.name = e.originalName; + e.flags = flags; + e.method = method; + e.crc = crc; + e.compressedSize = compressedSize; + e.size = size; + e.headerOffset = headerOffset; + if (extractVersion > MAX_EXTRACT_VERSION) { + throw new ZipError("zip file version " + extractVersion / 10.0 + " is not supported"); + } + decodeExtra(e, extra, crc32(rawName)); + e.headerOffset += concat; + entries.add(e); + total += CENTRAL_SIZE + nameLength + extraLength + commentLength; + } + List sorted = new ArrayList<>(entries); + Collections.sort(sorted, new Comparator() { + @Override + public int compare(Entry a, Entry b) { + return Long.compare(a.headerOffset, b.headerOffset); + } + }); + long endOffset = startDir; + for (int i = sorted.size() - 1; i >= 0; i--) { + sorted.get(i).endOffset = endOffset; + endOffset = sorted.get(i).headerOffset; + } + return new Zip(data, entries); + } + + /** The size and offset of the central directory, the end record's position and whether it is ZIP64. */ + private static long[] endRecord(byte[] data) throws ZipError { + int size = data.length; + if (size >= END_SIZE) { + int at = size - END_SIZE; + if (signature(data, at, 5, 6) && data[size - 2] == 0 && data[size - 1] == 0) { + return end64(data, at, new long[] {u32(data, at + 12), u32(data, at + 16), at, 0}); + } + } + int from = Math.max(size - MAX_COMMENT - END_SIZE, 0); + int start = -1; + for (int i = size - 4; i >= from; i--) { + if (signature(data, i, 5, 6)) { + start = i; + break; + } + } + if (start < 0 || size - start < END_SIZE) { + return null; + } + return end64(data, start, new long[] {u32(data, start + 12), u32(data, start + 16), start, 0}); + } + + private static long[] end64(byte[] data, int endAt, long[] record) throws ZipError { + byte[] locator = slice(data, Math.max(0, endAt - LOCATOR_SIZE), LOCATOR_SIZE); + if (locator.length != LOCATOR_SIZE || !signature(locator, 0, 6, 7)) { + return record; + } + long disk = u32(locator, 4); + long disks = u32(locator, 16); + if (disk != 0 || disks > 1) { + throw new ZipError("zipfiles that span multiple disks are not supported"); + } + byte[] end = slice(data, Math.max(0, endAt - LOCATOR_SIZE - END64_SIZE), END64_SIZE); + if (end.length != END64_SIZE || !signature(end, 0, 6, 6)) { + return record; + } + return new long[] {u64(end, 40), u64(end, 48), record[2], 1}; + } + + private static void decodeExtra(Entry e, byte[] extra, long nameCrc) throws ZipError { + int at = 0; + while (extra.length - at >= 4) { + int type = u16(extra, at); + int length = u16(extra, at + 2); + if (length + 4 > extra.length - at) { + throw new ZipError(String.format("Corrupt extra field %04x (size=%d)", type, length)); + } + byte[] field = Arrays.copyOfRange(extra, at + 4, at + 4 + length); + if (type == 0x0001) { + int f = 0; + if (e.size == 0xFFFFFFFFL) { + f = need(field, f, "File size"); + e.size = u64(field, f - 8); + } + if (e.compressedSize == 0xFFFFFFFFL) { + f = need(field, f, "Compress size"); + e.compressedSize = u64(field, f - 8); + } + if (e.headerOffset == 0xFFFFFFFFL) { + f = need(field, f, "Header offset"); + e.headerOffset = u64(field, f - 8); + } + } else if (type == 0x7075) { + if (field.length < 5) { + throw new ZipError("Corrupt unicode path extra field (0x7075)"); + } + if (field[0] == 1 && u32(field, 1) == nameCrc) { + byte[] name = Arrays.copyOfRange(field, 5, field.length); + if (Utf8.check(name) != null) { + throw new ZipError("Corrupt unicode path extra field (0x7075): invalid utf-8 bytes"); + } + } + } + at += 4 + length; + } + } + + private static int need(byte[] field, int f, String what) throws ZipError { + if (field.length - f < 8) { + throw new ZipError("Corrupt zip64 extra field. " + what + " not found."); + } + return f + 8; + } + + private static long crc32(byte[] bytes) { + CRC32 crc = new CRC32(); + crc.update(bytes); + return crc.getValue(); + } + + private static String name(byte[] raw, int flags) throws ZipError { + if ((flags & 0x800) != 0) { + if (Utf8.check(raw) != null) { + throw new ZipError("an entry name is not UTF-8"); + } + return new String(raw, StandardCharsets.UTF_8); + } + StringBuilder b = new StringBuilder(raw.length); + for (byte x : raw) { + int c = x & 0xFF; + b.append(c < 0x80 ? (char) c : CP437_HIGH.charAt(c - 0x80)); + } + return b.toString(); + } + + /** Whether an entry is stored or deflated and not encrypted: the only entries this reader reads. */ + static boolean readable(Entry e) { + return (e.method == 0 || e.method == 8) && (e.flags & 0x1) == 0; + } + + /** Reads an entry's bytes, checking its local header, its place in the archive and its CRC-32. */ + byte[] read(Entry e) throws ZipError { + return read(e, Long.MAX_VALUE); + } + + /** + * Reads at most limit bytes of an entry, whatever its header claims. The CRC-32 is checked + * when the read reaches the entry's end. + */ + byte[] read(Entry e, long limit) throws ZipError { + if (!readable(e)) { + throw new ZipError(e.name + ": neither stored nor deflated, or encrypted"); + } + long h = e.headerOffset; + if (h < 0 || h > data.length - LOCAL_SIZE) { + throw new ZipError("Truncated file header"); + } + if (!signature(data, h, 3, 4)) { + throw new ZipError("Bad magic number for file header"); + } + int localFlags = u16(data, h + 6); + int nameLength = u16(data, h + 26); + int extraLength = u16(data, h + 28); + byte[] rawName = slice(data, h + LOCAL_SIZE, nameLength); + if ((e.flags & 0x20) != 0) { + throw new ZipError("compressed patched data (flag bit 5)"); + } + if ((e.flags & 0x40) != 0) { + throw new ZipError("strong encryption (flag bit 6)"); + } + if (!name(rawName, localFlags).equals(e.originalName)) { + throw new ZipError("File name in directory and header differ"); + } + long start = h + LOCAL_SIZE + rawName.length + extraLength; + // Sizes of 2^63 and more come only from a ZIP64 field; they are as good as endless. + boolean beyond = e.compressedSize < 0 || start + e.compressedSize > e.endOffset; + if (beyond && e.endOffset != e.headerOffset) { + throw new ZipError("Overlapped entries (possible zip bomb)"); + } + if ((e.flags & 0x1) != 0) { + throw new ZipError("the entry is encrypted"); + } + if (e.compressedSize < 0 || start + e.compressedSize > data.length) { + throw new ZipError("the entry's data is cut off"); + } + long size = e.size < 0 ? Long.MAX_VALUE : e.size; + long cap = Math.min(size, limit); + byte[] out; + if (e.method == 0) { + out = Arrays.copyOfRange(data, (int) start, (int) (start + Math.min(e.compressedSize, cap))); + } else if (e.method == 8) { + out = inflate(Arrays.copyOfRange(data, (int) start, (int) (start + e.compressedSize)), cap); + } else { + throw new ZipError("compression type " + e.method + " is not supported"); + } + if (cap == size && crc32(out) != e.crc) { + throw new ZipError("Bad CRC-32 for file " + Py.repr(e.name)); + } + return out; + } + + private static byte[] inflate(byte[] compressed, long size) throws ZipError { + Inflater inflater = new Inflater(true); + try { + // The extra byte is the dummy input that zlib may want after raw deflate data. + inflater.setInput(Arrays.copyOf(compressed, compressed.length + 1)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[64 * 1024]; + long left = size; + while (left > 0 && !inflater.finished()) { + int n = inflater.inflate(buffer, 0, (int) Math.min(buffer.length, left)); + if (n == 0 && (inflater.needsInput() || inflater.needsDictionary())) { + break; + } + out.write(buffer, 0, n); + left -= n; + } + return out.toByteArray(); + } catch (DataFormatException ex) { + throw new ZipError("the entry's deflate data is broken: " + ex.getMessage()); + } finally { + inflater.end(); + } + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/toml/Toml.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/toml/Toml.java new file mode 100644 index 00000000..13acfa4c --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/toml/Toml.java @@ -0,0 +1,840 @@ +package io.github.davdxpx.mistel.mncf.toml; + +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * A parser for TOML 1.0.0 documents. + * + *

    A table becomes a {@link LinkedHashMap} whose keys keep the order in which they first appear + * in the document, an array becomes an {@link ArrayList}, and the other values become + * {@link String}, {@link Long}, {@link Double}, {@link Boolean} or {@link TomlDateTime}. A new + * line inside a multi-line string is returned as a line feed, also where the document has a + * carriage return and a line feed. + */ +public final class Toml { + + /** How deep arrays and inline tables may nest, so that no document can exhaust the stack. */ + private static final int MAX_NESTING = 128; + + private static final int BYTE_ORDER_MARK = 0xFEFF; + + private static final String DECIMAL = "[+-]?(?:0|[1-9](?:_?[0-9])*)"; + private static final String DIGITS = "[0-9](?:_?[0-9])*"; + private static final Pattern DECIMAL_INTEGER = Pattern.compile(DECIMAL); + private static final Pattern HEX_INTEGER = Pattern.compile("0x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*"); + private static final Pattern OCTAL_INTEGER = Pattern.compile("0o[0-7](?:_?[0-7])*"); + private static final Pattern BINARY_INTEGER = Pattern.compile("0b[01](?:_?[01])*"); + private static final Pattern FLOAT = + Pattern.compile(DECIMAL + "(?:\\." + DIGITS + ")?(?:[eE][+-]?" + DIGITS + ")?"); + private static final Pattern SPECIAL_FLOAT = Pattern.compile("[+-]?(?:inf|nan)"); + + /** How a table or an array came to be, which decides what later lines may add to it. */ + private enum Origin { + /** A table that so far is only named on the way to a table header. */ + IMPLICIT, + /** A table defined by a table header, or an element of an array of tables. */ + HEADER, + /** A table created by a dotted key. */ + DOTTED, + /** An inline table, complete as written. */ + INLINE, + /** An array of tables, which later headers may append to. */ + TABLE_ARRAY + } + + private final String src; + private final Map origins = new IdentityHashMap<>(); + private int pos; + private int nesting; + + private Toml(String src) { + this.src = src; + } + + /** + * Parses a whole TOML 1.0.0 document. + * + * @param text the document, already decoded from UTF-8; a byte order mark at the start is skipped + * @return the root table + * @throws TomlException if the document is not valid TOML 1.0.0 + */ + public static Map parse(String text) throws TomlException { + return new Toml(text).document(); + } + + private Map document() throws TomlException { + if (at(0) == BYTE_ORDER_MARK) { + pos = 1; + } + Map root = new LinkedHashMap<>(); + Map table = root; + while (pos < src.length()) { + skipSpaces(); + int c = peek(); + if (c == '[') { + table = tableHeader(root); + } else if (c != '#' && c != '\n' && c != '\r' && c != -1) { + keyValue(table); + } + endOfLine(); + } + return root; + } + + // Tables and keys + + private Map tableHeader(Map root) throws TomlException { + int start = pos; + boolean isArray = src.startsWith("[[", pos); + pos += isArray ? 2 : 1; + skipSpaces(); + List key = key(); + expect(isArray ? "]]" : "]"); + Map parent = root; + for (int i = 0; i < key.size() - 1; i++) { + parent = headerStep(parent, key, i, start); + } + String last = key.get(key.size() - 1); + Object existing = parent.get(last); + if (isArray) { + List tables; + if (existing == null) { + tables = new ArrayList<>(); + origins.put(tables, Origin.TABLE_ARRAY); + parent.put(last, tables); + } else if (origins.get(existing) == Origin.TABLE_ARRAY) { + tables = asList(existing); + } else { + throw error(start, "cannot append a table to " + name(key, key.size()) + + ", it is " + describe(existing)); + } + Map table = newTable(Origin.HEADER); + tables.add(table); + return table; + } + if (existing == null) { + Map table = newTable(Origin.HEADER); + parent.put(last, table); + return table; + } + if (origins.get(existing) == Origin.IMPLICIT) { + origins.put(existing, Origin.HEADER); + return asTable(existing); + } + throw error(start, "cannot define table " + name(key, key.size()) + + ", it is already " + describe(existing)); + } + + /** Steps from a table to the child that a table header names with key part i. */ + private Map headerStep(Map parent, List key, int i, + int start) throws TomlException { + Object child = parent.get(key.get(i)); + if (child == null) { + Map table = newTable(Origin.IMPLICIT); + parent.put(key.get(i), table); + return table; + } + Origin origin = origins.get(child); + if (origin == Origin.TABLE_ARRAY) { + List tables = asList(child); + return asTable(tables.get(tables.size() - 1)); + } + if (origin != Origin.IMPLICIT && origin != Origin.HEADER && origin != Origin.DOTTED) { + throw error(start, "cannot add a table to " + name(key, i + 1) + ", it is " + describe(child)); + } + return asTable(child); + } + + private void keyValue(Map table) throws TomlException { + int start = pos; + List key = key(); + expect("="); + skipSpaces(); + Map target = table; + for (int i = 0; i < key.size() - 1; i++) { + target = dottedStep(target, key, i, start); + } + String last = key.get(key.size() - 1); + if (target.containsKey(last)) { + throw error(start, "duplicate key " + name(key, key.size())); + } + target.put(last, value()); + } + + /** Steps from a table to the child that a dotted key names with key part i. */ + private Map dottedStep(Map parent, List key, int i, + int start) throws TomlException { + Object child = parent.get(key.get(i)); + if (child == null) { + Map table = newTable(Origin.DOTTED); + parent.put(key.get(i), table); + return table; + } + Origin origin = origins.get(child); + if (origin == Origin.IMPLICIT) { + origins.put(child, Origin.DOTTED); + } else if (origin != Origin.DOTTED) { + throw error(start, "cannot add keys to " + name(key, i + 1) + ", it is " + describe(child)); + } + return asTable(child); + } + + /** Reads a bare, quoted or dotted key and the spaces after it. */ + private List key() throws TomlException { + List parts = new ArrayList<>(); + while (true) { + parts.add(simpleKey()); + skipSpaces(); + if (peek() != '.') { + return parts; + } + pos++; + skipSpaces(); + } + } + + private String simpleKey() throws TomlException { + int c = peek(); + if (c == '"' || c == '\'') { + if (src.startsWith(c == '"' ? "\"\"\"" : "'''", pos)) { + throw error(pos, "a key cannot be a multi-line string"); + } + return c == '"' ? basicString() : literalString(); + } + int start = pos; + while (isBareKeyChar(peek())) { + pos++; + } + if (pos == start) { + throw error(pos, "expected a key, found " + found()); + } + return src.substring(start, pos); + } + + // Values + + private Object value() throws TomlException { + if (src.startsWith("true", pos)) { + pos += 4; + return Boolean.TRUE; + } + if (src.startsWith("false", pos)) { + pos += 5; + return Boolean.FALSE; + } + switch (peek()) { + case '"': + return src.startsWith("\"\"\"", pos) ? multiLineBasicString() : basicString(); + case '\'': + return src.startsWith("'''", pos) ? multiLineLiteralString() : literalString(); + case '[': + return array(); + case '{': + return inlineTable(); + default: + return startsDateTime() ? dateTime() : number(); + } + } + + private List array() throws TomlException { + enter(); + pos++; + List values = new ArrayList<>(); + skipBlank(); + while (peek() != ']') { + values.add(value()); + skipBlank(); + if (peek() == ',') { + pos++; + skipBlank(); + } else if (peek() == -1) { + throw error(pos, "unterminated array"); + } else if (peek() != ']') { + throw error(pos, "expected ',' or ']', found " + found()); + } + } + pos++; + nesting--; + return values; + } + + private Map inlineTable() throws TomlException { + enter(); + pos++; + Map table = newTable(Origin.INLINE); + skipSpaces(); + if (peek() != '}') { + while (true) { + keyValue(table); + skipSpaces(); + if (peek() != ',') { + break; + } + pos++; + skipSpaces(); + } + if (peek() != '}') { + throw error(pos, "expected ',' or '}', found " + found()); + } + } + pos++; + nesting--; + return table; + } + + private Object number() throws TomlException { + int start = pos; + while (isNumberChar(peek())) { + pos++; + } + String token = src.substring(start, pos); + if (token.isEmpty()) { + throw error(start, "expected a value, found " + found()); + } + String plain = token.replace("_", ""); + try { + if (DECIMAL_INTEGER.matcher(token).matches()) { + return Long.parseLong(plain); + } + if (HEX_INTEGER.matcher(token).matches()) { + return Long.parseLong(plain.substring(2), 16); + } + if (OCTAL_INTEGER.matcher(token).matches()) { + return Long.parseLong(plain.substring(2), 8); + } + if (BINARY_INTEGER.matcher(token).matches()) { + return Long.parseLong(plain.substring(2), 2); + } + } catch (NumberFormatException e) { + throw error(start, "integer " + token + " does not fit in 64 bits"); + } + if (FLOAT.matcher(token).matches()) { + return Double.parseDouble(plain); + } + if (SPECIAL_FLOAT.matcher(token).matches()) { + if (plain.endsWith("nan")) { + // TOML leaves the sign of a NaN to the parser; -nan keeps its sign bit, as in Python. + return plain.startsWith("-") ? Double.longBitsToDouble(0xFFF8000000000000L) : Double.NaN; + } + return plain.startsWith("-") ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; + } + throw error(start, "invalid value " + token); + } + + private boolean startsDateTime() { + return digitsAt(pos, 4) && at(pos + 4) == '-' || digitsAt(pos, 2) && at(pos + 2) == ':'; + } + + private TomlDateTime dateTime() throws TomlException { + int start = pos; + boolean hasDate = at(pos + 2) != ':'; + boolean hasTime = !hasDate; + boolean hasOffset = false; + int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, nanosecond = 0, offset = 0; + if (hasDate) { + year = digits(4); + expect("-"); + month = digits(2); + expect("-"); + day = digits(2); + if (month < 1 || month > 12) { + throw error(start, "invalid month " + month); + } + if (day < 1 || day > daysInMonth(year, month)) { + throw error(start, "invalid day " + day + " in month " + month + " of " + year); + } + int c = peek(); + hasTime = c == 'T' || c == 't' || c == ' ' && isDigit(at(pos + 1)); + if (hasTime) { + pos++; + } + } + if (hasTime) { + hour = digits(2); + expect(":"); + minute = digits(2); + expect(":"); + second = digits(2); + if (peek() == '.') { + pos++; + int from = pos; + while (isDigit(peek())) { + pos++; + } + if (pos == from) { + throw error(pos, "expected a digit, found " + found()); + } + for (int i = 0; i < 9; i++) { + nanosecond = nanosecond * 10 + (from + i < pos ? src.charAt(from + i) - '0' : 0); + } + } + if (hour > 23) { + throw error(start, "invalid hour " + hour); + } + if (minute > 59) { + throw error(start, "invalid minute " + minute); + } + if (second > 60) { + throw error(start, "invalid second " + second); + } + int sign = peek(); + if (hasDate && (sign == 'Z' || sign == 'z')) { + pos++; + hasOffset = true; + } else if (hasDate && (sign == '+' || sign == '-')) { + int offsetStart = pos++; + int offsetHour = digits(2); + expect(":"); + int offsetMinute = digits(2); + if (offsetHour > 23 || offsetMinute > 59) { + throw error(offsetStart, "invalid offset " + src.substring(offsetStart, pos)); + } + offset = (sign == '-' ? -1 : 1) * (offsetHour * 60 + offsetMinute); + hasOffset = true; + } + } + TomlDateTime.Kind kind = !hasDate ? TomlDateTime.Kind.LOCAL_TIME + : !hasTime ? TomlDateTime.Kind.LOCAL_DATE + : hasOffset ? TomlDateTime.Kind.OFFSET_DATE_TIME + : TomlDateTime.Kind.LOCAL_DATE_TIME; + return new TomlDateTime(kind, src.substring(start, pos), year, month, day, hour, minute, + second, nanosecond, offset); + } + + // Strings + + private String basicString() throws TomlException { + int start = pos++; + StringBuilder out = new StringBuilder(); + while (true) { + int c = peek(); + if (c == '"') { + pos++; + return out.toString(); + } + if (c == -1 || c == '\n' || c == '\r') { + throw error(start, "unterminated string"); + } + if (c == '\\') { + escape(out); + } else { + appendTextChar(out); + } + } + } + + private String literalString() throws TomlException { + int start = pos++; + while (true) { + int c = peek(); + if (c == '\'') { + pos++; + return src.substring(start + 1, pos - 1); + } + if (c == -1 || c == '\n' || c == '\r') { + throw error(start, "unterminated string"); + } + pos += textChar(); + } + } + + private String multiLineBasicString() throws TomlException { + int start = pos; + pos += 3; + newline(); + StringBuilder out = new StringBuilder(); + while (true) { + int c = peek(); + if (c == -1) { + throw error(start, "unterminated multi-line string"); + } + if (c == '"') { + if (closingQuotes('"', out)) { + return out.toString(); + } + } else if (c == '\\') { + if (!lineEndingBackslash()) { + escape(out); + } + } else if (!appendNewline(out)) { + appendTextChar(out); + } + } + } + + private String multiLineLiteralString() throws TomlException { + int start = pos; + pos += 3; + newline(); + StringBuilder out = new StringBuilder(); + while (true) { + int c = peek(); + if (c == -1) { + throw error(start, "unterminated multi-line string"); + } + if (c == '\'') { + if (closingQuotes('\'', out)) { + return out.toString(); + } + } else if (!appendNewline(out)) { + appendTextChar(out); + } + } + } + + /** + * Reads a run of quotes inside a multi-line string. Three quotes close the string, and up to + * two more before them still belong to it. Returns whether the string is closed. + */ + private boolean closingQuotes(char quote, StringBuilder out) { + int run = 0; + while (run < 5 && at(pos + run) == quote) { + run++; + } + boolean closes = run >= 3; + for (int i = closes ? 3 : 0; i < run; i++) { + out.append(quote); + } + pos += run; + return closes; + } + + /** Skips a backslash at the end of a line together with all spaces and new lines after it. */ + private boolean lineEndingBackslash() throws TomlException { + int p = pos + 1; + while (at(p) == ' ' || at(p) == '\t') { + p++; + } + if (at(p) != '\n' && at(p) != '\r') { + return false; + } + pos = p; + while (true) { + if (peek() == ' ' || peek() == '\t') { + pos++; + } else if (!newline()) { + return true; + } + } + } + + private void escape(StringBuilder out) throws TomlException { + int start = pos; + int c = at(pos + 1); + pos += 2; + switch (c) { + case 'b': + out.append('\b'); + return; + case 't': + out.append('\t'); + return; + case 'n': + out.append('\n'); + return; + case 'f': + out.append('\f'); + return; + case 'r': + out.append('\r'); + return; + case '"': + out.append('"'); + return; + case '\\': + out.append('\\'); + return; + case 'u': + unicodeEscape(out, start, 4); + return; + case 'U': + unicodeEscape(out, start, 8); + return; + default: + throw error(start, c > ' ' && c < 0x7F + ? "invalid escape sequence \\" + (char) c + : "invalid escape sequence"); + } + } + + private void unicodeEscape(StringBuilder out, int start, int digits) throws TomlException { + long code = 0; + for (int i = 0; i < digits; i++) { + int digit = hexValue(peek()); + if (digit < 0) { + throw error(start, "a \\" + src.charAt(start + 1) + " escape needs " + digits + " hex digits"); + } + code = code * 16 + digit; + pos++; + } + if (code > 0x10FFFF || code >= 0xD800 && code <= 0xDFFF) { + throw error(start, "escape " + src.substring(start, pos) + " is not a Unicode scalar value"); + } + out.appendCodePoint((int) code); + } + + /** Appends a new line as a line feed, if there is one at pos. */ + private boolean appendNewline(StringBuilder out) throws TomlException { + if (!newline()) { + return false; + } + out.append('\n'); + return true; + } + + private void appendTextChar(StringBuilder out) throws TomlException { + int length = textChar(); + out.append(src, pos, pos + length); + pos += length; + } + + /** + * Checks that the character at pos may stand in a string or a comment, and returns its length: + * 2 for a surrogate pair, else 1. + */ + private int textChar() throws TomlException { + char c = src.charAt(pos); + if (c < ' ' && c != '\t' || c == 0x7F) { + throw error(pos, "control character " + codePoint(c) + " is not allowed"); + } + if (!Character.isSurrogate(c)) { + return 1; + } + if (Character.isHighSurrogate(c) && pos + 1 < src.length() + && Character.isLowSurrogate(src.charAt(pos + 1))) { + return 2; + } + throw error(pos, "unpaired surrogate " + codePoint(c)); + } + + // Spaces, comments and new lines + + private void skipSpaces() { + while (peek() == ' ' || peek() == '\t') { + pos++; + } + } + + /** Skips spaces, comments and new lines, as they may stand between the values of an array. */ + private void skipBlank() throws TomlException { + do { + skipSpaces(); + if (peek() == '#') { + comment(); + } + } while (newline()); + } + + private void comment() throws TomlException { + pos++; + while (pos < src.length()) { + char c = src.charAt(pos); + if (c == '\n' || c == '\r' && at(pos + 1) == '\n') { + return; + } + pos += textChar(); + } + } + + /** Reads what may follow a key-value pair or a table header: spaces, a comment, a new line. */ + private void endOfLine() throws TomlException { + skipSpaces(); + if (peek() == '#') { + comment(); + } + if (pos < src.length() && !newline()) { + throw error(pos, "expected the end of the line, found " + found()); + } + } + + /** Skips a line feed, or a carriage return and a line feed, if there is one at pos. */ + private boolean newline() throws TomlException { + int c = peek(); + if (c == '\n') { + pos++; + return true; + } + if (c != '\r') { + return false; + } + if (at(pos + 1) != '\n') { + throw error(pos, "a carriage return must be followed by a line feed"); + } + pos += 2; + return true; + } + + // Small helpers + + private void enter() throws TomlException { + if (++nesting > MAX_NESTING) { + throw error(pos, "arrays and inline tables nest deeper than " + MAX_NESTING + " levels"); + } + } + + private void expect(String token) throws TomlException { + if (!src.startsWith(token, pos)) { + throw error(pos, "expected '" + token + "', found " + found()); + } + pos += token.length(); + } + + /** Reads exactly count ASCII digits as a number. */ + private int digits(int count) throws TomlException { + int value = 0; + for (int i = 0; i < count; i++) { + int c = peek(); + if (!isDigit(c)) { + throw error(pos, "expected a digit, found " + found()); + } + value = value * 10 + c - '0'; + pos++; + } + return value; + } + + private boolean digitsAt(int from, int count) { + for (int i = from; i < from + count; i++) { + if (!isDigit(at(i))) { + return false; + } + } + return true; + } + + private int peek() { + return at(pos); + } + + /** Returns the character at index i, or -1 past the end. */ + private int at(int i) { + return i < src.length() ? src.charAt(i) : -1; + } + + private Map newTable(Origin origin) { + Map table = new LinkedHashMap<>(); + origins.put(table, origin); + return table; + } + + /** Says what an existing value is, for an error message. */ + private String describe(Object value) { + Origin origin = origins.get(value); + if (origin == null) { + return value instanceof List ? "an array" : "a value"; + } + switch (origin) { + case IMPLICIT: + return "a table"; + case HEADER: + return "a table defined by a header"; + case DOTTED: + return "a table defined by dotted keys"; + case INLINE: + return "an inline table"; + default: + return "an array of tables"; + } + } + + /** Describes the character at pos, for an error message. */ + private String found() { + int c = peek(); + if (c == -1) { + return "the end of the file"; + } + if (c == '\n' || c == '\r') { + return "the end of the line"; + } + if (c > ' ' && c < 0x7F) { + return "'" + (char) c + "'"; + } + return codePoint(src.codePointAt(pos)); + } + + private TomlException error(int index, String reason) { + int end = Math.min(index, src.length()); + int line = 1; + int lineStart = 0; + for (int i = 0; i < end; i++) { + if (src.charAt(i) == '\n') { + line++; + lineStart = i + 1; + } + } + return new TomlException(reason, line, src.codePointCount(lineStart, end) + 1); + } + + /** Writes the first count parts of a key as TOML would, for an error message. */ + private static String name(List key, int count) { + StringBuilder out = new StringBuilder(); + for (int i = 0; i < count; i++) { + String part = key.get(i); + boolean bare = !part.isEmpty(); + for (int j = 0; j < part.length() && bare; j++) { + bare = isBareKeyChar(part.charAt(j)); + } + if (i > 0) { + out.append('.'); + } + if (bare) { + out.append(part); + } else { + out.append('"').append(part.replace("\\", "\\\\").replace("\"", "\\\"")).append('"'); + } + } + return out.toString(); + } + + private static String codePoint(int c) { + return String.format(Locale.ROOT, "U+%04X", c); + } + + private static int daysInMonth(int year, int month) { + if (month == 2) { + return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) ? 29 : 28; + } + return month == 4 || month == 6 || month == 9 || month == 11 ? 30 : 31; + } + + private static boolean isDigit(int c) { + return c >= '0' && c <= '9'; + } + + private static int hexValue(int c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return -1; + } + + private static boolean isBareKeyChar(int c) { + return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || isDigit(c) || c == '_' || c == '-'; + } + + private static boolean isNumberChar(int c) { + return isBareKeyChar(c) || c == '+' || c == '.'; + } + + @SuppressWarnings("unchecked") + private static Map asTable(Object value) { + return (Map) value; + } + + @SuppressWarnings("unchecked") + private static List asList(Object value) { + return (List) value; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/toml/TomlDateTime.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/toml/TomlDateTime.java new file mode 100644 index 00000000..ed53a935 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/toml/TomlDateTime.java @@ -0,0 +1,121 @@ +package io.github.davdxpx.mistel.mncf.toml; + +import java.util.Objects; + +/** + * A TOML date-time value of one of the four kinds, with its fields and the text it was written as. + * Fields that the kind does not have are 0: a local date has no time, a local time has no date, + * and only an offset date-time has an offset. + */ +public final class TomlDateTime { + + /** The four kinds of date-time values in TOML. */ + public enum Kind { + /** A date and a time with an offset from UTC, such as 1979-05-27T07:32:00Z. */ + OFFSET_DATE_TIME, + /** A date and a time without an offset, such as 1979-05-27T07:32:00. */ + LOCAL_DATE_TIME, + /** A date alone, such as 1979-05-27. */ + LOCAL_DATE, + /** A time of day alone, such as 07:32:00. */ + LOCAL_TIME + } + + private final Kind kind; + private final String text; + private final int year; + private final int month; + private final int day; + private final int hour; + private final int minute; + private final int second; + private final int nanosecond; + private final int offsetMinutes; + + TomlDateTime(Kind kind, String text, int year, int month, int day, int hour, int minute, + int second, int nanosecond, int offsetMinutes) { + this.kind = kind; + this.text = text; + this.year = year; + this.month = month; + this.day = day; + this.hour = hour; + this.minute = minute; + this.second = second; + this.nanosecond = nanosecond; + this.offsetMinutes = offsetMinutes; + } + + /** Returns which of the four kinds this value is. */ + public Kind getKind() { + return kind; + } + + /** Returns the value exactly as the document wrote it. */ + public String getText() { + return text; + } + + /** Returns the year, 0 to 9999. */ + public int getYear() { + return year; + } + + /** Returns the month, 1 to 12. */ + public int getMonth() { + return month; + } + + /** Returns the day of the month, 1 to 31. */ + public int getDay() { + return day; + } + + /** Returns the hour, 0 to 23. */ + public int getHour() { + return hour; + } + + /** Returns the minute, 0 to 59. */ + public int getMinute() { + return minute; + } + + /** Returns the second, 0 to 60, where 60 is a leap second. */ + public int getSecond() { + return second; + } + + /** Returns the fraction of the second in nanoseconds. Digits after the ninth are dropped. */ + public int getNanosecond() { + return nanosecond; + } + + /** Returns the offset from UTC in minutes, negative west of UTC. */ + public int getOffsetMinutes() { + return offsetMinutes; + } + + /** Two date-times are equal when their kinds and fields are, however they were written. */ + @Override + public boolean equals(Object other) { + if (!(other instanceof TomlDateTime)) { + return false; + } + TomlDateTime that = (TomlDateTime) other; + return kind == that.kind && year == that.year && month == that.month && day == that.day + && hour == that.hour && minute == that.minute && second == that.second + && nanosecond == that.nanosecond && offsetMinutes == that.offsetMinutes; + } + + @Override + public int hashCode() { + return Objects.hash(kind, year, month, day, hour, minute, second, nanosecond, offsetMinutes); + } + + /** Returns the value as the document wrote it. */ + @Override + public String toString() { + return text; + } +} diff --git a/android/app/src/main/java/io/github/davdxpx/mistel/mncf/toml/TomlException.java b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/toml/TomlException.java new file mode 100644 index 00000000..66eecf76 --- /dev/null +++ b/android/app/src/main/java/io/github/davdxpx/mistel/mncf/toml/TomlException.java @@ -0,0 +1,33 @@ +package io.github.davdxpx.mistel.mncf.toml; + +/** A document is not valid TOML 1.0.0. Says what is wrong and where, by line and column. */ +public final class TomlException extends Exception { + + private static final long serialVersionUID = 1L; + + private final String reason; + private final int line; + private final int column; + + TomlException(String reason, int line, int column) { + super("line " + line + ", column " + column + ": " + reason); + this.reason = reason; + this.line = line; + this.column = column; + } + + /** Returns what is wrong, without the position. */ + public String getReason() { + return reason; + } + + /** Returns the line of the error, counted from 1. */ + public int getLine() { + return line; + } + + /** Returns the column of the error in Unicode code points, counted from 1. */ + public int getColumn() { + return column; + } +} diff --git a/android/app/src/peanuts/res/drawable/pil_layout_bottom.xml b/android/app/src/peanuts/res/drawable/pil_layout_bottom.xml new file mode 100644 index 00000000..2ecdfaf1 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pil_layout_bottom.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pil_layout_right.xml b/android/app/src/peanuts/res/drawable/pil_layout_right.xml new file mode 100644 index 00000000..4bc848cd --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pil_layout_right.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pil_layout_two.xml b/android/app/src/peanuts/res/drawable/pil_layout_two.xml new file mode 100644 index 00000000..082854ef --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pil_layout_two.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_back.xml b/android/app/src/peanuts/res/drawable/pis_back.xml new file mode 100644 index 00000000..5bb8590c --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_back.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_bolt.xml b/android/app/src/peanuts/res/drawable/pis_bolt.xml new file mode 100644 index 00000000..204a364b --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_bolt.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_buttons.xml b/android/app/src/peanuts/res/drawable/pis_buttons.xml new file mode 100644 index 00000000..026915c4 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_buttons.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_cheats.xml b/android/app/src/peanuts/res/drawable/pis_cheats.xml new file mode 100644 index 00000000..7b6a4f65 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_cheats.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_close.xml b/android/app/src/peanuts/res/drawable/pis_close.xml new file mode 100644 index 00000000..845abc4e --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_close.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_controller.xml b/android/app/src/peanuts/res/drawable/pis_controller.xml new file mode 100644 index 00000000..dea6d594 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_controller.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_display.xml b/android/app/src/peanuts/res/drawable/pis_display.xml new file mode 100644 index 00000000..e44a1c1a --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_display.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_game.xml b/android/app/src/peanuts/res/drawable/pis_game.xml new file mode 100644 index 00000000..33831e1e --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_game.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_gauge.xml b/android/app/src/peanuts/res/drawable/pis_gauge.xml new file mode 100644 index 00000000..3a6c10a0 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_gauge.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_log.xml b/android/app/src/peanuts/res/drawable/pis_log.xml new file mode 100644 index 00000000..4f5f2681 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_log.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_mods.xml b/android/app/src/peanuts/res/drawable/pis_mods.xml new file mode 100644 index 00000000..ebb8b093 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_mods.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_panel.xml b/android/app/src/peanuts/res/drawable/pis_panel.xml new file mode 100644 index 00000000..c46081fc --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_panel.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_pause.xml b/android/app/src/peanuts/res/drawable/pis_pause.xml new file mode 100644 index 00000000..f7970e54 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_pause.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_play.xml b/android/app/src/peanuts/res/drawable/pis_play.xml new file mode 100644 index 00000000..c1ebfd88 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_play.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_save_up.xml b/android/app/src/peanuts/res/drawable/pis_save_up.xml new file mode 100644 index 00000000..816d4d31 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_save_up.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_settings.xml b/android/app/src/peanuts/res/drawable/pis_settings.xml new file mode 100644 index 00000000..3d457414 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_settings.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/drawable/pis_stop.xml b/android/app/src/peanuts/res/drawable/pis_stop.xml new file mode 100644 index 00000000..b2709541 --- /dev/null +++ b/android/app/src/peanuts/res/drawable/pis_stop.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/android/app/src/peanuts/res/values/peanuts_ingame.xml b/android/app/src/peanuts/res/values/peanuts_ingame.xml new file mode 100644 index 00000000..3f4a69ba --- /dev/null +++ b/android/app/src/peanuts/res/values/peanuts_ingame.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + diff --git a/peanuts/UPSTREAM-EDITS.md b/peanuts/UPSTREAM-EDITS.md index 08b4e8c4..0a6b00e9 100644 --- a/peanuts/UPSTREAM-EDITS.md +++ b/peanuts/UPSTREAM-EDITS.md @@ -2796,3 +2796,107 @@ Left as they were: the hunks the check also flags that were unmarked before 0.1. `dm/games/0100A6301214E000/game.tsv`, `dm/games/game.py`, `hle_nvn.c` `nvnWindowGetPresentInterval`, `vka_tex.c` (one line), `dm/host/dm.h`, `hle_fpslock.c` `limit_raw`, `loader.c` (two lines), `dm/host/tests/t_android_smap.c`, `dm/tools/docs_patches.py`, and the tests `test_android_soc.py`, `test_fpslocker_plan.py`, `test_game_profile.py`, `test_option_patch.py`, `test_vka_tex_registration.py`. + +### Cheats as .mncf: checked before they write, ready for game updates (2026-11-24, on Game page Part C and Mod menu Part F) + +Every cheat file a player adds is kept as one file of the Mistel Native Cheat Format (`.mncf`, Mistel's `format/spec/mncf-1.md`) for all of a game's +builds: an Atmosphère, Eden, Yuzu or Ryujinx file (a zip, a text file, a folder, upstream's export) is converted as it is added, with the game's own +main from the pack (`main.patched.bin` with `main.orig.bin` back at `main.changed.tsv`'s runs: `dev.peanuts.mods.MncfMain`), so each patch names the +original code at its place and finds the place by a pattern; an `.mncf` or an `.mncp` pack is kept byte for byte. A start makes each source ready for +the build that runs (`MncfBuild`: Mistel's evaluator, kept per build beside the source) and writes its cheats into the merged file as Atmosphère code, +so the host's cheat engine (Parts A and B) runs them unchanged. A cheat that cannot run here is listed, off, with the spec's reason in the player's +words (`MncfWords`). An `.mncf` value gets Part F's number field, a code immediate too. Export writes `.mncf` (one source) or `.mncp` (several). + +| File | Hunks | Change | Marker | +|---|---|---|---| +| `android/app/src/main/java/dev/nxnative/android/GameActivity.java` | 1 (Part C's block) | `cheatsEnv`'s `ModCheats.install` gets what a conversion knows (`CheatsBridge.known`) and the game with its pack (`CheatsBridge.game`) | inside Part C's `PEANUTS begin/end` | +| `android/app/src/main/java/dev/nxnative/android/ModCheats.java` | (Peanuts' own) | `install` converts earlier Atmosphère sources (`CheatSources.upgrade`) and merges the `.mncf` sources made ready for the build | allow-listed in `peanuts/upstream-unmarked.txt` | +| `android/app/src/main/java/dev/nxnative/android/CheatsBridge.java` | (Peanuts' own, Part C) | `known`, `game`, `convert`, `prepare`, `merged(..., make)`; Export writes `.mncf` / `.mncp` | Peanuts' own file | +| `android/NOTICE.md` | 1 | Mistel's MIT library and where it is | `` | + +Peanuts-owned: Mistel's MIT library for `.mncf` under `android/app/src/main/java/io/github/davdxpx/mistel/` (copied unchanged by +`peanuts/scripts/mncf-vendor.sh`, its `LICENSE` and `MISTEL.sha256` beside it), `MncfBuild`, `MncfConvert`, `MncfExport`, `MncfFacts`, `MncfMain`, +`MncfWords`, and the `.mncf` parts of `CheatSources`, `CheatImport`, `CheatImportUi`, `CheatsPage`, `CheatFile`, `CheatValues`, `CheatStatus`, +`ModsTab`. `upstream-update.sh --check` now counts `android/app/src/jvmtest/java/dev/peanuts/` as Peanuts-owned, and `ModCheats.java` is on the +allow-list: both were flagged since Part C. Tests: `peanuts/tests/test_cheat_loader.py` (`CheatLoaderJvmTest`: conversion, a pack's main, the build +made ready and kept, another build by its patterns, a rewritten place, the number field, relations, export, packs, the facts of a file), +`peanuts/tests/test_mod_cheats.py`, `peanuts/tests/test_mncf_vendor.py` (the copy unchanged, its MIT notice). + +### In-game menus: a game menu at the left, a quick menu at the right (2026-11-24, on .mncf cheats; the canvas page "In-game menus") + +Upstream's one in-game panel with five text tabs becomes two menus, as a console's: everything about this session at the left, everything that tunes +the running game at the right. The game keeps running behind both. + +- **The game menu** (`dev.peanuts.ingame.GameMenu`): the game's cover, name, version and how long this session has run; Back to the game, Pause the + game, Quick menu, Back up the save (the save the game runs on, copied while it runs: SaveStore checks the save before and after the copy, and the host + writes a save only by an atomic swap at the game's Commit, so a Commit in between fails the copy, which is tried again), Button mapping, Share log; + Stop the game set apart at the bottom, asked once inline (Keep playing first). The header and Stop stay while the rows scroll on a short screen. +- **The quick menu** is upstream's SidePanel with its tabs on a rail at the left (`dev.peanuts.ingame.Rail`): Performance, Display, Cheats, Mods, + Controls, and the menu's own settings at the bottom (upstream's General without Pause, Stop and Back to the game). Cheats and Mods are two tabs now + (`ModsTab.fill(..., part)`), each only when the game has some. The selected tab is a peanut-brown block across the rail that slides to the next one; + up and down on the rail switch the tab, left from a row comes back to the selected tab. Its header has Back and the tab's name. Section heads are in + capitals in peanut tan, a slider's label has its value at the right (`PanelPolish`). +- **Opening**: Home pressed, − and + held, Back and a swipe in from the left edge open the game menu; Home held (half a second, while still down), a + swipe in from the right edge, a long press on the on-screen controls' button and the game menu's Quick menu row open the quick menu. Home pressed + closes either; B in the quick menu goes back to the game menu when that opened it, onto its Quick menu row. Settings › Controller › In-game panel still decides whether Home + and − + open anything. On a device whose Home is Android's (the AYN Thor: it goes to the launcher), the controller's own Back does what Home does: + pressed the game menu with the selection shown, held the quick menu (`InGamePanel.backKey`); in the quick menu it goes one step back, and a Back made + from an unused B or by the edge swipe goes on to `onBackPressed` as before. A tool that watches the keys (on the Thor an accessibility service with a + screen swap on Back held) hands Back on as Android's own: that Back opens the game menu with the selection shown too while a controller is attached. +- **Icons**: a solid set for the rail and the game menu (`drawable/pis_*.xml` from `design/peanuts-native/icons/icons.py` SOLID, colours per state in + `values/peanuts_ingame.xml`): at rest a muted grey with a muted banana, selected peanut cream with banana yellow. +- **Motion**: in 240 ms decelerating, out 180 ms accelerating, the scrim with them; a tab's rows come up 8 dp and fade in; all on translation and alpha + with hardware layers (`dev.peanuts.ingame.Look`). +- **Feel** (`dev.peanuts.ui.MenuFeel`): a fine tick of the motor for each step of the controller's focus, a firmer one for a choice or a tab, through + the launcher's own haptics (`Haptics`: its gaps, the system's touch feedback, battery saver and heat); soft menu sounds made in the app (a few + milliseconds of a sine, no files), off by default. Both in the menu's own settings: Vibrate on each step, Menu sounds. +- **Console details**: Stop the game has the power sign. A tab's own action sits in the header beside its name with the controller's button (the Cheats + tab's "X All off", `Rail.action`) instead of a row of its own. The yellow focus frame keeps clear of a row's first letter (`PanelPolish.inset`: a + switch or list row reaches 10 dp into the side padding, its content 10 dp in) and shows on the short choices too (one line without a single-line + scroll, which moved the frame out of sight); no grey veil of the system's under it. The focus coming into a track of choices lands on the chosen + one, not the nearest (`PanelPolish.chosen`); in a list of choices (Console mode, the frame rate cap) each choice takes the row's width with its + mark and text 10 dp in, so the frame keeps clear of them too, its mark a still one of the panel's (a ring, with a yellow dot when chosen). Right from the rail goes into the rows (the first in sight), not to the header's Back. Left from any row goes back to the rail's tab. A Value cheat's + number takes the room between its − and + (a narrow menu narrows the number, + is never cut off), and a focused cheat is kept whole on the screen + once its line opens. + +| File | Hunks | Change | Marker | +|---|---|---|---| +| `android/app/src/main/java/dev/nxnative/android/SidePanel.java` | 8 | `TAB_CONTROLS` not final; the constructor's `InGamePanel.frame`; `tabBar`'s `InGamePanel.rail`; `showTab`'s `InGamePanel.railFocused`; `open`'s `InGamePanel.slideIn` and `close`'s `slideOut` instead of upstream's two animations; `padKey`'s back key `InGamePanel.panelBack`; `look`'s `InGamePanel.laid` | `// PEANUTS` on each line | +| `android/app/src/main/java/dev/nxnative/android/GameActivity.java` | 7 | `comboHeld` and the combination's TOGGLE through `InGamePanel.toggle`, the combination through `InGamePanel.key`; `onCreate`'s `InGamePanel.attach`; `dispatchKeyEvent`'s `InGamePanel.menuKey`; `onGenericMotionEvent`'s `InGamePanel.menuMotion`; `onBackPressed`'s `InGamePanel.back`; `runSave()` | `// PEANUTS` / `/* PEANUTS */` on each line | +| `android/app/src/main/java/dev/nxnative/android/SaveStore.java` | 1 | `backupLocked` not private | `// PEANUTS` | +| `android/app/src/main/java/dev/nxnative/android/InGamePanel.java` | new | Peanuts-owned, in upstream's package (as `ModsPanel.java`): the two menus, the keys, the backup while the game runs | Peanuts' own file | +| `android/app/src/main/java/dev/nxnative/android/ModsPanel.java` | (Peanuts' own, Part E) | the quick menu's tabs: Cheats and Mods apart, before Controls | Peanuts' own file | + +Peanuts-owned: `dev.peanuts.ingame` (`GameMenu`, `Rail`, `Look`), `dev.peanuts.ui.MenuFeel`, `drawable/pis_*.xml`, `values/peanuts_ingame.xml`, the halves +of `ModsTab` and its header action, the heads, valued sliders and row insets of `PanelPolish`. Tests: `peanuts/tests/test_ingame_menus.py` (the hooks, the rail's order, the rows, the text against UI-RULES.md, the +icons against icons.py), `peanuts/tests/test_cheat_loader.py` (Part E's hooks in their new place). + +### In-game menus as one menu: at the right over the game, or on the bottom screen with the game in full view on top (2026-11-24, on the in-game menus; two menus stay the default) + +The player picks the layout once: Home's list asks at the app's start until one is picked (`dev.peanuts.ui.LayoutChoice`, Later asks again at the +next start), with a picture of each (`drawable/pil_layout_*.xml` from `design/peanuts-native/layouts/layouts.py`): Two menus (the game menu at the left, +the quick menu at the right; kept until one is picked), One menu at the right, and on a device with a second screen (the AYN Thor) One menu on the bottom +screen, where the focus starts there. The menu's own settings change it later (Layout). `PeanutsPrefs.menuLayout` keeps both with when, the newer counts. One menu is a second +quick menu whose rail starts with Game (the game menu's rows, `dev.peanuts.ingame.GameRows`) above the quick menu's tabs; Home pressed, − and + held and +Back open it on Game, Home held (or the controller's Back held) on the tab shown last, L and R step over Game and the tabs, B closes it. On Game +its own header (the cover, the name, the version, this session's time) is the top, as in the game menu, without the tabs' header over it. + +**At the right** (`InGamePanel.openRight`): over the game as the quick menu is, sliding in from the right edge. The swipe in from the right edge and the +on-screen controls' button open it (one hook at the top of `SidePanel.open`, `InGamePanel.instead`); the left edge is the game's. + +**On the bottom screen** (`InGamePanel.openBottom`; without a second display now, the one at the right opens instead): the game stays in full view on +top, dimmed a little as behind the other menus (it runs on, but is not being played; a touch there closes the menu): a grey sheet slides up from the bottom edge (280 ms, decelerating) over what the screen shows (the game's live stats, a companion, Android's +launcher), its rail starting with Game (the game menu's rows, `dev.peanuts.ingame.GameRows`) above the quick menu's tabs. Home held opens it on the tab +shown last; on the stats page a faint grip (it moves with the pixel shifter) and a swipe up from the bottom edge open it on Game. L and R step over Game +and the tabs, B closes it (220 ms back down) and the screen is given back: its window (`dev.peanuts.ingame.BottomScreen`, a presentation that never takes +the input focus, so the controller stays with the game, whose keys go to the menu) goes when it has slid down, and at once when the game leaves the +screen. A touch sets a value directly, and the top screen shows its effect while the finger moves. Swipes on the top screen still open the menus there. + +| File | Hunks | Change | Marker | +|---|---|---|---| +| `android/app/src/main/java/dev/nxnative/android/SidePanel.java` | 2 | `rows()`: one menu builds the same rows; `open()`: `InGamePanel.instead` (with one menu at the right, what opens the quick menu opens that one) | `// PEANUTS` | +| `android/app/src/main/java/dev/nxnative/android/InGamePanel.java` | (Peanuts' own) | the one menu at the right and on the bottom screen, their keys and stick, their slide, Layout in General | Peanuts' own file | + +Peanuts-owned: `dev.peanuts.ingame.BottomScreen`, `GameRows`, `BottomMenu` (the grip and the edge), `Rail`'s Game, `PeanutsPrefs.menuLayout`, +`dev.peanuts.ui.LayoutChoice` and its line in `Library.fill`, `drawable/pil_layout_*.xml`, the grip on `GameScreen`'s Now playing page, +`Companion.second`, one line each in `dev.peanuts.ui.StatsView` (the grip) and `GameScreen` (the edge). Tests: `peanuts/tests/test_ingame_menus.py`. diff --git a/peanuts/scripts/mncf-vendor.sh b/peanuts/scripts/mncf-vendor.sh new file mode 100644 index 00000000..b8b743f2 --- /dev/null +++ b/peanuts/scripts/mncf-vendor.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# mncf-vendor.sh [] : copies Mistel's MIT library for .mncf cheat files (format/lib/java, package io.github.davdxpx.mistel.mncf) +# into the launcher, word for word, with the MIT notice of Mistel's format/ folder, and writes the list of what was copied (MISTEL.sha256: the commit, +# then a SHA-256 and a path a line). peanuts/tests/test_mncf_vendor.py checks the copy against that list, so a change to the copy itself fails the tests: +# fixes go to Mistel first (https://github.com/davdxpx/mistel), then come here with this script. defaults to origin/main of the checkout. +# Only format/ is MIT; nothing else of Mistel (GPL-3.0) may be copied into this repository. +set -eu +src="${1:?usage: mncf-vendor.sh []}" +rev="${2:-origin/main}" +cd "$(git rev-parse --show-toplevel)" +dst="android/app/src/main/java/io/github/davdxpx/mistel" +commit=$(git -C "$src" rev-parse --verify "$rev^{commit}") +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +git -C "$src" archive "$commit" format/LICENSE format/lib/java/src/main/java/io/github/davdxpx/mistel/mncf | tar -x -C "$tmp" +[ -f "$tmp/format/LICENSE" ] && grep -q '^MIT License' "$tmp/format/LICENSE" || { echo "mncf-vendor: $commit has no MIT format/LICENSE"; exit 1; } +rm -rf "$dst/mncf" +mkdir -p "$dst" +cp -R "$tmp/format/lib/java/src/main/java/io/github/davdxpx/mistel/mncf" "$dst/mncf" +cp "$tmp/format/LICENSE" "$dst/LICENSE" +{ + echo "# mistel $commit format/lib/java/src/main/java/io/github/davdxpx/mistel/mncf and format/LICENSE, unchanged (peanuts/scripts/mncf-vendor.sh)" + (cd "$dst" && find LICENSE mncf -type f | LC_ALL=C sort | while read -r f; do printf '%s %s\n' "$(sha256sum "$f" | cut -d' ' -f1)" "$f"; done) +} > "$dst/MISTEL.sha256" +echo "mncf-vendor: $(grep -c ' ' "$dst/MISTEL.sha256") files of mistel ${commit%"${commit#????????}"} in $dst" diff --git a/peanuts/scripts/upstream-update.sh b/peanuts/scripts/upstream-update.sh index 86fe8a5c..3208fee3 100755 --- a/peanuts/scripts/upstream-update.sh +++ b/peanuts/scripts/upstream-update.sh @@ -62,10 +62,12 @@ fi # `git log --diff-filter=A` + `git cat-file -e upstream/android:` when they were added), so # a whole-file diff against upstream is meaningless for them and they are exempt from the # hook-marker check below. android/app/src/peanuts/ is the flavor source set (PNG/XML assets) -- -# it does not exist upstream at all. +# it does not exist upstream at all. android/app/src/main/java/io/github/davdxpx/mistel/ is Mistel's MIT library for .mncf +# cheat files, copied unchanged by peanuts/scripts/mncf-vendor.sh (upstream has no io/ package at all). +# android/app/src/jvmtest/java/dev/peanuts/ holds the JVM tests of Peanuts' own classes (upstream's are under dev/nxnative). is_peanuts_owned() { case "$1" in - peanuts/*|dm/peanuts/*|android/app/src/main/java/dev/peanuts/*|android/app/src/peanuts/*|PEANUTS.md|\ + peanuts/*|dm/peanuts/*|android/app/src/main/java/dev/peanuts/*|android/app/src/jvmtest/java/dev/peanuts/*|android/app/src/peanuts/*|android/app/src/main/java/io/github/davdxpx/mistel/*|PEANUTS.md|\ dm/gfx/tools/split_pool.py|dm/gfx/tools/ue_ondevice.py) return 0 ;; *) diff --git a/peanuts/tests/test_cheat_loader.py b/peanuts/tests/test_cheat_loader.py index cad7e601..8cacba2b 100644 --- a/peanuts/tests/test_cheat_loader.py +++ b/peanuts/tests/test_cheat_loader.py @@ -16,7 +16,14 @@ MODS = APP / 'main/java/dev/peanuts/mods' LAUNCHER = APP / 'main/java/dev/nxnative/android' TEST = APP / 'jvmtest/java/dev/peanuts/mods/CheatLoaderJvmTest.java' -CORE = [MODS / 'CheatFile.java', MODS / 'CheatImport.java', MODS / 'CheatSources.java', MODS / 'CheatStatus.java', MODS / 'CheatValues.java'] +CORE = [MODS / 'CheatFile.java', MODS / 'CheatImport.java', MODS / 'CheatSources.java', MODS / 'CheatStatus.java', MODS / 'CheatValues.java', + MODS / 'MncfBuild.java', MODS / 'MncfConvert.java', MODS / 'MncfExport.java', MODS / 'MncfFacts.java', MODS / 'MncfMain.java', MODS / 'MncfWords.java'] +MISTEL = APP / 'main/java/io/github/davdxpx/mistel' # Mistel's MIT library for .mncf, copied unchanged (test_mncf_vendor.py) + + +def compile_mistel(out): + """Mistel's library into out (its own code: its warnings are Mistel's to fix, so not -Werror here)""" + subprocess.run(['javac', '-nowarn', '-encoding', 'UTF-8', '-d', str(out), *map(str, sorted(MISTEL.rglob('*.java')))], check=True, capture_output=True, text=True) UI_FILES = [MODS / 'CheatPick.java', LAUNCHER / 'CheatsBridge.java', MODS / 'CheatsPage.java', MODS / 'CheatImportUi.java', MODS / 'ModsTab.java', LAUNCHER / 'ModsPanel.java'] # the words the player reads @@ -26,8 +33,10 @@ class Jvm(unittest.TestCase): def test_cheat_loader(self): with tempfile.TemporaryDirectory() as t: d = Path(t) - subprocess.run(['javac', '-Xlint:all', '-Werror', '-encoding', 'UTF-8', '-d', str(d / 'classes'), *map(str, CORE), str(TEST)], - check=True, capture_output=True, text=True) + compile_mistel(d / 'classes') + r = subprocess.run(['javac', '-Xlint:all', '-Werror', '-encoding', 'UTF-8', '-cp', str(d / 'classes'), '-d', str(d / 'classes'), *map(str, CORE), str(TEST)], + capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr) (d / 'work').mkdir() args = ['java', '-cp', str(d / 'classes'), 'dev.peanuts.mods.CheatLoaderJvmTest', str(d / 'work')] real = os.environ.get('PEANUTS_CHEATS_REAL') @@ -73,10 +82,10 @@ def test_the_panel_has_a_mods_tab(self): # Part E for call in ('ModsPanel.opening(', 'ModsPanel.build(', 'ModsPanel.padKey(', 'ModsPanel.shows()', 'ModsPanel.afterLayout('): self.assertRegex(panel, re.escape(call) + r'.*// PEANUTS', f'SidePanel: the marked hook {call}') self.assertRegex(panel, r'static String\[\] TAB_NAMES = .*// PEANUTS') - self.assertRegex(panel, r'static int TAB_GENERAL = 3;\s+// PEANUTS') + self.assertRegex(panel, r'static int TAB_CONTROLS = 2, TAB_GENERAL = 3;\s+// PEANUTS') self.assertRegex(panel, r'if \(!ModsPanel\.shows\(\)\) cheatRows\(\);', "General keeps upstream's cheat switches only without the Mods tab") mp = (LAUNCHER / 'ModsPanel.java').read_text(encoding='utf-8') - self.assertIn('{"Performance", "Display", "Controls", MODS, "General"}', mp, 'Mods sits between Controls and General') + self.assertRegex(mp, r'if \(shows\) names\.add\(CHEATS\);\s+if \(mods\) names\.add\(MODS\);\s+names\.add\("Controls"\);', 'the quick menu: Cheats, then Mods, before Controls (the canvas page "In-game menus")') bridge = (LAUNCHER / 'CheatsBridge.java').read_text(encoding='utf-8') for call in ('Native.cheatStatus()', 'Native.cheatsReload()', 'Native.cheatSet('): self.assertIn(call, bridge, f'the tab reaches {call} through CheatsBridge (Native is package-private)') @@ -89,13 +98,13 @@ def test_the_panel_has_a_mods_tab(self): # Part E def test_a_value_cheat_has_a_number(self): # Part F mc = (LAUNCHER / 'ModCheats.java').read_text(encoding='utf-8') - self.assertIn('CheatSources.merge(blocks(s, folder, build, mods, -1), dev.peanuts.mods.CheatValues.read(folder))', mc, 'a start writes the kept numbers') + self.assertIn('CheatSources.merge(blocks, dev.peanuts.mods.CheatValues.read(folder))', mc, 'a start writes the kept numbers') tab = (MODS / 'ModsTab.java').read_text(encoding='utf-8') self.assertRegex(tab, r'public View focusSearch\(int direction\)', "the field steps on SidePanel's left / right (its focusSearch)") self.assertIn('CheatValues.plain(b.cheat)', tab, 'only a Value cheat with a plain number has the field; a code cheat keeps its words') self.assertIn('CheatsBridge.reload()', tab, 'the host reads the merged file again after a new number') self.assertIn('setNeutralButton("Reset"', tab, "the details give the file's own number back") - self.assertIn('"File: " + b.cheat.value()', tab, "a set number is marked with the file's own beside it") + self.assertIn('"File: " + b.cheat.number.own()', tab, "a set number is marked with the file's own beside it") def test_the_start_merges_the_sources(self): mc = (LAUNCHER / 'ModCheats.java').read_text(encoding='utf-8') diff --git a/peanuts/tests/test_ingame_menus.py b/peanuts/tests/test_ingame_menus.py new file mode 100644 index 00000000..6f38dd7e --- /dev/null +++ b/peanuts/tests/test_ingame_menus.py @@ -0,0 +1,201 @@ +"""The in-game menus (the canvas "Peanuts Settings Redesign", page "In-game menus"): the game menu at the left (dev.peanuts.ingame.GameMenu) and the quick +menu at the right (upstream's SidePanel with its tabs on a rail, dev.peanuts.ingame.Rail), joined by dev.nxnative.android.InGamePanel. Checks the marked +hooks in upstream's files, the rail's order and icons, the game menu's rows, the solid icons against design's icons.py output, and the text the player +reads against UI-RULES.md.""" +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +APP = REPO / 'android/app/src' +LAUNCHER = APP / 'main/java/dev/nxnative/android' +INGAME = APP / 'main/java/dev/peanuts/ingame' +RES = APP / 'peanuts/res' +UI_FILES = [LAUNCHER / 'InGamePanel.java', INGAME / 'GameMenu.java', INGAME / 'Rail.java', INGAME / 'Look.java', INGAME / 'GameRows.java', INGAME / 'BottomMenu.java', INGAME / 'BottomScreen.java', APP / 'main/java/dev/peanuts/ui/MenuFeel.java', + APP / 'main/java/dev/peanuts/ui/LayoutChoice.java'] + + +def marked(src, call): + """The line with call carries a PEANUTS marker""" + return any(call in line and 'PEANUTS' in line for line in src.splitlines()) + + +class Hooks(unittest.TestCase): + def test_side_panel(self): + p = (LAUNCHER / 'SidePanel.java').read_text(encoding='utf-8') + for call in ('InGamePanel.frame(this, sh, tabs, scroll)', 'InGamePanel.rail(this, tab, this::showTab)', 'InGamePanel.railFocused()', + 'InGamePanel.slideIn(this, sheet)', 'InGamePanel.slideOut(this, sheet,', 'InGamePanel.panelBack(this)', 'InGamePanel.laid(this, box, tab)'): + self.assertTrue(marked(p, call), f'SidePanel: the marked hook {call}') + self.assertRegex(p, r'static int TAB_CONTROLS = 2, TAB_GENERAL = 3;\s+// PEANUTS', 'Controls moves behind Cheats and Mods') + self.assertNotIn('setDuration(180)', p, "upstream's open animation is the quick menu's (InGamePanel.slideIn)") + + def test_game_activity(self): + g = (LAUNCHER / 'GameActivity.java').read_text(encoding='utf-8') + for call in ('InGamePanel.attach(this, root, panel)', 'InGamePanel.key(this, combo, k, down,', 'InGamePanel.toggle(this, true)', + 'InGamePanel.backKey(this, e)', + 'InGamePanel.menuKey(this, e, gamepad(e.getSource()))', 'InGamePanel.menuMotion(this, e)', 'InGamePanel.back(this)', + 'static File runSave()'): + self.assertTrue(marked(g, call), f'GameActivity: the marked hook {call}') + self.assertNotIn('panel.padToggle()', g, 'the controller opens the game menu, not the quick menu') + self.assertLess(g.index('InGamePanel.menuKey('), g.index('if (panel.isOpen() && gamepad(e.getSource()))'), 'the game menu takes the controller first') + self.assertLess(g.index('InGamePanel.backKey('), g.index('InGamePanel.key(this, combo'), "the controller's Back before the combination") + p = (LAUNCHER / 'InGamePanel.java').read_text(encoding='utf-8') + back = p[p.index('static boolean backKey('):] + back = back[:back.index('\n }\n') + 6] + self.assertIn('controllerBack(e)', back, "only the controller's own Back") + self.assertIn('supportsSource(InputDevice.SOURCE_GAMEPAD)', p, "the device tells a controller's Back: Android gives it the keyboard's source alone") + self.assertIn('FLAG_FALLBACK', p, "a Back Android made from an unused B is not the controller's Back") + self.assertIn('PadPanel.HOLD_MS', back, 'held as long as Home for the quick menu') + self.assertIn('toggle(a, true)', back, 'pressed: the game menu with the selection shown') + plain = p[p.index('static void back(Activity a)'):] + plain = plain[:plain.index('\n }\n')] + self.assertIn('padAttached()', plain, "Android's own Back (a key tool handed it on) with the selection while a controller is attached") + self.assertIn('menu.at(quickRow);', p, 'B from the quick menu: back on the Quick menu row') + + def test_save_store(self): + s = (LAUNCHER / 'SaveStore.java').read_text(encoding='utf-8') + self.assertTrue(marked(s, 'static Backup backupLocked('), 'backupLocked not private, marked') + b = (LAUNCHER / 'InGamePanel.java').read_text(encoding='utf-8') + self.assertIn('SaveStore.backupLocked(save, to, SaveUi.stamp())', b, "the game menu's backup is SaveStore's own, checked before and after the copy") + self.assertIn('GameActivity.runSave()', b, 'the save the game runs on (the player picked at the start)') + self.assertIn('contains("changed while")', b, 'a Commit during the copy is tried again') + + +class Menus(unittest.TestCase): + def test_the_rail(self): + mp = (LAUNCHER / 'ModsPanel.java').read_text(encoding='utf-8') + order = re.findall(r'names\.add\((\w+|"\w+")\)', mp) + self.assertEqual(order, ['CHEATS', 'MODS', '"Controls"', '"General"'], 'Performance, Display, then Cheats, Mods, Controls, the settings at the bottom') + rail = (INGAME / 'Rail.java').read_text(encoding='utf-8') + for tab, ic in (('Performance', 'bolt'), ('Display', 'display'), ('Cheats', 'cheats'), ('Mods', 'mods'), ('Controls', 'controller')): + self.assertIn(f'case "{tab}": return "{ic}";', rail, f'{tab} has the solid {ic}') + self.assertIn('"General".equals(tab) ? "Menu settings"', rail, "General is the menu's own settings") + + def test_the_game_menu(self): + b = (LAUNCHER / 'InGamePanel.java').read_text(encoding='utf-8') + rows = re.findall(r'new GameMenu\.Item\("([\w-]+)", "([^"]+)"', b) + self.assertEqual([t for _, t in rows], ['Back to the game', 'Pause the game', 'Quick menu', 'Back up the save', 'Button mapping', 'Share log', 'Stop the game']) + for icon, _ in rows: + self.assertTrue((RES / 'drawable' / f'pis_{icon.replace("-", "_")}.xml').is_file(), f'the solid icon {icon}') + gm = (INGAME / 'GameMenu.java').read_text(encoding='utf-8') + self.assertIn('"Keep playing"', gm, 'Stop asks once, the safe choice first') + tab = (APP / 'main/java/dev/peanuts/mods/ModsTab.java').read_text(encoding='utf-8') + self.assertIn('public static void fill(Activity a, LinearLayout box, Host host, int part)', tab, 'Cheats and Mods are two tabs') + + def test_solid_icons(self): + styles = (RES / 'values/peanuts_ingame.xml').read_text(encoding='utf-8') + for s in ('PeanutsSolidRest', 'PeanutsSolidSelected', 'PeanutsSolidMenu'): + self.assertIn(f'