Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

27.8 KB
Raw Blame
import SwiftUI
import XCTest
@testable import NX2Apple
@testable import NXCore
import NXModel
@testable import NXLauncher

/// Issue #97: the cheat files the launcher manages, as the host reads them (dm/host/hle_cheats.c, docs/frontends.md "Cheats"). The
/// expectations are written by hand from the contract and from the host's parser, not generated by the code under test. Everything
/// runs in a temporary folder, devicectl is a stand-in, and no test reaches a device or the real Application Support.
@MainActor final class CheatFilesTests: IsolatedDefaultsTestCase {
    private var temporary: URL!
    private let titleID = "010015100B514000"
    private let build = "CD57B23FA4BBAD65"
    private let fm = FileManager.default

    override func setUpWithError() throws {
        temporary = fm.temporaryDirectory.appendingPathComponent("nxnative-cheats-" + UUID().uuidString)
        try fm.createDirectory(at: temporary, withIntermediateDirectories: true)
    }

    override func tearDownWithError() throws { try fm.removeItem(at: temporary) }

    private var files: CheatFiles { CheatFiles(titleID: titleID, folder: temporary.appendingPathComponent("cheats")) }

    @discardableResult private func write(_ text: String, _ path: String, under root: URL? = nil) throws -> URL {
        let url = (root ?? files.folder).appendingPathComponent(path)
        try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
        try Data(text.utf8).write(to: url)
        return url
    }

    private func parse(_ text: String, meta: String? = nil) -> [CheatFiles.Cheat] { CheatFiles.parse(Data(text.utf8), meta: meta) }

    // ---- where things are, and which build ----

    func testTheMacFolderIsDMRootsCheatsFolder() {
        let support = URL(fileURLWithPath: "/Users/x/Library/Application Support")
        XCTAssertEqual(CheatFiles(titleID: "010015100b514000", support: support).folder.path,
                       "/Users/x/Library/Application Support/nxnative/010015100B514000/cheats", "dm/mac/launcher.c: DM_ROOT is <Application Support>/nxnative/<title ID>, DM_CHEATS defaults to <DM_ROOT>/cheats")
        XCTAssertEqual(CheatFiles.deviceFolder(titleID: "010015100b514000"), "Documents/games/010015100B514000/cheats", "main.m points DM_CHEATS there")
    }

    func testTheBuildIDIsTheFirst16DigitsOfTheMainNSOsIDInUpperCase() throws {
        XCTAssertEqual(CheatFiles.buildID(fixups: "# PATCH_OFF\t0x1ea0000\n# BUILD_ID\tcd57b23fa4bbad65803d9788c01821ee\n"), build)
        XCTAssertNil(CheatFiles.buildID(fixups: "# PATCH_OFF\t0x1ea0000\n"))
        XCTAssertNil(CheatFiles.buildID(fixups: "# BUILD_ID\tcd57\n"), "cut short: not a build ID")
        XCTAssertNil(CheatFiles.buildID(fixups: "# BUILD_ID\tzzzzzzzzzzzzzzzzzzzz\n"))
        let mac = temporary.appendingPathComponent("Game.app"), ios = temporary.appendingPathComponent("DmIOS.app")
        try write("# BUILD_ID\tcd57b23fa4bbad65803d9788c01821ee\n", "Contents/Resources/dm/main.fixups.tsv", under: mac)
        try write("# BUILD_ID\t1111111111111111aaaaaaaaaaaaaaaa\n", "dm/main.fixups.tsv", under: ios)
        XCTAssertEqual(CheatFiles.buildID(appPath: mac.path, iosAppPath: ios.path), build, "the Mac app first")
        XCTAssertEqual(CheatFiles.buildID(appPath: "", iosAppPath: ios.path), "1111111111111111", "the iOS app keeps it at its root")
        XCTAssertNil(CheatFiles.buildID(appPath: "", iosAppPath: ""))
        XCTAssertNil(CheatFiles.buildID(appPath: temporary.appendingPathComponent("none.app").path, iosAppPath: ""))
    }

    func testTheHostsThreeFoldersAreScannedInItsOrderAndTheFirstFileOfABuildWins() throws {
        try write("[A]\n00000000\n", "\(build).txt")
        try write("[B]\n00000000\n", "atmosphere/contents/\(titleID)/cheats/\(build).txt")
        try write("[C]\n00000000\n", "atmosphere/contents/\(titleID)/cheats/1111111111111111.TXT")
        try write("[D]\n00000000\n", "contents/\(titleID)/cheats/2222222222222222.txt")
        try write("x", "readme.txt")
        try write("x", "\(build).enabled")
        try write("x", "\(build).meta.tsv")
        try write("x", "short.txt")
        let found = files.found()
        XCTAssertEqual(found.map(\.buildID), [build, "1111111111111111", "2222222222222222"].sorted())
        XCTAssertEqual(found.first { $0.buildID == build }?.url.deletingLastPathComponent(), files.folder, "the flat folder comes first")
        XCTAssertEqual(found.first { $0.buildID == "1111111111111111" }?.url.lastPathComponent, "1111111111111111.TXT", "the suffix in any case")
    }

    // ---- reading a cheat file ----

    func testHeadersMastersLabelsAndTheKeysOfDuplicates() {
        let cheats = parse("""
        [Credits]
        {Master}
        04000000 00000010 00000001
        [Max HP]
        04000000 00000020 00000002
        [Max HP]
        04000000 00000030 00000003
        [Max HP]
        04000000 00000040 00000004
        """)
        XCTAssertEqual(cheats.map(\.name), ["Credits", "Master", "Max HP", "Max HP", "Max HP"])
        XCTAssertEqual(cheats.map(\.kind), [.label, .master, .cheat, .cheat, .cheat], "no code words: a label")
        XCTAssertEqual(cheats.map(\.key), ["Credits", "Master", "Max HP", "Max HP #2", "Max HP #3"], "Name, Name #2, Name #3: .enabled's keys")
        XCTAssertEqual(cheats.map(\.switchable), [false, false, true, true, true], "masters are always on, labels never run")
    }

    func testWordsAreEightHexDigitsAndAHeaderGluedToAWordIsSplitOff() {
        let cheats = parse("[A]\n0400000000123456 00000001\nby someone\n[B] 04000000 00000008[C]\n04000000 00000009\n")
        XCTAssertEqual(cheats.map(\.name), ["A", "B", "C"], "00000008[C] is a word and a header")
        XCTAssertEqual(cheats.map(\.kind), [.cheat, .cheat, .cheat])
        XCTAssertEqual(cheats.map(\.broken), [false, false, false], "a glued word is whole words, prose alone on a line is ignored")
    }

    func testALineThatMixesWordsWithTextOrHoldsAPartialWordKeepsTheCheatOff() {
        let cheats = parse("[A]\n04000000 0012 00000001\n[B]\n04000000 00000001 x\n[C]\njust some prose\n[D]\n04000000 00000001\n")
        XCTAssertEqual(cheats.map(\.broken), [true, true, true, false])
        XCTAssertEqual(cheats.map(\.kind), [.cheat, .cheat, .cheat, .cheat], "a cheat with only prose lines is a typo, not a label")
        XCTAssertEqual(cheats.map(\.switchable), [false, false, false, true])
    }

    func testAnUnclosedOrEmptyHeaderBelongsToNothingAndItsLinesAreIgnored() {
        let cheats = parse("[A]\n04000000 00000001\n[Oops\n04000000 00000002\n[]\n04000000 00000003\n[B]\n04000000 00000004\n")
        XCTAssertEqual(cheats.map(\.name), ["A", "B"])
        XCTAssertEqual(cheats.map(\.broken), [false, false])
    }

    func testANameIsCutAt127BytesOnACharacterBoundary() {
        let long = String(repeating: "a", count: 126) + "é" + "tail"   // the é starts at byte 126 and would end at 128
        let cheats = parse("[\(long)]\n04000000 00000001\n")
        XCTAssertEqual(cheats.first?.name, String(repeating: "a", count: 126), "a cut never ends inside a character: the host keeps 127 bytes at most")
    }

    func testEdiZonSectionsGroupTheEntriesAfterTheirMarker() {
        let cheats = parse("""
        [--SectionStart:Items--]
        [Rupees]
        04000000 00000001 00000001
        [--SectionEnd:Items--]
        [Loose]
        04000000 00000002 00000002
        """)
        XCTAssertEqual(cheats.map(\.section), ["Items", "Items", "Items", ""])
        XCTAssertEqual(cheats.map(\.kind), [.label, .cheat, .label, .cheat])
    }

    func testTheMetaFileMakesOnePassCheatsAndPairsOutOfTheirSwitches() {
        let meta = "# build\n" + [
            "name\tkind\tsection\ttype\taction\task\tvalue_words\tonce\tpair\tresolved\tnote\taddress",
            "Set money\tpatch\tStats\tu32\tset\t\t\t1\t\t\t\t",
            "Walk\tpatch\t\t\t\t\t\t\tWalk off\t\t\t",
            "Walk off\tpatch-off\t\t\t\t\t\t\t\t\t\t",
            "Gone\tunresolved\t\t\t\t\t\t\t\t\tno anchor\t",
            "Keep HP\tpatch\t\tu16\tnever-decrease\t\t\t\t\t\t\t0:0x10",
        ].joined(separator: "\n") + "\n"
        let cheats = parse("""
        [Set money]
        04000000 00000001 00000001
        [Walk]
        04000000 00000002 00000002
        [Walk off]
        04000000 00000003 00000003
        [Keep HP]
        [Fast on]
        04000000 00000004 00000004
        [Fast off]
        04000000 00000005 00000005
        """, meta: meta)
        XCTAssertEqual(cheats.map(\.name), ["Set money", "Walk", "Walk off", "Keep HP", "Fast on", "Fast off"])
        XCTAssertEqual(cheats.map(\.once), [true, false, false, false, false, false])
        XCTAssertEqual(cheats.map(\.pairOff), [false, false, true, false, false, true], "one switch for a pair: the on half's, also by the 'X on' / 'X off' names")
        XCTAssertEqual(cheats[3].kind, .cheat, "a typed address held by name only runs as a never-decrease cheat, not a label")
        XCTAssertEqual(cheats[0].section, "Stats")
        XCTAssertEqual(cheats.map(\.switchable), [false, true, false, true, true, false])
    }

    // ---- the switches: <build ID>.enabled ----

    func testEnabledIsOneKeyPerLineInFileOrderWithoutMastersLabelsOrOnePassCheats() {
        let cheats = parse("[Intro]\n{Master}\n04000000 00000001 00000001\n[B]\n04000000 00000002 00000002\n[A]\n04000000 00000003 00000003\n[A]\n04000000 00000004 00000004\n")
        XCTAssertEqual(CheatFiles.enabledText(cheats, on: ["A #2", "B", "Master", "Intro", "Ghost"]), "B\nA #2\n")
        XCTAssertEqual(CheatFiles.enabledText(cheats, on: []), "")
        XCTAssertEqual(CheatFiles.parseEnabled("B\r\nA #2\n\n"), ["B", "A #2"])
    }

    func testWritingTheSwitchesLeavesNoTemporaryFileAndTheFolderIsMadeWhenMissing() throws {
        let cheats = parse("[A]\n04000000 00000001 00000001\n[B]\n04000000 00000002 00000002\n")
        XCTAssertFalse(fm.fileExists(atPath: files.folder.path))
        try files.writeEnabled(build, cheats: cheats, on: ["B"])
        XCTAssertEqual(try String(contentsOf: files.enabledFile(build), encoding: .utf8), "B\n")
        XCTAssertEqual(files.enabled(build), ["B"])
        try files.writeEnabled(build, cheats: cheats, on: ["A", "B"])
        XCTAssertEqual(try String(contentsOf: files.enabledFile(build), encoding: .utf8), "A\nB\n")
        try files.writeEnabled(build, cheats: cheats, on: [])
        XCTAssertEqual(try String(contentsOf: files.enabledFile(build), encoding: .utf8), "", "all off is an empty file, as the host writes it")
        XCTAssertEqual(try fm.contentsOfDirectory(atPath: files.folder.path), [build + ".enabled"])
        XCTAssertEqual(files.enabled("1111111111111111"), [], "no file: nothing is on")
    }

    func testTheMasterSwitchIsTheFlagFileOfTheGame() throws {
        XCTAssertTrue(files.masterOn)
        try files.setMaster(false)
        XCTAssertEqual(try fm.contentsOfDirectory(atPath: files.folder.path), [".cheats-off-\(titleID)"])
        XCTAssertFalse(files.masterOn)
        try files.setMaster(false)   // twice is fine
        try files.setMaster(true)
        XCTAssertTrue(files.masterOn)
        try files.setMaster(true)
        XCTAssertEqual(try fm.contentsOfDirectory(atPath: files.folder.path), [])
    }

    func testSafeModeIsOnlyReadNeverWritten() throws {
        XCTAssertFalse(files.safeMode)
        try write(build + "\n", ".cheats-running-\(titleID)")
        XCTAssertTrue(files.safeMode)
    }

    // ---- importing ----

    func testAnSDCardsCheatsFolderComesInAsFlatFilesInUpperCase() throws {
        let card = temporary.appendingPathComponent("SD")
        try write("[A]\n00000000\n", "atmosphere/contents/\(titleID)/cheats/cd57b23fa4bbad65.txt", under: card)
        try write("[B]\n00000000\n", "atmosphere/contents/\(titleID)/cheats/1111111111111111.txt", under: card)
        try write("[Other game]\n00000000\n", "atmosphere/contents/0100000000010000/cheats/3333333333333333.txt", under: card)
        try write("x", "atmosphere/contents/\(titleID)/exefs.txt", under: card)
        let result = try files.importFiles(from: [card])
        XCTAssertEqual(Set(result.imported), [build, "1111111111111111"], "another game's folder on the card stays out")
        XCTAssertEqual(result.skipped, ["exefs.txt"], "no build ID in the name")
        XCTAssertEqual(try fm.contentsOfDirectory(atPath: files.folder.path).sorted(), ["1111111111111111.txt", build + ".txt"])
        XCTAssertEqual(try String(contentsOf: files.folder.appendingPathComponent(build + ".txt"), encoding: .utf8), "[A]\n00000000\n")
    }

    func testARyujinxFolderWithTheGamesTitleIDAndA32DigitName() throws {
        let ryujinx = temporary.appendingPathComponent("mods")
        try write("[A]\n00000000\n", "contents/\(titleID.lowercased())/cheats/cd57b23fa4bbad65803d9788c01821ee.txt", under: ryujinx)
        let result = try files.importFiles(from: [ryujinx])
        XCTAssertEqual(result.imported, [build], "cut to the 16 digits the host names the file by")
        XCTAssertEqual(files.found().map(\.buildID), [build])
    }

    func testSingleFilesAreImportedAsTheyAreAndAnotherNameIsSkipped() throws {
        let one = try write("[A]\n00000000\n", "drop/\(build).txt", under: temporary)
        let named = try write("[A]\n00000000\n", "drop/cheats.txt", under: temporary)
        let result = try files.importFiles(from: [one, named])
        XCTAssertEqual(result, CheatFiles.ImportResult(imported: [build], skipped: ["cheats.txt"]))
    }

    func testImportingAgainReplacesTheFileAndKeepsTheSwitches() throws {
        let one = try write("[A]\n00000000\n", "drop/\(build).txt", under: temporary)
        _ = try files.importFiles(from: [one])
        try files.writeEnabled(build, cheats: parse("[A]\n04000000 00000001 00000001\n"), on: ["A"])
        try Data("[A]\n04000000 00000001 00000002\n".utf8).write(to: one)
        _ = try files.importFiles(from: [one])
        XCTAssertEqual(try String(contentsOf: files.folder.appendingPathComponent(build + ".txt"), encoding: .utf8), "[A]\n04000000 00000001 00000002\n")
        XCTAssertEqual(files.enabled(build), ["A"])
        let inPlace = try files.importFiles(from: [files.folder])
        XCTAssertEqual(inPlace.imported, [build], "the folder itself: nothing to copy, nothing lost")
        XCTAssertEqual(try String(contentsOf: files.folder.appendingPathComponent(build + ".txt"), encoding: .utf8), "[A]\n04000000 00000001 00000002\n")
    }

    func testTheMetaFileComesAlongAndAStaleOneGoesWithTheFileItDescribed() throws {
        let withMeta = try write("[A]\n04000000 00000001 00000001\n", "a/\(build).txt", under: temporary)
        try write("name\tkind\nA\tpatch\n", "a/\(build).meta.tsv", under: temporary)
        let without = try write("[A]\n04000000 00000001 00000002\n", "b/\(build).txt", under: temporary)
        let first = try files.importFiles(from: [withMeta])
        XCTAssertEqual(first.imported, [build])
        XCTAssertTrue(fm.fileExists(atPath: files.metaFile(build).path))
        _ = try files.importFiles(from: [without])
        XCTAssertFalse(fm.fileExists(atPath: files.metaFile(build).path), "the new file has no meta file: the old one no longer describes it")
    }

    func testNothingUsableImportsNothing() throws {
        let empty = temporary.appendingPathComponent("empty")
        try fm.createDirectory(at: empty, withIntermediateDirectories: true)
        XCTAssertEqual(try files.importFiles(from: [empty, temporary.appendingPathComponent("missing")]), CheatFiles.ImportResult())
        XCTAssertFalse(fm.fileExists(atPath: files.folder.path), "nothing came in: the folder is not made")
    }

    func testTheImportMessageSaysWhatCameInAndWhatDidNot() {
        let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build; m.lang = .en
        XCTAssertEqual(CheatsView.importMessage(.init(imported: ["A", "B"]), loc: mStores.localizer).0, "Files imported: 2.")
        XCTAssertTrue(CheatsView.importMessage(.init(imported: ["A"], skipped: ["x.txt"]), loc: mStores.localizer).0.contains("x.txt"))
        XCTAssertFalse(CheatsView.importMessage(.init(), loc: mStores.localizer).1)
        XCTAssertTrue(CheatsView.importMessage(.init(imported: ["A"]), loc: mStores.localizer).1)
    }

    // ---- the copy to the device ----

    private func transfer(_ run: @escaping ([String]) -> (ok: Bool, output: String)) -> CheatTransfer {
        CheatTransfer(files: files, device: "00008150-AAAA", bundle: "com.example.game", devicectl: DeviceControl(run: run), scratch: temporary)
    }

    func testTheFolderGoesToTheDevicesGameFolderWithoutTheSafeModeFlag() throws {
        try write("[A]\n00000000\n", "\(build).txt")
        try write("A\n", "\(build).enabled")
        try write("x", ".cheats-off-\(titleID)")
        try write("x", ".cheats-running-\(titleID)")
        try write("x", "\(build).enabled.tmp")
        var seen: [String] = [], args: [String] = []
        let t = transfer { a in
            args = a
            let source = a[a.firstIndex(of: "--source")! + 1]
            seen = ((try? FileManager.default.contentsOfDirectory(atPath: source)) ?? []).sorted()
            XCTAssertEqual(URL(fileURLWithPath: source).lastPathComponent, "cheats")
            return (true, "")
        }
        try t.toDevice()
        XCTAssertEqual(seen, [".cheats-off-\(titleID)", "\(build).enabled", "\(build).txt"])
        XCTAssertEqual(args.first, "device")
        XCTAssertEqual(args[args.firstIndex(of: "--destination")! + 1], "Documents/games/\(titleID)/cheats")
        XCTAssertEqual(args[args.firstIndex(of: "--domain-identifier")! + 1], "com.example.game")
        XCTAssertEqual(args[args.firstIndex(of: "--domain-type")! + 1], "appDataContainer")
        XCTAssertFalse(args.contains("--remove-existing-content"), "devicectl's flag also deletes the destination's siblings (#250)")
        XCTAssertEqual(args[args.firstIndex(of: "--device")! + 1], "00008150-AAAA")
        XCTAssertEqual(try fm.contentsOfDirectory(atPath: temporary.path).filter { $0.hasPrefix("nxnative-cheats-") }, [], "the staged copy is removed")
    }

    /// #250: the cheats push must leave the game's romfs.img, aoc/ and save beside the cheats folder on the device.
    func testTheCheatsPushLeavesTheGameDataBesideIt() throws {
        try write("[A]\n00000000\n", "\(build).txt")
        let device = SaveTransferTests.FakeDevice(temporary.appendingPathComponent("container"))
        let game = device.container.appendingPathComponent("Documents/games/\(titleID)")
        for (name, text) in [("romfs.img", "img"), ("aoc/a.bin", "dlc"), ("save/data.bin", "save"), ("cheats/old.txt", "old")] {
            let url = game.appendingPathComponent(name)
            try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
            try Data(text.utf8).write(to: url)
        }
        try CheatTransfer(files: files, device: "00008150-AAAA", bundle: "com.example.game", devicectl: device.control, scratch: temporary).toDevice()
        func read(_ n: String) -> String? { (try? Data(contentsOf: game.appendingPathComponent(n))).map { String(decoding: $0, as: UTF8.self) } }
        XCTAssertEqual(read("romfs.img"), "img")
        XCTAssertEqual(read("aoc/a.bin"), "dlc")
        XCTAssertEqual(read("save/data.bin"), "save")
        XCTAssertNotNil(read("cheats/\(build).txt"))
        XCTAssertFalse(device.calls.contains { $0.contains("--remove-existing-content") })
    }

    func testAFailedCopyNamesDevicectlsLastLineAndAnEmptyFolderIsRefused() throws {
        XCTAssertThrowsError(try transfer { _ in (true, "") }.toDevice()) { XCTAssertEqual($0 as? CheatTransfer.Failure, .noFiles) }
        try write("[A]\n00000000\n", "\(build).txt")
        let t = transfer { _ in (false, "Starting\nERROR: The device is not connected. (error 4)\n") }
        XCTAssertThrowsError(try t.toDevice()) { XCTAssertEqual($0 as? CheatTransfer.Failure, .device("ERROR: The device is not connected. (error 4)")) }
    }

    func testTheSwitchesTheAtmosphereTreeCarriesCopyToo() throws {
        try write("[A]\n00000000\n", "atmosphere/contents/\(titleID)/cheats/\(build).txt")
        var seen: [String] = []
        try transfer { a in seen = ((try? FileManager.default.contentsOfDirectory(atPath: a[a.firstIndex(of: "--source")! + 1])) ?? []); return (true, "") }.toDevice()
        XCTAssertEqual(seen, ["atmosphere"])
    }

    // ---- the strings ----

    func testEveryCheatsStringHasAllThreeLanguagesNoSemicolonAndTheSameFormats() throws {
        let keys = L10n.table.keys.filter { $0.hasPrefix("cheats.") }
        XCTAssertGreaterThan(keys.count, 25)
        func formats(_ s: String) -> [String] {
            (try? NSRegularExpression(pattern: "%(\\d+\\$)?[@d]"))?.matches(in: s, range: NSRange(s.startIndex..., in: s)).map { String(s[Range($0.range, in: s)!]) } ?? []
        }
        for key in keys {
            let zh = L10n.string(key, .zh), en = L10n.string(key, .en), sv = L10n.string(key, .sv)
            XCTAssertNotNil(L10n.sv[key], "\(key) has no Swedish text")
            XCTAssertNotEqual(sv, en, "\(key): Swedish is not English")
            for text in [zh, en, sv] {
                XCTAssertFalse(text.contains(";") || text.contains(";"), "\(key) has a semicolon")
                XCTAssertFalse(text.contains("NX2Apple"), "\(key) names the product")
            }
            XCTAssertEqual(formats(zh), formats(en), key)
            XCTAssertEqual(formats(sv), formats(en), key)
        }
    }

    // ---- visual QA (NX_LAUNCHER_CAPTURE_DIR), matched by --filter testRenderCheatsForVisualQA ----

    @MainActor func testRenderCheatsForVisualQA() throws {
        guard let directory = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_DIR"] else { throw XCTSkip("Set NX_LAUNCHER_CAPTURE_DIR to capture native views") }
        let output = URL(fileURLWithPath: directory)
        try fm.createDirectory(at: output, withIntermediateDirectories: true)
        NSApplication.shared.setActivationPolicy(.accessory)
        let game = "01007EF00011E000"
        let app = temporary.appendingPathComponent("Zelda.app")
        for name in ["nxnative", "dmhost"] {
            try fm.createDirectory(at: app.appendingPathComponent("Contents/MacOS"), withIntermediateDirectories: true)
            try fm.createSymbolicLink(at: app.appendingPathComponent("Contents/MacOS/" + name), withDestinationURL: URL(fileURLWithPath: "/usr/bin/true"))
        }
        let info: [String: Any] = ["DMTitleID": game, "CFBundleDisplayName": "The Legend of Zelda: Breath of the Wild", "CFBundleExecutable": "nxnative"]
        try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))
        try write("# BUILD_ID\tcd57b23fa4bbad65803d9788c01821ee\n", "Contents/Resources/dm/main.fixups.tsv", under: app)
        let ios = temporary.appendingPathComponent("DmIOS.app")
        try fm.createDirectory(at: ios, withIntermediateDirectories: true)
        try PropertyListSerialization.data(fromPropertyList: ["CFBundleIdentifier": "com.example.zelda"], format: .xml, options: 0).write(to: ios.appendingPathComponent("Info.plist"))

        let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
        model.lang = .en
        MainActor.assumeIsolated { modelStores.dependencies.checked = true }
        MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }
        let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))
        let id = try library.addApp(app)
        library.recordCompletedIOS(archive: "", app: ios.path, device: "00008150-AAAA", for: id)
        let support = temporary.appendingPathComponent("Application Support")
        let folder = CheatFiles.macFolder(titleID: game, support: support)
        try write("""
        [Cheat Manager]
        {Always unlimited stamina}
        04000000 00000010 00000001
        [--SectionStart:Link--]
        [Infinite health]
        04000000 00000020 00000002
        [Infinite stamina]
        04000000 00000030 00000003
        [Max rupees]
        04000000 00000040 00000004
        [--SectionEnd:Link--]
        [--SectionStart:World--]
        [Walk through walls]
        04000000 00000050 00000005
        [Always sunny]
        04000000 00000060 00000006
        [Broken by hand]
        04000000 00000060 0006 junk
        [--SectionEnd:World--]
        """, "CD57B23FA4BBAD65.txt", under: folder)
        try write("[Other]\n04000000 00000001 00000001\n", "FF773E90972D5440.txt", under: folder)
        try write("Infinite health\nAlways sunny\n", "CD57B23FA4BBAD65.enabled", under: folder)

        func shot(_ name: String, _ view: some View, height: CGFloat = 700) throws {
            let host = NSHostingView(rootView: view.environmentObject(PadFocus()))
            let window = OffscreenWindow(size: NSSize(width: 600, height: height))
            window.contentView = host
            window.orderFront(nil)
            RunLoop.main.run(until: Date().addingTimeInterval(0.6))
            let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
            host.cacheDisplay(in: host.bounds, to: rep)
            try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent(name + ".png"))
            window.orderOut(nil)
        }
        try shot("cheats", CheatsView(m: model, library: library, gameID: id, devicectl: DeviceControl { _ in (true, "") }, support: support).environmentObject(modelStores.localizer))
        try shot("cheats-drop", CheatsView(m: model, library: library, gameID: id, support: support, dropped: true).environmentObject(modelStores.localizer))
        model.lang = .de
        try shot("cheats-de", CheatsView(m: model, library: library, gameID: id, support: support).environmentObject(modelStores.localizer))
        model.lang = .zh
        try shot("cheats-zh", CheatsView(m: model, library: library, gameID: id, support: support).environmentObject(modelStores.localizer))
        model.lang = .en
        try fm.removeItem(at: folder)
        try write("x", ".cheats-running-\(game)", under: folder)
        try shot("cheats-empty", CheatsView(m: model, library: library, gameID: id, support: support).environmentObject(modelStores.localizer))
    }
}

/// Issue #252: an iPhone or iPad game runs data cheats only, so the Cheats sheet carries a note for a game with an iOS build.
@MainActor final class CheatsIOSNoteTests: IsolatedDefaultsTestCase {
    func testNoteShowsOnlyWithAnIOSBuild() throws {
        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-iosnote-" + UUID().uuidString)
        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
        defer { try? FileManager.default.removeItem(at: dir) }
        let ipa = dir.appendingPathComponent("Game.ipa")
        try Data("x".utf8).write(to: ipa)
        let ios = dir.appendingPathComponent("Game.app")
        try FileManager.default.createDirectory(at: ios, withIntermediateDirectories: true)
        try Data("x".utf8).write(to: ios.appendingPathComponent("Info.plist"))

        var game = LibraryGame(titleID: "0100F2C0115B6000", name: "Game", appPath: "/gone/Game.app")
        XCTAssertFalse(game.cheatsNeedIOSNote, "a Mac-only game has no note")
        game.ipaPath = ipa.path
        XCTAssertTrue(game.cheatsNeedIOSNote, "a built IPA gets it")
        game.ipaPath = dir.appendingPathComponent("gone.ipa").path
        XCTAssertFalse(game.cheatsNeedIOSNote, "an IPA that is gone does not")
        game.iosAppPath = ios.path
        game.installedDevice = "device"
        XCTAssertTrue(game.cheatsNeedIOSNote, "a game installed on a device gets it")
    }

    func testNoteIsTranslatedWithoutSemicolons() {
        for lang in [Lang.en, .zh, .sv, .de] {
            let text = L10n.string("cheats.iosNote", lang)
            XCTAssertFalse(text.isEmpty); XCTAssertFalse(text.contains(";")); XCTAssertTrue(text.contains("iPhone"))
            XCTAssertFalse(text.contains("#724"), "data cheats run on the iPhone now, only code cheats are refused there")
        }
        XCTAssertTrue(L10n.string("cheats.iosNote", .en).contains("Mac app"))
    }
}