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
The shell folder caches every game's framework, and Settings names it (#398)
LNPANDY98de0bc9327f
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 4b41df70..d77d108b 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -214,6 +214,8 @@ TABLE: dict[str, tuple[str, str, str, str, str]] = {'library.clearSearch': ('清除搜索', 'Clear search', 'Rensa sökning', 'Suche löschen', 'Effacer la recherche'),'settings.heading': ('设置', 'Settings', 'Inställningar', 'Einstellungen', 'Réglages'),'settings.note': ('游戏文件夹、构建工具和应用更新,都在这里。', 'Library location, build tools and updates.', 'Biblioteksplats, byggverktyg och uppdateringar.', 'Speicherort der Bibliothek, Build-Werkzeuge und Updates.', 'Emplacement de la bibliothèque, outils de compilation et mises à jour.'),+ 'shellCache.row': ('缓存文件', 'Cache files', 'Cachefiler', 'Cachedateien', 'Fichiers de cache'),+ 'shellCache.note': ('壳的 framework 镜像、游戏库清单(shell.json)和横幅缓存。删掉它意味着每个游戏在下次安装时需要重新从构建文件夹提供 framework;构建文件夹也已删除的游戏需要重新构建。', "The shell's mirrored frameworks, its library file (shell.json) and the banner cache. Deleting it means every game's framework must come from its build folder again at the next install; a game whose build folder is also gone must be rebuilt.", 'Skalns speglade frameworks, dess biblioteksfil (shell.json) och banner-cachen. Raderar du dem måste varje spels framework åter levereras från dess byggmapp vid nästa installation; ett spel vars byggmapp också är borta måste byggas om.', 'Die gespiegelten Frameworks der Shell, ihre Bibliotheksdatei (shell.json) und der Banner-Cache. Wer sie löscht, muss bei der nächsten Installation das Framework jedes Spiels wieder aus dessen Build-Ordner liefern. Ein Spiel, dessen Build-Ordner auch weg ist, muss neu gebaut werden.', 'Les frameworks en miroir de la coque, son fichier de bibliothèque (shell.json) et le cache des bannières. Les supprimer signifie que le framework de chaque jeu doit à nouveau venir de son dossier de compilation à la prochaine installation ; un jeu dont le dossier de compilation a aussi disparu doit être recompilé.'),'settings.appNote': ('为 Apple 设备构建游戏', 'Build your games for Apple devices', 'Bygg dina spel för Apple-enheter', 'Baue deine Spiele für Apple-Geräte', 'Compilez vos jeux pour les appareils Apple'),'build.compatibility': ('兼容性选项', 'Older iPhone support', 'Stöd för äldre iPhone-modeller', 'Unterstützung für ältere iPhones', 'Prise en charge des anciens iPhone'),'build.macNote': ('在这台 Mac 上直接运行。', 'Play directly on this Mac.', 'Spela direkt på den här Mac-datorn.', 'Direkt auf diesem Mac spielen.', 'Jouez directement sur ce Mac.'),diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex bee713fa..3e8a87ee 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -117,6 +117,8 @@ final class BuildModel: ObservableObject {@Published var stages: [Stage] = []private var chainNoteShown = false // the shader-chain notice shows once per build@Published var running = false+ /// The shell folder the cache row shows: the frameworks' mirror, shell.json and the banner cache live here.+ var shellCachePath: String { ShellLibrary.resolveRoot(parent: outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir) }@Published var stopping = false@Published var logTail = ""@Published var done = false@@ -1440,9 +1442,11 @@ final class BuildModel: ObservableObject {// The game's archive, then its framework into the one shared app on the devicelet tid = Self.buildKey(self.basePath)let name = ((self.basePath as NSString).lastPathComponent as NSString).deletingPathExtension+ let fw = ShellInstall.frameworkPath(workDir: self.effectiveWorkDir, titleID: tid)self.packArchive(workDir: self.effectiveWorkDir) {- self.installShell(framework: ShellInstall.frameworkPath(workDir: self.effectiveWorkDir, titleID: tid),- titleID: tid, name: name, archive: $0)+ // The mirror in the shell folder is what survives a deleted build folder (#398).+ try? ShellInstall.mirrorFramework(framework: fw, root: ShellLibrary.resolveRoot(parent: (self.basePath as NSString).deletingLastPathComponent))+ self.installShell(framework: fw, titleID: tid, name: name, archive: $0)}}} else {@@ -3710,11 +3714,18 @@ struct BuilderView: View {Text(m.confirmingChannel.flatMap { m.engineSelection.channel.switchWarningKey(to: $0) }.map { m.t($0) } ?? "")}divider+ row(m.t("shellCache.row"), detail: m.t("shellCache.note") + "\n" + m.shellCachePath) {+ Button(m.t("shellCache.open")) { m.revealFolder(URL(fileURLWithPath: m.shellCachePath)) }+ .buttonStyle(LauncherSecondaryButtonStyle())+ }+ dividerrow(m.t("repo.auto"), detail: m.t("engine.autoNote")) {Toggle("", isOn: $m.autoUpdateRepo).labelsHidden().toggleStyle(LauncherSwitchStyle())}}++private func pickRepo() {let d = NSOpenPanel()d.canChooseDirectories = true; d.canChooseFiles = falsediff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex d1c9536e..81666826 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -255,6 +255,8 @@ enum L10n {"library.clearSearch": ("\u{6e05}\u{9664}\u{641c}\u{7d22}", "Clear search"),"settings.heading": ("\u{8bbe}\u{7f6e}", "Settings"),"settings.note": ("\u{6e38}\u{620f}\u{6587}\u{4ef6}\u{5939}\u{3001}\u{6784}\u{5efa}\u{5de5}\u{5177}\u{548c}\u{5e94}\u{7528}\u{66f4}\u{65b0}\u{ff0c}\u{90fd}\u{5728}\u{8fd9}\u{91cc}\u{3002}", "Library location, build tools and updates."),+ "shellCache.row": ("缓存文件", "Cache files"),+ "shellCache.note": ("壳的 framework 镜像、游戏库清单(shell.json)和横幅缓存。删掉它意味着每个游戏在下次安装时需要重新从构建文件夹提供 framework;构建文件夹也已删除的游戏需要重新构建。", "The shell's mirrored frameworks, its library file (shell.json) and the banner cache. Deleting it means every game's framework must come from its build folder again at the next install; a game whose build folder is also gone must be rebuilt."),"settings.appNote": ("\u{4e3a} Apple \u{8bbe}\u{5907}\u{6784}\u{5efa}\u{6e38}\u{620f}", "Build your games for Apple devices"),"build.compatibility": ("\u{517c}\u{5bb9}\u{6027}\u{9009}\u{9879}", "Older iPhone support"),"build.macNote": ("\u{5728}\u{8fd9}\u{53f0} Mac \u{4e0a}\u{76f4}\u{63a5}\u{8fd0}\u{884c}\u{3002}", "Play directly on this Mac."),@@ -1252,6 +1254,8 @@ enum L10n {"settings.language.de": "Deutsch","settings.language.fr": "Français","settings.heading": "Inställningar",+ "shellCache.row": "Cachefiler",+ "shellCache.note": "Skalns speglade frameworks, dess biblioteksfil (shell.json) och banner-cachen. Raderar du dem måste varje spels framework åter levereras från dess byggmapp vid nästa installation; ett spel vars byggmapp också är borta måste byggas om.","onboarding.welcome.title": "Välkommen.","onboarding.welcome.note": "Spela dina Switch-spel direkt på din Mac på ungefär 15 minuter.","onboarding.platform.title": "Var vill du spela?",@@ -2316,6 +2320,8 @@ enum L10n {"library.rescan": "Aktualisieren","library.clearSearch": "Suche löschen","settings.heading": "Einstellungen",+ "shellCache.row": "Cachedateien",+ "shellCache.note": "Die gespiegelten Frameworks der Shell, ihre Bibliotheksdatei (shell.json) und der Banner-Cache. Wer sie löscht, muss bei der nächsten Installation das Framework jedes Spiels wieder aus dessen Build-Ordner liefern. Ein Spiel, dessen Build-Ordner auch weg ist, muss neu gebaut werden.","settings.note": "Speicherort der Bibliothek, Build-Werkzeuge und Updates.","settings.appNote": "Baue deine Spiele für Apple-Geräte","build.compatibility": "Unterstützung für ältere iPhones",@@ -3365,6 +3371,8 @@ enum L10n {"library.rescan": "Actualiser","library.clearSearch": "Effacer la recherche","settings.heading": "Réglages",+ "shellCache.row": "Fichiers de cache",+ "shellCache.note": "Les frameworks en miroir de la coque, son fichier de bibliothèque (shell.json) et le cache des bannières. Les supprimer signifie que le framework de chaque jeu doit à nouveau venir de son dossier de compilation à la prochaine installation ; un jeu dont le dossier de compilation a aussi disparu doit être recompilé.","settings.note": "Emplacement de la bibliothèque, outils de compilation et mises à jour.","settings.appNote": "Compilez vos jeux pour les appareils Apple","build.compatibility": "Prise en charge des anciens iPhone",diff --git a/frontend/Sources/NSPortBuilder/ShellInstall.swift b/frontend/Sources/NSPortBuilder/ShellInstall.swiftindex 92a15637..c798e00f 100644--- a/frontend/Sources/NSPortBuilder/ShellInstall.swift+++ b/frontend/Sources/NSPortBuilder/ShellInstall.swift@@ -29,9 +29,16 @@ struct ShellLibrary: Codable, Equatable {if let i = games.firstIndex(where: { $0.titleID == game.titleID }) { games[i] = game } else { games.append(game) }}- /// Drops the games whose framework folder is gone (a deleted build folder), so the shell is never built against a missing one.- mutating func dropMissing(exists: (String) -> Bool = { FileManager.default.fileExists(atPath: $0) }) {- games.removeAll { !exists($0.framework) }+ /// Drops the games whose framework folder is gone (a deleted build folder) and has no mirror in the shell folder,+ /// so the shell is never built against a missing one. A mirrored framework is used in place of the lost one.+ mutating func dropMissing(exists: (String) -> Bool = { FileManager.default.fileExists(atPath: $0) },+ mirror: ((Game) -> String?)? = nil) {+ var out: [Game] = []+ for g in games {+ if exists(g.framework) { out.append(g); continue }+ if let m = mirror?(g) { out.append(Game(titleID: g.titleID, name: g.name, framework: m)) }+ }+ games = out}static func stateFile(root: String) -> String { root + "/shell.json" }@@ -70,6 +77,31 @@ enum ShellInstall {static func derivedData(root: String) -> String { root + "/derived-data" }static func appPath(root: String) -> String { derivedData(root: root) + "/Build/Products/Release-iphoneos/" + appName }+ /// The folder that mirrors every game's framework inside the shell folder: a game survives its build folder's deletion here.+ static func frameworksMirror(root: String) -> String { root + "/frameworks" }+ static func mirroredFramework(root: String, titleID: String) -> String {+ frameworksMirror(root: root) + "/DmGame\(titleID).framework"+ }++ /// Mirrors a freshly built framework into the shell folder: a hard link when both live on one volume (no extra space),+ /// a copy otherwise. Re-links over the previous mirror, so a rebuilt game's mirror follows.+ static func mirrorFramework(framework: String, root: String) throws {+ let fm = FileManager.default+ let mirror = mirroredFramework(root: root, titleID: Self.titleID(ofFramework: framework))+ let parent = (mirror as NSString).deletingLastPathComponent+ try? fm.createDirectory(atPath: parent, withIntermediateDirectories: true)+ try? fm.removeItem(atPath: mirror)+ do { try fm.linkItem(atPath: framework, toPath: mirror) }+ catch { try fm.copyItem(atPath: framework, toPath: mirror) } // another volume: a real copy+ }++ /// The title ID a framework path carries (`DmGame0100…framework`, the build script's name).+ static func titleID(ofFramework framework: String) -> String {+ let name = (framework as NSString).lastPathComponent+ return name.hasPrefix("DmGame") && name.hasSuffix(".framework")+ ? String(name.dropFirst("DmGame".count).dropLast(".framework".count)) : ""+ }+/// The framework the build script's `--shell-framework <folder>` writes for a game.static func frameworkPath(workDir: String, titleID: String) -> String {workDir + "/shell-framework/DmGame\(titleID).framework"@@ -358,7 +390,15 @@ struct ShellInstaller {var library = ShellLibrary.load(root: root)library.team = teamlibrary.add(.init(titleID: titleID, name: name, framework: framework))- library.dropMissing()+ library.dropMissing(mirror: { g in+ // The build folder is gone, the mirror in the shell folder stands in for the framework.+ let m = ShellInstall.mirroredFramework(root: root, titleID: g.titleID)+ if FileManager.default.fileExists(atPath: m) {+ log("library: \(g.titleID)'s framework is mirrored at \(m)\n")+ return m+ }+ return nil+ })// The 16:9 banner of the shell's library for every game in it (ShellHost reads <framework>/banner.<ext>, the square// icon.png is the fallback): a game rebuilt since its last install gets its banner back toofor game in library.games {@@ -367,6 +407,11 @@ struct ShellInstaller {log("banner: \(game.titleID) \(banner)\n")}}+ // A game whose build folder is gone plays from the mirror: the framework path points there.+ for i in library.games.indices where !FileManager.default.fileExists(atPath: library.games[i].framework) {+ let m = ShellInstall.mirroredFramework(root: root, titleID: library.games[i].titleID)+ if FileManager.default.fileExists(atPath: m) { library.games[i].framework = m }+ }do { try library.save(root: root) } catch {return Outcome(ok: false, message: fmt("shell.projectFailed", error.localizedDescription))}diff --git a/frontend/Tests/NSPortBuilderTests/ShellMirrorTests.swift b/frontend/Tests/NSPortBuilderTests/ShellMirrorTests.swiftnew file mode 100644index 00000000..d30b4d79--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/ShellMirrorTests.swift@@ -0,0 +1,33 @@+import XCTest+@testable import NSPortBuilder++final class ShellMirrorTests: XCTestCase {+ func testMirrorLinksAndStandsIn() throws {+ let tmp = NSHomeDirectory() + "/.nspb-mirror-test-\(UUID().uuidString)"+ try FileManager.default.createDirectory(atPath: tmp + "/fw", withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(atPath: tmp) }+ let fw = tmp + "/fw/DmGame0100A00019DE0000.framework"+ try FileManager.default.createDirectory(atPath: fw + "/inside", withIntermediateDirectories: true)+ try "x".write(toFile: fw + "/inside/f", atomically: true, encoding: .utf8)+ XCTAssertEqual(ShellInstall.titleID(ofFramework: fw), "0100A00019DE0000")+ try ShellInstall.mirrorFramework(framework: fw, root: tmp)+ let mirror = ShellInstall.mirroredFramework(root: tmp, titleID: "0100A00019DE0000")+ XCTAssertTrue(FileManager.default.fileExists(atPath: mirror))+ // 重镜像:删除原 framework 后重新链接不报错+ try ShellInstall.mirrorFramework(framework: fw, root: tmp)+ // dropMissing 的镜像回退:原路径没了,镜像顶上+ var lib = ShellLibrary()+ lib.add(.init(titleID: "0100A00019DE0000", name: "Test", framework: fw))+ try FileManager.default.removeItem(atPath: fw)+ lib.dropMissing(mirror: { g in+ let m = ShellInstall.mirroredFramework(root: tmp, titleID: g.titleID)+ return FileManager.default.fileExists(atPath: m) ? m : nil+ })+ XCTAssertEqual(lib.games.count, 1)+ XCTAssertEqual(lib.games[0].framework, mirror)+ // 无镜像时才真正剔除+ try FileManager.default.removeItem(atPath: mirror)+ lib.dropMissing(mirror: { _ in nil })+ XCTAssertEqual(lib.games.count, 0)+ }+}