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: narrow the all-languages row of a game with no language list to its RomFS (#668)
LNPANDY7899db8cb617
diff --git a/frontend-ios/Sources/ShellHost/RomfsLanguages.swift b/frontend-ios/Sources/ShellHost/RomfsLanguages.swiftindex 99334244..e3cddf44 100644--- a/frontend-ios/Sources/ShellHost/RomfsLanguages.swift+++ b/frontend-ios/Sources/ShellHost/RomfsLanguages.swift@@ -52,13 +52,39 @@ enum RomfsLanguages {return []}- static func withLanguageIfMissing(_ profile: LauncherProfile, options: [[String]]) -> LauncherProfile {- guard options.count > 1, !profile.settings.contains(where: { $0.env == "DM_LANG" }) else { return profile }+ /// Whether a `DM_LANG` row is the all-languages row `dm/games/settings.py` writes for a game with no language list (no control+ /// data: a dump or a NUP, seedds/nxnative aafe01d): every language of `table`, and a note that some of them may not be in the+ /// game. A game that really supports all of them has no note, so it is not taken for this row.+ static func isFallbackRow(_ row: LauncherSetting) -> Bool {+ guard row.env == "DM_LANG", !row.note.isEmpty, let codes = row.options?.compactMap(\.first) else { return false }+ return Set(codes) == Set(table.map(\.code))+ }++ /// The fallback row's options cut to the languages the RomFS offers, in the row's own order and labels. Nil when the RomFS names+ /// fewer than two languages, or lacks the row's default (the language the game is packed with): the row then stays as it is.+ static func narrowed(_ options: [[String]], default def: String, to romfs: [[String]]) -> [[String]]? {+ let offered = Set(romfs.compactMap(\.first))+ guard offered.count > 1, offered.contains(def) else { return nil }+ let kept = options.filter { offered.contains($0.first ?? "") }+ return kept.count > 1 ? kept : nil+ }++ /// The profile with the game's real languages: a `DM_LANG` row added when it has none, and the all-languages row of a game with no+ /// language list narrowed to what the RomFS has (its note is dropped, the list is right now).+ static func applying(to profile: LauncherProfile, options: [[String]]) -> LauncherProfile {+ guard options.count > 1 else { return profile }+ var updated = profile+ if let i = updated.settings.firstIndex(where: { $0.env == "DM_LANG" }) {+ let row = updated.settings[i]+ guard isFallbackRow(row), let kept = narrowed(row.options ?? [], default: row.def, to: options) else { return profile }+ updated.settings[i].options = kept+ updated.settings[i].note = ""+ return updated+ }let def = options.contains(where: { $0.first == "en-US" }) ? "en-US" : (options.first?.first ?? "en-US")let row = LauncherSetting(env: "DM_LANG", kind: "choice", section: "Game", label: "Game language", note: "", def: def,needs: nil, level: "basic", options: options, min: nil, max: nil, step: nil, on: nil, off: nil)- var updated = profilelet idx = updated.settings.lastIndex { $0.sectionTitle == "Game" }.map { $0 + 1 } ?? 0updated.settings.insert(row, at: idx)return updateddiff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swiftindex b0136adc..2c32a32f 100644--- a/frontend-ios/Sources/ShellHost/ShellHostModel.swift+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift@@ -217,8 +217,10 @@ public struct ShellHostConfig: Sendable {private func profile(for entry: CatalogueEntry, data: DataResolution? = nil) -> LauncherProfile? {guard let base = entry.profile, entry.problem == nil else { return nil }- guard !base.settings.contains(where: { $0.env == "DM_LANG" }),- let url = (data ?? self.data(for: entry)).url else { return base }+ // A DM_LANG row of the game's own list stays, except the all-languages row of a game with no language list (the engine's+ // fallback): the RomFS names the languages it really has (#668)+ if let row = base.settings.first(where: { $0.env == "DM_LANG" }), !RomfsLanguages.isFallbackRow(row) { return base }+ guard let url = (data ?? self.data(for: entry)).url else { return base }let opts: [[String]]if let cached = romfsLanguages[url] {opts = cached@@ -226,7 +228,7 @@ public struct ShellHostConfig: Sendable {opts = RomfsLanguages.options(in: url)romfsLanguages[url] = opts}- return RomfsLanguages.withLanguageIfMissing(base, options: opts)+ return RomfsLanguages.applying(to: base, options: opts)}private func image(_ url: URL?) -> Artwork? {diff --git a/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift b/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swiftindex e6d3cd21..10ceb6d4 100644--- a/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift+++ b/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift@@ -110,4 +110,55 @@ import Testing#expect(try codes(patched(idxOff + 3 * 24, .max, in: img)) == [], "a mask offset near UInt64.max must not overflow offset + size")#expect(try codes(patched(idxOff + 3 * 24 + 8, .max, in: img)) == [])}++ // MARK: The all-languages row of a game with no language list (seedds/nxnative aafe01d)++ /// The row `dm/games/settings.py` of seedds/nxnative 777a5f6 writes for 040074A01BF12000 over a control.nacp that does not exist.+ private static let fallbackRowJSON = """+ {"env":"DM_LANG","kind":"choice","section":"Game","label":"Game language","note":"This game's files do not list its languages, so some of these may not be in the game. It may then show another one.","default":"en-US","level":"basic","options":[["en-US","American English"],["en-GB","British English"],["ja","Japanese"],["fr","French"],["de","German"],["es-419","Latin American Spanish"],["es","Spanish"],["it","Italian"],["nl","Dutch"],["fr-CA","Canadian French"],["pt","Portuguese"],["ru","Russian"],["ko","Korean"],["zh-Hant","Traditional Chinese"],["zh-Hans","Simplified Chinese"],["pt-BR","Brazilian Portuguese"]]}+ """++ private func profile(row: String?) throws -> LauncherProfile {+ let opmode = #"{"env":"DM_OPMODE","kind":"choice","section":"Game","label":"Console mode","note":"","default":"1","options":[["1","Docked"],["0","Handheld"]]}"#+ let rows = [opmode, row].compactMap { $0 }.joined(separator: ",")+ return try LauncherProfile.parse(Data(#"{"schema":1,"game":"040074A01BF12000","settings":[\#(rows)]}"#.utf8))+ }++ private func langRow(_ p: LauncherProfile) -> LauncherSetting? { p.settings.first { $0.env == "DM_LANG" } }++ @Test func theAllLanguagesRowIsNarrowedToTheRomFS() throws {+ let p = try profile(row: Self.fallbackRowJSON)+ let img = Self.image(mask("JPja USen CNzh TWzh EUfr\n01111\n"))+ let narrowed = RomfsLanguages.applying(to: p, options: RomfsLanguages.options(in: try folder(with: img)))+ let row = try #require(langRow(narrowed))+ #expect(narrowed.settings.filter { $0.env == "DM_LANG" }.count == 1)+ #expect(row.options?.map { $0[0] } == ["en-US", "ja", "fr", "zh-Hant", "zh-Hans"])+ #expect(row.options?.first { $0[0] == "zh-Hans" } == ["zh-Hans", "Simplified Chinese"])+ #expect(row.note == "")+ #expect(row.def == "en-US")+ #expect(row.accepts("zh-Hans") && !row.accepts("pt-BR"), "a saved choice the game does not have reads as the default")+ }++ @Test func theRowStaysWhenTheRomFSCannotNarrowIt() throws {+ let p = try profile(row: Self.fallbackRowJSON)+ for text in ["Hello\n", "USen\n", "JPja EUfr\n"] { // no tag, one language, no American English (the packed default)+ let opts = RomfsLanguages.options(in: try folder(with: Self.image(mask(text))))+ #expect(RomfsLanguages.applying(to: p, options: opts) == p, "\(text)")+ }+ }++ @Test func aRowWithoutTheNoteIsTheGamesOwnListAndStays() throws {+ let exact = Self.fallbackRowJSON.replacingOccurrences(of: #""note":"This game's files do not list its languages, so some of these may not be in the game. It may then show another one.""#, with: #""note":"""#)+ let p = try profile(row: exact)+ let opts = RomfsLanguages.options(in: try folder(with: Self.image(mask("JPja USen\n01\n"))))+ #expect(RomfsLanguages.applying(to: p, options: opts) == p)+ #expect(RomfsLanguages.isFallbackRow(try #require(langRow(try profile(row: Self.fallbackRowJSON)))))+ #expect(!RomfsLanguages.isFallbackRow(try #require(langRow(p))))+ }++ @Test func aRowThatIsNotAllLanguagesIsNotTheFallback() throws {+ let some = #"{"env":"DM_LANG","kind":"choice","section":"Game","label":"Game language","note":"A note","default":"en-US","options":[["en-US","American English"],["ja","Japanese"]]}"#+ let p = try profile(row: some)+ #expect(!RomfsLanguages.isFallbackRow(try #require(langRow(p))))+ }}diff --git a/frontend/Sources/NX2Apple/Library.swift b/frontend/Sources/NX2Apple/Library.swiftindex 1ad38fc3..c24d8d0c 100644--- a/frontend/Sources/NX2Apple/Library.swift+++ b/frontend/Sources/NX2Apple/Library.swift@@ -142,7 +142,15 @@ struct LaunchSetting: Decodable, Identifiable {min: nil, max: nil, step: nil, on: nil, off: nil, unsetValue: "")list.insert(display, at: (list.firstIndex { $0.env == "DM_RENDER_SCALE" }).map { $0 + 1 } ?? 0)}- if !list.contains(where: { $0.env == "DM_LANG" }) {+ if let i = list.firstIndex(where: { $0.env == "DM_LANG" }) {+ // A game with no language list gets every language and a note from the engine (seedds/nxnative aafe01d, #668): the+ // RomFS names the ones it really has+ if RomFSLanguages.isFallbackRow(options: list[i].options, note: list[i].note),+ let kept = RomFSLanguages.narrowed(list[i].options ?? [], default: list[i].def, to: RomFSLanguages.options(in: app)) {+ list[i].options = kept+ list[i].note = ""+ }+ } else {let langs = RomFSLanguages.options(in: app)if langs.count > 1 {let def = RomFSLanguages.defaultLanguage(forApp: app, options: langs)diff --git a/frontend/Sources/NXCore/RomFSLanguages.swift b/frontend/Sources/NXCore/RomFSLanguages.swiftindex 412f8259..9903f66c 100644--- a/frontend/Sources/NXCore/RomFSLanguages.swift+++ b/frontend/Sources/NXCore/RomFSLanguages.swift@@ -63,17 +63,49 @@ package enum RomFSLanguages {return options.first?.first ?? "en-US"}- /// Adds a `DM_LANG` row to `launcher.json` at `launcherPath` when the file has none and `romfs` offers more than one language.- /// Used after packing a game's RomFS archive so a newly built iOS framework carries the row even before upstream merges #1208.+ /// Whether a `DM_LANG` row is the all-languages row `dm/games/settings.py` writes for a game with no language list (no control+ /// data: a dump or a NUP, seedds/nxnative aafe01d): every language of `table`, and a note that some of them may not be in the+ /// game. A game that really supports all of them has no note, so it is not taken for this row.+ package static func isFallbackRow(options: [[String]]?, note: String) -> Bool {+ guard !note.isEmpty, let codes = options?.compactMap(\.first) else { return false }+ return Set(codes) == Set(table.map(\.code))+ }++ /// The fallback row's options cut to the languages the RomFS offers, in the row's own order and labels. Nil when the RomFS names+ /// fewer than two languages, or lacks the row's default (the packed language, which the app starts with when nothing is chosen):+ /// the row then stays as it is.+ package static func narrowed(_ options: [[String]], default def: String, to romfs: [[String]]) -> [[String]]? {+ let offered = Set(romfs.compactMap(\.first))+ guard offered.count > 1, offered.contains(def) else { return nil }+ let kept = options.filter { offered.contains($0.first ?? "") }+ return kept.count > 1 ? kept : nil+ }++ /// Makes `launcher.json` at `launcherPath` offer the game's real languages, from `romfs`: adds a `DM_LANG` row when the file has+ /// none, and narrows the all-languages row of a game with no language list. Used after packing a game's RomFS archive, so a newly+ /// built iOS framework is right before the Mac launcher and the shell read it. False when nothing changed.@discardableResult- package static func addToLauncherJSONIfMissing(at launcherPath: String, romfs: String, defaultLanguage: String = "en-US",- fm: FileManager = .default) -> Bool {+ package static func applyToLauncherJSON(at launcherPath: String, romfs: String, defaultLanguage: String = "en-US",+ fm: FileManager = .default) -> Bool {guard let data = fm.contents(atPath: launcherPath),var root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],- var settings = root["settings"] as? [[String: Any]],- !settings.contains(where: { ($0["env"] as? String) == "DM_LANG" }) else { return false }+ var settings = root["settings"] as? [[String: Any]] else { return false }let opts = options(in: romfs, fm: fm)guard opts.count > 1 else { return false }+ func write() -> Bool {+ root["settings"] = settings+ guard let out = try? JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys]),+ (try? out.write(to: URL(fileURLWithPath: launcherPath), options: .atomic)) != nil else { return false }+ return true+ }+ if let i = settings.firstIndex(where: { ($0["env"] as? String) == "DM_LANG" }) {+ let row = settings[i]+ guard isFallbackRow(options: row["options"] as? [[String]], note: row["note"] as? String ?? ""),+ let kept = narrowed(row["options"] as? [[String]] ?? [], default: row["default"] as? String ?? "", to: opts) else { return false }+ settings[i]["options"] = kept+ settings[i]["note"] = ""+ return write()+ }let codes = Set(opts.compactMap(\.first))let def = codes.contains(defaultLanguage) ? defaultLanguage : (codes.contains("en-US") ? "en-US" : opts[0][0])let row: [String: Any] = [@@ -88,10 +120,7 @@ package enum RomFSLanguages {]let after = settings.lastIndex { ($0["section"] as? String ?? "Game") == "Game" }.map { $0 + 1 } ?? 0settings.insert(row, at: after)- root["settings"] = settings- guard let out = try? JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys]),- (try? out.write(to: URL(fileURLWithPath: launcherPath), options: .atomic)) != nil else { return false }- return true+ return write()}private static func candidates(for path: String) -> [String] {diff --git a/frontend/Sources/NXModel/BuildStore+Archive.swift b/frontend/Sources/NXModel/BuildStore+Archive.swiftindex 4d0e8b50..145594e5 100644--- a/frontend/Sources/NXModel/BuildStore+Archive.swift+++ b/frontend/Sources/NXModel/BuildStore+Archive.swift@@ -15,7 +15,7 @@ extension BuildStore {let n = RomFSArchive.copyAddOnContent(from: workDir + "/aoc", to: dest + "/aoc")if n > 0 { say(String(format: t("msg.aocCopied"), n)) }if let fw = ShellInstall.builtFramework(workDir: workDir) {- RomFSLanguages.addToLauncherJSONIfMissing(at: fw + "/dm/launcher.json", romfs: dest)+ RomFSLanguages.applyToLauncherJSON(at: fw + "/dm/launcher.json", romfs: dest)}}diff --git a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swiftindex 66d88db1..b9b734bd 100644--- a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift+++ b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift@@ -129,11 +129,75 @@ final class MacAppLanguageTests: IsolatedDefaultsTestCase {let fwLauncher = temporary.appendingPathComponent("DmGame040074A01BF12000.framework/dm/launcher.json")try FileManager.default.createDirectory(at: fwLauncher.deletingLastPathComponent(), withIntermediateDirectories: true)try Data(noLangJSON.utf8).write(to: fwLauncher)- XCTAssertTrue(RomFSLanguages.addToLauncherJSONIfMissing(at: fwLauncher.path, romfs: imgURL.path))+ XCTAssertTrue(RomFSLanguages.applyToLauncherJSON(at: fwLauncher.path, romfs: imgURL.path))let parsed = try XCTUnwrap(LaunchList.parse(Data(contentsOf: fwLauncher)))XCTAssertEqual(parsed.settings.first { $0.env == "DM_LANG" }?.options?.map { $0[0] }, ["en-US", "ja", "fr", "zh-Hant", "zh-Hans"])}+ /// The DM_LANG row `dm/games/settings.py` of seedds/nxnative 777a5f6 (aafe01d) writes for 040074A01BF12000 over a control.nacp that does+ /// not exist (a dump has none): every language and a note. Regenerate it with `SETTINGS_PLATFORM=mac GFXAPI=nvn DM_LANG=en-US python3+ /// dm/games/settings.py 040074A01BF12000 <dir with an empty main.fixups.tsv> /nonexistent/control.nacp out.json`.+ private static let fallbackLangRow = ###"{"env":"DM_LANG","kind":"choice","section":"Game","label":"Game language","note":"This game's files do not list its languages, so some of these may not be in the game. It may then show another one.","default":"en-US","level":"basic","options":[["en-US","American English"],["en-GB","British English"],["ja","Japanese"],["fr","French"],["de","German"],["es-419","Latin American Spanish"],["es","Spanish"],["it","Italian"],["nl","Dutch"],["fr-CA","Canadian French"],["pt","Portuguese"],["ru","Russian"],["ko","Korean"],["zh-Hant","Traditional Chinese"],["zh-Hans","Simplified Chinese"],["pt-BR","Brazilian Portuguese"]]}"###++ /// A Mac app of 040074A01BF12000 with the given DM_LANG row (nil: none) in its launcher.json and a RomFS image naming `mask`.+ private func appWithLangRow(_ row: String?, mask: String) throws -> (app: URL, image: URL) {+ let app = temporary.appendingPathComponent("Game-\(UUID().uuidString).app")+ let dm = app.appendingPathComponent("Contents/Resources/dm")+ try FileManager.default.createDirectory(at: dm, withIntermediateDirectories: true)+ let opmode = #"{"env": "DM_OPMODE", "kind": "choice", "section": "Game", "label": "Console mode", "note": "", "default": "1", "level": "basic", "options": [["1", "Docked"], ["0", "Handheld"]]}"#+ try Data(#"{"schema": 1, "game": "040074A01BF12000", "settings": [\#([opmode, row].compactMap { $0 }.joined(separator: ","))]}"#.utf8)+ .write(to: dm.appendingPathComponent("launcher.json"))+ let info: [String: Any] = ["CFBundleIdentifier": bundleID, "DMTitleID": "040074A01BF12000", "DMLanguage": "en-US"]+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))+ let image = app.appendingPathComponent("Contents/Resources/romfs.img")+ try Self.makeDMROMFSImage(mask: mask).write(to: image)+ return (app, image)+ }++ /// Since seedds/nxnative aafe01d a game with no language list gets every language and a note. The RomFS names the real ones (#668).+ func testRomFSNarrowsTheAllLanguagesRowOfAGameWithNoLanguageList() throws {+ let (app, _) = try appWithLangRow(Self.fallbackLangRow, mask: "JPja USen CNzh TWzh EUfr\n01111\n")+ let list = try XCTUnwrap(LaunchSetting.forMac(app: app.path, titleID: "040074A01BF12000", repo: "", labels: { L10n.string($0, .en) }))+ let lang = try XCTUnwrap(list.first { $0.env == "DM_LANG" })+ XCTAssertEqual(list.filter { $0.env == "DM_LANG" }.count, 1)+ XCTAssertEqual(lang.options?.map { $0[0] }, ["en-US", "ja", "fr", "zh-Hant", "zh-Hans"], "the row's own order, only what the RomFS has")+ XCTAssertEqual(lang.options?.first { $0[0] == "zh-Hans" }, ["zh-Hans", "Simplified Chinese"])+ XCTAssertEqual(lang.note, "", "the list is right now: nothing may be missing from the game")+ XCTAssertEqual(lang.def, "en-US")+ XCTAssertTrue(lang.storeBacked, "the engine's own row stays a saved choice, which the app's launcher reads")+ }++ /// The row is left alone when the RomFS cannot say: no list, one language, or the packed default is not among them.+ func testTheAllLanguagesRowStaysWhenTheRomFSCannotNarrowIt() throws {+ for mask in ["Hello\n", "USen\n", "JPja EUfr\n"] { // no tag, one language, no American English (the packed default)+ let (app, _) = try appWithLangRow(Self.fallbackLangRow, mask: mask)+ let lang = try XCTUnwrap(LaunchSetting.forMac(app: app.path, titleID: "040074A01BF12000", repo: "", labels: { L10n.string($0, .en) })?+ .first { $0.env == "DM_LANG" })+ XCTAssertEqual(lang.options?.count, 16, mask)+ XCTAssertFalse(lang.note.isEmpty, mask)+ }+ }++ /// A game whose control data lists languages has no note and its list is the game's own: the RomFS does not touch it.+ func testARowWithoutTheNoteIsNeverNarrowed() throws {+ let exact = Self.fallbackLangRow.replacingOccurrences(of: #""note":"This game's files do not list its languages, so some of these may not be in the game. It may then show another one.""#, with: #""note":"""#)+ let (app, _) = try appWithLangRow(exact, mask: "JPja USen\n01\n")+ let lang = try XCTUnwrap(LaunchSetting.forMac(app: app.path, titleID: "040074A01BF12000", repo: "", labels: { L10n.string($0, .en) })?+ .first { $0.env == "DM_LANG" })+ XCTAssertEqual(lang.options?.count, 16)+ }++ /// The archive step makes a newly built iOS framework's launcher.json right too.+ func testTheArchiveStepNarrowsTheAllLanguagesRowOfAFrameworkLauncherJSON() throws {+ let (app, image) = try appWithLangRow(Self.fallbackLangRow, mask: "JPja USen CNzh TWzh EUfr\n01111\n")+ let json = app.appendingPathComponent("Contents/Resources/dm/launcher.json")+ XCTAssertTrue(RomFSLanguages.applyToLauncherJSON(at: json.path, romfs: image.path))+ let lang = try XCTUnwrap(LaunchList.parse(Data(contentsOf: json))?.settings.first { $0.env == "DM_LANG" })+ XCTAssertEqual(lang.options?.map { $0[0] }, ["en-US", "ja", "fr", "zh-Hant", "zh-Hans"])+ XCTAssertEqual(lang.note, "")+ XCTAssertFalse(RomFSLanguages.applyToLauncherJSON(at: json.path, romfs: image.path), "narrowed already: nothing more to change")+ }+private func writeImage(_ data: Data) throws -> String {let url = temporary.appendingPathComponent("img-\(UUID().uuidString).img")try data.write(to: url)