Skip to content

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

launcher: keep languages the launcher cannot name, read an image once by its size and date (#668)

LNPANDY4892d11d2ff2
diff --git a/frontend-ios/Sources/ShellHost/RomfsLanguages.swift b/frontend-ios/Sources/ShellHost/RomfsLanguages.swift
index e3cddf44..b49aabc1 100644
--- a/frontend-ios/Sources/ShellHost/RomfsLanguages.swift
+++ b/frontend-ios/Sources/ShellHost/RomfsLanguages.swift
@@ -46,7 +46,7 @@ enum RomfsLanguages {
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)
+ let found = isDir.boolValue ? fromDirectory(candidate, fm: fm) : cachedFromImage(candidate, fm: fm)
if found.count > 1 { return found }
}
return []
@@ -57,16 +57,18 @@ enum RomfsLanguages {
/// 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))
+ return Set(table.map(\.code)).isSubset(of: codes) // a superset: the engine may add languages to its table later
}
- /// 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.
+ /// The fallback row's options cut to the languages the RomFS offers, in the row's own order and labels. An option goes only when its
+ /// code is one the RomFS tags can name (`table`) and the RomFS lacks it: a code this app does not know, a language the engine adds
+ /// later, stays. Nil when the RomFS names fewer than two languages, or the row's default (the language the game is packed with)
+ /// would go: 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
+ let offered = Set(romfs.compactMap(\.first)), known = Set(table.map(\.code))
+ guard offered.count > 1 else { return nil }
+ let kept = options.filter { o in o.first.map { !known.contains($0) || offered.contains($0) } ?? false }
+ return kept.count > 1 && kept.contains { $0.first == def } ? 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
@@ -90,6 +92,29 @@ enum RomfsLanguages {
return updated
}
+ /// What an image gave, by path, size and modification date: the shell asks again whenever it builds a game's settings, and a copy that
+ /// is cut off, replaced or finished later is read again. Only a list is kept: a failure is read again.
+ private final class ImageCache: @unchecked Sendable {
+ private let lock = NSLock()
+ private var lists: [String: [[String]]] = [:]
+ func get(_ key: String) -> [[String]]? { lock.lock(); defer { lock.unlock() }; return lists[key] }
+ func set(_ key: String, _ value: [[String]]) {
+ lock.lock(); defer { lock.unlock() }
+ if lists.count > 64 { lists.removeAll() }
+ lists[key] = value
+ }
+ }
+ private static let imageCache = ImageCache()
+
+ private static func cachedFromImage(_ url: URL, fm: FileManager) -> [[String]] {
+ let a = try? fm.attributesOfItem(atPath: url.path)
+ let key = "\(url.path)|\((a?[.size] as? NSNumber)?.int64Value ?? -1)|\((a?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0)"
+ if let hit = imageCache.get(key) { return hit }
+ let found = fromImage(url)
+ if found.count > 1 { imageCache.set(key, found) }
+ return found
+ }
+
private static func tagsFromMask(_ text: String) -> [String] {
for raw in text.components(separatedBy: .newlines) {
let line = raw.trimmingCharacters(in: .whitespacesAndNewlines)
diff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
index 2c32a32f..a542fff1 100644
--- a/frontend-ios/Sources/ShellHost/ShellHostModel.swift
+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
@@ -71,7 +71,6 @@ 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
@@ -221,14 +220,7 @@ public struct ShellHostConfig: Sendable {
// 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
- } else {
- opts = RomfsLanguages.options(in: url)
- romfsLanguages[url] = opts
- }
- return RomfsLanguages.applying(to: base, options: opts)
+ return RomfsLanguages.applying(to: base, options: RomfsLanguages.options(in: url)) // read once per image: RomfsLanguages caches by size and date
}
private func image(_ url: URL?) -> Artwork? {
diff --git a/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift b/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift
index 10ceb6d4..2ad53186 100644
--- a/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift
+++ b/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift
@@ -156,6 +156,32 @@ import Testing
#expect(!RomfsLanguages.isFallbackRow(try #require(langRow(p))))
}
+ /// The engine may add languages to its table later (seedds/nxnative#1231 asks for Thai and Polish). The row is still recognised, and a
+ /// language this app cannot name from a RomFS tag is kept, not dropped with the ones the RomFS lacks.
+ @Test func aLanguageTheAppDoesNotKnowIsKept() throws {
+ let extended = Self.fallbackRowJSON.replacingOccurrences(of: #"["pt-BR","Brazilian Portuguese"]]"#, with: #"["pt-BR","Brazilian Portuguese"],["th","Thai"],["pl","Polish"]]"#)
+ let p = try profile(row: extended)
+ #expect(RomfsLanguages.isFallbackRow(try #require(langRow(p))))
+ let opts = RomfsLanguages.options(in: try folder(with: Self.image(mask("JPja USen CNzh\n011\n"))))
+ let row = try #require(langRow(RomfsLanguages.applying(to: p, options: opts)))
+ #expect(row.options?.map { $0[0] } == ["en-US", "ja", "zh-Hans", "th", "pl"])
+ #expect(row.note == "")
+ }
+
+ /// A copy that is cut off, finished later or replaced is read again: only a list is kept, and by size and date.
+ @Test func anImageThatChangesIsReadAgain() throws {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("romfs-change-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let path = dir.appendingPathComponent("romfs.img")
+ let two = Self.image(mask("USen JPja\n"))
+ try two.prefix(two.count - 10).write(to: path)
+ #expect(RomfsLanguages.options(in: dir) == [])
+ try two.write(to: path)
+ #expect(RomfsLanguages.options(in: dir).map { $0[0] } == ["en-US", "ja"])
+ try Self.image(mask("USen JPja EUfr\n")).write(to: path)
+ #expect(RomfsLanguages.options(in: dir).map { $0[0] } == ["en-US", "ja", "fr"])
+ }
+
@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)
diff --git a/frontend/Sources/NXCore/RomFSLanguages.swift b/frontend/Sources/NXCore/RomFSLanguages.swift
index 9903f66c..dd2e7a20 100644
--- a/frontend/Sources/NXCore/RomFSLanguages.swift
+++ b/frontend/Sources/NXCore/RomFSLanguages.swift
@@ -45,7 +45,7 @@ package enum RomFSLanguages {
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)
+ let found = isDir.boolValue ? fromDirectory(candidate, fm: fm) : cachedFromImage(candidate, fm: fm)
if found.count > 1 { return found }
}
return []
@@ -68,17 +68,18 @@ package enum RomFSLanguages {
/// 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))
+ return Set(table.map(\.code)).isSubset(of: codes) // a superset: the engine may add languages to its table later
}
- /// 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.
+ /// The fallback row's options cut to the languages the RomFS offers, in the row's own order and labels. An option goes only when its
+ /// code is one the RomFS tags can name (`table`) and the RomFS lacks it: a code this launcher does not know, a language the engine adds
+ /// later, stays. Nil when the RomFS names fewer than two languages, or the row's default (the packed language, which the app starts
+ /// with when nothing is chosen) would go: 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
+ let offered = Set(romfs.compactMap(\.first)), known = Set(table.map(\.code))
+ guard offered.count > 1 else { return nil }
+ let kept = options.filter { o in o.first.map { !known.contains($0) || offered.contains($0) } ?? false }
+ return kept.count > 1 && kept.contains { $0.first == def } ? kept : nil
}
/// Makes `launcher.json` at `launcherPath` offer the game's real languages, from `romfs`: adds a `DM_LANG` row when the file has
@@ -123,6 +124,29 @@ package enum RomFSLanguages {
return write()
}
+ /// What an image gave, by path, size and modification date, so the many reads of one settings sheet (it asks again at every redraw) cost
+ /// one read of the index, and a file that is copied over or replaced is read again. Only a list is kept: a failure is read again.
+ private final class ImageCache: @unchecked Sendable {
+ private let lock = NSLock()
+ private var lists: [String: [[String]]] = [:]
+ func get(_ key: String) -> [[String]]? { lock.lock(); defer { lock.unlock() }; return lists[key] }
+ func set(_ key: String, _ value: [[String]]) {
+ lock.lock(); defer { lock.unlock() }
+ if lists.count > 64 { lists.removeAll() }
+ lists[key] = value
+ }
+ }
+ private static let imageCache = ImageCache()
+
+ private static func cachedFromImage(_ path: String, fm: FileManager) -> [[String]] {
+ let a = try? fm.attributesOfItem(atPath: path)
+ let key = "\(path)|\((a?[.size] as? NSNumber)?.int64Value ?? -1)|\((a?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0)"
+ if let hit = imageCache.get(key) { return hit }
+ let found = fromImage(path)
+ if found.count > 1 { imageCache.set(key, found) }
+ return found
+ }
+
private static func candidates(for path: String) -> [String] {
[
path + "/Contents/Resources/romfs.img",
diff --git a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
index b9b734bd..3fd8e0d3 100644
--- a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
+++ b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
@@ -187,6 +187,30 @@ final class MacAppLanguageTests: IsolatedDefaultsTestCase {
XCTAssertEqual(lang.options?.count, 16)
}
+ /// The engine may add languages to its table later (seedds/nxnative#1231 asks for Thai and Polish). The row is still recognised, and a
+ /// language this launcher cannot name from a RomFS tag is kept, not dropped with the ones the RomFS lacks.
+ func testALanguageTheLauncherDoesNotKnowIsKept() throws {
+ let extended = Self.fallbackLangRow.replacingOccurrences(of: #"["pt-BR","Brazilian Portuguese"]]"#, with: #"["pt-BR","Brazilian Portuguese"],["th","Thai"],["pl","Polish"]]"#)
+ XCTAssertTrue(extended.contains(#"["th","Thai"]"#))
+ let (app, _) = try appWithLangRow(extended, mask: "JPja USen CNzh\n011\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?.map { $0[0] }, ["en-US", "ja", "zh-Hans", "th", "pl"])
+ XCTAssertEqual(lang.note, "")
+ }
+
+ /// A copy that is cut off, finished later or replaced is read again: only a list is kept, and by size and date.
+ func testAnImageThatChangesIsReadAgain() throws {
+ let path = temporary.appendingPathComponent("changing.img")
+ let two = Self.makeDMROMFSImage(mask: "USen JPja\n")
+ try two.prefix(two.count - 10).write(to: path) // cut off: no list
+ XCTAssertEqual(RomFSLanguages.options(in: path.path), [])
+ try two.write(to: path) // the copy finished
+ XCTAssertEqual(RomFSLanguages.options(in: path.path).map { $0[0] }, ["en-US", "ja"])
+ try Self.makeDMROMFSImage(mask: "USen JPja EUfr\n").write(to: path) // replaced by another version
+ XCTAssertEqual(RomFSLanguages.options(in: path.path).map { $0[0] }, ["en-US", "ja", "fr"])
+ }
+
/// 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")