Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Launcher: a Cheats sheet in the Manage menu (#97)
v0lumehi76b1048a1f85
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex ea04024a..f8e6bf6c 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -255,6 +255,36 @@ TABLE: dict[str, tuple[str, str, str]] = {'saves.noMacSave': ('这台 Mac 上还没有这个游戏的存档。', 'This Mac has no save for this game yet.', 'Den här Mac-datorn har ingen sparfil för spelet ännu.'),'saves.noDeviceSave': ('%@ 上还没有这个游戏的存档。', '%@ has no save for this game yet.', '%@ har ingen sparfil för spelet ännu.'),'saves.failed': ('复制失败:%@', 'Copying failed: %@', 'Kopieringen misslyckades: %@'),+ 'cheats.menu': ('金手指…', 'Cheats…', 'Fusk …'),+ 'cheats.title': ('金手指', 'Cheats', 'Fusk'),+ 'cheats.buildLabel': ('这个游戏版本的构建 ID', 'Build ID of this game', 'Spelets bygg-ID'),+ 'cheats.buildUnknown': ('还不知道。先构建游戏。', 'Not known yet. Build the game first.', 'Inte känt än. Bygg spelet först.'),+ 'cheats.master': ('游戏中运行金手指', 'Run cheats in the game', 'Kör fusk i spelet'),+ 'cheats.safeMode': ('上次运行没有正常退出,所以金手指一开始是关闭的。请在游戏的金手指面板中恢复。', "The last run did not end cleanly, so cheats start off. Restore them in the game's Cheats panel.", 'Senaste körningen avslutades inte rent, så fusket börjar avstängt. Återställ det i spelets fuskpanel.'),+ 'cheats.empty': ('这个游戏还没有金手指。把文件夹或 <构建 ID>.txt 文件拖到这里,或选择“导入…”。', 'No cheats for this game yet. Drop a folder or <build ID>.txt files here, or choose Import…', 'Inget fusk för spelet än. Släpp en mapp eller <bygg-ID>.txt-filer här eller välj Importera …'),+ 'cheats.noBuildFile': ('要开关金手指,需要先知道游戏的构建 ID。先构建游戏。', 'To switch cheats, the build ID of the game has to be known. Build the game first.', 'För att slå på fusk måste spelets bygg-ID vara känt. Bygg spelet först.'),+ 'cheats.noFileForBuild': ('没有适用于构建 %@ 的文件。导入一个以它命名的 .txt 文件。', 'No file for build %@. Import a .txt file named after it.', 'Ingen fil för bygget %@. Importera en .txt-fil med det namnet.'),+ 'cheats.thisBuild': ('此版本', 'This build', 'Det här bygget'),+ 'cheats.otherBuild': ('其他版本', 'Other build', 'Annat bygge'),+ 'cheats.otherHint': ('这个文件属于游戏的另一个构建,不能用于当前构建,所以没有开关。', 'This file is for another build of the game and cannot run on this one, so it has no switches.', 'Den här filen är för ett annat bygge av spelet och kan inte köras på det här, så den har inga reglage.'),+ 'cheats.alwaysOn': ('始终开启', 'Always on', 'Alltid på'),+ 'cheats.broken': ('格式有误,不会运行', 'Malformed, will not run', 'Felformaterad, körs inte'),+ 'cheats.once': ('运行一次,在游戏窗口中使用', 'Runs once, used from the game window', 'Körs en gång, används från spelfönstret'),+ 'cheats.import': ('导入…', 'Import…', 'Importera …'),+ 'cheats.showFolder': ('显示文件夹', 'Show folder', 'Visa mappen'),+ 'cheats.toDevice': ('复制到 %@', 'Copy to %@', 'Kopiera till %@'),+ 'cheats.copying': ('正在复制金手指…', 'Copying the cheats…', 'Kopierar fusket …'),+ 'cheats.copied': ('已复制到 %@。', 'Copied to %@.', 'Kopierat till %@.'),+ 'cheats.copyFailed': ('复制失败:%@', 'Copying failed: %@', 'Kopieringen misslyckades: %@'),+ 'cheats.writeFailed': ('无法写入:%@', 'Could not write: %@', 'Kunde inte skriva: %@'),+ 'cheats.running': ('%@ 正在这台 Mac 上运行。改动要在游戏里选择“Reload cheats”(⌘R)或下次启动后才生效。', '%@ is running on this Mac. A change takes effect after Reload cheats (⌘R) in the game, or at the next start.', '%@ körs på den här Mac-datorn. En ändring gäller efter Reload cheats (⌘R) i spelet eller vid nästa start.'),+ 'cheats.imported': ('已导入的文件:%d。', 'Files imported: %d.', 'Importerade filer: %d.'),+ 'cheats.notNamed': ('没有导入(名称里没有构建 ID):%@。', 'Not imported (no build ID in the name): %@.', 'Inte importerade (inget bygg-ID i namnet): %@.'),+ 'cheats.nothingFound': ('那里没有找到这个游戏的 <构建 ID>.txt 文件。', 'No <build ID>.txt file for this game was found there.', 'Ingen <bygg-ID>.txt-fil för spelet hittades där.'),+ 'cheats.pickMessage': ('选择 Ryujinx 的金手指文件夹、SD 卡(atmosphere/contents/<title ID>/cheats)或 <构建 ID>.txt 文件', 'Choose a Ryujinx cheats folder, an SD card (atmosphere/contents/<title ID>/cheats) or <build ID>.txt files', 'Välj en Ryujinx-mapp med fusk, ett SD-kort (atmosphere/contents/<titel-id>/cheats) eller <bygg-ID>.txt-filer'),+ 'cheats.dropHint': ('松开以导入金手指', 'Drop to import cheats', 'Släpp för att importera fusk'),+ 'cheats.note': ('开关会立即保存,游戏下次启动时生效。', 'Switches are saved at once and apply the next time the game starts.', 'Reglagen sparas direkt och gäller nästa gång spelet startas.'),+ 'cheats.noteDevice': ('更改后请再次复制到 %@。', 'Copy to %@ again after a change.', 'Kopiera till %@ igen efter en ändring.'),'pad.manage': ('管理', 'Manage', 'Hantera'),'dev.signStage': ('为 %@ 签名', 'Sign for %@', 'Signerar för %@'),'dev.installStage': ('安装到 %@', 'Install on %@', 'Installerar på %@'),diff --git a/frontend/README.md b/frontend/README.mdindex 1bf79d8c..24a37320 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -111,6 +111,30 @@ copy later. The device side uses the install's route: `devicectl device info filthe date and `devicectl device copy from` / `copy to` with the app's data container. Onlya game installed from here has a known bundle ID, so a sideloaded IPA has no device side.+## Cheats++**Manage > Cheats…** manages a game's cheat files, the contract that `docs/frontends.md` ("Cheats") describes and+the host reads (`dm/host/hle_cheats.c`, carried here from [seedds/nxnative#406](https://github.com/seedds/nxnative/pull/406)+while it is open). The files live in `~/Library/Application Support/nxnative/<title ID>/cheats`, which is what the Mac+app's launcher (`dm/mac/launcher.c`) sets `DM_ROOT` to, whatever the library folder is.++- **Import** by dropping onto the sheet or **Import…**: a Ryujinx folder, an SD card's `atmosphere/contents/<title ID>/cheats`+ (or the card itself, where another game's folder is left out), or single `<build ID>.txt` files. Each comes in as+ `<build ID>.txt` in upper case, replacing an older file of that build, with the `.meta.tsv` of `scripts/cheat_anchor.py`+ beside it when there is one. A file whose name carries no build ID is reported, since it cannot be matched to a version.+- **Switches.** The sheet names the build ID the game uses (`# BUILD_ID` in the app's `dm/main.fixups.tsv`, the first 16 digits)+ and marks the file for it. Files for other builds are listed dimmed without switches. Each cheat of this build's file has a+ switch, written at once to `<build ID>.enabled` (one name per line, `Name #2` for a duplicate, never masters, labels,+ one-pass cheats or the off half of an on / off pair), the file the game's own Cheats panel reads and writes. **Run cheats+ in the game** is the master switch (the flag file `.cheats-off-<title ID>`).+- **iPhone / iPad.** For a game installed from here, **Copy to iPhone** replaces the app's `Documents/games/<title ID>/cheats`+ with this folder over the install's route (`devicectl device copy to`, as the Saves sheet does), without the Mac's+ safe-mode flag. The iOS app points `DM_CHEATS` at that folder (fork patch `ios-game-data-folder`), so copy again after a+ change.++The host reads the files when the game starts, or on its Reload cheats (⌘R) on the Mac, and never watches the folder. So a+change while the game runs applies after a reload, and the sheet says so. Live switching from the launcher is not part of it.+## Your games folderSet **Your games folder** in Settings once. The launcher remembers it, checks itdiff --git a/frontend/Sources/NSPortBuilder/CheatFiles.swift b/frontend/Sources/NSPortBuilder/CheatFiles.swiftnew file mode 100644index 00000000..275d7ebe--- /dev/null+++ b/frontend/Sources/NSPortBuilder/CheatFiles.swift@@ -0,0 +1,412 @@+import Foundation++/// A game's cheat files, as the host reads them (dm/host/hle_cheats.c, and docs/frontends.md "Cheats", the contract for front+/// ends): Atmosphere-format `<build ID>.txt` files in a folder, and the player's switches beside them in `<build ID>.enabled`.+/// This file holds the logic only (where the folder is, which build the game is, how a cheat file reads, importing, the switches,+/// the copy to a device), so the sheet (CheatsView.swift) stays a view and the tests need no window.+///+/// The folder: `DM_CHEATS`, else `<DM_ROOT>/cheats`. The Mac app's launcher (dm/mac/launcher.c) sets DM_ROOT to+/// ~/Library/Application Support/nxnative/<title ID> whatever the library folder is, so the files live in+/// `<that>/cheats`. The iPhone app's `main.m` (fork patch ios-game-data-folder) sets DM_CHEATS to+/// `Documents/games/<title ID>/cheats`, next to the game's data, which is where the copy to the device goes.+struct CheatFiles {+ let titleID: String // upper case+ let folder: URL // the game's cheats folder on this Mac++ /// A cheat file found in the folder.+ struct Found: Equatable, Identifiable {+ let buildID: String // 16 hex digits, upper case+ let url: URL+ var id: String { buildID }+ }++ /// One entry of a cheat file, the way the host parses it (parse_file).+ struct Cheat: Equatable, Identifiable {+ enum Kind: Equatable { case cheat, master, label }+ var name: String+ var key: String // the name in `.enabled`: `Name`, `Name #2` for the second entry of that name+ var kind: Kind+ var section = ""+ var broken = false // a malformed line: the host keeps the cheat off+ var once = false // runs one pass, set from the game window (the meta file): never in `.enabled`+ var pairOff = false // the off half of an on / off pair: the on half carries the switch+ var id: String { key }+ /// Does it get a switch here: a plain cheat that the host would save as on.+ var switchable: Bool { kind == .cheat && !broken && !once && !pairOff }+ }++ init(titleID: String, folder: URL) {+ self.titleID = titleID.uppercased()+ self.folder = folder+ }++ init(titleID: String, support: URL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]) {+ self.init(titleID: titleID, folder: Self.macFolder(titleID: titleID, support: support))+ }++ // ---- where things are ----++ /// The Mac app's cheats folder: DM_ROOT/cheats with DM_ROOT as dm/mac/launcher.c sets it.+ static func macFolder(titleID: String, support: URL) -> URL {+ support.appendingPathComponent("nxnative").appendingPathComponent(titleID.uppercased()).appendingPathComponent("cheats")+ }++ /// The folder in the iPhone app's data container, where main.m points DM_CHEATS.+ static func deviceFolder(titleID: String) -> String { "Documents/games/\(titleID.uppercased())/cheats" }++ /// The build ID the cheat files are named by: the first 16 hex digits of the main NSO's build ID, upper case. The packed app+ /// records the whole ID in `dm/main.fixups.tsv` (`# BUILD_ID <hex>`): the Mac app under Contents/Resources, the iOS app at its root.+ static func buildID(appPath: String, iosAppPath: String) -> String? {+ let candidates = [appPath.isEmpty ? nil : appPath + "/Contents/Resources/dm/main.fixups.tsv",+ iosAppPath.isEmpty ? nil : iosAppPath + "/dm/main.fixups.tsv"]+ for path in candidates.compactMap({ $0 }) {+ guard let text = try? String(contentsOfFile: path, encoding: .utf8), let id = buildID(fixups: text) else { continue }+ return id+ }+ return nil+ }++ static func buildID(fixups text: String) -> String? {+ for line in text.split(whereSeparator: \.isNewline) where line.hasPrefix("#") {+ let fields = line.dropFirst().split(whereSeparator: { $0 == " " || $0 == "\t" })+ guard fields.count >= 2, fields[0] == "BUILD_ID", fields[1].count >= 16, isHex(fields[1].prefix(16)) else { continue }+ return fields[1].prefix(16).uppercased()+ }+ return nil+ }++ static func isHex<S: StringProtocol>(_ s: S) -> Bool { !s.isEmpty && s.allSatisfy(\.isHexDigit) }++ /// The folders the host scans for `<build ID>.txt`, in its order (scan_dirs): the flat folder, the Atmosphere tree under it,+ /// and the tree with the folder itself as the "atmosphere" half.+ var scanFolders: [URL] {+ [folder,+ folder.appendingPathComponent("atmosphere/contents/\(titleID)/cheats"),+ folder.appendingPathComponent("contents/\(titleID)/cheats")]+ }++ func enabledFile(_ buildID: String) -> URL { folder.appendingPathComponent(buildID.uppercased() + ".enabled") }+ func metaFile(_ buildID: String) -> URL { folder.appendingPathComponent(buildID.uppercased() + ".meta.tsv") }+ /// The master switch: while this file exists no cheat of the game runs, the switches kept.+ var masterOffFile: URL { folder.appendingPathComponent(".cheats-off-\(titleID)") }+ /// The host's own safe-mode flag (Mac only): a front end leaves it alone, and may say what it means.+ var runningFlag: URL { folder.appendingPathComponent(".cheats-running-\(titleID)") }++ // ---- the files ----++ /// The cheat files in the folder, one per build, in the host's order (the first of a build wins), by build ID. A file counts when+ /// its name starts with 16 hex digits and ends in .txt (collect_dir, name_hex16).+ func found() -> [Found] {+ var seen = Set<String>(), out: [Found] = []+ for dir in scanFolders {+ let names = ((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? []).sorted()+ for name in names where name.count >= 5 && name.lowercased().hasSuffix(".txt") && Self.isHex(name.prefix(16)) && name.count >= 16 {+ let id = name.prefix(16).uppercased()+ guard seen.insert(id).inserted else { continue }+ out.append(Found(buildID: id, url: dir.appendingPathComponent(name)))+ }+ }+ return out.sorted { $0.buildID < $1.buildID }+ }++ /// The cheats of a build's file with the meta file applied, nil when the file cannot be read.+ func cheats(of file: Found) -> [Cheat]? {+ guard let data = try? Data(contentsOf: file.url) else { return nil }+ let metaURL = file.url.deletingPathExtension().appendingPathExtension("meta.tsv")+ let meta = (try? String(contentsOf: metaURL, encoding: .utf8)) ?? (try? String(contentsOf: metaFile(file.buildID), encoding: .utf8))+ return Self.parse(data, meta: meta)+ }++ // ---- the switches ----++ /// `<build ID>.enabled`: one key per line. Missing or unreadable: nothing is on.+ func enabled(_ buildID: String) -> Set<String> {+ guard let text = try? String(contentsOf: enabledFile(buildID), encoding: .utf8) else { return [] }+ return Self.parseEnabled(text)+ }++ static func parseEnabled(_ text: String) -> Set<String> {+ Set(text.split(whereSeparator: \.isNewline).map(String.init)) // "\r\n" is one Character in Swift: isNewline, not == "\n"+ }++ /// The file's text for the switches that are on: the keys of the plain cheats in the file's own order, as the host writes it+ /// (masters are always on, labels never run, one-pass cheats and the off half of a pair are never listed).+ static func enabledText(_ cheats: [Cheat], on: Set<String>) -> String {+ cheats.filter { $0.switchable && on.contains($0.key) }.map { $0.key + "\n" }.joined()+ }++ /// Writes `<build ID>.enabled` with the keys that are on, through a temporary file that replaces the old one, so it is never half+ /// written. The folder is made when it is missing.+ func writeEnabled(_ buildID: String, cheats: [Cheat], on: Set<String>) throws {+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ try Data(Self.enabledText(cheats, on: on).utf8).write(to: enabledFile(buildID), options: .atomic)+ }++ var masterOn: Bool { !FileManager.default.fileExists(atPath: masterOffFile.path) }++ func setMaster(_ on: Bool) throws {+ if on { if !masterOn { try FileManager.default.removeItem(at: masterOffFile) } }+ else {+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ try Data().write(to: masterOffFile)+ }+ }++ /// The last run ended with cheats on and without a clean exit: the game starts with every cheat off until its panel restores them.+ var safeMode: Bool { FileManager.default.fileExists(atPath: runningFlag.path) }++ // ---- reading a cheat file (parse_file) ----++ private struct Entry { var cheat: Cheat; var words = 0; var junk = false; var pairName = ""; var offByMeta = false; var nd = false }++ private static let nameMax = 127 // characters of a [Name] header the host keeps (NAME_MAX 128 with its terminator)+ private static let cheatMax = 256 // cheats in one file: the host skips the rest++ /// Entries as the host parses them: `[Name]` and `{Name}` start one, 8-digit hex words are its code, and a header glued to a+ /// word ("00000008[Next]") is split off. An entry without code words is a label (credits, an EdiZon section marker that sets+ /// the section of the entries after it). A line mixing words with other text, or a hex token that is not whole words, keeps+ /// its cheat off (broken). The meta file of scripts/cheat_anchor.py then marks one-pass cheats and on / off pairs.+ static func parse(_ data: Data, meta: String? = nil) -> [Cheat] {+ let raw = [UInt8](data)+ func ws(_ c: UInt8) -> Bool { c == 0x20 || c == 0x09 || c == 0x0A || c == 0x0D }+ func hex(_ c: UInt8) -> Bool { (c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66) }+ var text: [UInt8] = []+ text.reserveCapacity(raw.count * 2)+ for (i, c) in raw.enumerated() {+ if (c == 0x5B || c == 0x7B) && i >= 8, raw[(i - 8)..<i].allSatisfy(hex), i == 8 || ws(raw[i - 9]) { text.append(0x0B) }+ text.append(c)+ }++ var entries: [Entry] = []+ var section = ""+ for piece in text.split(omittingEmptySubsequences: false, whereSeparator: { $0 == 0x0A || $0 == 0x0B }) {+ var p = piece[...]+ while let f = p.first, f == 0x20 || f == 0x09 { p = p.dropFirst() }+ var rest = p+ if let f = p.first, f == 0x5B || f == 0x7B {+ let end: UInt8 = f == 0x5B ? 0x5D : 0x7D+ guard let q = p.dropFirst().firstIndex(of: end), q > p.startIndex + 1, entries.count < cheatMax else {+ // an unclosed or empty header, or past the limit: the entry is skipped, and its lines belong to nothing+ entries.append(Entry(cheat: Cheat(name: "", key: "", kind: .label), words: -1))+ continue+ }+ var keep = min(q - (p.startIndex + 1), nameMax)+ while keep > 0, (p[p.startIndex + 1 + keep] & 0xC0) == 0x80 { keep -= 1 }+ let name = String(decoding: p[(p.startIndex + 1)..<(p.startIndex + 1 + keep)], as: UTF8.self)+ var cheat = Cheat(name: name, key: name, kind: f == 0x7B ? .master : .cheat)+ let mark = sectionMarker(name)+ if let m = mark, m.start { section = m.name }+ cheat.section = section+ if let m = mark, !m.start { section = "" }+ let earlier = entries.filter { $0.words >= 0 && $0.cheat.name == name }.count+ if earlier > 0 { cheat.key = "\(name) #\(earlier + 1)" }+ entries.append(Entry(cheat: cheat))+ rest = p[(q + 1)...]+ while let r = rest.first, r == 0x20 || r == 0x09 || r == 0x0D { rest = rest.dropFirst() }+ if rest.isEmpty { continue }+ }+ guard var current = entries.last, current.words >= 0 else { continue } // words before any header, or after a skipped one+ var ngot = 0, prose = false, oddhex = false+ for token in rest.split(whereSeparator: { $0 == 0x20 || $0 == 0x09 || $0 == 0x0D }) {+ if !token.allSatisfy(hex) { prose = true; continue }+ if token.count % 8 != 0 { oddhex = true; continue }+ ngot += token.count / 8+ }+ if ngot == 0 && !prose && !oddhex { continue }+ if prose && ngot == 0 && !oddhex { current.junk = true }+ else if prose || oddhex { current.cheat.broken = true }+ else { current.words += ngot }+ entries[entries.count - 1] = current+ }+ entries.removeAll { $0.words < 0 }++ for i in entries.indices where !entries[i].cheat.broken {+ if entries[i].words == 0 && entries[i].junk { entries[i].cheat.broken = true }+ else if entries[i].words == 0 { entries[i].cheat.kind = .label }+ }+ if let meta { applyMeta(meta, to: &entries) }+ return entries.map(\.cheat)+ }+++ private static func applyMeta(_ meta: String, to entries: inout [Entry]) {+ var head: [String: Int]?+ var cursor = 0+ for line in meta.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) where !line.hasPrefix("#") && !line.isEmpty {+ let f = line.split(separator: "\t", omittingEmptySubsequences: false).map(String.init)+ guard let h = head else {+ var map: [String: Int] = [:]+ for (i, n) in f.enumerated() { map[n] = i }+ if map["name"] == nil { return }+ head = map+ continue+ }+ func col(_ n: String) -> String { h[n].flatMap { $0 < f.count ? f[$0] : nil } ?? "" }+ let kind = col("kind")+ if kind == "unresolved" { continue }+ var j = cursor+ while j < entries.count && entries[j].cheat.name != col("name") { j += 1 }+ if j >= entries.count { continue }+ cursor = j + 1+ if !col("section").isEmpty && entries[j].cheat.section.isEmpty { entries[j].cheat.section = col("section") }+ if col("once") == "1" { entries[j].cheat.once = true }+ if kind == "patch-off" { entries[j].offByMeta = true }+ entries[j].pairName = col("pair")+ // a typed address held by name only (no code words): the host runs it as a never-decrease cheat, not a label+ let address = col("address"), type = col("type")+ if col("action") == "never-decrease", entries[j].words == 0, !type.isEmpty, let colon = address.firstIndex(of: ":"),+ (Int(address[..<colon]) ?? 0) <= 1 {+ entries[j].nd = true+ entries[j].cheat.kind = .cheat+ }+ }+ linkPairs(&entries)+ }++ private static func linkPairs(_ entries: inout [Entry]) {+ var pair = [Int?](repeating: nil, count: entries.count)+ func plain(_ e: Entry) -> Bool { e.cheat.kind == .cheat && !e.nd && !e.cheat.broken }+ for i in entries.indices where !entries[i].pairName.isEmpty && pair[i] == nil && plain(entries[i]) {+ guard let j = entries.indices.first(where: { $0 != i && pair[$0] == nil && plain(entries[$0]) && entries[$0].cheat.name == entries[i].pairName }) else { continue }+ pair[i] = j; pair[j] = i+ }+ for i in entries.indices where pair[i] == nil && plain(entries[i]) {+ guard let a = onOffSplit(entries[i].cheat.name) else { continue }+ for j in (i + 1)..<max(entries.count, i + 1) where pair[j] == nil && plain(entries[j]) {+ guard let b = onOffSplit(entries[j].cheat.name), a.off != b.off, a.base.lowercased() == b.base.lowercased() else { continue }+ pair[i] = j; pair[j] = i+ entries[i].offByMeta = a.off; entries[j].offByMeta = b.off+ break+ }+ }+ for i in entries.indices where pair[i] != nil && entries[i].offByMeta { entries[i].cheat.pairOff = true }+ }++ /// `[--SectionStart:Name--]` and `[--SectionEnd:Name--]`, EdiZon's markers.+ private static func sectionMarker(_ name: String) -> (start: Bool, name: String)? {+ guard name.count >= 4, name.hasSuffix("--") else { return nil }+ for (prefix, start) in [("--SectionStart:", true), ("--SectionEnd:", false)] where name.hasPrefix(prefix) {+ return (start, String(name.dropFirst(prefix.count).dropLast(2)))+ }+ return nil+ }++ /// "X - on" / "X - off" (also "X on", "X: off", "X (off)"): the base name and which half, nil when the name has no such form+ /// (onoff_split).+ private static func onOffSplit(_ name: String) -> (base: String, off: Bool)? {+ var s = Substring(name)+ while let l = s.last, l.isWhitespace { s = s.dropLast() }+ if let l = s.last, l == ")" || l == "]" { s = s.dropLast() }+ let off: Bool+ if s.count >= 3, s.suffix(3).lowercased() == "off" { off = true; s = s.dropLast(3) }+ else if s.count >= 2, s.suffix(2).lowercased() == "on" { off = false; s = s.dropLast(2) }+ else { return nil }+ var sep = false+ while let l = s.last, " -:_([".contains(l) { s = s.dropLast(); sep = true }+ guard sep, !s.isEmpty else { return nil }+ return (String(s), off)+ }++ // ---- importing ----++ struct ImportResult: Equatable {+ var imported: [String] = [] // build IDs of the files now in the folder+ var skipped: [String] = [] // file names that carry no build ID, so no version of the game to match+ }++ /// The build ID a cheat file's name carries: `<16 hex>.txt`, or the 32 digits a build ID is written with elsewhere (cut to 16,+ /// the way cheat sites and Atmosphere name the file). Nil for any other name.+ static func buildID(ofFileNamed name: String) -> String? {+ guard name.lowercased().hasSuffix(".txt") else { return nil }+ let stem = String(name.dropLast(4))+ guard isHex(stem), stem.count == 16 || stem.count == 32 else { return nil }+ return stem.prefix(16).uppercased()+ }++ /// The cheat files under the picked items: files as they are, folders searched (a Ryujinx folder, or an SD card's+ /// `atmosphere/contents/<title ID>/cheats`, or the card itself). Inside a folder, a file under another game's title ID is not+ /// this game's and stays out; hidden files and the folder's own state files are not cheat files.+ func candidates(in urls: [URL]) -> [URL] {+ let fm = FileManager.default+ var out: [URL] = []+ for url in urls {+ var isDir: ObjCBool = false+ guard fm.fileExists(atPath: url.path, isDirectory: &isDir) else { continue }+ guard isDir.boolValue else { out.append(url); continue }+ guard let walk = fm.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { continue }+ for case let file as URL in walk {+ guard file.pathExtension.lowercased() == "txt", (try? file.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true else { continue }+ let below = file.deletingLastPathComponent().pathComponents.dropFirst(url.pathComponents.count)+ let ids = below.filter { $0.count == 16 && Self.isHex($0) }.map { $0.uppercased() }+ if ids.contains(where: { $0 != titleID }) { continue }+ out.append(file)+ }+ }+ return out+ }++ /// Copies the cheat files among the picked items into the folder as `<build ID>.txt` (upper case), replacing an older file of that+ /// build, with the `.meta.tsv` of scripts/cheat_anchor.py beside it when the source has one (a meta file describes its own+ /// `.txt`, so one left from the file just replaced goes). Switches in `.enabled` stay.+ func importFiles(from urls: [URL]) throws -> ImportResult {+ let fm = FileManager.default+ var result = ImportResult()+ for source in candidates(in: urls) {+ guard let id = Self.buildID(ofFileNamed: source.lastPathComponent) else {+ if !source.lastPathComponent.lowercased().hasSuffix(".meta.tsv") { result.skipped.append(source.lastPathComponent) }+ continue+ }+ try fm.createDirectory(at: folder, withIntermediateDirectories: true)+ let target = folder.appendingPathComponent(id + ".txt")+ if source.standardizedFileURL != target.standardizedFileURL { try Data(contentsOf: source).write(to: target, options: .atomic) }+ let sourceMeta = source.deletingPathExtension().appendingPathExtension("meta.tsv")+ if fm.fileExists(atPath: sourceMeta.path) {+ if sourceMeta.standardizedFileURL != metaFile(id).standardizedFileURL { try Data(contentsOf: sourceMeta).write(to: metaFile(id), options: .atomic) }+ } else { try? fm.removeItem(at: metaFile(id)) }+ // the same build's file in the Atmosphere tree would win over a flat one only when the flat is missing: the flat one is picked first+ if !result.imported.contains(id) { result.imported.append(id) }+ }+ return result+ }+}++/// The folder copied to the iPhone or iPad the launcher installed the game on, the way the Saves sheet copies saves+/// (SaveTransfer: `devicectl device copy to` with the app's data container). The device's folder is replaced by the Mac's, so the+/// device holds the same files and switches and nothing older beside them.+struct CheatTransfer {+ let files: CheatFiles+ let device: String // the device's UDID+ let bundle: String // the installed app's bundle ID+ let devicectl: DeviceControl+ var scratch = FileManager.default.temporaryDirectory++ enum Failure: Error, Equatable {+ case noFiles+ case device(String) // devicectl's last line+ }++ var destination: String { CheatFiles.deviceFolder(titleID: files.titleID) }++ /// What goes: the folder's files without the host's safe-mode flag (a Mac-only state) and half-written temporaries.+ func stage() throws -> URL {+ let fm = FileManager.default+ let names = ((try? fm.contentsOfDirectory(atPath: files.folder.path)) ?? []).filter { !$0.hasPrefix(".cheats-running-") && !$0.hasSuffix(".tmp") }+ guard names.contains(where: { $0.lowercased().hasSuffix(".txt") }) || fm.fileExists(atPath: files.folder.appendingPathComponent("atmosphere").path) else { throw Failure.noFiles }+ let dir = scratch.appendingPathComponent("nxnative-cheats-\(UUID().uuidString)").appendingPathComponent("cheats")+ try fm.createDirectory(at: dir, withIntermediateDirectories: true)+ for n in names { try fm.copyItem(at: files.folder.appendingPathComponent(n), to: dir.appendingPathComponent(n)) }+ return dir+ }++ func toDevice() throws {+ let staged = try stage()+ defer { try? FileManager.default.removeItem(at: staged.deletingLastPathComponent()) }+ let r = devicectl.run(Self.copyCommand(device: device, bundle: bundle, source: staged.path, destination: destination))+ guard r.ok else { throw Failure.device(SaveTransfer.lastLine(r.output)) }+ }++ /// The save transfer's copy-to-device command: the destination is the folder itself, and what the Mac does not have goes.+ static func copyCommand(device: String, bundle: String, source: String, destination: String) -> [String] {+ SaveTransfer.copyToCommand(device: device, bundle: bundle, source: source, destination: destination)+ }+}diff --git a/frontend/Sources/NSPortBuilder/CheatsView.swift b/frontend/Sources/NSPortBuilder/CheatsView.swiftnew file mode 100644index 00000000..69df8421--- /dev/null+++ b/frontend/Sources/NSPortBuilder/CheatsView.swift@@ -0,0 +1,328 @@+import AppKit+import SwiftUI++/// The Cheats sheet (#97): a game's cheat files, an on / off switch per cheat, an import by drop or pick, and a copy to the+/// iPhone or iPad the game was installed on. The files and what the switches write are CheatFiles.swift (the contract of+/// docs/frontends.md "Cheats"), so this is only the view. It never touches a running game: the host reads the files when it+/// starts (or on its own Reload cheats).+struct CheatsView: View {+ @ObservedObject var m: BuildModel+ @ObservedObject var library: GameLibrary+ let gameID: UUID+ var devicectl: DeviceControl? = nil // tests and the visual QA hand in a stand-in+ var support: URL? = nil // the Application Support folder; tests use a temporary one+ var dropped = false // the drop highlight drawn from the start (visual QA)+ @Environment(\.dismiss) private var dismiss+ @EnvironmentObject private var focus: PadFocus++ @State private var files: [CheatFiles.Found] = []+ @State private var cheats: [CheatFiles.Cheat] = []+ @State private var on: Set<String> = []+ @State private var master = true+ @State private var safeMode = false+ @State private var busy = false+ @State private var result: (text: String, ok: Bool)?++ private var game: LibraryGame? { library.games.first { $0.id == gameID } }+ private var deviceName: String { game.map { m.deviceName($0.installedDevice) } ?? "iPhone" }++ private var cheatFiles: CheatFiles? {+ guard let game else { return nil }+ return support.map { CheatFiles(titleID: game.titleID, support: $0) } ?? CheatFiles(titleID: game.titleID)+ }++ private var buildID: String? { game.flatMap { CheatFiles.buildID(appPath: $0.appPath, iosAppPath: $0.iosAppPath) } }+ private var current: CheatFiles.Found? { buildID.flatMap { id in files.first { $0.buildID == id } } }+ private var bundle: String { game.flatMap { NSDictionary(contentsOfFile: $0.iosAppPath + "/Info.plist")?["CFBundleIdentifier"] as? String } ?? "" }+ private var canCopy: Bool { !busy && (game?.onDevice ?? false) && !bundle.isEmpty && !files.isEmpty }+ private var shown: [CheatFiles.Cheat] { cheats.filter { !$0.pairOff && !($0.kind == .label && $0.name.isEmpty) } }++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ VStack(alignment: .leading, spacing: 4) {+ Text(m.t("cheats.title")).font(.manrope(26, .heavy)).tracking(-0.6)+ if let game { Text(game.name).font(.manrope(14)).foregroundStyle(.secondary) }+ }+ .padding(.horizontal, 30).padding(.top, 28).padding(.bottom, 16)+ VStack(alignment: .leading, spacing: 14) {+ buildCard+ if files.isEmpty { emptyCard } else { listCard }+ actions+ if busy {+ HStack(spacing: 10) {+ ProgressView().controlSize(.small)+ Text(m.t("cheats.copying")).font(.manrope(13)).foregroundStyle(.secondary)+ }+ } else if let result {+ Label(result.text, systemImage: result.ok ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")+ .font(.manrope(13)).foregroundStyle(result.ok ? LauncherPalette.ready : LauncherPalette.building)+ .fixedSize(horizontal: false, vertical: true)+ }+ }+ .padding(.horizontal, 30)+ Spacer(minLength: 0)+ Divider().opacity(0.3)+ HStack(spacing: 14) {+ Text(m.t("cheats.note") + ((game?.onDevice ?? false) ? " " + String(format: m.t("cheats.noteDevice"), deviceName) : "")).font(.manrope(12)).foregroundStyle(.secondary)+ .lineLimit(3).fixedSize(horizontal: false, vertical: true)+ Spacer(minLength: 8)+ Button { dismiss() } label: {+ Text(m.t("launch.done")).font(.manrope(13.5, .bold)).foregroundStyle(.black)+ .padding(.horizontal, 22).padding(.vertical, 9)+ .background(LauncherPalette.cream, in: Capsule())+ }+ .buttonStyle(.plain).keyboardShortcut(.defaultAction).disabled(busy)+ .padTarget("cheats.done", scope: "cheats", radius: 20) { if !busy { dismiss() } }+ }+ .padding(.horizontal, 30).padding(.vertical, 16)+ }+ .padScope("cheats", focus)+ .frame(width: 600, height: 700)+ .background(LauncherPalette.background)+ .font(.manrope(13))+ .preferredColorScheme(.dark)+ .tint(LauncherPalette.cream)+ .modifier(GameFilesDrop(enabled: !busy, label: m.t("cheats.dropHint"), targeted: dropped) { importPaths($0) })+ .onAppear(perform: refresh)+ }++ // ---- the cards ----++ private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {+ VStack(spacing: 0, content: content)+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))+ }++ /// The build the game is, and the master switch.+ private var buildCard: some View {+ card {+ HStack(spacing: 14) {+ Image(systemName: "number").font(.system(size: 16, weight: .light)).foregroundStyle(.secondary).frame(width: 26)+ VStack(alignment: .leading, spacing: 3) {+ Text(m.t("cheats.buildLabel")).font(.manrope(14, .medium))+ Text(buildID ?? m.t("cheats.buildUnknown")).font(buildID == nil ? .manrope(12) : .system(size: 12.5, design: .monospaced))+ .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }+ Spacer(minLength: 12)+ }+ .padding(.horizontal, 18).padding(.vertical, 11)+ Divider().opacity(0.25).padding(.leading, 18)+ HStack(spacing: 14) {+ Image(systemName: "power").font(.system(size: 16, weight: .light)).foregroundStyle(.secondary).frame(width: 26)+ VStack(alignment: .leading, spacing: 3) {+ Text(m.t("cheats.master")).font(.manrope(14, .medium))+ if safeMode {+ Text(m.t("cheats.safeMode")).font(.manrope(12)).foregroundStyle(LauncherPalette.building).fixedSize(horizontal: false, vertical: true)+ }+ }+ Spacer(minLength: 12)+ Toggle("", isOn: Binding(get: { master }, set: { setMaster($0) })).toggleStyle(CheatSwitchStyle()).labelsHidden()+ .accessibilityLabel(m.t("cheats.master"))+ .padTarget("cheats.master", scope: "cheats") { setMaster(!master) }+ }+ .padding(.horizontal, 18).padding(.vertical, 11)+ }+ }++ private var emptyCard: some View {+ card {+ VStack(spacing: 10) {+ Image(systemName: "square.and.arrow.down").font(.system(size: 26, weight: .light)).foregroundStyle(.secondary)+ Text(m.t("cheats.empty")).font(.manrope(13)).foregroundStyle(.secondary).multilineTextAlignment(.center)+ .fixedSize(horizontal: false, vertical: true)+ }+ .frame(maxWidth: .infinity, minHeight: 150).padding(18)+ }+ }++ /// The files by build, the ones for another build marked, and the cheats of the build the game is.+ private var listCard: some View {+ card {+ ForEach(files) { file in+ fileRow(file)+ Divider().opacity(0.25).padding(.leading, 18)+ }+ if current == nil {+ Text(buildID == nil ? m.t("cheats.noBuildFile") : String(format: m.t("cheats.noFileForBuild"), buildID ?? ""))+ .font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ .padding(.horizontal, 18).padding(.vertical, 14).frame(maxWidth: .infinity, alignment: .leading)+ } else {+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 0) { ForEach(Array(shown.enumerated()), id: \.element.id) { cheatRow($0.element, index: $0.offset) } }+ .padding(.vertical, 4)+ }+ .frame(maxHeight: .infinity)+ }+ }+ }++ private func fileRow(_ file: CheatFiles.Found) -> some View {+ let isCurrent = file.buildID == buildID+ return HStack(spacing: 12) {+ Image(systemName: "doc.text").font(.system(size: 15, weight: .light)).foregroundStyle(.secondary).frame(width: 26)+ Text(file.buildID + ".txt").font(.system(size: 12.5, design: .monospaced))+ Spacer(minLength: 8)+ Text((isCurrent ? m.t("cheats.thisBuild") : m.t("cheats.otherBuild")).uppercased()).font(.manrope(10.5, .bold)).tracking(1.1)+ .foregroundStyle(isCurrent ? .black : .secondary)+ .padding(.horizontal, 10).padding(.vertical, 4)+ .background(isCurrent ? AnyShapeStyle(LauncherPalette.cream) : AnyShapeStyle(Color.white.opacity(0.08)), in: Capsule())+ }+ .padding(.horizontal, 18).padding(.vertical, 9)+ .opacity(isCurrent ? 1 : 0.6)+ .help(isCurrent ? "" : m.t("cheats.otherHint"))+ }++ @ViewBuilder private func cheatRow(_ cheat: CheatFiles.Cheat, index: Int) -> some View {+ let first = index == 0 || shown[index - 1].section != cheat.section+ if first && !cheat.section.isEmpty {+ Text(cheat.section.uppercased()).font(.manrope(10.5, .bold)).tracking(1.1).foregroundStyle(.secondary)+ .padding(.horizontal, 18).padding(.top, 10).padding(.bottom, 4)+ }+ switch cheat.kind {+ case .label where cheat.name.hasPrefix("--Section"):+ EmptyView()+ case .label:+ Text(cheat.name).font(.manrope(12)).foregroundStyle(.secondary).padding(.horizontal, 18).padding(.vertical, 5)+ case .master:+ HStack(spacing: 10) {+ Text(cheat.name).font(.manrope(13))+ Spacer(minLength: 8)+ Text(m.t("cheats.alwaysOn")).font(.manrope(11.5)).foregroundStyle(.secondary)+ }+ .padding(.horizontal, 18).padding(.vertical, 6)+ case .cheat:+ HStack(spacing: 10) {+ VStack(alignment: .leading, spacing: 1) {+ Text(cheat.name).font(.manrope(13)).lineLimit(2)+ if cheat.broken { Text(m.t("cheats.broken")).font(.manrope(11.5)).foregroundStyle(LauncherPalette.building) }+ else if cheat.once { Text(m.t("cheats.once")).font(.manrope(11.5)).foregroundStyle(.secondary) }+ }+ Spacer(minLength: 8)+ if cheat.switchable {+ Toggle("", isOn: Binding(get: { on.contains(cheat.key) }, set: { set(cheat, $0) })).toggleStyle(CheatSwitchStyle()).labelsHidden()+ .accessibilityLabel(cheat.name)+ .padTarget("cheats.row.\(cheat.key)", scope: "cheats") { set(cheat, !on.contains(cheat.key)) }+ }+ }+ .padding(.horizontal, 18).padding(.vertical, 5)+ }+ }++ /// Import, the folder, and the copy to the device.+ private var actions: some View {+ HStack(spacing: 10) {+ Button(m.t("cheats.import")) { pick() }.disabled(busy)+ .padTarget("cheats.import", scope: "cheats") { if !busy { pick() } }+ Button(m.t("cheats.showFolder")) { showFolder() }+ .padTarget("cheats.folder", scope: "cheats") { showFolder() }+ Spacer(minLength: 8)+ if game?.onDevice ?? false {+ Button(String(format: m.t("cheats.toDevice"), deviceName)) { copyToDevice() }.disabled(!canCopy)+ .padTarget("cheats.toDevice", scope: "cheats") { if canCopy { copyToDevice() } }+ }+ }+ .buttonStyle(LauncherSecondaryButtonStyle())+ }++ // ---- what the controls do ----++ private func refresh() {+ guard let cheatFiles else { return }+ files = cheatFiles.found()+ master = cheatFiles.masterOn+ safeMode = cheatFiles.safeMode+ if let file = current { cheats = cheatFiles.cheats(of: file) ?? []; on = cheatFiles.enabled(file.buildID) } else { cheats = []; on = [] }+ }++ private func set(_ cheat: CheatFiles.Cheat, _ value: Bool) {+ guard let cheatFiles, let file = current else { return }+ var next = on+ if value { next.insert(cheat.key) } else { next.remove(cheat.key) }+ do {+ try cheatFiles.writeEnabled(file.buildID, cheats: cheats, on: next)+ on = next+ result = game.flatMap { CheatsView.running(game: $0) ? (String(format: m.t("cheats.running"), $0.name), false) : nil }+ } catch { result = (String(format: m.t("cheats.writeFailed"), error.localizedDescription), false) }+ }++ private func setMaster(_ value: Bool) {+ guard let cheatFiles else { return }+ do { try cheatFiles.setMaster(value); master = value } catch { result = (String(format: m.t("cheats.writeFailed"), error.localizedDescription), false) }+ }++ private func pick() {+ let panel = NSOpenPanel()+ panel.canChooseDirectories = true+ panel.canChooseFiles = true+ panel.allowsMultipleSelection = true+ panel.message = m.t("cheats.pickMessage")+ if panel.runModal() == .OK { importPaths(panel.urls.map(\.path)) }+ }++ private func importPaths(_ paths: [String]) {+ guard let cheatFiles else { return }+ do {+ let outcome = try cheatFiles.importFiles(from: paths.map { URL(fileURLWithPath: $0) })+ refresh()+ result = Self.importMessage(outcome, m: m)+ } catch { result = (String(format: m.t("cheats.writeFailed"), error.localizedDescription), false) }+ }++ /// What an import says: how many files came in, and the ones without a build ID in their name.+ static func importMessage(_ r: CheatFiles.ImportResult, m: BuildModel) -> (String, Bool) {+ var parts: [String] = []+ if !r.imported.isEmpty { parts.append(String(format: m.t("cheats.imported"), r.imported.count)) }+ if !r.skipped.isEmpty { parts.append(String(format: m.t("cheats.notNamed"), r.skipped.prefix(3).joined(separator: ", "))) }+ if parts.isEmpty { return (m.t("cheats.nothingFound"), false) }+ return (parts.joined(separator: " "), !r.imported.isEmpty)+ }++ private func showFolder() {+ guard let cheatFiles else { return }+ try? FileManager.default.createDirectory(at: cheatFiles.folder, withIntermediateDirectories: true)+ NSWorkspace.shared.open(cheatFiles.folder)+ }++ private func copyToDevice() {+ guard let cheatFiles, let game else { return }+ let transfer = CheatTransfer(files: cheatFiles, device: game.installedDevice, bundle: bundle, devicectl: devicectl ?? .xcrun(m.xcrunPath))+ busy = true; result = nil+ DispatchQueue.global(qos: .userInitiated).async {+ let outcome: (String, Bool)+ do { try transfer.toDevice(); outcome = (String(format: m.t("cheats.copied"), deviceName), true) }+ catch CheatTransfer.Failure.noFiles { outcome = (m.t("cheats.empty"), false) }+ catch CheatTransfer.Failure.device(let line) { outcome = (String(format: m.t("cheats.copyFailed"), line), false) }+ catch { outcome = (String(format: m.t("cheats.copyFailed"), error.localizedDescription), false) }+ DispatchQueue.main.async { busy = false; result = outcome; focus.focused = "cheats.done" }+ }+ }++ static func running(game: LibraryGame) -> Bool { SaveTransfer.runningOnMac(titleID: game.titleID) }+}++extension View {+ /// The Cheats sheet of the game `id` names, with the controller's scope following it (the launcher's other sheets do the same inline).+ func cheatsSheet(for id: Binding<UUID?>, m: BuildModel, library: GameLibrary, pad: PadFocus, restoreScope: @escaping () -> String) -> some View {+ sheet(isPresented: Binding(get: { id.wrappedValue != nil }, set: { if !$0 { id.wrappedValue = nil } })) {+ if let game = id.wrappedValue { CheatsView(m: m, library: library, gameID: game).environmentObject(pad) }+ }+ .onChange(of: id.wrappedValue) { open in pad.scope = open != nil ? "cheats" : restoreScope() }+ }+}++/// An on / off switch that reads the same in a window that is not key (the system's drops its colour there): cream when on, a dim track when off.+struct CheatSwitchStyle: ToggleStyle {+ func makeBody(configuration: Configuration) -> some View {+ Button { configuration.isOn.toggle() } label: {+ Capsule().fill(configuration.isOn ? LauncherPalette.cream : Color.white.opacity(0.16))+ .frame(width: 40, height: 23)+ .overlay(alignment: configuration.isOn ? .trailing : .leading) {+ Circle().fill(configuration.isOn ? Color.black.opacity(0.85) : Color.white.opacity(0.85)).frame(width: 17, height: 17).padding(3)+ }+ .animation(.easeOut(duration: 0.12), value: configuration.isOn)+ }+ .buttonStyle(.plain)+ .accessibilityValue(configuration.isOn ? "1" : "0")+ }+}diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 8d845969..4a3c3227 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -42,6 +42,7 @@ struct ContentView: View {@State private var freeSpaceFor: UUID? // the game whose Free space sheet is open@State private var controlsOpen = false@State private var savesFor: UUID? // the game whose Saves sheet is open (SaveTransfer.swift)+ @State private var cheatsFor: UUID? // the game whose Cheats sheet is open (CheatsView.swift)@State private var manageOpenFor: UUID? // the game whose Manage menu is open (ManageMenu.swift)@StateObject private var controls: ControlLayout@StateObject private var gamepad = LauncherGamepad()@@ -235,6 +236,7 @@ struct ContentView: View {if let id = savesFor { SavesView(m: m, library: library, gameID: id).environmentObject(padFocus) }}.onChange(of: savesFor) { id in padFocus.scope = id != nil ? "saves" : currentPadScope }+ .cheatsSheet(for: $cheatsFor, m: m, library: library, pad: padFocus) { currentPadScope }.onChange(of: optionsFor) { id in padFocus.scope = id != nil ? "launch" : (controlsOpen ? "controls" : "main") }.onChange(of: controlsOpen) { open in padFocus.scope = open ? "controls" : (optionsFor != nil ? "launch" : "main") }.onChange(of: page) { _ in padFocus.focused = nil }@@ -716,7 +718,7 @@ struct ContentView: View {}return}- let sheetOpen = controllerSheet || optionsFor != nil || controlsOpen || savesFor != nil || freeSpaceFor != nil+ let sheetOpen = controllerSheet || optionsFor != nil || controlsOpen || savesFor != nil || cheatsFor != nil || freeSpaceFor != nilswitch ManagePad.route(action, menuOpen: manageOpenFor != nil, sheetOpen: sheetOpen, hasGame: library.selected != nil && page == .library) {case .close: manageOpenFor = nil; returncase .swallow: return@@ -729,6 +731,7 @@ struct ContentView: View {}if action == .b, controllerSheet { controllerSheet = false; return }if action == .b, savesFor != nil { savesFor = nil; return }+ if action == .b, cheatsFor != nil { cheatsFor = nil; return }// The Free space sheet: B closes it, the D-pad and A work in it, X, L and R do nothing behind itif freeSpaceFor != nil && [.b, .x, .l, .r].contains(action) { if action == .b { freeSpaceFor = nil }; return }if action == .b {@@ -767,7 +770,7 @@ struct ContentView: View {hasBuildFolder: BuildFolder.location(for: game) != nil,hasLog: GameLog.latest(titleID: game.titleID, appPath: game.appPath) != nil,actions: ManageActions(- rebuild: { configureBuild(game) }, options: { optionsFor = game.id }, saves: { savesFor = game.id },+ rebuild: { configureBuild(game) }, options: { optionsFor = game.id }, saves: { savesFor = game.id }, cheats: { cheatsFor = game.id },changeArtwork: { chooseArtwork(game) }, resetArtwork: { library.setArtwork("", for: game.id) },reveal: { if let path = game.revealTarget { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)]) } },showLog: { if let log = GameLog.latest(titleID: game.titleID, appPath: game.appPath) { GameLog.show(log) } },@@ -778,7 +781,7 @@ struct ContentView: View {/// The scope a controller acts in when no menu is open: the innermost sheet, else the window.private var currentPadScope: String {- controllerSheet ? "console.controllers" : savesFor != nil ? "saves" : freeSpaceFor != nil ? "free" : optionsFor != nil ? "launch" : controlsOpen ? "controls" : "main"+ controllerSheet ? "console.controllers" : savesFor != nil ? "saves" : cheatsFor != nil ? "cheats" : freeSpaceFor != nil ? "free" : optionsFor != nil ? "launch" : controlsOpen ? "controls" : "main"}/// The space the collection row keeps around its cards for the focus ring (PadFocus draws it 4 pt outside a target).diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex f5acba13..7530c640 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -296,6 +296,36 @@ enum L10n {"saves.noMacSave": ("这台 Mac 上还没有这个游戏的存档。", "This Mac has no save for this game yet."),"saves.noDeviceSave": ("%@ 上还没有这个游戏的存档。", "%@ has no save for this game yet."),"saves.failed": ("复制失败:%@", "Copying failed: %@"),+ "cheats.menu": ("金手指…", "Cheats…"),+ "cheats.title": ("金手指", "Cheats"),+ "cheats.buildLabel": ("这个游戏版本的构建 ID", "Build ID of this game"),+ "cheats.buildUnknown": ("还不知道。先构建游戏。", "Not known yet. Build the game first."),+ "cheats.master": ("游戏中运行金手指", "Run cheats in the game"),+ "cheats.safeMode": ("上次运行没有正常退出,所以金手指一开始是关闭的。请在游戏的金手指面板中恢复。", "The last run did not end cleanly, so cheats start off. Restore them in the game's Cheats panel."),+ "cheats.empty": ("这个游戏还没有金手指。把文件夹或 <构建 ID>.txt 文件拖到这里,或选择“导入…”。", "No cheats for this game yet. Drop a folder or <build ID>.txt files here, or choose Import…"),+ "cheats.noBuildFile": ("要开关金手指,需要先知道游戏的构建 ID。先构建游戏。", "To switch cheats, the build ID of the game has to be known. Build the game first."),+ "cheats.noFileForBuild": ("没有适用于构建 %@ 的文件。导入一个以它命名的 .txt 文件。", "No file for build %@. Import a .txt file named after it."),+ "cheats.thisBuild": ("此版本", "This build"),+ "cheats.otherBuild": ("其他版本", "Other build"),+ "cheats.otherHint": ("这个文件属于游戏的另一个构建,不能用于当前构建,所以没有开关。", "This file is for another build of the game and cannot run on this one, so it has no switches."),+ "cheats.alwaysOn": ("始终开启", "Always on"),+ "cheats.broken": ("格式有误,不会运行", "Malformed, will not run"),+ "cheats.once": ("运行一次,在游戏窗口中使用", "Runs once, used from the game window"),+ "cheats.import": ("导入…", "Import…"),+ "cheats.showFolder": ("显示文件夹", "Show folder"),+ "cheats.toDevice": ("复制到 %@", "Copy to %@"),+ "cheats.copying": ("正在复制金手指…", "Copying the cheats…"),+ "cheats.copied": ("已复制到 %@。", "Copied to %@."),+ "cheats.copyFailed": ("复制失败:%@", "Copying failed: %@"),+ "cheats.writeFailed": ("无法写入:%@", "Could not write: %@"),+ "cheats.running": ("%@ 正在这台 Mac 上运行。改动要在游戏里选择“Reload cheats”(⌘R)或下次启动后才生效。", "%@ is running on this Mac. A change takes effect after Reload cheats (⌘R) in the game, or at the next start."),+ "cheats.imported": ("已导入的文件:%d。", "Files imported: %d."),+ "cheats.notNamed": ("没有导入(名称里没有构建 ID):%@。", "Not imported (no build ID in the name): %@."),+ "cheats.nothingFound": ("那里没有找到这个游戏的 <构建 ID>.txt 文件。", "No <build ID>.txt file for this game was found there."),+ "cheats.pickMessage": ("选择 Ryujinx 的金手指文件夹、SD 卡(atmosphere/contents/<title ID>/cheats)或 <构建 ID>.txt 文件", "Choose a Ryujinx cheats folder, an SD card (atmosphere/contents/<title ID>/cheats) or <build ID>.txt files"),+ "cheats.dropHint": ("松开以导入金手指", "Drop to import cheats"),+ "cheats.note": ("开关会立即保存,游戏下次启动时生效。", "Switches are saved at once and apply the next time the game starts."),+ "cheats.noteDevice": ("更改后请再次复制到 %@。", "Copy to %@ again after a change."),"pad.manage": ("管理", "Manage"),"dev.signStage": ("\u{4e3a} %@ \u{7b7e}\u{540d}", "Sign for %@"),"dev.installStage": ("\u{5b89}\u{88c5}\u{5230} %@", "Install on %@"),@@ -1132,6 +1162,36 @@ enum L10n {"saves.noMacSave": "Den här Mac-datorn har ingen sparfil för spelet ännu.","saves.noDeviceSave": "%@ har ingen sparfil för spelet ännu.","saves.failed": "Kopieringen misslyckades: %@",+ "cheats.menu": "Fusk …",+ "cheats.title": "Fusk",+ "cheats.buildLabel": "Spelets bygg-ID",+ "cheats.buildUnknown": "Inte känt än. Bygg spelet först.",+ "cheats.master": "Kör fusk i spelet",+ "cheats.safeMode": "Senaste körningen avslutades inte rent, så fusket börjar avstängt. Återställ det i spelets fuskpanel.",+ "cheats.empty": "Inget fusk för spelet än. Släpp en mapp eller <bygg-ID>.txt-filer här eller välj Importera …",+ "cheats.noBuildFile": "För att slå på fusk måste spelets bygg-ID vara känt. Bygg spelet först.",+ "cheats.noFileForBuild": "Ingen fil för bygget %@. Importera en .txt-fil med det namnet.",+ "cheats.thisBuild": "Det här bygget",+ "cheats.otherBuild": "Annat bygge",+ "cheats.otherHint": "Den här filen är för ett annat bygge av spelet och kan inte köras på det här, så den har inga reglage.",+ "cheats.alwaysOn": "Alltid på",+ "cheats.broken": "Felformaterad, körs inte",+ "cheats.once": "Körs en gång, används från spelfönstret",+ "cheats.import": "Importera …",+ "cheats.showFolder": "Visa mappen",+ "cheats.toDevice": "Kopiera till %@",+ "cheats.copying": "Kopierar fusket …",+ "cheats.copied": "Kopierat till %@.",+ "cheats.copyFailed": "Kopieringen misslyckades: %@",+ "cheats.writeFailed": "Kunde inte skriva: %@",+ "cheats.running": "%@ körs på den här Mac-datorn. En ändring gäller efter Reload cheats (⌘R) i spelet eller vid nästa start.",+ "cheats.imported": "Importerade filer: %d.",+ "cheats.notNamed": "Inte importerade (inget bygg-ID i namnet): %@.",+ "cheats.nothingFound": "Ingen <bygg-ID>.txt-fil för spelet hittades där.",+ "cheats.pickMessage": "Välj en Ryujinx-mapp med fusk, ett SD-kort (atmosphere/contents/<titel-id>/cheats) eller <bygg-ID>.txt-filer",+ "cheats.dropHint": "Släpp för att importera fusk",+ "cheats.note": "Reglagen sparas direkt och gäller nästa gång spelet startas.",+ "cheats.noteDevice": "Kopiera till %@ igen efter en ändring.","pad.manage": "Hantera","dev.signStage": "Signerar för %@","dev.installStage": "Installerar på %@",diff --git a/frontend/Sources/NSPortBuilder/ManageMenu.swift b/frontend/Sources/NSPortBuilder/ManageMenu.swiftindex 24573378..9b4bf2de 100644--- a/frontend/Sources/NSPortBuilder/ManageMenu.swift+++ b/frontend/Sources/NSPortBuilder/ManageMenu.swift@@ -6,6 +6,7 @@ struct ManageActions {var rebuild: () -> Void = {}var options: () -> Void = {}var saves: () -> Void = {}+ var cheats: () -> Void = {}var changeArtwork: () -> Void = {}var resetArtwork: () -> Void = {}var reveal: () -> Void = {}@@ -33,6 +34,7 @@ struct ManageItem: Identifiable {enabled: !running && !game.inputs["base", default: []].isEmpty, run: a.rebuild)]if game.isReady { items.append(.init(id: "options", symbol: "slider.horizontal.3", title: t("launch.title"), run: a.options)) }items.append(.init(id: "saves", symbol: "tray.and.arrow.down", title: t("saves.menu"), run: a.saves))+ items.append(.init(id: "cheats", symbol: "wand.and.stars", title: t("cheats.menu"), run: a.cheats))items.append(.init(id: "artwork", symbol: "photo", title: t("library.changeArtwork"), run: a.changeArtwork))if !game.artworkPath.isEmpty { items.append(.init(id: "resetArtwork", symbol: "arrow.uturn.backward", title: t("library.resetArtwork"), run: a.resetArtwork)) }if game.revealTarget != nil { items.append(.init(id: "reveal", symbol: "folder", title: t("install.reveal"), run: a.reveal)) }diff --git a/frontend/Tests/NSPortBuilderTests/CheatFilesTests.swift b/frontend/Tests/NSPortBuilderTests/CheatFilesTests.swiftnew file mode 100644index 00000000..07f38804--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/CheatFilesTests.swift@@ -0,0 +1,410 @@+import SwiftUI+import XCTest+@testable import NSPortBuilder++/// 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.+final class CheatFilesTests: XCTestCase {+ 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 m = BuildModel(); m.lang = .en+ XCTAssertEqual(CheatsView.importMessage(.init(imported: ["A", "B"]), m: m).0, "Files imported: 2.")+ XCTAssertTrue(CheatsView.importMessage(.init(imported: ["A"], skipped: ["x.txt"]), m: m).0.contains("x.txt"))+ XCTAssertFalse(CheatsView.importMessage(.init(), m: m).1)+ XCTAssertTrue(CheatsView.importMessage(.init(imported: ["A"]), m: m).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")+ XCTAssertEqual(args[args.firstIndex(of: "--remove-existing-content")! + 1], "true", "the device holds the Mac's files and nothing older")+ 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")+ }++ 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 model = BuildModel()+ model.lang = .en+ model.depsChecked = true+ model.deps = [BuildModel.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(ipa: "", 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 = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: height), styleMask: [.titled], backing: .buffered, defer: false)+ 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))+ try shot("cheats-drop", CheatsView(m: model, library: library, gameID: id, support: support, dropped: true))+ model.lang = .sv+ try shot("cheats-sv", CheatsView(m: model, library: library, gameID: id, support: support))+ model.lang = .zh+ try shot("cheats-zh", CheatsView(m: model, library: library, gameID: id, support: support))+ 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))+ }+}diff --git a/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swift b/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swiftindex eb8f0897..ce6447ec 100644--- a/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swift+++ b/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swift@@ -39,8 +39,8 @@ final class ManageMenuTests: XCTestCase {var game = try readyGame()game.artworkPath = "/art.png"let list = items(game, folder: true, log: true)- XCTAssertEqual(list.map(\.id), ["rebuild", "options", "saves", "artwork", "resetArtwork", "reveal", "log", "freeSpace", "remove"])- XCTAssertEqual(list.map(\.title), ["library.buildAgain", "launch.title", "saves.menu", "library.changeArtwork", "library.resetArtwork", "install.reveal", "library.showLog", "free.menu", "library.remove"]+ XCTAssertEqual(list.map(\.id), ["rebuild", "options", "saves", "cheats", "artwork", "resetArtwork", "reveal", "log", "freeSpace", "remove"])+ XCTAssertEqual(list.map(\.title), ["library.buildAgain", "launch.title", "saves.menu", "cheats.menu", "library.changeArtwork", "library.resetArtwork", "install.reveal", "library.showLog", "free.menu", "library.remove"].map { L10n.string($0, .en) })XCTAssertTrue(list.allSatisfy(\.enabled))XCTAssertEqual(list.last?.destructive, true)@@ -52,7 +52,7 @@ final class ManageMenuTests: XCTestCase {func testANotBuiltGameLeavesOutTheRowsThatNeedABuild() {var game = LibraryGame(titleID: titleID, name: "Hades")var list = items(game)- XCTAssertEqual(list.map(\.id), ["rebuild", "saves", "artwork", "remove"], "no launch options, Finder or Free space without a build")+ XCTAssertEqual(list.map(\.id), ["rebuild", "saves", "cheats", "artwork", "remove"], "no launch options, Finder or Free space without a build")XCTAssertFalse(list[0].enabled, "no recorded inputs: nothing to build again")game.inputs = ["base": ["/preview/Hades.nsp"]]list = items(game)@@ -94,10 +94,10 @@ final class ManageMenuTests: XCTestCase {let game = try readyGame()var log: [String] = []let actions = ManageActions(rebuild: { log.append("rebuild") }, options: { log.append("options") }, saves: { log.append("saves") },- changeArtwork: { log.append("artwork") }, resetArtwork: { log.append("reset") }, reveal: { log.append("reveal") }, showLog: { log.append("log") },+ cheats: { log.append("cheats") }, changeArtwork: { log.append("artwork") }, resetArtwork: { log.append("reset") }, reveal: { log.append("reveal") }, showLog: { log.append("log") },freeSpace: { log.append("free") }, remove: { log.append("remove") })for item in items(game, folder: true, log: true, actions: actions) { item.run() }- XCTAssertEqual(log, ["rebuild", "options", "saves", "artwork", "reveal", "log", "free", "remove"])+ XCTAssertEqual(log, ["rebuild", "options", "saves", "cheats", "artwork", "reveal", "log", "free", "remove"])}func testTheControllerLandsOnTheFirstUsableRow() throws {