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
nxnative for Mac: install an iPhone build on a paired device
v0lumehi1aa5f861d5f5
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 7ca373ee..8bfa2962 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -25,6 +25,23 @@ TABLE: dict[str, tuple[str, str]] = {'build.iosNote': ('为你的 iPhone 或 iPad 创建应用。', 'Create an app for your iPhone or iPad.'),'build.folderCTA': ('选择游戏文件夹', 'Choose game folder'),'build.folderSelected': ('已选择游戏文件夹', 'Game folder selected'),+ 'dev.section': ('安装到设备', 'Install'),+ 'dev.target': ('安装到', 'Install on'),+ 'dev.none': ('不安装,只导出 IPA', "Don't install, export the IPA"),+ 'dev.notConnected': ('未连接', 'not connected'),+ 'dev.noDevices': ('没有与这台 Mac 配对的 iPhone 或 iPad(需要 Xcode)。', 'No iPhone or iPad paired with this Mac (needs Xcode).'),+ 'dev.refresh': ('刷新', 'Refresh'),+ 'dev.team': ('签名团队', 'Signing team'),+ 'dev.noTeam': ('没有开发证书。在 Xcode 中登录 Apple ID(设置 → 账户)即可获得。', 'No development certificate. Sign in to Xcode with your Apple ID (Settings → Accounts) to get one.'),+ 'dev.note': ('Xcode 会为这台设备签名并直接安装,游戏文件已包含在 App 中,安装可能需要几分钟。第一次需要在设备上开启开发者模式,并信任开发者(设置 → 通用 → VPN 与设备管理)。', 'Xcode signs the game for this device and installs it there, with the game files inside the app; installing can take a few minutes. The first time, turn on Developer Mode on the device and trust the developer (Settings → General → VPN & Device Management).'),+ 'dev.signStage': ('为 %@ 签名', 'Sign for %@'),+ 'dev.installStage': ('安装到 %@', 'Install on %@'),+ 'dev.installed': ('已安装到 %@', 'Installed on %@'),+ 'dev.installedNote': ('游戏已在设备上,可以直接打开。', 'The game is on the device, ready to open.'),+ 'dev.open': ('在 %@ 上打开', 'Open on %@'),+ 'dev.signFailed': ('签名失败:%@', 'Signing failed: %@'),+ 'dev.installFailed': ('安装失败:%@', 'Installing failed: %@'),+ 'dev.noProject': ('没有找到:%@', 'Not found: %@'),'prog.eta': ('还剩 %@', '%@ left'),'activity.mac': ('正在构建 Mac 版', 'Mac build in progress'),'activity.ios': ('正在构建 iPhone 版', 'iPhone build in progress'),diff --git a/frontend/README.md b/frontend/README.mdindex 4b748f21..fc7d3709 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -20,16 +20,37 @@ writes them as PNG (from a copy of your library, with example paths), and2. Add an update or DLC under **Updates & add-on content** when needed.3. Choose **This Mac** or **iPhone / iPad**, then **Build game**.-Setup lives under **Settings**: the repository, dependency checks and installers,-repository updates, app updates, and interface language are still available.-Missing setup is linked from the build screen. Build details and logs are-collapsible; the yellow activity bar shows the current step and its percentage-when the script reports one. Stop waits for the child process to exit before-allowing another build.+Setup lives under **Settings**: the games folder, the repository and its updates,+the dependency checks and installers, and app updates. Missing setup is linked+from the build screen. The progress shows each of the script's steps with its+count, the time it has been running and, while the script's estimate lasts, the+time left; the build log opens under it. **Stop** ends the script and every tool+it started (the build runs in a process group of its own), and so does quitting+the app.A completed Mac build appears in the collection automatically and can be started-with **Play**. An iPhone build offers its IPA and the existing sideloading and-RomFS-copy instructions. This app does not install anything on an iPhone.+with **Play**. An iPhone build, by default, offers its unsigned IPA and the+sideloading and RomFS-copy instructions.++## Install on an iPhone or iPad++With Xcode, a development certificate (sign in to Xcode with your Apple ID under+Settings → Accounts) and a device paired with this Mac, an iPhone build can go+straight to the device: choose it under **Install on** and the **Signing team**+next to it. The script then prepares the game's Xcode project+(`--prepare-xcode --team-id`, the route it offers developers) instead of an IPA,+`xcodebuild -allowProvisioningUpdates` signs it for that device with the team+(Xcode makes the provisioning profile), and `xcrun devicectl device install app`+installs it. The game files are inside the app, so there is no RomFS to copy;+installing a large game takes a few minutes. The game then appears in the+collection, and its button opens it on the device.++The first time, turn on Developer Mode on the device and trust the developer+under Settings → General → VPN & Device Management. With a free Apple ID the+profile expires after seven days. **Don't install, export the IPA** keeps the+unsigned IPA as before. The devices and teams are read with `devicectl list+devices` and `security find-identity`; the team is the certificate's+organizational unit, not the code in its name.## Your games folderdiff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 0c16fd94..2e970eac 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -120,6 +120,42 @@ final class BuildModel: ObservableObject {/// default under the input folder (issue #5 — an upstream checkout has no --work-dir).var effectiveWorkDir = ""+ // ---- Installing on an iPhone or iPad (Xcode with a development certificate) ----+ // Optional: with a paired device and a signing team chosen, the script prepares the game's Xcode project+ // (--prepare-xcode, the route its README gives developers), xcodebuild signs it for that device with the+ // team (Xcode makes the provisioning profile), and devicectl installs it. The game files are inside the app,+ // so no RomFS copy follows. Without a device or a team the build stays an unsigned IPA, as before.+ @Published var devices: [AppleDevice] = []+ @Published var teams: [SigningTeam] = []+ @Published var devicesChecked = false+ @Published var installDevice = UserDefaults.standard.string(forKey: "installDevice") ?? "" {+ didSet { UserDefaults.standard.set(installDevice, forKey: "installDevice") }+ }+ @Published var signingTeam = UserDefaults.standard.string(forKey: "signingTeam") ?? "" {+ didSet { UserDefaults.standard.set(signingTeam, forKey: "signingTeam") }+ }+ @Published var installedOn = "" // the device the last build went to (its UDID)+ @Published var installedAppPath = "" // the signed app that went there+ private var bundleID = "" // from the script's "bundle ID:" line+ var xcrunPath = "/usr/bin/xcrun" // tests stand in for xcodebuild and devicectl++ /// This iPhone build goes straight to a device.+ var installsDirectly: Bool { target != "mac-app" && !installDevice.isEmpty && !signingTeam.isEmpty }++ func deviceName(_ udid: String) -> String { devices.first { $0.id == udid }?.name ?? "iPhone" }++ /// The paired devices and the signing teams, read in the background (devicectl can take a few seconds).+ func refreshDevices() {+ let xcrun = xcrunPath+ DispatchQueue.global(qos: .userInitiated).async {+ let devices = DeviceTools.devices(xcrun: xcrun), teams = DeviceTools.teams()+ DispatchQueue.main.async {+ self.devices = devices; self.teams = teams; self.devicesChecked = true+ if !teams.contains(where: { $0.id == self.signingTeam }) { self.signingTeam = teams.first?.id ?? "" }+ }+ }+ }+@Published var deps: [Dep] = []@Published var depsChecked = false/// Whether the dependency list is expanded. nil = not chosen yet: open while something is@@ -623,6 +659,7 @@ final class BuildModel: ObservableObject {guard !running else { return }stopping = falserunning = true; done = false; doneNote = ""; stages = []; logTail = ""; lineBuf = ""; chainNoteShown = false+ installedOn = ""; installedAppPath = ""; bundleID = ""guard repoOK else {fail(repoPath.isEmpty ? t("msg.repoInvalidEmpty") : String(format: t("msg.repoInvalid"), shortPath(repoPath)))return@@ -698,6 +735,9 @@ final class BuildModel: ObservableObject {args += ["--platform", "mac-app"]macAppPath = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + ".app"args += ["-o", macAppPath]+ } else if installsDirectly {+ // The game's Xcode project instead of an IPA, signed for the device after the script (signAndInstall)+ args += ["--prepare-xcode", "--keep-extracted", "--team-id", signingTeam]} else if !outDir.isEmpty {ipaPath = outDir + "/" + tidHex + ".ipa"args += ["-o", ipaPath]@@ -750,6 +790,8 @@ final class BuildModel: ObservableObject {self.doneNote = self.t(made ? "msg.macAppDone" : "msg.macAppMissing")self.running = falseself.cleanupStaging()+ } else if self.installsDirectly {+ self.signAndInstall() // keeps running=true until the app is on the device} else {self.packArchive(workDir: self.effectiveWorkDir) // keeps running=true until the archive is done}@@ -858,6 +900,7 @@ final class BuildModel: ObservableObject {}append(line + "\n")noteChainChange(line)+ noteBundleID(line)if let range = line.range(of: "output IPA: ") {ipaPath = String(line[range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)}@@ -888,6 +931,12 @@ final class BuildModel: ObservableObject {a.runModal()}+ /// The script's "app name: …; version: …; bundle ID: org.nxnative.…" line: the app to open on the device.+ private func noteBundleID(_ text: String) {+ guard let range = text.range(of: #"bundle ID: [A-Za-z0-9.\-]+"#, options: .regularExpression) else { return }+ bundleID = String(text[range].dropFirst("bundle ID: ".count))+ }+/// One event of `--progress json`: the stage list follows it, and the log gets a readable line (no count updates).private func handleEvent(_ kind: String, _ e: [String: Any]) {let k = (e["k"] as? NSNumber)?.intValue ?? 0@@ -919,6 +968,7 @@ final class BuildModel: ObservableObject {let msg = e["msg"] as? String ?? ""append(msg + "\n")noteChainChange(msg)+ noteBundleID(msg)if let range = msg.range(of: "output IPA: ") {ipaPath = String(msg[range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)}@@ -1099,6 +1149,144 @@ final class BuildModel: ObservableObject {}}+ // MARK: Installing on a device++ /// After the script prepared the Xcode project: sign it for the device, then install it there.+ private func signAndInstall() {+ let work = effectiveWorkDir, project = work + "/xcode/DmIOS.xcodeproj", derived = work + "/xcode-derived-data"+ let device = installDevice, team = signingTeam, name = deviceName(device), xcrun = xcrunPath+ guard FileManager.default.fileExists(atPath: project) else { return finishInstall(String(format: t("dev.noProject"), shortPath(project))) }+ DispatchQueue.global(qos: .userInitiated).async {+ let scheme = Self.scheme(of: project, xcrun: xcrun)+ DispatchQueue.main.async {+ guard let scheme else { return self.finishInstall(String(format: self.t("dev.noProject"), self.shortPath(project))) }+ let sign = [xcrun, "xcodebuild", "-project", project, "-scheme", scheme, "-configuration", "Release",+ "-destination", "id=\(device)", "-derivedDataPath", derived, "-allowProvisioningUpdates",+ "DEVELOPMENT_TEAM=\(team)", "build"]+ self.runTool(id: 1001, name: String(format: self.t("dev.signStage"), name), sign, step: Self.xcodeStep) { error in+ if let error { return self.finishInstall(String(format: self.t("dev.signFailed"), error)) }+ let app = derived + "/Build/Products/Release-iphoneos/DmIOS.app"+ guard FileManager.default.fileExists(atPath: app) else { return self.finishInstall(String(format: self.t("dev.noProject"), self.shortPath(app))) }+ self.runTool(id: 1002, name: String(format: self.t("dev.installStage"), name),+ [xcrun, "devicectl", "device", "install", "app", "--device", device, app], step: Self.installStep) { error in+ if let error { return self.finishInstall(String(format: self.t("dev.installFailed"), error)) }+ self.installedOn = device+ self.installedAppPath = app+ self.finishInstall(nil)+ }+ }+ }+ }+ }++ private func finishInstall(_ failure: String?) {+ running = false+ done = failure == nil+ doneNote = failure ?? String(format: t("dev.installed"), deviceName(installDevice))+ cleanupStaging()+ }++ /// The scheme the script made for the game ("<name> (<profile>)"), from `xcodebuild -list`.+ nonisolated static func scheme(of project: String, xcrun: String) -> String? {+ let p = Process(), out = Pipe()+ p.executableURL = URL(fileURLWithPath: xcrun)+ p.arguments = ["xcodebuild", "-list", "-json", "-project", project]+ p.standardOutput = out; p.standardError = FileHandle.nullDevice+ guard (try? p.run()) != nil else { return nil }+ let data = out.fileHandleForReading.readDataToEndOfFile()+ p.waitUntilExit()+ let start = data.firstIndex(of: UInt8(ascii: "{")) ?? data.startIndex // xcodebuild may print a line before the JSON+ guard let root = try? JSONSerialization.jsonObject(with: data[start...]) as? [String: Any],+ let schemes = (root["project"] as? [String: Any])?["schemes"] as? [String] else { return nil }+ return schemes.first { $0 != "DmIOS" } ?? schemes.first+ }++ /// What xcodebuild is doing, from the actions it prints.+ nonisolated static func xcodeStep(_ line: String) -> (detail: String, percent: Double?)? {+ let actions = [("CompileC ", "compiling"), ("SwiftCompile ", "compiling"), ("Ld ", "linking"),+ ("PhaseScriptExecution ", "copying the game files"), ("CodeSign ", "signing"), ("ProcessProductPackaging ", "provisioning")]+ return actions.first { line.hasPrefix($0.0) }.map { ($0.1, nil) }+ }++ /// devicectl's install progress ("… 45%").+ nonisolated static func installStep(_ line: String) -> (detail: String, percent: Double?)? {+ guard let range = line.range(of: #"(\d{1,3})%"#, options: .regularExpression), let n = Double(line[range].dropLast()) else { return nil }+ return ("installing", min(n, 100))+ }++ /// One of Xcode's tools as a stage of the build: in its own process group (Stop ends it), its output in the log,+ /// its progress in the stage. `then` gets nil on success, else the last error line.+ private func runTool(id: Int, name: String, _ command: [String], step: @escaping (String) -> (detail: String, percent: Double?)?,+ then: @escaping (String?) -> Void) {+ stages.append(Stage(id: id, name: name, state: .running, started: Date()))+ append("[\(name)] \(command.joined(separator: " "))\n")+ let p = Process()+ p.executableURL = URL(fileURLWithPath: command[0])+ p.arguments = Array(command.dropFirst())+ p.environment = ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": NSHomeDirectory(), "USER": NSUserName(), "LANG": "en_US.UTF-8"]+ Self.inOwnGroup(p, python: pythonPath.isEmpty ? "/usr/bin/python3" : pythonPath)+ let pipe = Pipe(); p.standardOutput = pipe; p.standardError = pipe+ var buffer = "", lastError = ""+ pipe.fileHandleForReading.readabilityHandler = { [weak self] h in+ let d = h.availableData+ guard !d.isEmpty, let chunk = String(data: d, encoding: .utf8) else { return }+ DispatchQueue.main.async {+ guard let self else { return }+ buffer += chunk+ while let nl = buffer.firstIndex(of: "\n") {+ let line = String(buffer[..<nl]); buffer = String(buffer[buffer.index(after: nl)...])+ self.append(line + "\n")+ if line.contains("error:") || line.hasPrefix("ERROR:") { lastError = line.trimmingCharacters(in: .whitespaces) }+ if let s = step(line), let i = self.stages.firstIndex(where: { $0.id == id }) {+ self.stages[i].detail = s.detail+ if let percent = s.percent { self.stages[i].percent = percent }+ }+ }+ }+ }+ p.terminationHandler = { [weak self] status in+ Self.untrack(status)+ DispatchQueue.main.async {+ guard let self else { return }+ pipe.fileHandleForReading.readabilityHandler = nil+ if self.stopping {+ self.stopping = false; self.running = false+ self.resetProgress(); self.doneNote = self.t("msg.stopped"); self.cleanupStaging()+ return+ }+ let ok = status.terminationStatus == 0+ if let i = self.stages.firstIndex(where: { $0.id == id }) {+ self.stages[i].state = ok ? .done : .failed+ if ok { self.stages[i].percent = 100; self.stages[i].detail = "" }+ }+ then(ok ? nil : (lastError.isEmpty ? String(format: self.t("msg.exitCode"), status.terminationStatus) : lastError))+ }+ }+ proc = p+ do { try p.run(); Self.track(p) } catch { then(error.localizedDescription) }+ }++ /// Start the game on the device it was installed on.+ func openOnDevice(udid: String, app: String, completion: @escaping (String?) -> Void) {+ let info = NSDictionary(contentsOfFile: app + "/Info.plist")+ guard let bundle = info?["CFBundleIdentifier"] as? String else { return completion(String(format: t("dev.noProject"), shortPath(app))) }+ let xcrun = xcrunPath+ DispatchQueue.global(qos: .userInitiated).async {+ let p = Process(), out = Pipe()+ p.executableURL = URL(fileURLWithPath: xcrun)+ p.arguments = ["devicectl", "device", "process", "launch", "--device", udid, bundle]+ p.standardOutput = out; p.standardError = out+ var message: String?+ do {+ try p.run()+ let text = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)+ p.waitUntilExit()+ if p.terminationStatus != 0 { message = text.split(separator: "\n").last(where: { $0.contains("rror") }).map(String.init) ?? text }+ } catch { message = error.localizedDescription }+ DispatchQueue.main.async { completion(message) }+ }+ }+// MARK: Dependenciesstruct Dep: Identifiable {@@ -1574,11 +1762,41 @@ struct BuilderView: View {}files.disabled(m.running)target+ if m.target != "mac-app" { install.disabled(m.running) }actionoutcomeprogress}+ /// Where an iPhone build goes: exported as an IPA (as before), or signed and installed on a paired device.+ private var install: some View {+ let devices = [(value: "", label: m.t("dev.none"))] + m.devices.map { d in+ (value: d.id, label: d.name + (d.reachable ? "" : " (" + m.t("dev.notConnected") + ")"))+ }+ let teams = m.teams.map { t in+ (value: t.id, label: t.identity.replacingOccurrences(of: #"^(Apple Development|iPhone Developer): "#, with: "", options: .regularExpression)+ .replacingOccurrences(of: #" \([A-Z0-9]+\)$"#, with: "", options: .regularExpression) + " · " + t.id)+ }+ return group(m.t("dev.section"), footnote: m.installDevice.isEmpty ? "" : m.t("dev.note")) {+ row(m.t("dev.target"), detail: m.devicesChecked && m.devices.isEmpty ? m.t("dev.noDevices") : "") {+ if !m.devicesChecked { ProgressView().controlSize(.small) }+ Button(m.t("dev.refresh")) { m.refreshDevices() }.buttonStyle(.plain).font(.manrope(13)).foregroundStyle(.secondary)+ LauncherMenuPicker(options: devices, selection: m.installDevice) { m.installDevice = $0 }+ }+ if !m.installDevice.isEmpty {+ divider+ if teams.isEmpty {+ row(m.t("dev.team"), detail: m.t("dev.noTeam"), dot: LauncherPalette.building) { EmptyView() }+ } else {+ row(m.t("dev.team")) {+ LauncherMenuPicker(options: teams, selection: m.signingTeam) { m.signingTeam = $0 }+ }+ }+ }+ }+ .onAppear { if !m.devicesChecked { m.refreshDevices() } }+ }+private var files: some View {// The report's own mistake, and a reasonable one: the output folder silently decides where// the build cache lives, so changing it threw away a finished build. Say it under Save to, all the time.@@ -1691,7 +1909,15 @@ struct BuilderView: View {}}}- if m.done && m.target != "mac-app" {+ if m.done && !m.installedOn.isEmpty {+ group(String(format: m.t("dev.installed"), m.deviceName(m.installedOn))) {+ row(m.t("dev.installedNote"), dot: LauncherPalette.ready) {+ 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 } }+ }+ }+ }+ } else if m.done && m.target != "mac-app" {group(m.t("install.title")) {VStack(alignment: .leading, spacing: 10) {guideRow(m.t("install.step1")); guideRow(m.t("install.step2")); guideRow(m.t("install.step3"))diff --git a/frontend/Sources/NSPortBuilder/Devices.swift b/frontend/Sources/NSPortBuilder/Devices.swiftnew file mode 100644index 00000000..c57c27d9--- /dev/null+++ b/frontend/Sources/NSPortBuilder/Devices.swift@@ -0,0 +1,88 @@+import Foundation++/// An iPhone or iPad paired with this Mac (Xcode's `devicectl`), a target for installing a build directly.+struct AppleDevice: Identifiable, Equatable {+ let id: String // the UDID+ let name: String+ let model: String+ let os: String+ let reachable: Bool // connected now, by cable or the local network+}++/// A development signing identity in the keychain and the team it signs for.+struct SigningTeam: Identifiable, Equatable {+ let id: String // the team ID: the certificate's organizational unit, not the code in its name+ let identity: String // "Apple Development: Name (ABCDE12345)"+}++/// Xcode's own tools for devices and signing: `xcrun devicectl` and `security`. Nothing here signs or installs;+/// it only reads what is paired and what can sign.+enum DeviceTools {+ /// The paired physical iPhones and iPads, reachable ones first.+ static func devices(xcrun: String = "/usr/bin/xcrun") -> [AppleDevice] {+ let file = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-devices-\(UUID().uuidString).json")+ defer { try? FileManager.default.removeItem(at: file) }+ guard run(xcrun, ["devicectl", "list", "devices", "--json-output", file.path]) != nil,+ let data = try? Data(contentsOf: file) else { return [] }+ return parseDevices(data)+ }++ static func parseDevices(_ data: Data) -> [AppleDevice] {+ guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let result = root["result"] as? [String: Any], let list = result["devices"] as? [[String: Any]] else { return [] }+ let devices: [AppleDevice] = list.compactMap { d in+ let hardware = d["hardwareProperties"] as? [String: Any] ?? [:]+ let properties = d["deviceProperties"] as? [String: Any] ?? [:]+ let connection = d["connectionProperties"] as? [String: Any] ?? [:]+ guard hardware["reality"] as? String == "physical", hardware["platform"] as? String == "iOS",+ connection["pairingState"] as? String == "paired",+ let udid = hardware["udid"] as? String, !udid.isEmpty else { return nil }+ return AppleDevice(id: udid, name: properties["name"] as? String ?? udid,+ model: hardware["marketingName"] as? String ?? "",+ os: properties["osVersionNumber"] as? String ?? "",+ reachable: connection["transportType"] is String)+ }+ return devices.sorted { ($0.reachable ? 0 : 1, $0.name) < ($1.reachable ? 0 : 1, $1.name) }+ }++ /// The development identities that can sign for a device, with their teams.+ static func teams() -> [SigningTeam] {+ guard let list = run("/usr/bin/security", ["find-identity", "-v", "-p", "codesigning"]) else { return [] }+ var seen = Set<String>()+ return identities(list).compactMap { identity in+ guard let pem = run("/usr/bin/security", ["find-certificate", "-c", identity, "-p"]),+ let subject = run("/usr/bin/openssl", ["x509", "-noout", "-subject"], input: pem),+ let team = team(fromSubject: subject), seen.insert(team + identity).inserted else { return nil }+ return SigningTeam(id: team, identity: identity)+ }+ }++ /// The quoted names of `security find-identity` that sign for devices (development, not distribution).+ static func identities(_ text: String) -> [String] {+ text.split(separator: "\n").compactMap { line in+ guard let open = line.firstIndex(of: "\""), let close = line.lastIndex(of: "\""), open < close else { return nil }+ let name = String(line[line.index(after: open)..<close])+ return name.hasPrefix("Apple Development:") || name.hasPrefix("iPhone Developer:") ? name : nil+ }+ }++ /// OU= of a certificate subject, as `openssl x509 -subject` prints it.+ static func team(fromSubject subject: String) -> String? {+ guard let range = subject.range(of: #"OU\s*=\s*([A-Z0-9]{10})"#, options: .regularExpression) else { return nil }+ return subject[range].split(separator: "=").last.map { $0.trimmingCharacters(in: .whitespaces) }+ }++ private static func run(_ tool: String, _ args: [String], input: String? = nil) -> String? {+ let p = Process(), out = Pipe(), inPipe = Pipe()+ p.executableURL = URL(fileURLWithPath: tool)+ p.arguments = args+ p.standardOutput = out+ p.standardError = FileHandle.nullDevice+ p.standardInput = input == nil ? FileHandle.nullDevice : inPipe+ do { try p.run() } catch { return nil }+ if let input { inPipe.fileHandleForWriting.write(Data(input.utf8)); try? inPipe.fileHandleForWriting.close() }+ let data = out.fileHandleForReading.readDataToEndOfFile()+ p.waitUntilExit()+ return p.terminationStatus == 0 ? String(decoding: data, as: UTF8.self) : nil+ }+}diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 17ee83b5..cb259f6d 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -74,7 +74,7 @@ struct ContentView: View {.frame(minWidth: 900, idealWidth: 1280, minHeight: 680, idealHeight: 900).onAppear {refreshArtwork()- if performStartupChecks { library.discover(); fetchArtwork() }+ if performStartupChecks { library.discover(); fetchArtwork(); m.refreshDevices() }if performStartupChecks {m.checkDeps()if m.repoOK && m.repoIsGit { m.checkRepoUpdates(silent: true) }@@ -263,7 +263,9 @@ struct ContentView: View {.tracking(-1.6).lineLimit(2).shadow(color: .black.opacity(0.25), radius: 12)HStack(spacing: 18) {Button { primaryAction(game) } label: {- Label(m.t(game.isReady ? "library.play" : (game.hasIOSBuild ? "library.showIOS" : "library.newBuild")),+ Label(game.isReady ? m.t("library.play")+ : (game.onDevice ? String(format: m.t("dev.open"), m.deviceName(game.installedDevice))+ : m.t(game.hasIOSBuild ? "library.showIOS" : "library.newBuild")),systemImage: game.isReady ? "play.fill" : (game.hasIOSBuild ? "iphone" : "hammer.fill")).font(.manrope(18, .bold)).foregroundStyle(.black).padding(.horizontal, 30).padding(.vertical, 14)@@ -459,6 +461,14 @@ struct ContentView: View {}private func primaryAction(_ game: LibraryGame) {+ if !game.isReady && game.onDevice { // installed on a device: start it there+ launching = true+ m.openOnDevice(udid: game.installedDevice, app: game.iosAppPath) { error in+ launching = false+ if let error { launchError = error }+ }+ return+ }if !game.isReady && game.hasIOSBuild {NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: game.ipaPath)])return@@ -482,7 +492,7 @@ struct ContentView: View {private func recordBuild() {guard m.done, let id = activeBuildID else { return }if m.target == "mac-app" { library.recordCompletedApp(path: m.macAppPath, for: id) }- else { library.recordCompletedIOS(ipa: m.ipaPath, archive: m.archivePath, for: id) }+ else { library.recordCompletedIOS(ipa: m.ipaPath, archive: m.archivePath, app: m.installedAppPath, device: m.installedOn, for: id) }refreshArtwork()}diff --git a/frontend/Sources/NSPortBuilder/Library.swift b/frontend/Sources/NSPortBuilder/Library.swiftindex eb347e1a..f5e0b521 100644--- a/frontend/Sources/NSPortBuilder/Library.swift+++ b/frontend/Sources/NSPortBuilder/Library.swift@@ -22,6 +22,9 @@ struct LibraryGame: Codable, Identifiable, Equatable {return app.titleID == titleID}+ /// Signed and installed on a paired device (installedDevice is its UDID): Play starts it there.+ var onDevice: Bool { !installedDevice.isEmpty && FileManager.default.fileExists(atPath: iosAppPath + "/Info.plist") }+var hasIOSBuild: Bool {(!ipaPath.isEmpty && FileManager.default.fileExists(atPath: ipaPath)) ||(!iosAppPath.isEmpty && FileManager.default.fileExists(atPath: iosAppPath + "/Info.plist"))@@ -288,10 +291,10 @@ final class GameLibrary: ObservableObject {func recordCompletedIOS(ipa: String, archive: String, app: String = "", device: String = "", for id: UUID) {guard var game = games.first(where: { $0.id == id }),FileManager.default.fileExists(atPath: ipa) || FileManager.default.fileExists(atPath: app + "/Info.plist") else { return }- game.ipaPath = ipa- game.archivePath = archive- game.iosAppPath = app- game.installedDevice = device+ // What this build made; an earlier build's IPA or installed app stays when this one made none+ if !ipa.isEmpty { game.ipaPath = ipa }+ if !archive.isEmpty { game.archivePath = archive }+ if !app.isEmpty { game.iosAppPath = app; game.installedDevice = device }upsert(game)}diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex fd28f470..2e03b257 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -59,6 +59,23 @@ enum L10n {"build.folderCTA": ("\u{9009}\u{62e9}\u{6e38}\u{620f}\u{6587}\u{4ef6}\u{5939}", "Choose game folder"),"build.folderSelected": ("\u{5df2}\u{9009}\u{62e9}\u{6e38}\u{620f}\u{6587}\u{4ef6}\u{5939}", "Game folder selected"),// ---- Launcher and guided builds ----+ "dev.section": ("\u{5b89}\u{88c5}\u{5230}\u{8bbe}\u{5907}", "Install"),+ "dev.target": ("\u{5b89}\u{88c5}\u{5230}", "Install on"),+ "dev.none": ("\u{4e0d}\u{5b89}\u{88c5}\u{ff0c}\u{53ea}\u{5bfc}\u{51fa} IPA", "Don't install, export the IPA"),+ "dev.notConnected": ("\u{672a}\u{8fde}\u{63a5}", "not connected"),+ "dev.noDevices": ("\u{6ca1}\u{6709}\u{4e0e}\u{8fd9}\u{53f0} Mac \u{914d}\u{5bf9}\u{7684} iPhone \u{6216} iPad\u{ff08}\u{9700}\u{8981} Xcode\u{ff09}\u{3002}", "No iPhone or iPad paired with this Mac (needs Xcode)."),+ "dev.refresh": ("\u{5237}\u{65b0}", "Refresh"),+ "dev.team": ("\u{7b7e}\u{540d}\u{56e2}\u{961f}", "Signing team"),+ "dev.noTeam": ("\u{6ca1}\u{6709}\u{5f00}\u{53d1}\u{8bc1}\u{4e66}\u{3002}\u{5728} Xcode \u{4e2d}\u{767b}\u{5f55} Apple ID\u{ff08}\u{8bbe}\u{7f6e} \u{2192} \u{8d26}\u{6237}\u{ff09}\u{5373}\u{53ef}\u{83b7}\u{5f97}\u{3002}", "No development certificate. Sign in to Xcode with your Apple ID (Settings \u{2192} Accounts) to get one."),+ "dev.note": ("Xcode \u{4f1a}\u{4e3a}\u{8fd9}\u{53f0}\u{8bbe}\u{5907}\u{7b7e}\u{540d}\u{5e76}\u{76f4}\u{63a5}\u{5b89}\u{88c5}\u{ff0c}\u{6e38}\u{620f}\u{6587}\u{4ef6}\u{5df2}\u{5305}\u{542b}\u{5728} App \u{4e2d}\u{ff0c}\u{5b89}\u{88c5}\u{53ef}\u{80fd}\u{9700}\u{8981}\u{51e0}\u{5206}\u{949f}\u{3002}\u{7b2c}\u{4e00}\u{6b21}\u{9700}\u{8981}\u{5728}\u{8bbe}\u{5907}\u{4e0a}\u{5f00}\u{542f}\u{5f00}\u{53d1}\u{8005}\u{6a21}\u{5f0f}\u{ff0c}\u{5e76}\u{4fe1}\u{4efb}\u{5f00}\u{53d1}\u{8005}\u{ff08}\u{8bbe}\u{7f6e} \u{2192} \u{901a}\u{7528} \u{2192} VPN \u{4e0e}\u{8bbe}\u{5907}\u{7ba1}\u{7406}\u{ff09}\u{3002}", "Xcode signs the game for this device and installs it there, with the game files inside the app; installing can take a few minutes. The first time, turn on Developer Mode on the device and trust the developer (Settings \u{2192} General \u{2192} VPN & Device Management)."),+ "dev.signStage": ("\u{4e3a} %@ \u{7b7e}\u{540d}", "Sign for %@"),+ "dev.installStage": ("\u{5b89}\u{88c5}\u{5230} %@", "Install on %@"),+ "dev.installed": ("\u{5df2}\u{5b89}\u{88c5}\u{5230} %@", "Installed on %@"),+ "dev.installedNote": ("\u{6e38}\u{620f}\u{5df2}\u{5728}\u{8bbe}\u{5907}\u{4e0a}\u{ff0c}\u{53ef}\u{4ee5}\u{76f4}\u{63a5}\u{6253}\u{5f00}\u{3002}", "The game is on the device, ready to open."),+ "dev.open": ("\u{5728} %@ \u{4e0a}\u{6253}\u{5f00}", "Open on %@"),+ "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: %@"),"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 5bb2e507..59b68e8c 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -265,6 +265,112 @@ final class LibraryTests: XCTestCase {XCTAssertEqual(model.doneNote, model.t("msg.stopped"))}+ func testPairedDevicesAndSigningTeamsAreRead() {+ let json = """+ {"result": {"devices": [+ {"hardwareProperties": {"reality": "physical", "platform": "iOS", "udid": "00008150-AAAA", "marketingName": "iPhone 17 Pro Max"},+ "deviceProperties": {"name": "Z", "osVersionNumber": "27.0.1"}, "connectionProperties": {"pairingState": "paired", "transportType": "wired"}},+ {"hardwareProperties": {"reality": "physical", "platform": "iOS", "udid": "00008110-BBBB", "marketingName": "iPad mini"},+ "deviceProperties": {"name": "Kunegunde"}, "connectionProperties": {"pairingState": "paired"}},+ {"hardwareProperties": {"reality": "simulated", "platform": "iOS", "udid": "SIM"}, "deviceProperties": {"name": "Simulator"},+ "connectionProperties": {"pairingState": "paired", "transportType": "sameMachine"}},+ {"hardwareProperties": {"reality": "physical", "platform": "iOS", "udid": "UNPAIRED"}, "deviceProperties": {"name": "Other"},+ "connectionProperties": {"pairingState": "unpaired"}}]}}+ """+ let devices = DeviceTools.parseDevices(Data(json.utf8))+ XCTAssertEqual(devices.map(\.id), ["00008150-AAAA", "00008110-BBBB"]) // physical and paired, reachable first+ XCTAssertEqual(devices.map(\.reachable), [true, false])+ let identities = DeviceTools.identities("""+ 1) 0123456789ABCDEF0123456789ABCDEF01234567 "Apple Development: Jo Doe (ABCDE12345)"+ 2) 89ABCDEF0123456789ABCDEF0123456789ABCDEF "Apple Distribution: Jo Doe (TEAM123456)"+ 2 valid identities found+ """)+ XCTAssertEqual(identities, ["Apple Development: Jo Doe (ABCDE12345)"]) // development only: distribution does not sign for a device+ XCTAssertEqual(DeviceTools.team(fromSubject: "subject=UID=X, CN=Apple Development: Jo Doe (ABCDE12345), OU=TEAM123456, O=Jo Doe, C=US"), "TEAM123456")+ XCTAssertNil(DeviceTools.team(fromSubject: "subject=CN=Something"))+ }++ /// An iPhone build with a device and a team: the script prepares the Xcode project, xcodebuild signs it for the+ /// device, devicectl installs it, and the library opens it there. The tools are stand-ins; nothing is signed.+ @MainActor func testBuildSignsAndInstallsOnTheChosenDevice() throws {+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("System Python is required for the process fixture") }+ let saved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam"].map { ($0, UserDefaults.standard.object(forKey: $0)) }+ defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }+ let model = BuildModel()+ model.repoPath = temporary.path+ model.target = "ios"+ model.outDir = temporary.path+ model.pythonPath = "/usr/bin/python3"+ model.dotnetPath = "/usr/bin/true"+ model.depsChecked = true+ model.deps = [BuildModel.Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]+ model.installDevice = "00008150-AAAA"+ model.signingTeam = "TEAM123456"+ let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")+ try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data().write(to: marker)+ let calls = temporary.appendingPathComponent("calls.txt")+ let script = temporary.appendingPathComponent("scripts/build_ipa_from_nsp.py")+ try FileManager.default.createDirectory(at: script.deletingLastPathComponent(), withIntermediateDirectories: true)+ try """+ import sys, json, pathlib # stand-in for the NSP script; it takes '--work-dir'+ open('\(calls.path)', 'a').write('script ' + ' '.join(sys.argv[1:]) + '\\n')+ work = pathlib.Path(sys.argv[sys.argv.index('--work-dir') + 1])+ (work / 'xcode/DmIOS.xcodeproj').mkdir(parents=True)+ def ev(**e): print(json.dumps(e), flush=True)+ ev(ev='stage', k=1, n=1, name='prepare Xcode')+ ev(ev='say', msg='[12:00:00] app name: Test; version: 1.0; bundle ID: org.nxnative.test')+ ev(ev='stage_end', k=1, name='prepare Xcode', ok=True, summary='', elapsed=1)+ """.write(to: script, atomically: true, encoding: .utf8)+ let xcrun = temporary.appendingPathComponent("xcrun")+ try """+ #!/usr/bin/python3+ import sys, json, pathlib, plistlib # stand-in for xcrun: xcodebuild -list / build, devicectl install / launch+ a = sys.argv[1:]+ open('\(calls.path)', 'a').write(' '.join(a) + '\\n')+ if a[0] == 'xcodebuild' and '-list' in a:+ print('Command line invocation:'); print(json.dumps({'project': {'schemes': ['DmIOS', 'Test (0100535012974000)']}}))+ elif a[0] == 'xcodebuild':+ app = pathlib.Path(a[a.index('-derivedDataPath') + 1]) / 'Build/Products/Release-iphoneos/DmIOS.app'+ app.mkdir(parents=True)+ with (app / 'Info.plist').open('wb') as f: plistlib.dump({'CFBundleIdentifier': 'org.nxnative.test'}, f)+ print('CodeSign ' + str(app), flush=True)+ elif a[:3] == ['devicectl', 'device', 'install']:+ print('45%', flush=True); print('App installed', flush=True)+ """.write(to: xcrun, atomically: true, encoding: .utf8)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: xcrun.path)+ model.xcrunPath = xcrun.path+ let base = temporary.appendingPathComponent("Test [\(titleID)].nsp"), keys = temporary.appendingPathComponent("prod.keys")+ try Data([0]).write(to: base); try Data().write(to: keys)+ model.slots[0].paths = [base.path]; model.slots[3].paths = [keys.path]+ let finished = expectation(description: "Signed and installed")+ let token = model.$done.filter { $0 }.prefix(1).sink { _ in finished.fulfill() }+ model.startBuild()+ wait(for: [finished], timeout: 20)+ withExtendedLifetime(token) {}+ let log = try String(contentsOf: calls, encoding: .utf8).split(separator: "\n").map(String.init)+ let work = temporary.appendingPathComponent(titleID + "_build").path+ XCTAssertTrue(log[0].contains("--prepare-xcode --keep-extracted --team-id TEAM123456"))+ XCTAssertFalse(log[0].contains(" -o ")) // no IPA: the project goes to the device+ let build = try XCTUnwrap(log.first { $0.hasPrefix("xcodebuild -project") })+ for part in ["-scheme Test (0100535012974000)", "-destination id=00008150-AAAA", "-derivedDataPath \(work)/xcode-derived-data",+ "-allowProvisioningUpdates", "DEVELOPMENT_TEAM=TEAM123456"] { XCTAssertTrue(build.contains(part), part) }+ let app = work + "/xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app"+ XCTAssertTrue(log.contains("devicectl device install app --device 00008150-AAAA \(app)"))+ XCTAssertEqual(model.installedOn, "00008150-AAAA")+ XCTAssertEqual(model.stages.filter { $0.id >= 1001 }.map(\.state), [.done, .done])+ XCTAssertFalse(model.stages.contains { $0.id == 1000 }) // no RomFS archive: the game files are in the app+ let library = GameLibrary(file: temporary.appendingPathComponent("library.json"))+ model.slots[0].paths = [base.path]+ let id = try XCTUnwrap(library.rememberInputs(model))+ library.recordCompletedIOS(ipa: model.ipaPath, archive: model.archivePath, app: model.installedAppPath, device: model.installedOn, for: id)+ XCTAssertTrue(library.games[0].onDevice)+ let opened = expectation(description: "Opened on the device")+ model.openOnDevice(udid: model.installedOn, app: model.installedAppPath) { error in XCTAssertNil(error); opened.fulfill() }+ wait(for: [opened], timeout: 10)+ XCTAssertTrue(try String(contentsOf: calls, encoding: .utf8).contains("devicectl device process launch --device 00008150-AAAA org.nxnative.test"))+ }+func testCorruptLibraryIsReportedWithoutOverwritingIt() throws {let file = temporary.appendingPathComponent("library.json")let data = Data("broken JSON".utf8)@@ -533,6 +639,17 @@ final class LibraryTests: XCTestCase {try capture("build", page: .builds)try capture("build-small", width: 900, height: 680, page: .builds)try capture("settings", page: .settings)+ // An iPhone build with a paired device and a team (example values)+ let previousTarget = model.target+ model.target = "ios"+ model.devicesChecked = true+ model.devices = [AppleDevice(id: "00008150-AAAA", name: "iPhone", model: "iPhone 17 Pro Max", os: "27.0", reachable: true),+ AppleDevice(id: "00008110-BBBB", name: "iPad mini", model: "iPad mini", os: "26.2", reachable: false)]+ model.teams = [SigningTeam(id: "TEAM123456", identity: "Apple Development: Jo Doe (ABCDE12345)")]+ let previousDevice = model.installDevice, previousTeam = model.signingTeam+ model.installDevice = "00008150-AAAA"; model.signingTeam = "TEAM123456"+ try capture("build-install", height: 1300, page: .builds)+ model.installDevice = previousDevice; model.signingTeam = previousTeam; model.target = previousTargetif let json = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_SETTINGS"] { // a launcher.json from dm/games/settings.pylet first = library.games[0]let dm = URL(fileURLWithPath: first.appPath).appendingPathComponent("Contents/Resources/dm")