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
Install: a reinstall and a saved IPA from the app the last sign produced
LNPANDY9fe5038ab2ce
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 8c1bd0be..873e5d38 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -1709,13 +1709,95 @@ final class BuildModel: ObservableObject {}}- private func finishInstall(_ failure: String?) {+ private func finishInstall(_ failure: String?, note: String? = nil) {running = falsedone = failure == nil- doneNote = failure ?? String(format: t("dev.installed"), deviceName(installDevice))+ doneNote = failure ?? note ?? String(format: t("dev.installed"), deviceName(installDevice))cleanupStaging()}+ /// Reinstall the signed app that is already in derived data, without unpacking, signing or packing again: the+ /// device keeps the app's Documents (game data and saves), as the bundle ID does not change. A reinstall that+ /// fails on an expired signature says so in devicectl's words; signing again is not this button's job.+ func reinstallOnDevice(then: (() -> Void)? = nil) {+ let device = installedOn, app = installedAppPath+ guard !device.isEmpty, !app.isEmpty else { then?(); return }+ guard FileManager.default.fileExists(atPath: app) else {+ doneNote = String(format: t("dev.reinstallMissing"), shortPath(app))+ then?(); return+ }+ running = true+ runTool(id: 1004, name: String(format: t("dev.reinstallStage"), deviceName(device)),+ Self.reinstallCommand(xcrun: xcrunPath, device: device, app: app), step: Self.installStep) { error in+ if let error {+ // The app is still on the device: a failed reinstall is a note, not a failed build+ self.running = false+ self.doneNote = String(format: self.t("dev.reinstallFailed"), error)+ } else {+ self.finishInstall(nil, note: String(format: self.t("dev.reinstalled"), self.deviceName(device)))+ }+ then?()+ }+ }++ nonisolated static func reinstallCommand(xcrun: String, device: String, app: String) -> [String] {+ [xcrun, "devicectl", "device", "install", "app", "--device", device, app]+ }++ /// Ask where to write the .ipa, then pack the signed app there.+ func saveIPAPanel() {+ let p = NSSavePanel()+ p.title = t("dev.saveIPATitle")+ p.allowedFileTypes = ["ipa"]+ p.nameFieldStringValue = defaultIPAName()+ p.canCreateDirectories = true+ guard p.runModal() == .OK, let url = p.url else { return }+ saveIPA(to: url)+ }++ /// The signed app as an .ipa (Payload/<name>.app, the layout iOS and the sideloaders install): useful while the+ /// signature lasts, and the thing to re-sign when it expires. The game data is not in it — it stays in the app's+ /// Documents (romfs.img), as a normal iOS build has it.+ func saveIPA(to url: URL, then: (() -> Void)? = nil) {+ let app = installedAppPath, fm = FileManager.default+ guard !app.isEmpty, fm.fileExists(atPath: app) else {+ doneNote = String(format: t("dev.saveNeedsApp"), shortPath(app))+ then?(); return+ }+ let stage = fm.temporaryDirectory.appendingPathComponent("nspb-ipa-" + UUID().uuidString)+ let payload = stage.appendingPathComponent("Payload")+ do {+ try fm.createDirectory(at: payload, withIntermediateDirectories: true)+ try fm.copyItem(atPath: app, toPath: payload.appendingPathComponent((app as NSString).lastPathComponent).path)+ } catch {+ try? fm.removeItem(at: stage)+ doneNote = String(format: t("dev.saveFailed"), error.localizedDescription)+ then?(); return+ }+ running = true+ runTool(id: 1005, name: t("dev.saveStage"), Self.ipaCommand(payload: payload.path, ipa: url.path), step: { _ in nil }) { error in+ try? fm.removeItem(at: stage)+ self.running = false+ self.doneNote = error.map { String(format: self.t("dev.saveFailed"), $0) }+ ?? String(format: self.t("dev.savedIPA"), self.shortPath(url.path))+ then?()+ }+ }++ /// ditto writes the archive the way Finder's "compress" does; the IPA's root must be Payload/, and --norsrc keeps+ /// __MACOSX out (the signature itself lives in _CodeSignature inside the app).+ nonisolated static func ipaCommand(payload: String, ipa: String) -> [String] {+ ["/usr/bin/ditto", "-c", "-k", "--norsrc", "--keepParent", payload, ipa]+ }++ /// The name the save panel offers: the app's display name, so two games' IPAs do not collide. A slash or colon in a+ /// game's name would split the file name or show as a folder in Finder.+ func defaultIPAName() -> String {+ let plist = NSDictionary(contentsOfFile: installedAppPath + "/Info.plist")+ let name = (plist?["CFBundleDisplayName"] as? String) ?? (plist?["CFBundleExecutable"] as? String) ?? "DmIOS"+ return name.replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: ":", with: "_") + ".ipa"+ }+/// The game's folder (romfs.img, aoc/) into the installed app's Documents, where main.m looks for this game's files first.nonisolated static func archiveCopy(xcrun: String, device: String, bundle: String, archive: String, titleID: String) -> [String] {[xcrun, "devicectl", "device", "copy", "to", "--device", device, "--source", archive,@@ -2622,6 +2704,18 @@ struct BuilderView: View {Button(String(format: m.t("dev.open"), m.deviceName(m.installedOn))) {m.openOnDevice(udid: m.installedOn, app: m.installedAppPath) { error in if let error { m.doneNote = error } }}+ Button(m.t("dev.reinstall")) { m.reinstallOnDevice() }+ .disabled(m.running)+ }+ // The signed app stays in derived data; keeping it as an .ipa means a sideloader (or another Mac)+ // can install it without building the game again, while the signature lasts.+ if !m.installedAppPath.isEmpty {+ divider+ row(m.t("dev.signedApp"), detail: m.shortPath(m.installedAppPath), dot: LauncherPalette.ready, help: m.installedAppPath) {+ Button(m.t("install.reveal")) { reveal(m.installedAppPath) }+ Button(m.t("dev.saveIPA")) { m.saveIPAPanel() }+ .disabled(m.running)+ }}// The game files were copied (or, after a skipped transfer, await a manual copy — a// fast external drive handed to the device is quicker than USB): show where they are.diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 885f0763..0d3edfaa 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -204,6 +204,18 @@ enum L10n {"dev.signFailed": ("\u{7b7e}\u{540d}\u{5931}\u{8d25}\u{ff1a}%@", "Signing failed: %@"),"dev.installFailed": ("\u{5b89}\u{88c5}\u{5931}\u{8d25}\u{ff1a}%@", "Installing failed: %@"),"dev.noProject": ("\u{6ca1}\u{6709}\u{627e}\u{5230}\u{ff1a}%@", "Not found: %@"),+ "dev.reinstall": ("重装", "Reinstall"),+ "dev.reinstallStage": ("重装到 %@", "Reinstalling on %@"),+ "dev.reinstalled": ("已重新安装到 %@(游戏数据保留)", "Reinstalled on %@ (the game data is kept)"),+ "dev.reinstallFailed": ("重装失败:%@(签名已过期时请重新签名并安装)", "Reinstalling failed: %@ (if the signature has expired, sign and install again)"),+ "dev.reinstallMissing": ("找不到已签名的 App:%@(请重新构建)", "The signed app is not there: %@ (build again)"),+ "dev.signedApp": ("已签名的 App", "Signed app"),+ "dev.saveIPA": ("保存 IPA…", "Save IPA…"),+ "dev.saveIPATitle": ("保存已签名的 IPA", "Save the signed IPA"),+ "dev.saveStage": ("打包 IPA", "Packing the IPA"),+ "dev.savedIPA": ("已保存 IPA:%@", "Saved the IPA: %@"),+ "dev.saveFailed": ("保存 IPA 失败:%@(请检查目标位置的可用空间和写入权限)", "Saving the IPA failed: %@ (check free space and write permission at the destination)"),+ "dev.saveNeedsApp": ("没有可打包的已签名 App:%@(请重新构建)", "No signed app to pack: %@ (build again)"),"prog.eta": ("\u{8fd8}\u{5269} %@", "%@ left"),"activity.mac": ("\u{6b63}\u{5728}\u{6784}\u{5efa} Mac \u{7248}", "Mac build in progress"),"activity.ios": ("\u{6b63}\u{5728}\u{6784}\u{5efa} iPhone \u{7248}", "iPhone build in progress"),diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swiftindex 622b8e57..d1988858 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -436,6 +436,88 @@ final class LibraryTests: XCTestCase {XCTAssertTrue(try String(contentsOf: calls, encoding: .utf8).contains("devicectl device process launch --device 00008150-AAAA org.nxnative.test"))}+ /// A deleted app comes back without unpacking, signing or packing anything again: the signed app already in+ /// derived data is installed as it is, and the device keeps the game data (the bundle ID does not change).+ @MainActor func testReinstallInstallsTheSignedAppWithoutBuildingAgain() throws {+ let (model, _, calls, _) = try runInstallFlow(transfer: true)+ let app = model.installedAppPath+ let buildsBefore = try String(contentsOf: calls, encoding: .utf8).split(separator: "\n").filter { $0.hasPrefix("xcodebuild") }.count+ let done = expectation(description: "Reinstalled")+ model.reinstallOnDevice { done.fulfill() }+ wait(for: [done], timeout: 20)+ let log = try String(contentsOf: calls, encoding: .utf8).split(separator: "\n").map(String.init)+ XCTAssertEqual(log.filter { $0.hasPrefix("devicectl device install app") }.count, 2)+ XCTAssertEqual(log.last { $0.hasPrefix("devicectl device install app") }, "devicectl device install app --device 00008150-AAAA \(app)")+ XCTAssertEqual(log.filter { $0.hasPrefix("xcodebuild") }.count, buildsBefore) // no second build+ XCTAssertEqual(log.filter { $0.hasPrefix("romfs_image") }.count, 1) // the game files are not re-packed+ XCTAssertEqual(model.stages.last?.id, 1004)+ XCTAssertEqual(model.stages.last?.state, .done)+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.reinstalled"), "iPhone"))+ XCTAssertFalse(model.running)+ }++ /// The saved package is an ordinary IPA — Payload/DmIOS.app/… at the archive's root, no __MACOSX — so a+ /// sideloader or another Mac installs it while the signature lasts, without building the game again.+ @MainActor func testSaveIPAWritesAnOrdinaryPayloadArchive() throws {+ let (model, _, _, _) = try runInstallFlow(transfer: true)+ XCTAssertEqual(model.defaultIPAName(), "DmIOS.ipa")+ let ipa = temporary.appendingPathComponent("Test Game.ipa")+ let saved = expectation(description: "Saved the IPA")+ model.saveIPA(to: ipa) { saved.fulfill() }+ wait(for: [saved], timeout: 30)+ XCTAssertTrue(FileManager.default.fileExists(atPath: ipa.path))+ let unzip = Process(), out = Pipe()+ unzip.executableURL = URL(fileURLWithPath: "/usr/bin/unzip")+ unzip.arguments = ["-l", ipa.path]+ unzip.standardOutput = out+ try unzip.run(); unzip.waitUntilExit()+ let listing = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)+ XCTAssertEqual(unzip.terminationStatus, 0, listing)+ XCTAssertTrue(listing.contains("Payload/DmIOS.app/Info.plist"), listing)+ XCTAssertFalse(listing.contains("__MACOSX"), listing)+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.savedIPA"), model.shortPath(ipa.path)))+ XCTAssertFalse(model.running)+ }++ /// Both actions name what is missing instead of doing nothing, and a failed reinstall is a note on the installed+ /// app, not a failed build (the app is still on the device).+ @MainActor func testReinstallAndSaveReportAMissingSignedApp() throws {+ let (model, _, _, _) = try runInstallFlow(transfer: true)+ try FileManager.default.removeItem(atPath: model.installedAppPath)+ var reported = expectation(description: "Reinstall says what is missing")+ model.reinstallOnDevice { reported.fulfill() }+ wait(for: [reported], timeout: 10)+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.reinstallMissing"), model.shortPath(model.installedAppPath)))+ XCTAssertTrue(model.done)+ reported = expectation(description: "Save says what is missing")+ let ipa = temporary.appendingPathComponent("missing.ipa")+ model.saveIPA(to: ipa) { reported.fulfill() }+ wait(for: [reported], timeout: 10)+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.saveNeedsApp"), model.shortPath(model.installedAppPath)))+ XCTAssertFalse(FileManager.default.fileExists(atPath: ipa.path))+ }++ /// The save panel's name comes from the app, with the separators a game name can carry replaced: a slash would make+ /// a subfolder, a colon shows as a folder in Finder.+ @MainActor func testTheIPANameComesFromTheDisplayNameWithoutPathSeparators() throws {+ let app = temporary.appendingPathComponent("DmIOS.app")+ try FileManager.default.createDirectory(at: app, withIntermediateDirectories: true)+ let info: [String: Any] = ["CFBundleDisplayName": "Zelda: Echoes/of Wisdom"]+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)+ .write(to: app.appendingPathComponent("Info.plist"))+ let model = BuildModel()+ model.installedAppPath = app.path+ XCTAssertEqual(model.defaultIPAName(), "Zelda_ Echoes_of Wisdom.ipa")+ }++ /// The two commands the actions build: a plain devicectl install of the cached app, and ditto's Payload archive.+ func testTheReinstallAndIPARecipes() {+ XCTAssertEqual(BuildModel.reinstallCommand(xcrun: "/x", device: "D", app: "/a/DmIOS.app"),+ ["/x", "devicectl", "device", "install", "app", "--device", "D", "/a/DmIOS.app"])+ XCTAssertEqual(BuildModel.ipaCommand(payload: "/t/Payload", ipa: "/o/Game.ipa"),+ ["/usr/bin/ditto", "-c", "-k", "--norsrc", "--keepParent", "/t/Payload", "/o/Game.ipa"])+ }+func testCorruptLibraryIsReportedWithoutOverwritingIt() throws {let file = temporary.appendingPathComponent("library.json")let data = Data("broken JSON".utf8)