Skip to content

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

launcher: read game languages from RomFS when launcher.json has no DM_LANG (#668)

LNPANDYa5cdb7d03eb4
diff --git a/frontend-ios/Sources/ShellHost/RomfsLanguages.swift b/frontend-ios/Sources/ShellHost/RomfsLanguages.swift
new file mode 100644
index 00000000..60dcbc1a
--- /dev/null
+++ b/frontend-ios/Sources/ShellHost/RomfsLanguages.swift
@@ -0,0 +1,161 @@
+import Foundation
+
+/// Languages a game's RomFS offers when its `launcher.json` has no `DM_LANG` row (a game built from a dump folder or a NUP without
+/// `control.nacp`, LNPANDY/NX2Apple#668, seedds/nxnative#1208). Reads `System/RegionLangMask.txt` or `Mals/<Tag>.Product.*` from the
+/// game's `romfs.img` (`DMROMFS1` index at the end of the file) or `romfs/` folder.
+enum RomfsLanguages {
+ static let table: [(code: String, label: String)] = [
+ ("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")
+ ]
+
+ static let regionTags: [String: String] = [
+ "USen": "en-US", "EUen": "en-GB", "JPja": "ja", "EUfr": "fr",
+ "EUde": "de", "USes": "es-419", "EUes": "es", "EUit": "it",
+ "EUnl": "nl", "USfr": "fr-CA", "EUpt": "pt", "EUru": "ru",
+ "KRko": "ko", "TWzh": "zh-Hant", "CNzh": "zh-Hans", "USpt": "pt-BR"
+ ]
+
+ static func options(forTags tags: some Sequence<String>) -> [[String]] {
+ let codes = Set(tags.compactMap { regionTags[$0] })
+ return table.filter { codes.contains($0.code) }.map { [$0.code, $0.label] }
+ }
+
+ static func options(in url: URL, fm: FileManager = .default) -> [[String]] {
+ let candidates = [
+ url.appendingPathComponent("romfs.img"),
+ url.appendingPathComponent("RomFS.img"),
+ url.appendingPathComponent("romfs", isDirectory: true),
+ url.appendingPathComponent("RomFS", isDirectory: true),
+ url
+ ]
+ for candidate in candidates {
+ var isDir: ObjCBool = false
+ guard fm.fileExists(atPath: candidate.path, isDirectory: &isDir) else { continue }
+ let found = isDir.boolValue ? fromDirectory(candidate, fm: fm) : fromImage(candidate)
+ if found.count > 1 { return found }
+ }
+ return []
+ }
+
+ static func withLanguageIfMissing(_ profile: LauncherProfile, options: [[String]]) -> LauncherProfile {
+ guard options.count > 1, !profile.settings.contains(where: { $0.env == "DM_LANG" }) else { return profile }
+ 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 = profile
+ let idx = updated.settings.lastIndex { $0.sectionTitle == "Game" }.map { $0 + 1 } ?? 0
+ updated.settings.insert(row, at: idx)
+ return updated
+ }
+
+ private static func tagsFromMask(_ text: String) -> [String] {
+ for raw in text.components(separatedBy: .newlines) {
+ let line = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !line.isEmpty, !line.hasPrefix("#"), !line.hasPrefix("/") {
+ return line.split(whereSeparator: \.isWhitespace).map(String.init)
+ }
+ }
+ return []
+ }
+
+ private static func tagsFromMals(_ names: some Sequence<String>) -> [String] {
+ names.compactMap { name -> String? in
+ guard name.contains(".Product."), let dot = name.firstIndex(of: ".") else { return nil }
+ return String(name[..<dot])
+ }
+ }
+
+ private static func fromDirectory(_ dir: URL, fm: FileManager) -> [[String]] {
+ let maskURL = dir.appendingPathComponent("System/RegionLangMask.txt")
+ if let data = fm.contents(atPath: maskURL.path), let text = String(data: data, encoding: .utf8) {
+ let opts = options(forTags: tagsFromMask(text))
+ if opts.count > 1 { return opts }
+ }
+ if let names = try? fm.contentsOfDirectory(atPath: dir.appendingPathComponent("Mals").path) {
+ let opts = options(forTags: tagsFromMals(names))
+ if opts.count > 1 { return opts }
+ }
+ return []
+ }
+
+ private static func fromImage(_ url: URL) -> [[String]] {
+ guard let handle = try? FileHandle(forReadingFrom: url) else { return [] }
+ defer { try? handle.close() }
+ guard let fileSize = try? handle.seekToEnd(), (try? handle.seek(toOffset: 0)) != nil,
+ let headData = try? handle.read(upToCount: 32), headData.count == 32 else { return [] }
+ let head = [UInt8](headData)
+ func u64(_ bytes: [UInt8], _ o: Int) -> UInt64 {
+ (0..<8).reduce(0) { $0 | UInt64(bytes[o + $1]) << (8 * UInt64($1)) }
+ }
+ func u32(_ bytes: [UInt8], _ o: Int) -> Int {
+ Int(bytes[o]) | Int(bytes[o + 1]) << 8 | Int(bytes[o + 2]) << 16 | Int(bytes[o + 3]) << 24
+ }
+ func u16(_ bytes: [UInt8], _ o: Int) -> Int {
+ Int(bytes[o]) | Int(bytes[o + 1]) << 8
+ }
+ guard head[0..<8].elementsEqual("DMROMFS1".utf8) else { return [] }
+ let idxOff = u64(head, 8), idxSize = u64(head, 16), count = u64(head, 24)
+ guard idxOff >= 32, idxOff <= fileSize, idxSize == fileSize - idxOff,
+ idxSize <= 64 * 1024 * 1024, count >= 1, count * 24 <= idxSize,
+ (try? handle.seek(toOffset: idxOff)) != nil,
+ let idxData = try? handle.read(upToCount: Int(idxSize)), idxData.count == Int(idxSize) else { return [] }
+ let idx = [UInt8](idxData)
+ let namesBase = Int(count) * 24
+
+ struct Entry {
+ var a: UInt64
+ var b: UInt64
+ var name: String
+ var type: UInt8
+ }
+ func entry(_ i: Int) -> Entry? {
+ guard i >= 0, i < Int(count) else { return nil }
+ let o = i * 24
+ let nOff = namesBase + u32(idx, o + 16), nLen = u16(idx, o + 20)
+ guard nOff >= namesBase, nOff + nLen <= idx.count else { return nil }
+ let name = String(decoding: idx[nOff..<(nOff + nLen)], as: UTF8.self)
+ return Entry(a: u64(idx, o), b: u64(idx, o + 8), name: name, type: idx[o + 22])
+ }
+ func children(of dirIndex: Int) -> [Int] {
+ guard let dir = entry(dirIndex), dir.type == 2,
+ dir.a <= count, dir.b <= count - dir.a else { return [] }
+ return Array(Int(dir.a)..<Int(dir.a + dir.b))
+ }
+ func findChild(in dirIndex: Int, named target: String) -> Int? {
+ children(of: dirIndex).first { entry($0)?.name == target }
+ }
+
+ if let sys = findChild(in: 0, named: "System"),
+ let maskIdx = findChild(in: sys, named: "RegionLangMask.txt"),
+ let mask = entry(maskIdx), mask.type == 1, mask.b > 0, mask.b <= 65536,
+ mask.a + mask.b <= idxOff,
+ (try? handle.seek(toOffset: mask.a)) != nil,
+ let maskData = try? handle.read(upToCount: Int(mask.b)),
+ let text = String(data: maskData, encoding: .utf8) {
+ let opts = options(forTags: tagsFromMask(text))
+ if opts.count > 1 { return opts }
+ }
+ if let mals = findChild(in: 0, named: "Mals") {
+ let names = children(of: mals).compactMap { entry($0)?.name }
+ let opts = options(forTags: tagsFromMals(names))
+ if opts.count > 1 { return opts }
+ }
+ return []
+ }
+}
diff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
index 90939e30..e04356c8 100644
--- a/frontend-ios/Sources/ShellHost/ShellHostModel.swift
+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
@@ -70,6 +70,7 @@ public struct ShellHostConfig: Sendable {
@ObservationIgnored private var dataStores: [String: BookmarkStore] = [:]
@ObservationIgnored private var cloudStores: [String: BookmarkStore] = [:]
@ObservationIgnored private var artwork: [URL: Artwork] = [:]
+ @ObservationIgnored private var romfsLanguages: [URL: [[String]]] = [:]
/// The shell-level settings every game falls back to (game > shell > built-in).
@ObservationIgnored public let shellSettings: ShellSettingsStore
@ObservationIgnored private let shellData: BookmarkStore
@@ -210,6 +211,20 @@ public struct ShellHostConfig: Sendable {
global: shellData.resolve(), shellMatch: shellMatches[manifest.titleID])
}
+ 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 }
+ let opts: [[String]]
+ if let cached = romfsLanguages[url] {
+ opts = cached
+ } else {
+ opts = RomfsLanguages.options(in: url)
+ romfsLanguages[url] = opts
+ }
+ return RomfsLanguages.withLanguageIfMissing(base, options: opts)
+ }
+
private func image(_ url: URL?) -> Artwork? {
guard let url else { return nil }
if let a = artwork[url] { return a }
@@ -225,7 +240,7 @@ public struct ShellHostConfig: Sendable {
let tile = GameTile(id: entry.id, title: entry.title, subtitle: entry.manifest.map { ShellFormat.version($0.displayVersion) } ?? "",
banner: image(entry.bannerURL), icon: image(entry.iconURL), state: state,
recentlyPlayed: played.map { ShellFormat.played($0, now: config.now()) })
- guard let profile = entry.profile, entry.problem == nil else {
+ guard let profile = profile(for: entry, data: data) else {
return GameDetail(game: tile, dataNote: dataNote(data, found: false))
}
let store = GameSettingsStore(profile: profile, defaults: config.defaults(entry.id), shell: shellSettings.gameDefaults)
@@ -308,7 +323,7 @@ public struct ShellHostConfig: Sendable {
}
public func change(_ id: String, setting: String, value: String) {
- guard let profile = entry(id)?.profile else { return }
+ guard let entry = entry(id), let profile = profile(for: entry) else { return }
if setting.hasPrefix("pad.") {
GamePadMapStore(defaults: config.defaults(id)).change(setting, value: value)
} else {
@@ -318,7 +333,7 @@ public struct ShellHostConfig: Sendable {
}
public func resetDefaults(_ id: String) {
- guard let profile = entry(id)?.profile else { return }
+ guard let entry = entry(id), let profile = profile(for: entry) else { return }
GameSettingsStore(profile: profile, defaults: config.defaults(id)).reset()
GamePadMapStore(defaults: config.defaults(id)).reset()
refresh(id)
@@ -446,8 +461,10 @@ public struct ShellHostConfig: Sendable {
}
func playNow(_ id: String) async {
- guard !launchingGame, let entry = entry(id), let manifest = entry.manifest, let profile = entry.profile, let framework = entry.frameworkURL,
- details.first(where: { $0.id == id })?.game.state == .playable, let dataURL = data(for: entry).url else { return }
+ guard !launchingGame, let entry = entry(id), let manifest = entry.manifest, let framework = entry.frameworkURL,
+ details.first(where: { $0.id == id })?.game.state == .playable,
+ case let resolved = data(for: entry), let dataURL = resolved.url,
+ let profile = profile(for: entry, data: resolved) else { return }
launchingGame = true
defer { launchingGame = false }
var cloud: URL?
diff --git a/frontend-ios/Tests/ShellHostTests/SettingsTests.swift b/frontend-ios/Tests/ShellHostTests/SettingsTests.swift
index 5660d68f..5554bfbd 100644
--- a/frontend-ios/Tests/ShellHostTests/SettingsTests.swift
+++ b/frontend-ios/Tests/ShellHostTests/SettingsTests.swift
@@ -96,4 +96,25 @@ import ShellUI
#expect(sections[1].rows[2].kind == .range(min: 0.5, max: 1.5, step: 0.05, unit: "×"))
#expect(sections[1].rows[2].value == "1.0")
}
+
+ @MainActor @Test func romfsLanguagesSupplyTheGameLanguageRowWhenLauncherJSONHasNone() throws {
+ let box = try Sandbox()
+ let gameData = try box.giveAppData(Fixtures.orbit)
+ try box.write("JPja USen CNzh TWzh\n0111\n", to: gameData.appendingPathComponent("romfs/System/RegionLangMask.txt"))
+
+ let model = ShellHostModel(config: box.config())
+ let detail = try #require(model.details.first { $0.id == Fixtures.orbit })
+ let gameSection = try #require(detail.sections.first { $0.id == "Game" })
+ let langRow = try #require(gameSection.rows.first { $0.id == "DM_LANG" })
+ #expect(langRow.value == "en-US")
+ if case .choice(let opts) = langRow.kind {
+ #expect(opts.map(\.id) == ["en-US", "ja", "zh-Hant", "zh-Hans"])
+ } else {
+ Issue.record("expected DM_LANG to be a choice row")
+ }
+
+ model.change(Fixtures.orbit, setting: "DM_LANG", value: "zh-Hans")
+ let updated = try #require(model.details.first { $0.id == Fixtures.orbit })
+ #expect(updated.sections.first { $0.id == "Game" }?.rows.first { $0.id == "DM_LANG" }?.value == "zh-Hans")
+ }
}
diff --git a/frontend/Sources/NX2Apple/Library.swift b/frontend/Sources/NX2Apple/Library.swift
index b07aec31..1ad38fc3 100644
--- a/frontend/Sources/NX2Apple/Library.swift
+++ b/frontend/Sources/NX2Apple/Library.swift
@@ -142,6 +142,18 @@ 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" }) {
+ let langs = RomFSLanguages.options(in: app)
+ if langs.count > 1 {
+ let def = RomFSLanguages.defaultLanguage(forApp: app, options: langs)
+ let row = LaunchSetting(env: "DM_LANG", kind: "choice", label: "Game language", note: "", def: def,
+ section: "Game", options: langs, min: nil, max: nil, step: nil, on: nil, off: nil,
+ level: "basic", unsetValue: def).localized(labels)
+ let idx = list.firstIndex { $0.env == "DM_FULLSCREEN" }
+ ?? list.lastIndex { $0.sectionTitle == "Game" }.map { $0 + 1 } ?? 0
+ list.insert(row, at: idx)
+ }
+ }
if let i = list.firstIndex(where: { $0.env == "DM_RENDER_SCALE" && $0.base == nil }), let base = renderBase(titleID: titleID, repo: repo) {
list[i].base = base
}
diff --git a/frontend/Sources/NXCore/RomFSLanguages.swift b/frontend/Sources/NXCore/RomFSLanguages.swift
new file mode 100644
index 00000000..9e513416
--- /dev/null
+++ b/frontend/Sources/NXCore/RomFSLanguages.swift
@@ -0,0 +1,205 @@
+import Foundation
+
+/// Languages a game's RomFS offers when the game was built without `control.nacp` (a dump folder or a NUP without control data,
+/// LNPANDY/NX2Apple#668, seedds/nxnative#1208). Nintendo's first-party titles list their compiled region-language packs in
+/// `System/RegionLangMask.txt` and ship one archive per pack under `Mals/<Tag>.Product.*`.
+package enum RomFSLanguages {
+ /// Horizon's 16 language codes and English labels in the order `dm/tools/nacp.py` (`LANGUAGES`) writes them.
+ package static let table: [(code: String, label: String)] = [
+ ("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")
+ ]
+
+ /// Nintendo region-language tags (`System/RegionLangMask.txt`, `Mals/<Tag>.Product.*`) to Horizon language codes.
+ package static let regionTags: [String: String] = [
+ "USen": "en-US", "EUen": "en-GB", "JPja": "ja", "EUfr": "fr",
+ "EUde": "de", "USes": "es-419", "EUes": "es", "EUit": "it",
+ "EUnl": "nl", "USfr": "fr-CA", "EUpt": "pt", "EUru": "ru",
+ "KRko": "ko", "TWzh": "zh-Hant", "CNzh": "zh-Hans", "USpt": "pt-BR"
+ ]
+
+ /// `[code, label]` pairs in `table` order for a set of Nintendo region-language tags.
+ package static func options(forTags tags: some Sequence<String>) -> [[String]] {
+ let codes = Set(tags.compactMap { regionTags[$0] })
+ return table.filter { codes.contains($0.code) }.map { [$0.code, $0.label] }
+ }
+
+ /// Reads the `[code, label]` pairs from a RomFS image (`romfs.img`), a RomFS tree (`romfs/`), a folder holding either, or a
+ /// `.app` bundle (`Contents/Resources/romfs.img` or `Contents/Resources/romfs`). Empty when fewer than two languages are found.
+ package static func options(in path: String, fm: FileManager = .default) -> [[String]] {
+ guard !path.isEmpty else { return [] }
+ for candidate in candidates(for: path) {
+ var isDir: ObjCBool = false
+ guard fm.fileExists(atPath: candidate, isDirectory: &isDir) else { continue }
+ let found = isDir.boolValue ? fromDirectory(candidate, fm: fm) : fromImage(candidate)
+ if found.count > 1 { return found }
+ }
+ return []
+ }
+
+ /// The default language code for a Mac `.app`: its `DMLanguage` from `Contents/Info.plist` when the game offers it, else
+ /// `en-US` when offered, else the first offered language.
+ package static func defaultLanguage(forApp app: String, options: [[String]]) -> String {
+ let codes = Set(options.compactMap(\.first))
+ if let plist = NSDictionary(contentsOfFile: app + "/Contents/Info.plist"),
+ let lang = plist["DMLanguage"] as? String, codes.contains(lang) {
+ return lang
+ }
+ if codes.contains("en-US") { return "en-US" }
+ 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.
+ @discardableResult
+ package static func addToLauncherJSONIfMissing(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 }
+ let opts = options(in: romfs, fm: fm)
+ guard opts.count > 1 else { return false }
+ 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] = [
+ "env": "DM_LANG",
+ "kind": "choice",
+ "section": "Game",
+ "label": "Game language",
+ "note": "",
+ "default": def,
+ "level": "basic",
+ "options": opts
+ ]
+ let after = settings.lastIndex { ($0["section"] as? String ?? "Game") == "Game" }.map { $0 + 1 } ?? 0
+ settings.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
+ }
+
+ private static func candidates(for path: String) -> [String] {
+ [
+ path + "/Contents/Resources/romfs.img",
+ path + "/Contents/Resources/romfs",
+ path + "/romfs.img",
+ path + "/RomFS.img",
+ path + "/romfs",
+ path + "/RomFS",
+ path
+ ]
+ }
+
+ private static func tagsFromMask(_ text: String) -> [String] {
+ for raw in text.components(separatedBy: .newlines) {
+ let line = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !line.isEmpty, !line.hasPrefix("#"), !line.hasPrefix("/") {
+ return line.split(whereSeparator: \.isWhitespace).map(String.init)
+ }
+ }
+ return []
+ }
+
+ private static func tagsFromMals(_ names: some Sequence<String>) -> [String] {
+ names.compactMap { name -> String? in
+ guard name.contains(".Product."), let dot = name.firstIndex(of: ".") else { return nil }
+ return String(name[..<dot])
+ }
+ }
+
+ private static func fromDirectory(_ dir: String, fm: FileManager) -> [[String]] {
+ let maskPath = dir + "/System/RegionLangMask.txt"
+ if let data = fm.contents(atPath: maskPath), let text = String(data: data, encoding: .utf8) {
+ let opts = options(forTags: tagsFromMask(text))
+ if opts.count > 1 { return opts }
+ }
+ if let names = try? fm.contentsOfDirectory(atPath: dir + "/Mals") {
+ let opts = options(forTags: tagsFromMals(names))
+ if opts.count > 1 { return opts }
+ }
+ return []
+ }
+
+ /// Reads `System/RegionLangMask.txt` or `Mals/` from a `DMROMFS1` image (`dm/tools/romfs.py`) by seeking to the index at the
+ /// end of the file, without reading the multi-GB data region.
+ private static func fromImage(_ path: String) -> [[String]] {
+ guard let handle = FileHandle(forReadingAtPath: path) else { return [] }
+ defer { try? handle.close() }
+ guard let fileSize = try? handle.seekToEnd(), (try? handle.seek(toOffset: 0)) != nil,
+ let headData = try? handle.read(upToCount: 32), headData.count == 32 else { return [] }
+ let head = [UInt8](headData)
+ func u64(_ bytes: [UInt8], _ o: Int) -> UInt64 {
+ (0..<8).reduce(0) { $0 | UInt64(bytes[o + $1]) << (8 * UInt64($1)) }
+ }
+ func u32(_ bytes: [UInt8], _ o: Int) -> Int {
+ Int(bytes[o]) | Int(bytes[o + 1]) << 8 | Int(bytes[o + 2]) << 16 | Int(bytes[o + 3]) << 24
+ }
+ func u16(_ bytes: [UInt8], _ o: Int) -> Int {
+ Int(bytes[o]) | Int(bytes[o + 1]) << 8
+ }
+ guard head[0..<8].elementsEqual("DMROMFS1".utf8) else { return [] }
+ let idxOff = u64(head, 8), idxSize = u64(head, 16), count = u64(head, 24)
+ guard idxOff >= 32, idxOff <= fileSize, idxSize == fileSize - idxOff,
+ idxSize <= 64 * 1024 * 1024, count >= 1, count * 24 <= idxSize,
+ (try? handle.seek(toOffset: idxOff)) != nil,
+ let idxData = try? handle.read(upToCount: Int(idxSize)), idxData.count == Int(idxSize) else { return [] }
+ let idx = [UInt8](idxData)
+ let namesBase = Int(count) * 24
+
+ struct Entry {
+ var a: UInt64
+ var b: UInt64
+ var name: String
+ var type: UInt8
+ }
+ func entry(_ i: Int) -> Entry? {
+ guard i >= 0, i < Int(count) else { return nil }
+ let o = i * 24
+ let nOff = namesBase + u32(idx, o + 16), nLen = u16(idx, o + 20)
+ guard nOff >= namesBase, nOff + nLen <= idx.count else { return nil }
+ let name = String(decoding: idx[nOff..<(nOff + nLen)], as: UTF8.self)
+ return Entry(a: u64(idx, o), b: u64(idx, o + 8), name: name, type: idx[o + 22])
+ }
+ func children(of dirIndex: Int) -> [Int] {
+ guard let dir = entry(dirIndex), dir.type == 2,
+ dir.a <= count, dir.b <= count - dir.a else { return [] }
+ return Array(Int(dir.a)..<Int(dir.a + dir.b))
+ }
+ func findChild(in dirIndex: Int, named target: String) -> Int? {
+ children(of: dirIndex).first { entry($0)?.name == target }
+ }
+
+ if let sys = findChild(in: 0, named: "System"),
+ let maskIdx = findChild(in: sys, named: "RegionLangMask.txt"),
+ let mask = entry(maskIdx), mask.type == 1, mask.b > 0, mask.b <= 65536,
+ mask.a + mask.b <= idxOff,
+ (try? handle.seek(toOffset: mask.a)) != nil,
+ let maskData = try? handle.read(upToCount: Int(mask.b)),
+ let text = String(data: maskData, encoding: .utf8) {
+ let opts = options(forTags: tagsFromMask(text))
+ if opts.count > 1 { return opts }
+ }
+ if let mals = findChild(in: 0, named: "Mals") {
+ let names = children(of: mals).compactMap { entry($0)?.name }
+ let opts = options(forTags: tagsFromMals(names))
+ if opts.count > 1 { return opts }
+ }
+ return []
+ }
+}
diff --git a/frontend/Sources/NXModel/BuildStore+Archive.swift b/frontend/Sources/NXModel/BuildStore+Archive.swift
index 6359b8ec..4d0e8b50 100644
--- a/frontend/Sources/NXModel/BuildStore+Archive.swift
+++ b/frontend/Sources/NXModel/BuildStore+Archive.swift
@@ -14,6 +14,9 @@ extension BuildStore {
package func placeAddOnContent(workDir: String, in dest: String) {
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)
+ }
}
/// Pack the extracted RomFS into one romfs.img. The extracted folder is
diff --git a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
index bbac8066..705df641 100644
--- a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
+++ b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
@@ -101,6 +101,60 @@ final class MacAppLanguageTests: IsolatedDefaultsTestCase {
XCTAssertEqual(env["DM_LAUNCHER"], "0")
}
+ /// A dump or NACP-less game whose launcher.json has no DM_LANG row gets one from its RomFS (System/RegionLangMask.txt or Mals/, #668).
+ func testRomFSLanguagesSupplyTheRowWhenLauncherJSONHasNone() throws {
+ let app = temporary.appendingPathComponent("Bananza.app")
+ let dm = app.appendingPathComponent("Contents/Resources/dm")
+ try FileManager.default.createDirectory(at: dm, withIntermediateDirectories: true)
+ let noLangJSON = #"{"schema": 1, "game": "040074A01BF12000", "settings": [{"env": "DM_OPMODE", "kind": "choice", "section": "Game", "label": "Console mode", "note": "", "default": "1", "level": "basic", "options": [["1", "Docked"], ["0", "Handheld"]]}]}"#
+ try Data(noLangJSON.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 imgURL = app.appendingPathComponent("Contents/Resources/romfs.img")
+ try Self.makeDMROMFSImage(mask: "JPja USen CNzh TWzh EUfr\n01111\n").write(to: imgURL)
+
+ 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" })
+ XCTAssertFalse(lang.storeBacked, "the app's Info.plist has no DMSettings rule for DM_LANG, so the launcher keeps and passes the choice")
+ XCTAssertEqual(lang.def, "en-US")
+ XCTAssertEqual(lang.options?.map { $0[0] }, ["en-US", "ja", "fr", "zh-Hant", "zh-Hans"])
+
+ var game = LibraryGame(titleID: "040074A01BF12000", name: "Donkey Kong Bananza", appPath: app.path)
+ XCTAssertNil(game.launchEnvironment(list)["DM_LANG"], "at the default language the variable stays unset so env.txt still works")
+ game.launchOptions["DM_LANG"] = "zh-Hans"
+ XCTAssertEqual(game.launchEnvironment(list)["DM_LANG"], "zh-Hans")
+
+ // The archive step also adds the row to an iOS framework's launcher.json when it lacks one.
+ 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))
+ 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"])
+ }
+
+ /// Minimal DMROMFS1 image with `/System/RegionLangMask.txt` containing `mask`.
+ private static func makeDMROMFSImage(mask: String) -> Data {
+ let payload = [UInt8](mask.utf8)
+ let dataOff: UInt64 = 32
+ let paddedLen = (payload.count + 7) & ~7
+ let idxOff = dataOff + UInt64(paddedLen)
+ let names = [UInt8]("SystemRegionLangMask.txt".utf8)
+ func le64(_ v: UInt64) -> [UInt8] { (0..<8).map { UInt8((v >> (8 * UInt64($0))) & 0xff) } }
+ func le32(_ v: UInt32) -> [UInt8] { (0..<4).map { UInt8((v >> (8 * UInt32($0))) & 0xff) } }
+ func le16(_ v: UInt16) -> [UInt8] { [UInt8(v & 0xff), UInt8((v >> 8) & 0xff)] }
+ func entry(_ a: UInt64, _ b: UInt64, _ nOff: UInt32, _ nLen: UInt16, _ type: UInt8) -> [UInt8] {
+ le64(a) + le64(b) + le32(nOff) + le16(nLen) + [type, 0]
+ }
+ let entries = entry(1, 1, 0, 0, 2)
+ + entry(2, 1, 0, 6, 2)
+ + entry(dataOff, UInt64(payload.count), 6, 18, 1)
+ let idx = entries + names
+ let head = [UInt8]("DMROMFS1".utf8) + le64(idxOff) + le64(UInt64(idx.count)) + le64(3)
+ return Data(head + payload + [UInt8](repeating: 0, count: paddedLen - payload.count) + idx)
+ }
+
/// settings.py output, as described above.
private static let launcherJSON = ###"""
{