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
Ask before the build when the shared app holds frameworks of an old shader chain (#449)
v0lumehi048b442ef6d1
diff --git a/frontend/Sources/NX2Apple/ContentView.swift b/frontend/Sources/NX2Apple/ContentView.swiftindex a9641641..c52ab444 100644--- a/frontend/Sources/NX2Apple/ContentView.swift+++ b/frontend/Sources/NX2Apple/ContentView.swift@@ -119,6 +119,7 @@ final class BuildModel: ObservableObject {@Published var stages: [Stage] = []private var chainNoteShown = false // the shader-chain notice shows once per build@Published var running = false+ @Published var staleFrameworks: [StaleFrameworks.Entry] = [] // the prompt of StaleFrameworksPrompt.swift (#449)/// The shell folder the cache row shows: the frameworks' mirror, shell.json and the banner cache live here.var shellCachePath: String { shellRoot }/// The shell folder of the install and of the cache row: the saved one, else next to the output folder (or the game's folder).@@ -1243,6 +1244,7 @@ final class BuildModel: ObservableObject {return}shellDeviceChecked = false+ if target != BuildTarget.mac, askAboutStaleFrameworks() { return } // StaleFrameworksPrompt.swift (#449)stopping = falserunning = true; done = false; doneNote = ""; stages = []; logTail = ""; lineBuf = ""; chainNoteShown = falsefailure = nil; confirmingOverride = nil@@ -2758,7 +2760,6 @@ final class BuildModel: ObservableObject {return BuildTarget.normalized(defaults.string(forKey: "buildTarget")) != BuildTarget.mac}-/// The rows for the build tools (xcodegen, zstd, spirv-cross, glslangValidator) and the Homebrew row they may need./// A tool the app carries counts as present and says "bundled"; otherwise Homebrew's copy counts (`installed` answers/// a binary name with its path in a Homebrew folder, or nil). The Homebrew row appears only when some tool is neither@@ -3427,6 +3428,7 @@ struct BuilderView: View {.keyboardShortcut(.return, modifiers: .command)}.padding(.top, 2)+ .staleFrameworksPrompt(m)}@ViewBuilder private var statusText: some View {@@ -3730,8 +3732,6 @@ struct BuilderView: View {}}--private func pickRepo() {let d = NSOpenPanel()d.canChooseDirectories = true; d.canChooseFiles = falsediff --git a/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift b/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swiftnew file mode 100644index 00000000..c2dff10d--- /dev/null+++ b/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift@@ -0,0 +1,69 @@+import SwiftUI+import NXCore++// LNPANDY/NX2Apple#449: a build for the iPhone or iPad asks before the long steps when the shell folder holds frameworks of+// another shader chain than the engine this build uses. Stop leaves every file as it is. Continue deletes the stale frameworks+// (and their entries in the shell's library) and starts the build again. Without stale frameworks nothing is asked. A framework+// whose chain cannot be read is not decided here, build_shell.sh's own check at the last step stays for it.++extension BuildModel {+ /// The stale frameworks of the shared app for the engine this build runs, nothing when the check cannot decide.+ func staleFrameworkEntries() -> [StaleFrameworks.Entry] {+ guard let chain = StaleFrameworks.currentChain(engineRoot: EngineLayout.root(repoPath)) else { return [] }+ let root = shellRoot+ let known = ShellLibrary.load(root: root).games.map { (titleID: $0.titleID, name: $0.name, framework: $0.framework) }+ return StaleFrameworks.find(root: root, chain: chain, known: known, except: Self.buildKey(basePath))+ }++ /// True when the build must wait for the player's answer: the prompt is showing (`staleFrameworks` is set).+ func askAboutStaleFrameworks() -> Bool {+ let entries = staleFrameworkEntries()+ guard !entries.isEmpty else { return false }+ staleFrameworks = entries+ return true+ }++ /// Stop the build: nothing was touched.+ func stopForStaleFrameworks() { staleFrameworks = [] }++ /// Continue: delete the stale frameworks, drop their games from the shell's library, and start the build.+ func continueWithStaleFrameworks(then start: (() -> Void)? = nil) {+ let entries = staleFrameworks+ staleFrameworks = []+ let failed = Self.removeStaleFrameworks(entries, root: shellRoot)+ if !failed.isEmpty {+ done = false+ doneNote = String(format: t("stale.removeFailed"), failed.map { ($0 as NSString).lastPathComponent }.joined(separator: ", "))+ return+ }+ (start ?? startBuild)()+ }++ /// The folders of `entries` are deleted and the games leave `<root>/shell.json`. Returns the folders that could not be deleted.+ static func removeStaleFrameworks(_ entries: [StaleFrameworks.Entry], root: String) -> [String] {+ let failed = StaleFrameworks.remove(entries)+ var library = ShellLibrary.load(root: root)+ let gone = Set(entries.map { $0.titleID.lowercased() })+ library.games.removeAll { gone.contains($0.titleID.lowercased()) }+ try? library.save(root: root)+ return failed+ }+}++private struct StaleFrameworksPrompt: ViewModifier {+ @ObservedObject var m: BuildModel++ func body(content: Content) -> some View {+ content.alert(m.t("stale.title"), isPresented: Binding(get: { !m.staleFrameworks.isEmpty },+ set: { if !$0 { m.stopForStaleFrameworks() } })) {+ Button(m.t("stale.go")) { m.continueWithStaleFrameworks() }+ Button(m.t("stale.stop"), role: .cancel) { m.stopForStaleFrameworks() }+ } message: {+ Text(String(format: m.t("stale.message"), StaleFrameworks.list(m.staleFrameworks)))+ }+ }+}++extension View {+ func staleFrameworksPrompt(_ m: BuildModel) -> some View { modifier(StaleFrameworksPrompt(m: m)) }+}diff --git a/frontend/Sources/NXCore/Localization.swift b/frontend/Sources/NXCore/Localization.swiftindex 485b074f..25ed7a4e 100644--- a/frontend/Sources/NXCore/Localization.swift+++ b/frontend/Sources/NXCore/Localization.swift@@ -4218,7 +4218,7 @@ package enum L10n {]package static func string(_ key: String, _ lang: Lang) -> String {- guard let row = table[key] else { return key } // shows up in the UI rather than a blank control+ guard let row = table[key] else { return extra(key, lang) } // shows up in the UI rather than a blank controlswitch lang {case .zh: return row.zhcase .en: return row.endiff --git a/frontend/Sources/NXCore/LocalizationStaleFrameworks.swift b/frontend/Sources/NXCore/LocalizationStaleFrameworks.swiftnew file mode 100644index 00000000..4b9da6ed--- /dev/null+++ b/frontend/Sources/NXCore/LocalizationStaleFrameworks.swift@@ -0,0 +1,40 @@+import Foundation++// The strings of the stale-frameworks prompt (LNPANDY/NX2Apple#449). `L10n.string` asks `extra` for a key the main table does not+// hold. Localization.swift is above the size limit and may only shrink, so a new feature's strings live in their own file.+extension L10n {+ package static func extra(_ key: String, _ lang: Lang) -> String {+ guard let row = staleFrameworks[key] else { return key }+ return row[lang] ?? row[.en] ?? key+ }++ private static let staleFrameworks: [String: [Lang: String]] = [+ "stale.title": [+ .en: "Build the installed games again?",+ .zh: "要重新构建已安装的游戏吗?",+ .de: "Die installierten Spiele neu bauen?",+ .sv: "Bygga de installerade spelen igen?",+ .fr: "Reconstruire les jeux installés\u{a0}?",+ ],+ "stale.message": [+ .en: "The engine changed its shader chain. Installing a new game needs the games already in the shared app to be built again:\n\n%@\n\nContinue removes them from the shared app and deletes their local framework cache, then the build goes on. Stop the build leaves everything as it is.",+ .zh: "引擎更换了着色器链。安装新游戏需要重新构建共用应用中已有的游戏:\n\n%@\n\n选择“继续”会把它们从共用应用中移除,并删除它们的本地框架缓存,然后继续构建。选择“停止构建”则不会改动任何内容。",+ .de: "Die Engine hat ihre Shader-Kette gewechselt. Für ein neues Spiel müssen die Spiele, die schon in der gemeinsamen App sind, neu gebaut werden:\n\n%@\n\nMit „Fortfahren“ werden sie aus der gemeinsamen App entfernt und ihr lokaler Framework-Cache wird gelöscht, dann geht der Build weiter. „Build stoppen“ lässt alles, wie es ist.",+ .sv: "Motorn har bytt shaderkedja. För att installera ett nytt spel måste spelen som redan finns i den gemensamma appen byggas igen:\n\n%@\n\nFortsätt tar bort dem från den gemensamma appen och raderar deras lokala ramverkscache, sedan går bygget vidare. Stoppa bygget lämnar allt som det är.",+ .fr: "Le moteur a changé de chaîne de shaders. Installer un nouveau jeu demande de reconstruire les jeux déjà présents dans l’app partagée\u{a0}:\n\n%@\n\nContinuer les retire de l’app partagée et supprime leur cache local de frameworks, puis la construction se poursuit. Arrêter la construction ne touche à rien.",+ ],+ "stale.removeFailed": [+ .en: "The old frameworks could not be removed: %@. Remove them from NX2Apple-shell/frameworks and build again.",+ .zh: "无法移除旧的框架:%@。请从 NX2Apple-shell/frameworks 中删除它们,然后重新构建。",+ .de: "Die alten Frameworks konnten nicht entfernt werden: %@. Entferne sie aus NX2Apple-shell/frameworks und baue erneut.",+ .sv: "De gamla ramverken kunde inte tas bort: %@. Ta bort dem från NX2Apple-shell/frameworks och bygg igen.",+ .fr: "Les anciens frameworks n’ont pas pu être supprimés\u{a0}: %@. Supprimez-les de NX2Apple-shell/frameworks et reconstruisez.",+ ],+ "stale.go": [+ .en: "Continue", .zh: "继续", .de: "Fortfahren", .sv: "Fortsätt", .fr: "Continuer",+ ],+ "stale.stop": [+ .en: "Stop the build", .zh: "停止构建", .de: "Build stoppen", .sv: "Stoppa bygget", .fr: "Arrêter la construction",+ ],+ ]+}diff --git a/frontend/Sources/NXCore/StaleFrameworks.swift b/frontend/Sources/NXCore/StaleFrameworks.swiftnew file mode 100644index 00000000..7c6a156e--- /dev/null+++ b/frontend/Sources/NXCore/StaleFrameworks.swift@@ -0,0 +1,84 @@+import Foundation++/// LNPANDY/NX2Apple#449: the shared iPhone and iPad app takes frameworks of one shader chain only. After an engine update that+/// changes the chain, the frameworks already in the shell folder are stale, and build_shell.sh refuses them at the last step.+/// This finds them before the long steps. The chain of the engine is the `DMSH_CHAIN` of `dm/gfx/nvn/dmsh_chain.h` (the+/// `b-<chain>` folder name), the chain of a framework is the `chain` of its `game.manifest.json`, the two values the script compares.+package enum StaleFrameworks {+ package struct Entry: Equatable {+ package var titleID: String+ package var name: String+ package var chain: String+ package var paths: [String]+ }++ /// `b-<chain>` of the engine tree at `engineRoot`, or nil when the header cannot be read.+ package static func currentChain(engineRoot: String) -> String? {+ guard let text = try? String(contentsOfFile: engineRoot + "/dm/gfx/nvn/dmsh_chain.h", encoding: .utf8) else { return nil }+ let prefix = "#define DMSH_CHAIN \""+ for line in text.split(separator: "\n") where line.hasPrefix(prefix) {+ let value = line.dropFirst(prefix.count).prefix { $0 != "\"" }+ return value.isEmpty ? nil : "b-" + value+ }+ return nil+ }++ /// The manifest of a framework folder: its `chain`, `title_id` and `name`. nil when it has none or it cannot be read.+ private static func manifest(of framework: String) -> (chain: String, titleID: String, name: String)? {+ guard let data = FileManager.default.contents(atPath: framework + "/game.manifest.json"),+ let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ let chain = json["chain"] as? String else { return nil }+ return (chain, json["title_id"] as? String ?? "", json["name"] as? String ?? "")+ }++ /// The frameworks of another chain than `chain`: those in the shell folder's mirror (`<root>/frameworks`) and those the+ /// library names (`known`: title ID, name and framework folder of each game in shell.json). One entry per title ID, with every+ /// folder that holds it. A framework whose manifest cannot be read is not decided here: build_shell.sh's own check stays+ /// for it. `except` is the game being built now, whose framework this build replaces.+ package static func find(root: String, chain: String, known: [(titleID: String, name: String, framework: String)],+ except: String? = nil) -> [Entry] {+ let fm = FileManager.default+ let mirror = root + "/frameworks"+ var folders = known.map(\.framework)+ for item in ((try? fm.contentsOfDirectory(atPath: mirror)) ?? []).sorted() where item.hasSuffix(".framework") {+ folders.append(mirror + "/" + item)+ }+ var entries: [Entry] = []+ var seen = Set<String>()+ for folder in folders where seen.insert(folder).inserted && fm.fileExists(atPath: folder) {+ guard let m = manifest(of: folder), m.chain != chain else { continue }+ let id = m.titleID.isEmpty ? titleID(ofFolder: folder) : m.titleID+ if let except, except.caseInsensitiveCompare(id) == .orderedSame { continue }+ if let i = entries.firstIndex(where: { $0.titleID.caseInsensitiveCompare(id) == .orderedSame }) {+ entries[i].paths.append(folder)+ continue+ }+ let name = known.first { $0.titleID.caseInsensitiveCompare(id) == .orderedSame }?.name ?? ""+ entries.append(Entry(titleID: id, name: name.isEmpty ? (m.name.isEmpty ? id : m.name) : name, chain: m.chain, paths: [folder]))+ }+ return entries+ }++ /// `DmGame<title ID>.framework` as the title ID.+ private static func titleID(ofFolder folder: String) -> String {+ let name = (folder as NSString).lastPathComponent+ return name.hasPrefix("DmGame") && name.hasSuffix(".framework")+ ? String(name.dropFirst("DmGame".count).dropLast(".framework".count)) : name+ }++ /// Deletes the stale frameworks' folders and nothing else. Returns the folders it could not delete.+ @discardableResult+ package static func remove(_ entries: [Entry]) -> [String] {+ var failed: [String] = []+ for path in entries.flatMap(\.paths) {+ do { try FileManager.default.removeItem(atPath: path) }+ catch { if FileManager.default.fileExists(atPath: path) { failed.append(path) } }+ }+ return failed+ }++ /// The names the prompt lists, one per line.+ package static func list(_ entries: [Entry]) -> String {+ entries.map { "• " + $0.name }.joined(separator: "\n")+ }+}diff --git a/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift b/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swiftnew file mode 100644index 00000000..9d8d3861--- /dev/null+++ b/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift@@ -0,0 +1,163 @@+import XCTest+import SwiftUI+@testable import NX2Apple+@testable import NXCore++/// LNPANDY/NX2Apple#449: a shell folder with one framework of the current chain and one of the old chain.+final class StaleFrameworksTests: XCTestCase {+ private let current = "b-b7cd656abd7c"+ private let old = "b-e65a4ebd3322"+ private let oldID = "0100A00019DE0000"+ private let newID = "0100B00000000000"+ private var tmp = ""++ override func setUpWithError() throws {+ tmp = NSTemporaryDirectory() + "stale-frameworks-\(UUID().uuidString)"+ try FileManager.default.createDirectory(atPath: tmp + "/engine/dm/gfx/nvn", withIntermediateDirectories: true)+ try "// Generated file\n#define DMSH_CHAIN \"b7cd656abd7c\"\n".write(toFile: tmp + "/engine/dm/gfx/nvn/dmsh_chain.h", atomically: true, encoding: .utf8)+ }++ override func tearDownWithError() throws { try? FileManager.default.removeItem(atPath: tmp) }++ private func framework(_ titleID: String, name: String, chain: String) throws -> String {+ let fw = tmp + "/shell/frameworks/DmGame\(titleID).framework"+ try FileManager.default.createDirectory(atPath: fw, withIntermediateDirectories: true)+ let manifest = ["title_id": titleID, "name": name, "chain": chain, "framework": "DmGame\(titleID).framework"]+ try JSONSerialization.data(withJSONObject: manifest).write(to: URL(fileURLWithPath: fw + "/game.manifest.json"))+ try "binary".write(toFile: fw + "/DmGame\(titleID)", atomically: true, encoding: .utf8)+ return fw+ }++ private func exists(_ path: String) -> Bool { FileManager.default.fileExists(atPath: path) }++ private func shell() throws -> (stale: String, fresh: String) {+ let stale = try framework(oldID, name: "Old Game", chain: old)+ let fresh = try framework(newID, name: "Fresh Game", chain: current)+ var library = ShellLibrary()+ library.add(ShellLibrary.Game(titleID: oldID, name: "Old Game", framework: stale))+ library.add(ShellLibrary.Game(titleID: newID, name: "Fresh Game", framework: fresh))+ try library.save(root: tmp + "/shell")+ return (stale, fresh)+ }++ private func found(except: String? = nil) -> [StaleFrameworks.Entry] {+ let known = ShellLibrary.load(root: tmp + "/shell").games.map { (titleID: $0.titleID, name: $0.name, framework: $0.framework) }+ return StaleFrameworks.find(root: tmp + "/shell", chain: current, known: known, except: except)+ }++ func testTheEnginesChainIsTheHeadersWithBPrefix() {+ XCTAssertEqual(StaleFrameworks.currentChain(engineRoot: tmp + "/engine"), current)+ XCTAssertNil(StaleFrameworks.currentChain(engineRoot: tmp + "/nowhere"))+ }++ func testOnlyTheFrameworkOfAnotherChainIsStaleAndItIsNamedByTheLibrary() throws {+ _ = try shell()+ let entries = found()+ XCTAssertEqual(entries.count, 1)+ XCTAssertEqual(entries.first?.titleID, oldID)+ XCTAssertEqual(entries.first?.name, "Old Game")+ XCTAssertEqual(entries.first?.chain, old)+ }++ func testNothingIsAskedWhenEveryFrameworkIsCurrent() throws {+ _ = try framework(newID, name: "Fresh Game", chain: current)+ XCTAssertEqual(found(), [])+ XCTAssertEqual(StaleFrameworks.find(root: tmp + "/empty", chain: current, known: []), [])+ }++ func testTheGameBeingBuiltIsNotAskedAboutBecauseTheBuildReplacesIt() throws {+ _ = try shell()+ XCTAssertEqual(found(except: oldID.lowercased()), [])+ }++ func testAFrameworkWithoutAReadableManifestIsLeftToTheScriptsOwnCheck() throws {+ let fw = try framework(oldID, name: "Old Game", chain: old)+ try "not json".write(toFile: fw + "/game.manifest.json", atomically: true, encoding: .utf8)+ XCTAssertEqual(found(), [])+ }++ func testStopLeavesEveryFileAsItWas() throws {+ let (stale, fresh) = try shell()+ let before = try Data(contentsOf: URL(fileURLWithPath: ShellLibrary.stateFile(root: tmp + "/shell")))+ let model = BuildModel()+ model.staleFrameworks = found()+ XCTAssertFalse(model.staleFrameworks.isEmpty)+ model.stopForStaleFrameworks()+ XCTAssertTrue(model.staleFrameworks.isEmpty)+ XCTAssertTrue(exists(stale))+ XCTAssertTrue(exists(fresh))+ XCTAssertEqual(try Data(contentsOf: URL(fileURLWithPath: ShellLibrary.stateFile(root: tmp + "/shell"))), before)+ }++ func testContinueRemovesTheStaleFrameworkAndKeepsTheCurrentOne() throws {+ let (stale, fresh) = try shell()+ let failed = BuildModel.removeStaleFrameworks(found(), root: tmp + "/shell")+ XCTAssertEqual(failed, [])+ XCTAssertFalse(exists(stale))+ XCTAssertTrue(exists(fresh))+ XCTAssertEqual(ShellLibrary.load(root: tmp + "/shell").games.map(\.titleID), [newID])+ XCTAssertEqual(found(), [], "the shared app now holds only games of the current chain")+ }++ func testContinueStartsTheBuildAndTheModelEndsWithoutAPrompt() throws {+ _ = try shell()+ let model = BuildModel()+ model.staleFrameworks = found()+ var started = false+ UserDefaults.standard.set(tmp + "/shell", forKey: "shellRoot")+ defer { UserDefaults.standard.removeObject(forKey: "shellRoot") }+ model.continueWithStaleFrameworks { started = true }+ XCTAssertTrue(started)+ XCTAssertTrue(model.staleFrameworks.isEmpty)+ XCTAssertEqual(found(), [])+ }++ func testAllFiveLanguagesHaveTheTextsAndNoneUsesASemicolon() {+ for lang in Lang.allCases {+ for key in ["stale.title", "stale.message", "stale.go", "stale.stop", "stale.removeFailed"] {+ let text = L10n.string(key, lang)+ XCTAssertNotEqual(text, key, "\(key) in \(lang)")+ XCTAssertFalse(text.contains(";") || text.contains(";") || text.contains("—"), "\(key) in \(lang)")+ }+ XCTAssertTrue(L10n.string("stale.message", lang).contains("%@"))+ }+ XCTAssertNotEqual(L10n.string("stale.go", .zh), L10n.string("stale.go", .en))+ }++ // MARK: Visual QA (matched by --filter testRenderStalePromptForVisualQA)++ /// The prompt's title, message and two buttons laid out like the system alert, for the pull request's screenshots.+ @MainActor func testRenderStalePromptForVisualQA() 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 FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ let lang = ProcessInfo.processInfo.environment["NX_CAPTURE_LANG"].flatMap { Lang(rawValue: $0) } ?? .en+ let entries = [StaleFrameworks.Entry(titleID: oldID, name: "Super Mario Odyssey", chain: old, paths: []),+ StaleFrameworks.Entry(titleID: newID, name: "Hades", chain: old, paths: [])]+ let alert = VStack(spacing: 12) {+ Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 36)).foregroundStyle(.yellow)+ Text(L10n.string("stale.title", lang)).font(.headline)+ Text(String(format: L10n.string("stale.message", lang), StaleFrameworks.list(entries)))+ .font(.callout).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)+ HStack(spacing: 10) {+ Text(L10n.string("stale.stop", lang)).frame(maxWidth: .infinity).padding(.vertical, 6)+ .background(Color.gray.opacity(0.3), in: RoundedRectangle(cornerRadius: 6))+ Text(L10n.string("stale.go", lang)).frame(maxWidth: .infinity).padding(.vertical, 6)+ .background(Color.accentColor, in: RoundedRectangle(cornerRadius: 6))+ }+ }+ .padding(20).frame(width: 340).background(Color(white: 0.16)).environment(\.colorScheme, .dark)+ NSApplication.shared.setActivationPolicy(.accessory)+ let host = NSHostingView(rootView: alert)+ host.frame = NSRect(origin: .zero, size: host.fittingSize)+ let window = NSWindow(contentRect: host.frame, styleMask: [.titled], backing: .buffered, defer: false)+ window.contentView = host+ window.orderFront(nil)+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))+ host.layoutSubtreeIfNeeded()+ 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("stale-frameworks-\(lang.rawValue).png"))+ window.orderOut(nil)+ }+}