Skip to content

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

Mac launcher: install target for one app on the device that holds every game

v0lumehibb56c8c9403b
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.py
index eb9c9607..dc8ff7a0 100644
--- a/frontend-qt/nspb_qt/localization.py
+++ b/frontend-qt/nspb_qt/localization.py
@@ -217,6 +217,34 @@ TABLE: dict[str, tuple[str, str, str, str]] = {
'build.compatibility': ('兼容性选项', 'Older iPhone support', 'Stöd för äldre iPhone-modeller', 'Unterstützung für ältere iPhones'),
'build.macNote': ('在这台 Mac 上直接运行。', 'Play directly on this Mac.', 'Spela direkt på den här Mac-datorn.', 'Direkt auf diesem Mac spielen.'),
'build.iosNote': ('为你的 iPhone 或 iPad 创建应用。', 'Create an app for your iPhone or iPad.', 'Skapa en app för din iPhone eller iPad.', 'Erstelle eine App für dein iPhone oder iPad.'),
+ 'build.shell': ('iPhone 或 iPad(所有游戏共用一个应用)', 'iPhone or iPad (one app for all games)', 'iPhone eller iPad (en app för alla spel)', 'iPhone or iPad (one app for all games)'),
+ 'build.shellNote': ('设备上的一个应用装下你添加的所有游戏。每个游戏的数据只复制一次。', "One app on the device holds every game you add. Each game's data is copied once.", 'En app på enheten rymmer alla spel du lägger till. Varje spels data kopieras en gång.', "One app on the device holds every game you add. Each game's data is copied once."),
+ 'shell.projectStage': ('准备共用应用', 'Prepare the shared app', 'Förbereder den gemensamma appen', 'Prepare the shared app'),
+ 'shell.projectFailed': ('无法准备共用应用:%@', 'The shared app could not be prepared: %@', 'Den gemensamma appen kunde inte förberedas: %@', 'The shared app could not be prepared: %@'),
+ 'shell.checkStage': ('比较 %@ 上的游戏数据', 'Compare the game data on %@', 'Jämför speldata på %@', 'Compare the game data on %@'),
+ 'shell.dataAlready': ('已安装到 %@,游戏数据已经在设备上', 'Installed on %@, the game data was already on the device', 'Installerad på %@, speldatan fanns redan på enheten', 'Installed on %@, the game data was already on the device'),
+ 'shell.noSpace': ('%@ 上空间不足:游戏数据需要 %.1f GB,设备只剩 %.1f GB。请先释放空间再安装', 'Not enough space on %@: the game data needs %.1f GB and the device has %.1f GB free. Free up space, then install again', 'Inte tillräckligt med utrymme på %@: speldatan behöver %.1f GB och enheten har %.1f GB ledigt. Frigör utrymme och installera igen', 'Not enough space on %@: the game data needs %.1f GB and the device has %.1f GB free. Free up space, then install again'),
+ 'shell.noFramework': ('没有找到游戏的框架:%@', "The game's framework was not found: %@", 'Spelets ramverk hittades inte: %@', "The game's framework was not found: %@"),
+ 'shell.needsDevice': ('共用应用需要一台设备和一个签名团队。请先在“安装到”里选择。', 'The shared app needs a device and a signing team. Choose them under Install on first.', 'Den gemensamma appen behöver en enhet och ett signeringsteam. Välj dem först under Installera på.', 'The shared app needs a device and a signing team. Choose them under Install on first.'),
+ 'shell.copySize': ('要复制的游戏数据:%@,共 %d 个文件。', 'Game data to copy: %@ in %d files.', 'Speldata att kopiera: %@ i %d filer.', 'Game data to copy: %@ in %d files.'),
+ 'shell.copyWired': ('复制完成前请保持 %@ 解锁。', 'Keep %@ unlocked until the copy finishes.', 'Låt %@ vara olåst tills kopieringen är klar.', 'Keep %@ unlocked until the copy finishes.'),
+ 'shell.copyWifi': ('已通过 Wi-Fi 连接:复制 %@ 大约需要 %d 到 %d 分钟。用数据线会更快。', 'Connected over Wi-Fi: copying %@ takes about %d to %d minutes. A cable is faster.', 'Ansluten via Wi-Fi: att kopiera %@ tar ungefär %d till %d minuter. En kabel går fortare.', 'Connected over Wi-Fi: copying %@ takes about %d to %d minutes. A cable is faster.'),
+ 'shell.copyWifiOne': ('已通过 Wi-Fi 连接:复制 %@ 大约需要 %d 分钟。用数据线会更快。', 'Connected over Wi-Fi: copying %@ takes about %d minutes. A cable is faster.', 'Ansluten via Wi-Fi: att kopiera %@ tar ungefär %d minuter. En kabel går fortare.', 'Connected over Wi-Fi: copying %@ takes about %d minutes. A cable is faster.'),
+ 'shell.copyWifiMinute': ('已通过 Wi-Fi 连接:复制 %@ 大约需要一分钟。用数据线会更快。', 'Connected over Wi-Fi: copying %@ takes about a minute. A cable is faster.', 'Ansluten via Wi-Fi: att kopiera %@ tar ungefär en minut. En kabel går fortare.', 'Connected over Wi-Fi: copying %@ takes about a minute. A cable is faster.'),
+ 'shell.copyNotConnected': ('%@ 目前没有连接。请用数据线连接并保持解锁。', '%@ is not connected right now. Connect it with a cable and keep it unlocked.', '%@ är inte ansluten just nu. Anslut den med kabel och låt den vara olåst.', '%@ is not connected right now. Connect it with a cable and keep it unlocked.'),
+ 'shell.copyWaiting': ('正在等待数据线。%@ 接上后会自动开始复制。', 'Waiting for a cable. The copy starts when %@ is connected.', 'Väntar på en kabel. Kopieringen startar när %@ är ansluten.', 'Waiting for a cable. The copy starts when %@ is connected.'),
+ 'shell.copyTitle': ('复制游戏数据', 'Copy the game data', 'Kopiera speldata', 'Copy the game data'),
+ 'shell.copyContinue': ('继续', 'Continue', 'Fortsätt', 'Continue'),
+ 'shell.copyWaitCable': ('等待数据线', 'Wait for a cable', 'Vänta på kabel', 'Wait for a cable'),
+ 'shell.copySkip': ('暂不复制', 'Not now', 'Inte nu', 'Not now'),
+ 'shell.copyStopWaiting': ('不再等待', 'Stop waiting', 'Sluta vänta', 'Stop waiting'),
+ 'shell.retry': ('重试', 'Retry', 'Försök igen', 'Retry'),
+ 'shell.notPaired': ('这台 Mac 还没有与 %@ 配对。请用数据线连接,在设备上点「信任」并输入设备密码,然后重新开始。', '%@ is not paired with this Mac. Connect it with a cable, tap Trust on the device and enter its passcode. Then start again.', '%@ är inte ihopparad med den här Mac-datorn. Anslut den med kabel, tryck på Lita på i enheten och ange enhetens lösenkod. Starta sedan om.', '%@ is not paired with this Mac. Connect it with a cable, tap Trust on the device and enter its passcode. Then start again.'),
+ 'shell.copyIncomplete': ('%@ 上的游戏数据不完整:%@。重试会补全。', 'The game data on %@ is incomplete: %@. Retry finishes it.', 'Speldatan på %@ är ofullständig: %@. Försök igen så blir den klar.', 'The game data on %@ is incomplete: %@. Retry finishes it.'),
+ 'fail.devicePairing.what': ('这台 Mac 还没有与设备配对。', 'This Mac is not paired with the device.', 'Den här Mac-datorn är inte ihopparad med enheten.', 'This Mac is not paired with the device.'),
+ 'fail.devicePairing.next': ('用数据线连接设备,在设备上点「信任」并输入设备密码,然后重试。', 'Connect the device with a cable, tap Trust on the device and enter its passcode. Then try again.', 'Anslut enheten med kabel, tryck på Lita på i enheten och ange dess lösenkod. Försök sedan igen.', 'Connect the device with a cable, tap Trust on the device and enter its passcode. Then try again.'),
+ 'fail.shellDataIncomplete.what': ('设备上的游戏数据不完整。', 'The game data on the device is incomplete.', 'Speldatan på enheten är ofullständig.', 'The game data on the device is incomplete.'),
+ 'fail.shellDataIncomplete.next': ('游戏还不能玩。请解锁设备并保持连接,然后点重试,只会补上缺少或不完整的文件。', 'The game is not ready to play. Unlock the device and keep it connected, then retry. Only the missing or incomplete files are copied.', 'Spelet är inte klart att spela. Lås upp enheten och håll den ansluten och försök sedan igen. Bara de filer som saknas eller är ofullständiga kopieras.', 'The game is not ready to play. Unlock the device and keep it connected, then retry. Only the missing or incomplete files are copied.'),
'build.folderCTA': ('选择游戏文件夹', 'Choose game folder', 'Välj spelmapp', 'Spieleordner wählen'),
'build.folderSelected': ('已选择游戏文件夹', 'Game folder selected', 'Spelmapp vald', 'Spieleordner ausgewählt'),
'dev.section': ('安装到设备', 'Install', 'Installera', 'Installation'),
diff --git a/frontend/README.md b/frontend/README.md
index 169f86e8..2d341278 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -84,6 +84,18 @@ that did not change, so a reinstall sends the code and shaders, not the whole ga
again. The first copy of a large game takes a few minutes. The game then appears
in the collection, and its button opens it on the device.
+**iPhone or iPad (one app for all games)** is a third target for the same device. The build
+script makes only the game's framework (`--shell-framework`), and one shared app on the device
+holds every game you add. The launcher keeps the list of games in `shell.json` in the
+`NX2Apple-shell` folder (next to the output folder, saved as `shellRoot`), generates the app's
+project with `dm/ios/tools/build_shell.sh --prepare-xcode`, signs it with `xcodebuild` and
+installs it over the one already there, which keeps the app's Documents. Game data is
+compared with the device by path and size and only what is missing is copied, so a second
+install of the same game copies nothing. The same steps run without the window:
+
+ NSPortBuilder --install-shell --framework <path> --archive <games/TITLEID folder> --title-id <id> \
+ --name <name> --device <udid> --team <team> --repo <repo> [--shell-root <dir>] [--python <path>]
+
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
diff --git a/frontend/Sources/NSPortBuilder/BuildFailure.swift b/frontend/Sources/NSPortBuilder/BuildFailure.swift
index 28b40a1f..91c9be50 100644
--- a/frontend/Sources/NSPortBuilder/BuildFailure.swift
+++ b/frontend/Sources/NSPortBuilder/BuildFailure.swift
@@ -13,6 +13,8 @@ enum BuildFailureKind: String, CaseIterable {
/// The build folder is in iCloud Drive or another cloud folder (CloudFolder.swift): the launcher stops before the build, and the
/// codesign line of xcodebuild is the same stop for a build that got past that check.
case cloudFolder
+ /// The shared app's install: a device this Mac never paired, and game data that went over only in part.
+ case devicePairing, shellDataIncomplete
/// The engine's online sync (tools/engine.py sync, Engine.swift): no network or GitHub unreachable, or any other stop of it.
case engineOffline, engineSync
case unknown
diff --git a/frontend/Sources/NSPortBuilder/BuildFailureView.swift b/frontend/Sources/NSPortBuilder/BuildFailureView.swift
index c228e1d5..cfef05c6 100644
--- a/frontend/Sources/NSPortBuilder/BuildFailureView.swift
+++ b/frontend/Sources/NSPortBuilder/BuildFailureView.swift
@@ -58,8 +58,10 @@ struct BuildFailureCard: View {
fix(kind, "fail.cloudFolder.button")
case .teamTaken, .noSigningAccount:
if BuildModel.installedXcode() != nil { fix(kind, "fail.openXcode") }
- case .deviceTransfer:
+ case .deviceTransfer, .devicePairing:
fix(kind, "fail.retry")
+ case .shellDataIncomplete:
+ fix(kind, "shell.retry")
case .engineOffline, .engineSync:
Button(m.t("fail.retry")) { m.retryEngineSync() }.disabled(m.engineSyncing)
default: EmptyView()
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 284802b0..fff0e291 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -156,6 +156,12 @@ final class BuildModel: ObservableObject {
}
@Published var installedOn = "" // the device the last build went to (its UDID)
@Published var installedAppPath = "" // the signed app that went there
+ /// The shared app's copy question: the size and the connection (nil: none is up).
+ @Published var shellCopy: ShellCopyPlan?
+ @Published var shellWaiting = false // waiting for a cable before the game data goes over
+ fileprivate var shellCopyAnswer: ((ShellCopyDecision) -> Void)?
+ let shellWaitCancelled = LockedFlag()
+ private var shellRetry: (framework: String, titleID: String, name: String, archive: String)?
@Published var transferAsk = false // the transfer-the-game-files question is up: USB from the Mac is slow, so copying is the player's call
private var transferHandler: ((Bool) -> Void)?
@@ -247,12 +253,12 @@ final class BuildModel: ObservableObject {
p.executableURL = URL(fileURLWithPath: python)
}
- private static func track(_ p: Process) {
+ static func track(_ p: Process) {
_ = exitHandlers
groupsLock.lock(); groups.insert(p.processIdentifier); groupsLock.unlock()
}
- private static func untrack(_ p: Process) {
+ static func untrack(_ p: Process) {
groupsLock.lock(); groups.remove(p.processIdentifier); groupsLock.unlock()
}
@@ -1209,6 +1215,13 @@ final class BuildModel: ObservableObject {
func startBuild() {
guard !running else { return }
+ // The shared app needs a device this Mac knows. Found out here, before an hour of building, not after it.
+ if target == "ios-shell", !shellDeviceChecked {
+ guard installsDirectly else { doneNote = t("shell.needsDevice"); done = false; return }
+ verifyShellDevice()
+ return
+ }
+ shellDeviceChecked = false
stopping = false
running = true; done = false; doneNote = ""; stages = []; logTail = ""; lineBuf = ""; chainNoteShown = false
failure = nil; confirmingOverride = nil
@@ -1338,6 +1351,9 @@ final class BuildModel: ObservableObject {
args += ["--platform", "mac-app"]
macAppPath = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + ".app"
args += ["-o", macAppPath]
+ } else if target == "ios-shell" {
+ // Only the game's framework: the one shared app is made and signed after the script (installShell)
+ args += ShellInstall.buildArguments(workDir: workDir, team: signingTeam)
} 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]
@@ -1411,6 +1427,14 @@ final class BuildModel: ObservableObject {
}
self.running = false
self.cleanupStaging()
+ } else if self.target == "ios-shell" {
+ // The same archive, then the game's framework into the one shared app on the device
+ let tid = Self.titleID(self.basePath).map { String(format: "%016llX", $0) } ?? "game"
+ let name = ((self.basePath as NSString).lastPathComponent as NSString).deletingPathExtension
+ self.packArchive(workDir: self.effectiveWorkDir) {
+ self.installShell(framework: ShellInstall.frameworkPath(workDir: self.effectiveWorkDir, titleID: tid),
+ titleID: tid, name: name, archive: $0)
+ }
} else if self.installsDirectly {
// The same archive as for sideloading, then the app without the game files, then the archive into its Documents
self.packArchive(workDir: self.effectiveWorkDir) { self.signAndInstall(archive: $0) }
@@ -1444,6 +1468,27 @@ final class BuildModel: ObservableObject {
do { try p.run(); Self.track(p) } catch { fail(String(format: t("msg.launchFailed"), error.localizedDescription)) }
}
+ private var shellDeviceChecked = false
+
+ /// Looks the device up in `devicectl list devices` (in the background), then starts the build, or says how to pair it.
+ private func verifyShellDevice() {
+ running = true; done = false; doneNote = ""; failure = nil; stages = []
+ let xcrun = xcrunPath, device = installDevice
+ DispatchQueue.global(qos: .userInitiated).async {
+ let link = ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20))
+ DispatchQueue.main.async {
+ self.running = false
+ if link == .notPaired {
+ self.failure = BuildFailure(kind: .devicePairing, gameName: nil)
+ self.doneNote = String(format: self.t("shell.notPaired"), self.deviceName(device))
+ return
+ }
+ self.shellDeviceChecked = true
+ self.startBuild()
+ }
+ }
+ }
+
/// The build's last step is done either way: release the button and show the outcome.
func finishBuild(ok: Bool, note: String) {
running = false
@@ -1536,8 +1581,10 @@ final class BuildModel: ObservableObject {
chooseBuildFolder()
case .teamTaken, .noSigningAccount:
openXcode()
- case .deviceTransfer:
+ case .deviceTransfer, .devicePairing:
startBuild()
+ case .shellDataIncomplete:
+ retryShellData()
default: break
}
}
@@ -2085,6 +2132,87 @@ final class BuildModel: ObservableObject {
}
}
+ /// Steps 4 to 7 of the shared app (ShellInstall.swift) for a game whose framework is built and whose archive is packed: the
+ /// shell's project, signing, the install over the app that is already there, and the game data the device lacks.
+ func installShell(framework: String, titleID: String, name: String, archive: String, dataOnly: Bool = false) {
+ running = true
+ if dataOnly { failure = nil; done = false; doneNote = "" }
+ shellRetry = (framework, titleID, name, archive)
+ let python = pythonPath.isEmpty ? Self.findPython().path : pythonPath
+ let root = ShellLibrary.resolveRoot(parent: outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir)
+ var installer = ShellInstaller(xcrun: xcrunPath, repo: repoPath, python: python, root: root, device: installDevice, team: signingTeam)
+ installer.deviceName = deviceName(installDevice)
+ installer.lang = lang
+ installer.ownGroup = true
+ installer.toolPath = Self.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: python)
+ installer.log = { s in DispatchQueue.main.async { self.append(s) } }
+ installer.stage = { s in DispatchQueue.main.async {
+ if let i = self.stages.firstIndex(where: { $0.id == s.id }) {
+ self.stages[i].name = s.name; self.stages[i].state = s.state; self.stages[i].detail = s.detail
+ if let percent = s.percent { self.stages[i].percent = percent }
+ if s.state == .running, self.stages[i].started == nil { self.stages[i].started = Date() }
+ } else {
+ self.stages.append(Stage(id: s.id, name: s.name, state: s.state, detail: s.detail, percent: s.percent,
+ started: s.state == .running ? Date() : nil))
+ }
+ } }
+ installer.processStarted = { p in DispatchQueue.main.async { self.proc = p; Self.track(p) } }
+ installer.processEnded = { p in Self.untrack(p) }
+ // The size and the connection are shown with Continue, "Wait for a cable" and "Not now" (ShellCopyCard)
+ installer.decideCopy = { plan in
+ let answered = DispatchSemaphore(value: 0)
+ var answer = ShellCopyDecision.skip
+ DispatchQueue.main.async {
+ self.shellWaitCancelled.set(false)
+ self.shellCopyAnswer = { answer = $0; answered.signal() }
+ self.shellCopy = plan
+ }
+ answered.wait()
+ return answer
+ }
+ installer.waiting = { on in DispatchQueue.main.async { self.shellWaiting = on } }
+ installer.waitCancelled = { self.shellWaitCancelled.value }
+ let device = installDevice
+ DispatchQueue.global(qos: .userInitiated).async {
+ let result = dataOnly ? installer.installData(titleID: titleID, archive: archive)
+ : installer.install(framework: framework, titleID: titleID, name: name, archive: archive)
+ DispatchQueue.main.async {
+ self.shellCopy = nil; self.shellWaiting = false
+ if self.stopping {
+ self.stopping = false; self.running = false
+ self.resetProgress(); self.doneNote = self.t("msg.stopped"); self.cleanupStaging()
+ return
+ }
+ guard result.ok else {
+ self.finishInstall(result.message)
+ if let kind = result.failure { self.failure = BuildFailure(kind: kind, gameName: nil) }
+ else if let step = result.step { self.noteInstallFailure(step, error: result.message) }
+ return
+ }
+ self.installedOn = device
+ self.installedAppPath = result.appPath
+ self.finishInstall(nil, note: result.message)
+ }
+ }
+ }
+
+ /// What the player picked on the copy card (Continue, wait for a cable, not now), handed to the install waiting for it.
+ func answerShellCopy(_ decision: ShellCopyDecision) {
+ guard let answer = shellCopyAnswer else { return }
+ shellCopyAnswer = nil
+ shellCopy = nil
+ answer(decision)
+ }
+
+ /// "Stop waiting" while the install waits for a cable: the poll ends at its next look and the game data stays for later.
+ func cancelShellWait() { shellWaitCancelled.set(true) }
+
+ /// Retry after game data that went over in part: only the data step runs again (listing, diff, copy).
+ func retryShellData() {
+ guard !running, let r = shellRetry else { return }
+ installShell(framework: r.framework, titleID: r.titleID, name: r.name, archive: r.archive, dataOnly: true)
+ }
+
private func finishInstall(_ failure: String?, note: String? = nil) {
running = false
done = failure == nil
@@ -2130,26 +2258,33 @@ final class BuildModel: ObservableObject {
doneNote = t("dev.resignNoTeam")
then?(); return
}
- guard let bundle = NSDictionary(contentsOfFile: app + "/Info.plist")?["CFBundleIdentifier"] as? String else {
+ let shell = ShellInstall.paths(ofApp: app)
+ // The shared app's identifier is the one shell.json holds, the others' is the installed app's own
+ guard let bundle = shell.map({ ShellLibrary.load(root: $0.root).bundleID })
+ ?? (NSDictionary(contentsOfFile: app + "/Info.plist")?["CFBundleIdentifier"] as? String) else {
doneNote = String(format: t("dev.noProject"), shortPath(app + "/Info.plist"))
then?(); return
}
- guard let paths = Self.buildPaths(ofApp: app), FileManager.default.fileExists(atPath: paths.project) else {
+ guard let paths = shell.map({ (project: $0.project, derived: $0.derived) }) ?? Self.buildPaths(ofApp: app),
+ FileManager.default.fileExists(atPath: paths.project) else {
doneNote = String(format: t("dev.resignNoProject"), shortPath(Self.buildPaths(ofApp: app)?.project ?? app))
then?(); return
}
let xcrun = xcrunPath, team = signingTeam, name = deviceName(device)
DispatchQueue.global(qos: .userInitiated).async {
- let scheme = Self.scheme(of: paths.project, xcrun: xcrun)
+ let scheme = shell != nil ? ShellInstall.scheme : Self.scheme(of: paths.project, xcrun: xcrun)
DispatchQueue.main.async {
guard let scheme else {
self.doneNote = String(format: self.t("dev.noProject"), self.shortPath(paths.project))
then?(); return
}
self.running = true
+ // The shared app is signed again under the identifier shell.json holds, so the device keeps its Documents
+ let command = shell.map { ShellInstall.buildCommand(xcrun: xcrun, root: $0.root, device: device, team: team, bundleID: bundle) }
+ ?? Self.resignCommand(xcrun: xcrun, project: paths.project, scheme: scheme, device: device,
+ derived: paths.derived, team: team, bundle: bundle)
self.runTool(id: 1006, name: String(format: self.t("dev.resignStage"), name),
- Self.resignCommand(xcrun: xcrun, project: paths.project, scheme: scheme, device: device,
- derived: paths.derived, team: team, bundle: bundle), step: Self.xcodeStep) { error in
+ command, step: Self.xcodeStep) { error in
if let error, !error.isEmpty {
self.running = false
self.doneNote = String(format: self.t("dev.resignFailed"), error)
@@ -3205,6 +3340,7 @@ struct BuilderView: View {
if m.target != "mac-app" { install.disabled(m.running) }
logPanel
action
+ ShellCopyCard(m: m)
BuildFailureCard(m: m)
outcome
progress
@@ -3296,6 +3432,7 @@ struct BuilderView: View {
HStack(spacing: 14) {
targetCard("mac-app", symbol: "desktopcomputer", title: "build.mac", note: "build.macNote")
targetCard("ios", symbol: "iphone", title: "build.ios", note: "build.iosNote")
+ targetCard("ios-shell", symbol: "square.stack.3d.up", title: "build.shell", note: "build.shellNote")
}
// A Mac app runs on this Mac's GPU, which always decodes BC textures: the switch is the iPhone's only.
if m.target != "mac-app" {
@@ -3785,3 +3922,11 @@ struct BuilderView: View {
if d.runModal() == .OK, let u = d.url { m.repoPath = u.path }
}
}
+
+/// A flag two threads share (the cancel button on the main thread, the install's wait loop on a background one).
+final class LockedFlag: @unchecked Sendable {
+ private let lock = NSLock()
+ private var flag = false
+ func set(_ value: Bool) { lock.lock(); flag = value; lock.unlock() }
+ var value: Bool { lock.lock(); defer { lock.unlock() }; return flag }
+}
diff --git a/frontend/Sources/NSPortBuilder/Devices.swift b/frontend/Sources/NSPortBuilder/Devices.swift
index 6857ca65..1537b4a7 100644
--- a/frontend/Sources/NSPortBuilder/Devices.swift
+++ b/frontend/Sources/NSPortBuilder/Devices.swift
@@ -7,6 +7,10 @@ struct AppleDevice: Identifiable, Equatable {
let model: String
let os: String
let reachable: Bool // connected now, by cable or the local network
+ var transport = "" // devicectl's connectionProperties.transportType: "wired" (cable), "localNetwork" (Wi-Fi), "" when not connected
+
+ var wired: Bool { transport == "wired" }
+ var overNetwork: Bool { transport == "localNetwork" }
}
/// A team the launcher can sign for: from a development certificate in the keychain, from an account signed in to
@@ -64,7 +68,8 @@ enum DeviceTools {
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)
+ reachable: connection["transportType"] is String,
+ transport: connection["transportType"] as? String ?? "")
}
return devices.sorted { ($0.reachable ? 0 : 1, $0.name) < ($1.reachable ? 0 : 1, $1.name) }
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index c4ceef82..3a56e8f5 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -256,6 +256,34 @@ enum L10n {
"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."),
"build.iosNote": ("\u{4e3a}\u{4f60}\u{7684} iPhone \u{6216} iPad \u{521b}\u{5efa}\u{5e94}\u{7528}\u{3002}", "Create an app for your iPhone or iPad."),
+ "build.shell": ("iPhone 或 iPad(所有游戏共用一个应用)", "iPhone or iPad (one app for all games)"),
+ "build.shellNote": ("设备上的一个应用装下你添加的所有游戏。每个游戏的数据只复制一次。", "One app on the device holds every game you add. Each game's data is copied once."),
+ "shell.projectStage": ("准备共用应用", "Prepare the shared app"),
+ "shell.projectFailed": ("无法准备共用应用:%@", "The shared app could not be prepared: %@"),
+ "shell.checkStage": ("比较 %@ 上的游戏数据", "Compare the game data on %@"),
+ "shell.dataAlready": ("已安装到 %@,游戏数据已经在设备上", "Installed on %@, the game data was already on the device"),
+ "shell.noSpace": ("%@ 上空间不足:游戏数据需要 %.1f GB,设备只剩 %.1f GB。请先释放空间再安装", "Not enough space on %@: the game data needs %.1f GB and the device has %.1f GB free. Free up space, then install again"),
+ "shell.noFramework": ("没有找到游戏的框架:%@", "The game's framework was not found: %@"),
+ "shell.needsDevice": ("共用应用需要一台设备和一个签名团队。请先在“安装到”里选择。", "The shared app needs a device and a signing team. Choose them under Install on first."),
+ "shell.copySize": ("要复制的游戏数据:%@,共 %d 个文件。", "Game data to copy: %@ in %d files."),
+ "shell.copyWired": ("复制完成前请保持 %@ 解锁。", "Keep %@ unlocked until the copy finishes."),
+ "shell.copyWifi": ("已通过 Wi-Fi 连接:复制 %@ 大约需要 %d 到 %d 分钟。用数据线会更快。", "Connected over Wi-Fi: copying %@ takes about %d to %d minutes. A cable is faster."),
+ "shell.copyWifiOne": ("已通过 Wi-Fi 连接:复制 %@ 大约需要 %d 分钟。用数据线会更快。", "Connected over Wi-Fi: copying %@ takes about %d minutes. A cable is faster."),
+ "shell.copyWifiMinute": ("已通过 Wi-Fi 连接:复制 %@ 大约需要一分钟。用数据线会更快。", "Connected over Wi-Fi: copying %@ takes about a minute. A cable is faster."),
+ "shell.copyNotConnected": ("%@ 目前没有连接。请用数据线连接并保持解锁。", "%@ is not connected right now. Connect it with a cable and keep it unlocked."),
+ "shell.copyWaiting": ("正在等待数据线。%@ 接上后会自动开始复制。", "Waiting for a cable. The copy starts when %@ is connected."),
+ "shell.copyTitle": ("复制游戏数据", "Copy the game data"),
+ "shell.copyContinue": ("继续", "Continue"),
+ "shell.copyWaitCable": ("等待数据线", "Wait for a cable"),
+ "shell.copySkip": ("暂不复制", "Not now"),
+ "shell.copyStopWaiting": ("不再等待", "Stop waiting"),
+ "shell.retry": ("重试", "Retry"),
+ "shell.notPaired": ("这台 Mac 还没有与 %@ 配对。请用数据线连接,在设备上点「信任」并输入设备密码,然后重新开始。", "%@ is not paired with this Mac. Connect it with a cable, tap Trust on the device and enter its passcode. Then start again."),
+ "shell.copyIncomplete": ("%@ 上的游戏数据不完整:%@。重试会补全。", "The game data on %@ is incomplete: %@. Retry finishes it."),
+ "fail.devicePairing.what": ("这台 Mac 还没有与设备配对。", "This Mac is not paired with the device."),
+ "fail.devicePairing.next": ("用数据线连接设备,在设备上点「信任」并输入设备密码,然后重试。", "Connect the device with a cable, tap Trust on the device and enter its passcode. Then try again."),
+ "fail.shellDataIncomplete.what": ("设备上的游戏数据不完整。", "The game data on the device is incomplete."),
+ "fail.shellDataIncomplete.next": ("游戏还不能玩。请解锁设备并保持连接,然后点重试,只会补上缺少或不完整的文件。", "The game is not ready to play. Unlock the device and keep it connected, then retry. Only the missing or incomplete files are copied."),
"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 ----
@@ -1242,6 +1270,34 @@ enum L10n {
"build.compatibility": "Stöd för äldre iPhone-modeller",
"build.macNote": "Spela direkt på den här Mac-datorn.",
"build.iosNote": "Skapa en app för din iPhone eller iPad.",
+ "build.shell": "iPhone eller iPad (en app för alla spel)",
+ "build.shellNote": "En app på enheten rymmer alla spel du lägger till. Varje spels data kopieras en gång.",
+ "shell.projectStage": "Förbereder den gemensamma appen",
+ "shell.projectFailed": "Den gemensamma appen kunde inte förberedas: %@",
+ "shell.checkStage": "Jämför speldata på %@",
+ "shell.dataAlready": "Installerad på %@, speldatan fanns redan på enheten",
+ "shell.noSpace": "Inte tillräckligt med utrymme på %@: speldatan behöver %.1f GB och enheten har %.1f GB ledigt. Frigör utrymme och installera igen",
+ "shell.noFramework": "Spelets ramverk hittades inte: %@",
+ "shell.needsDevice": "Den gemensamma appen behöver en enhet och ett signeringsteam. Välj dem först under Installera på.",
+ "shell.copySize": "Speldata att kopiera: %@ i %d filer.",
+ "shell.copyWired": "Låt %@ vara olåst tills kopieringen är klar.",
+ "shell.copyWifi": "Ansluten via Wi-Fi: att kopiera %@ tar ungefär %d till %d minuter. En kabel går fortare.",
+ "shell.copyWifiOne": "Ansluten via Wi-Fi: att kopiera %@ tar ungefär %d minuter. En kabel går fortare.",
+ "shell.copyWifiMinute": "Ansluten via Wi-Fi: att kopiera %@ tar ungefär en minut. En kabel går fortare.",
+ "shell.copyNotConnected": "%@ är inte ansluten just nu. Anslut den med kabel och låt den vara olåst.",
+ "shell.copyWaiting": "Väntar på en kabel. Kopieringen startar när %@ är ansluten.",
+ "shell.copyTitle": "Kopiera speldata",
+ "shell.copyContinue": "Fortsätt",
+ "shell.copyWaitCable": "Vänta på kabel",
+ "shell.copySkip": "Inte nu",
+ "shell.copyStopWaiting": "Sluta vänta",
+ "shell.retry": "Försök igen",
+ "shell.notPaired": "%@ är inte ihopparad med den här Mac-datorn. Anslut den med kabel, tryck på Lita på i enheten och ange enhetens lösenkod. Starta sedan om.",
+ "shell.copyIncomplete": "Speldatan på %@ är ofullständig: %@. Försök igen så blir den klar.",
+ "fail.devicePairing.what": "Den här Mac-datorn är inte ihopparad med enheten.",
+ "fail.devicePairing.next": "Anslut enheten med kabel, tryck på Lita på i enheten och ange dess lösenkod. Försök sedan igen.",
+ "fail.shellDataIncomplete.what": "Speldatan på enheten är ofullständig.",
+ "fail.shellDataIncomplete.next": "Spelet är inte klart att spela. Lås upp enheten och håll den ansluten och försök sedan igen. Bara de filer som saknas eller är ofullständiga kopieras.",
"build.folderCTA": "Välj spelmapp",
"build.folderSelected": "Spelmapp vald",
"dev.section": "Installera",
diff --git a/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift b/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift
index 09422970..61bcbc3b 100644
--- a/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift
+++ b/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift
@@ -1,6 +1,17 @@
import SwiftUI
+/// The terminal switches run before any window exists: `--install-shell` is the shell install of Route C without the GUI
+/// (ShellInstall.swift). Everything else starts the app.
@main
+enum Entry {
+ static func main() {
+ if CommandLine.arguments.contains("--install-shell") {
+ exit(ShellCLI.run(Array(CommandLine.arguments.dropFirst())))
+ }
+ NSPortBuilderApp.main()
+ }
+}
+
struct NSPortBuilderApp: App {
@NSApplicationDelegateAdaptor private var delegate: AppDelegate
@StateObject private var console = ConsoleCoordinator()
diff --git a/frontend/Sources/NSPortBuilder/ShellCopyView.swift b/frontend/Sources/NSPortBuilder/ShellCopyView.swift
new file mode 100644
index 00000000..244ae3a3
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/ShellCopyView.swift
@@ -0,0 +1,41 @@
+import SwiftUI
+
+/// Before the shared app's game data goes over USB or Wi-Fi: how much, over which connection, and what to do about it. A cable
+/// gets one short note. Wi-Fi gets an estimate with Continue and a way to wait for a cable (the copy then starts by itself when the
+/// device shows up wired). While it waits, the card says so and offers to stop.
+struct ShellCopyCard: View {
+ @ObservedObject var m: BuildModel
+
+ var body: some View {
+ if let plan = m.shellCopy {
+ card {
+ Text(m.t("shell.copyTitle")).font(.manrope(14, .semibold))
+ Text(plan.sizeText).font(.manrope(13)).foregroundStyle(.secondary)
+ Text(plan.connectionText).font(.manrope(13)).fixedSize(horizontal: false, vertical: true)
+ HStack(spacing: 10) {
+ Button(m.t("shell.copyContinue")) { m.answerShellCopy(.copy) }
+ if plan.canWaitForCable { Button(m.t("shell.copyWaitCable")) { m.answerShellCopy(.waitForCable) } }
+ Button(m.t("shell.copySkip")) { m.answerShellCopy(.skip) }
+ }
+ .buttonStyle(LauncherSecondaryButtonStyle()).padding(.top, 2)
+ }
+ } else if m.shellWaiting {
+ card {
+ HStack(spacing: 8) {
+ ProgressView().controlSize(.small)
+ Text(String(format: m.t("shell.copyWaiting"), m.deviceName(m.installDevice))).font(.manrope(13))
+ }
+ Button(m.t("shell.copyStopWaiting")) { m.cancelShellWait() }
+ .buttonStyle(LauncherSecondaryButtonStyle()).padding(.top, 2)
+ }
+ }
+ }
+
+ private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {
+ VStack(alignment: .leading, spacing: 8, content: content)
+ .padding(18)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))
+ }
+}
diff --git a/frontend/Sources/NSPortBuilder/ShellInstall.swift b/frontend/Sources/NSPortBuilder/ShellInstall.swift
new file mode 100644
index 00000000..5258e2f6
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/ShellInstall.swift
@@ -0,0 +1,628 @@
+import Foundation
+
+// Route C: one app on the iPhone or iPad that holds several games. The build script makes only each game's framework
+// (`--shell-framework`), and this file does the rest: the shell's library file (shell.json), the shell's Xcode project
+// (dm/ios/tools/build_shell.sh), signing, the install, and the game data. Everything pure (the file, the commands, the listing
+// parser, the diff) is a static function with its own tests. `ShellInstaller` strings them together, blocking, so the same code
+// runs under the build model (on a background queue) and from the terminal (`NSPortBuilder --install-shell`).
+
+/// The shell's library: which games are in it, and the bundle ID the app has on the device. It lives in `<shell root>/shell.json`.
+struct ShellLibrary: Codable, Equatable {
+ struct Game: Codable, Equatable {
+ var titleID: String
+ var name: String
+ var framework: String
+ }
+
+ static let defaultBundleID = "org.nxnative.shell"
+
+ var bundleID = ShellLibrary.defaultBundleID
+ var team = ""
+ var games: [Game] = []
+
+ /// The identifier a team falls back to when `org.nxnative.shell` is registered to another team (the same per-team variant the
+ /// per-game install uses). Once stored in shell.json it stays: the app's Documents (game data, saves) belong to the identifier.
+ static func teamVariant(team: String) -> String { defaultBundleID + "." + team }
+
+ /// Adding a game replaces the entry with the same title ID (a rebuilt game has a new framework folder), otherwise appends.
+ mutating func add(_ game: Game) {
+ 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) }
+ }
+
+ static func stateFile(root: String) -> String { root + "/shell.json" }
+
+ /// The file's library, or a fresh one when there is none (or it cannot be read: the next save writes a valid one).
+ static func load(root: String) -> ShellLibrary {
+ guard let data = FileManager.default.contents(atPath: stateFile(root: root)),
+ let library = try? JSONDecoder().decode(ShellLibrary.self, from: data) else { return ShellLibrary() }
+ return library
+ }
+
+ func save(root: String) throws {
+ try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true)
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
+ try encoder.encode(self).write(to: URL(fileURLWithPath: Self.stateFile(root: root)), options: .atomic)
+ }
+
+ /// The shell root: the saved one (`shellRoot` in `defaults`), else `<parent>/NX2Apple-shell`, which is then saved so the shell
+ /// stays where it was first made, whatever output folder a later build uses.
+ static func resolveRoot(defaults: UserDefaults = .standard, parent: String) -> String {
+ if let saved = defaults.string(forKey: "shellRoot"), !saved.isEmpty { return saved }
+ let root = parent + "/NX2Apple-shell"
+ defaults.set(root, forKey: "shellRoot")
+ return root
+ }
+}
+
+/// The commands and parsers of the shell install, as pure functions.
+enum ShellInstall {
+ static let appName = "DmShell.app"
+ static let scheme = "DmShell"
+ static let projectName = "DmShell.xcodeproj"
+
+ static func projectFolder(root: String) -> String { root + "/project" }
+ static func derivedData(root: String) -> String { root + "/derived-data" }
+ static func appPath(root: String) -> String { derivedData(root: root) + "/Build/Products/Release-iphoneos/" + appName }
+
+ /// 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"
+ }
+
+ /// The part of the build script's argument list that makes the game's framework instead of an Xcode project.
+ static func buildArguments(workDir: String, team: String) -> [String] {
+ ["--shell-framework", workDir + "/shell-framework", "--team-id", team]
+ }
+
+ // ---- 4: the project ----
+
+ static func projectCommand(repo: String) -> [String] {
+ ["/bin/bash", repo + "/dm/ios/tools/build_shell.sh", "--prepare-xcode"]
+ }
+
+ /// What build_shell.sh reads. `path` is the build's own tool PATH (xcodegen must be found on it).
+ static func projectEnvironment(root: String, frameworks: [String], bundleID: String, team: String, python: String,
+ path: String, home: String, user: String, tmp: String? = nil) -> [String: String] {
+ var env = ["SHELL_DIR": projectFolder(root: root),
+ "DM_SHELL_FRAMEWORKS": frameworks.joined(separator: "\n"),
+ "DM_BUNDLE_ID": bundleID,
+ "DM_TEAM_ID": team,
+ "DM_XCODE_DERIVED_DATA": derivedData(root: root),
+ "FONT_PY": python,
+ "PATH": path, "HOME": home, "USER": user, "LANG": "en_US.UTF-8"]
+ if let tmp { env["TMPDIR"] = tmp }
+ return env
+ }
+
+ // ---- 5 and 6: sign, build, install ----
+
+ /// `bundleID` goes in as PRODUCT_BUNDLE_IDENTIFIER every time: the identifier stored in shell.json is the one the device's
+ /// copy of the app has, and installing under another would start an app with empty Documents.
+ static func buildCommand(xcrun: String, root: String, device: String, team: String, bundleID: String) -> [String] {
+ [xcrun, "xcodebuild", "-project", projectFolder(root: root) + "/" + projectName, "-scheme", scheme,
+ "-configuration", "Release", "-destination", "id=\(device)", "-derivedDataPath", derivedData(root: root),
+ "-allowProvisioningUpdates", "DEVELOPMENT_TEAM=\(team)", "PRODUCT_BUNDLE_IDENTIFIER=\(bundleID)", "build"]
+ }
+
+ /// Installing over the existing app keeps its Documents.
+ static func installCommand(xcrun: String, device: String, app: String) -> [String] {
+ [xcrun, "devicectl", "device", "install", "app", "--device", device, app]
+ }
+
+ // ---- 7: the game data ----
+
+ static func gameFolder(titleID: String) -> String { "Documents/games/\(titleID)" }
+
+ /// Kept free beyond the data on the device (the game's saves, shader caches, the system).
+ static let freeSpaceMargin: Int64 = 2_000_000_000
+
+ /// The shell's own log from the device (Documents/shell-log.txt, written at every start).
+ static func shellLogCommand(xcrun: String, device: String, bundleID: String, destination: String) -> [String] {
+ [xcrun, "devicectl", "device", "copy", "from", "--device", device, "--domain-type", "appDataContainer",
+ "--domain-identifier", bundleID, "--source", "Documents/shell-log.txt", "--destination", destination]
+ }
+
+ /// The last "shell: free space <bytes> bytes" line of the shell's log, nil without one.
+ static func freeSpace(inShellLog text: String?) -> Int64? {
+ guard let text else { return nil }
+ return text.split(separator: "\n").reversed().lazy.compactMap { line -> Int64? in
+ guard line.hasPrefix("shell: free space ") else { return nil }
+ return Int64(line.dropFirst("shell: free space ".count).split(separator: " ").first ?? "")
+ }.first.flatMap { $0 >= 0 ? $0 : nil }
+ }
+
+ /// xcodebuild's words when the provisioning profile lacks the Increased Memory Limit the shell asks for.
+ static func memoryCapabilityMissing(_ output: String) -> Bool {
+ output.contains("doesn't include the Increased Memory Limit capability") || output.contains("doesn't include the com.apple.developer.kernel.increased-memory-limit entitlement")
+ }
+
+ /// Copies the game's banner into its framework as banner.<ext>, the picture the shell's library shows: the player's own pick,
+ /// else the eShop banner the launcher caches per title ID (ArtworkStore). The cache is only read. Without either, an older
+ /// banner is removed and the library shows the framework's icon.png. Returns the picture used.
+ @discardableResult static func placeBanner(titleID: String, framework: String, banners: URL, picked: String?,
+ fm: FileManager = .default) -> String? {
+ let source = [picked, ArtworkStore.cachedBanner(titleID, in: banners)?.path].compactMap { $0 }.first { !$0.isEmpty && fm.fileExists(atPath: $0) }
+ for ext in ["png", "jpg", "jpeg", "heic", "webp"] { try? fm.removeItem(atPath: framework + "/banner." + ext) }
+ guard let source else { return nil }
+ let ext = (source as NSString).pathExtension.lowercased()
+ let dest = framework + "/banner." + (["png", "jpg", "jpeg", "heic", "webp"].contains(ext) ? ext : "jpg")
+ return (try? fm.copyItem(atPath: source, toPath: dest)) != nil ? source : nil
+ }
+
+ /// devicectl's recursive listing of the game's folder in the app's container, written as JSON to `json`.
+ static func listCommand(xcrun: String, device: String, bundleID: String, titleID: String, json: String) -> [String] {
+ [xcrun, "devicectl", "device", "info", "files", "--device", device, "--domain-type", "appDataContainer",
+ "--domain-identifier", bundleID, "--subdirectory", gameFolder(titleID: titleID), "--json-output", json]
+ }
+
+ /// One file into the game's folder. A file destination creates the parent folders and names the file. Never
+ /// `--remove-existing-content true`: on a real device it deletes the destination's siblings too (#266).
+ static func copyCommand(xcrun: String, device: String, bundleID: String, titleID: String, source: String, relativePath: String) -> [String] {
+ [xcrun, "devicectl", "device", "copy", "to", "--device", device, "--source", source,
+ "--destination", gameFolder(titleID: titleID) + "/" + relativePath,
+ "--domain-type", "appDataContainer", "--domain-identifier", bundleID]
+ }
+
+ /// The device's files (path relative to the game's folder → size) from the listing JSON. The error JSON of a folder that does
+ /// not exist (or an app that is new) and anything unreadable mean "nothing on the device": an empty list.
+ static func parseListing(_ data: Data?) -> [String: Int64] {
+ guard let data, let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let files = (root["result"] as? [String: Any])?["files"] as? [[String: Any]] else { return [:] }
+ var found: [String: Int64] = [:]
+ for file in files {
+ if (file["resources"] as? [String: Any])?["isDirectory"] as? Bool == true { continue }
+ guard let path = (file["relativePath"] as? String) ?? (file["name"] as? String),
+ let size = (file["metadata"] as? [String: Any])?["size"] as? NSNumber else { continue }
+ found[path] = size.int64Value
+ }
+ return found
+ }
+
+ /// The archive folder's files (relative path → size), without dot files (.packstamp) and without folders.
+ static func localFiles(in archive: String) -> [String: Int64] {
+ let fm = FileManager.default
+ var found: [String: Int64] = [:]
+ for case let path as String in fm.enumerator(atPath: archive) ?? FileManager.DirectoryEnumerator() {
+ if path.split(separator: "/").contains(where: { $0.hasPrefix(".") }) { continue }
+ var isDirectory: ObjCBool = false
+ guard fm.fileExists(atPath: archive + "/" + path, isDirectory: &isDirectory), !isDirectory.boolValue,
+ let size = (try? fm.attributesOfItem(atPath: archive + "/" + path))?[.size] as? NSNumber else { continue }
+ found[path] = size.int64Value
+ }
+ return found
+ }
+
+ /// The local files to copy: missing on the device, or of another size. Sorted, so the copies run in a stable order.
+ /// Path and size only: a file with the same size and other content stays. A hash comparison (a manifest the device keeps next to
+ /// the game's folder) can close that gap later.
+ static func filesToCopy(local: [String: Int64], device: [String: Int64]) -> [String] {
+ local.filter { device[$0.key] != $0.value }.map(\.key).sorted()
+ }
+
+ /// The reason the build_shell.sh run failed, for the player: its last `[RED]` line (the refusals, for example two different
+ /// games in one shell), else its last `FAIL:` line, else the last line it printed.
+ static func scriptFailure(_ output: String) -> String? {
+ let lines = output.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
+ if let red = lines.last(where: { $0.contains("[RED]") }), let r = red.range(of: "[RED]") {
+ return String(red[r.upperBound...]).trimmingCharacters(in: .whitespaces)
+ }
+ if let fail = lines.last(where: { $0.contains("FAIL:") }), let r = fail.range(of: "FAIL:") {
+ return String(fail[r.upperBound...]).trimmingCharacters(in: .whitespaces)
+ }
+ return lines.last
+ }
+
+ // ---- the connection of the copy ----
+
+ /// How the device is connected to this Mac, from `devicectl list devices` (connectionProperties.transportType: "wired" for a
+ /// cable, "localNetwork" for Wi-Fi, absent when the device is not reachable). A device the list does not show, or shows
+ /// unpaired, was never paired with this Mac.
+ enum Connection: Equatable {
+ case wired, network, other, notConnected, notPaired
+ }
+
+ static func connection(of udid: String, in devices: [AppleDevice]) -> Connection {
+ guard let device = devices.first(where: { $0.id == udid }) else { return .notPaired }
+ if device.wired { return .wired }
+ if device.overNetwork { return .network }
+ return device.reachable ? .other : .notConnected
+ }
+
+ /// Minutes a copy of `bytes` takes over Wi-Fi, as a range: devicectl over the local network does about 17 to 25 MB/s, so
+ /// 15 GB is 10 to 15 minutes. At least one minute.
+ static func wifiEstimate(bytes: Int64) -> (low: Int, high: Int) {
+ let low = max(1, Int((Double(bytes) / 25e6 / 60).rounded()))
+ return (low, max(low, Int((Double(bytes) / 17e6 / 60).rounded())))
+ }
+
+ static func sizeText(_ bytes: Int64) -> String {
+ // Decimal units as devicectl and the Finder count, and the same text in every locale
+ if bytes >= 1_000_000_000 { return String(format: "%.1f GB", Double(bytes) / 1e9) }
+ if bytes >= 1_000_000 { return String(format: "%.0f MB", Double(bytes) / 1e6) }
+ return String(format: "%.0f KB", (Double(bytes) / 1e3).rounded(.up))
+ }
+
+ /// An installed app's shell paths, from its own path (<root>/derived-data/Build/Products/Release-iphoneos/DmShell.app), nil for
+ /// any other app. A re-sign runs on that project and derived data.
+ static func paths(ofApp app: String) -> (root: String, project: String, derived: String)? {
+ guard (app as NSString).lastPathComponent == appName, let marker = app.range(of: "/Build/Products/") else { return nil }
+ let derived = String(app[..<marker.lowerBound])
+ guard (derived as NSString).lastPathComponent == "derived-data" else { return nil }
+ let root = (derived as NSString).deletingLastPathComponent
+ return (root, projectFolder(root: root) + "/" + projectName, derived)
+ }
+}
+
+/// What the player is told before the game data goes over: how much, and over which connection. The GUI shows it with its
+/// buttons, the terminal prints it and copies.
+struct ShellCopyPlan: Equatable {
+ var files: Int
+ var bytes: Int64
+ var connection: ShellInstall.Connection
+ var deviceName: String
+ /// "15 GB in 2 files."
+ var sizeText: String
+ /// The cable note, or the Wi-Fi hint with its estimate.
+ var connectionText: String
+ /// Whether waiting for a cable is offered (the device is on Wi-Fi, or not connected).
+ var canWaitForCable: Bool { connection == .network || connection == .notConnected }
+}
+
+enum ShellCopyDecision: Equatable { case copy, skip, waitForCable }
+
+/// One stage of the install, as the model and the terminal show it.
+struct ShellStage {
+ var id: Int
+ var name: String
+ var state: StepState
+ var detail = ""
+ var percent: Double? = nil
+}
+
+/// Steps 3 to 7: the shell's library, its project, signing, the install and the game data, blocking. A tool that fails ends the
+/// install with its own last error line.
+struct ShellInstaller {
+ var xcrun = "/usr/bin/xcrun"
+ var repo: String
+ var python: String
+ var root: String
+ var device: String
+ var team: String
+ var deviceName = "iPhone"
+ var lang: Lang = .en
+ /// Run tools in a process group of their own (the model's Stop ends the group). The terminal does not need it.
+ var ownGroup = false
+ var toolPath = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
+ var log: (String) -> Void = { _ in }
+ var stage: (ShellStage) -> Void = { _ in }
+ var processStarted: (Process) -> Void = { _ in }
+ var processEnded: (Process) -> Void = { _ in }
+ /// Asked once, only when something must be copied, with the size and the connection. The terminal answers `.copy`.
+ var decideCopy: (ShellCopyPlan) -> ShellCopyDecision = { _ in .copy }
+ /// While waiting for a cable: told true when the wait starts and false when it ends, and asked between polls whether the
+ /// player cancelled.
+ var waiting: (Bool) -> Void = { _ in }
+ var waitCancelled: () -> Bool = { false }
+ /// Seconds between two looks at `devicectl list devices` while waiting for a cable.
+ var pollInterval: TimeInterval = 4
+ /// Where the eShop banners are cached (ArtworkStore), read only: the game's goes into its framework for the shell's library.
+ var banners: URL = ArtworkStore.shared.directory
+ /// A picture the player chose for the game in the library, which wins over the cached banner (nil: none).
+ var pickedArtwork: String? = nil
+
+ struct Outcome {
+ var ok: Bool
+ var message: String
+ var step: BuildFailureClassifier.InstallStep? = nil // the failed device step, for the failure card
+ var appPath = ""
+ var bundleID = ""
+ var copied = 0
+ var copySkipped = false
+ /// The card the launcher shows for the failure, when it has words for it.
+ var failure: BuildFailureKind? = nil
+ /// Signed without the Increased Memory Limit, because the team's profile cannot carry it yet.
+ var noMemoryCapability = false
+ }
+
+ static let projectStageID = 1010, signStageID = 1001, installStageID = 1002, copyStageID = 1003, checkStageID = 1011
+
+ private func t(_ key: String) -> String { L10n.string(key, lang) }
+ private func fmt(_ key: String, _ args: CVarArg...) -> String { String(format: t(key), arguments: args) }
+
+ private struct ToolResult { var status: Int32; var output: String; var lastError: String? }
+
+ func install(framework: String, titleID: String, name: String, archive: String) -> Outcome {
+ guard FileManager.default.fileExists(atPath: framework) else {
+ return Outcome(ok: false, message: fmt("shell.noFramework", framework))
+ }
+ // A device this Mac never paired is found out now, not after the signing: nothing is built for it
+ if let refused = pairingRefusal() { return refused }
+ // The 16:9 banner of the shell's library (ShellHost reads <framework>/banner.<ext>, the square icon.png is the fallback)
+ if let banner = ShellInstall.placeBanner(titleID: titleID, framework: framework, banners: banners, picked: pickedArtwork) {
+ log("banner: \(banner)\n")
+ }
+ // 3: the library
+ var library = ShellLibrary.load(root: root)
+ library.team = team
+ library.add(.init(titleID: titleID, name: name, framework: framework))
+ library.dropMissing()
+ do { try library.save(root: root) } catch {
+ return Outcome(ok: false, message: fmt("shell.projectFailed", error.localizedDescription))
+ }
+
+ // 4: the project
+ var env = ShellInstall.projectEnvironment(root: root, frameworks: library.games.map(\.framework), bundleID: library.bundleID,
+ team: team, python: python, path: toolPath, home: NSHomeDirectory(), user: NSUserName(),
+ tmp: NSTemporaryDirectory())
+ env.merge(BundledTools.environment(for: python)) { $1 }
+ let projectName = t("shell.projectStage")
+ begin(Self.projectStageID, projectName)
+ let project = run(ShellInstall.projectCommand(repo: repo), env: env, label: projectName, step: { _ in nil })
+ if project.status != 0 {
+ let why = ShellInstall.scriptFailure(project.output) ?? fmt("msg.exitCode", project.status)
+ end(Self.projectStageID, projectName, ok: false, detail: why)
+ return Outcome(ok: false, message: fmt("shell.projectFailed", why))
+ }
+ end(Self.projectStageID, projectName, ok: true)
+
+ // 5: sign and build, with one retry under this team's own identifier
+ let signName = fmt("dev.signStage", deviceName)
+ func sign(_ bundleID: String) -> ToolResult {
+ begin(Self.signStageID, signName)
+ return run(ShellInstall.buildCommand(xcrun: xcrun, root: root, device: device, team: team, bundleID: bundleID),
+ env: nil, label: signName, step: BuildModel.xcodeStep)
+ }
+ var bundleID = library.bundleID
+ var built = sign(bundleID)
+ let variant = ShellLibrary.teamVariant(team: team)
+ if built.status != 0, BuildFailureClassifier.signingTeamTaken(built.output), bundleID != variant {
+ log("signing: \(bundleID) is registered to another team, retrying as \(variant)\n")
+ bundleID = variant
+ built = sign(bundleID)
+ if built.status == 0 {
+ library.bundleID = variant
+ try? library.save(root: root)
+ }
+ }
+ // A team whose profiles cannot carry the Increased Memory Limit (a free Apple ID, or a paid one whose holder has not yet
+ // accepted the current Program License Agreement, so Xcode cannot add the capability) fails here. The shell is generated
+ // again without the request and signed with what the team has: it installs and runs, and the log says that a large game may
+ // run out of memory until the capability can be added (the next install asks for it again).
+ var noMemoryCapability = false
+ if built.status != 0, ShellInstall.memoryCapabilityMissing(built.output) {
+ log("signing: the team's provisioning profile cannot carry the Increased Memory Limit capability; signing without it (a large game may run out of memory)\n")
+ var plain = env; plain["DM_ENTITLEMENTS"] = ""
+ let again = run(ShellInstall.projectCommand(repo: repo), env: plain, label: projectName, step: { _ in nil })
+ if again.status == 0 { noMemoryCapability = true; built = sign(bundleID) }
+ }
+ if built.status != 0 {
+ let why = built.lastError ?? fmt("msg.exitCode", built.status)
+ end(Self.signStageID, signName, ok: false, detail: why)
+ return Outcome(ok: false, message: fmt("dev.signFailed", why), step: .sign)
+ }
+ end(Self.signStageID, signName, ok: true)
+
+ // 6: install over the existing app, which keeps its Documents
+ let app = ShellInstall.appPath(root: root)
+ guard FileManager.default.fileExists(atPath: app) else {
+ return Outcome(ok: false, message: fmt("dev.noProject", app), step: .install)
+ }
+ let installName = fmt("dev.installStage", deviceName)
+ begin(Self.installStageID, installName)
+ let installed = run(ShellInstall.installCommand(xcrun: xcrun, device: device, app: app), env: nil, label: installName, step: BuildModel.installStep)
+ if installed.status != 0 {
+ let why = installed.lastError ?? fmt("msg.exitCode", installed.status)
+ end(Self.installStageID, installName, ok: false, detail: why)
+ return Outcome(ok: false, message: fmt("dev.installFailed", why), step: .install)
+ }
+ end(Self.installStageID, installName, ok: true)
+
+ // 7: the game data, only what the device does not have yet
+ var outcome = Outcome(ok: true, message: fmt("dev.installed", deviceName), appPath: app, bundleID: bundleID)
+ outcome.noMemoryCapability = noMemoryCapability
+ return copyGameData(titleID: titleID, archive: archive, app: app, bundleID: bundleID, outcome: outcome)
+ }
+
+ /// Step 7 on its own, for a Retry after a copy that failed midway: the listing, the diff and the copy, nothing else. The app
+ /// is on the device already, under the identifier shell.json holds.
+ func installData(titleID: String, archive: String) -> Outcome {
+ if let refused = pairingRefusal() { return refused }
+ let bundleID = ShellLibrary.load(root: root).bundleID, app = ShellInstall.appPath(root: root)
+ return copyGameData(titleID: titleID, archive: archive, app: app, bundleID: bundleID,
+ outcome: Outcome(ok: true, message: fmt("dev.installed", deviceName), appPath: app, bundleID: bundleID))
+ }
+
+ /// The pairing steps as a failure when this Mac does not know the device, else nil.
+ private func pairingRefusal() -> Outcome? {
+ guard connection() == .notPaired else { return nil }
+ return Outcome(ok: false, message: fmt("shell.notPaired", deviceName), failure: .devicePairing)
+ }
+
+ private func connection() -> ShellInstall.Connection {
+ ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20))
+ }
+
+ private func copyGameData(titleID: String, archive: String, app: String, bundleID: String, outcome start: Outcome) -> Outcome {
+ var outcome = start
+ let checkName = fmt("shell.checkStage", deviceName)
+ begin(Self.checkStageID, checkName)
+ let listing = NSTemporaryDirectory() + "nspb-shell-files-\(UUID().uuidString.prefix(8)).json"
+ defer { try? FileManager.default.removeItem(atPath: listing) }
+ // A folder that does not exist yet makes devicectl exit non-zero with an error JSON: nothing on the device, not a failure
+ _ = run(ShellInstall.listCommand(xcrun: xcrun, device: device, bundleID: bundleID, titleID: titleID, json: listing),
+ env: nil, label: checkName, step: { _ in nil })
+ let onDevice = ShellInstall.parseListing(FileManager.default.contents(atPath: listing))
+ let local = ShellInstall.localFiles(in: archive)
+ let missing = ShellInstall.filesToCopy(local: local, device: onDevice)
+ end(Self.checkStageID, checkName, ok: true)
+ guard !missing.isEmpty else {
+ outcome.message = fmt("shell.dataAlready", deviceName)
+ return outcome
+ }
+ // Free space first: the shell writes it to its log at every start (ShellMain.m), and a game's data is many GB. Without a log
+ // (a shell never opened yet) the copy goes ahead and devicectl reports a full device itself.
+ let needed = missing.reduce(Int64(0)) { $0 + (local[$1] ?? 0) }
+ let logCopy = NSTemporaryDirectory() + "nspb-shell-log-\(UUID().uuidString.prefix(8)).txt"
+ defer { try? FileManager.default.removeItem(atPath: logCopy) }
+ _ = run(ShellInstall.shellLogCommand(xcrun: xcrun, device: device, bundleID: bundleID, destination: logCopy), env: nil, label: checkName, step: { _ in nil })
+ if let free = ShellInstall.freeSpace(inShellLog: try? String(contentsOfFile: logCopy, encoding: .utf8)) {
+ log("device free space: \(free) bytes, the game data to copy: \(needed) bytes\n")
+ if needed + ShellInstall.freeSpaceMargin > free {
+ return Outcome(ok: false, message: fmt("shell.noSpace", deviceName, Double(needed) / 1e9, Double(free) / 1e9), appPath: app, bundleID: bundleID)
+ }
+ }
+ // The size and the connection first: a cable needs the device unlocked, Wi-Fi takes long enough that a cable may be worth it
+ var link = connection()
+ var plan = copyPlan(files: missing.count, bytes: needed, connection: link)
+ log(plan.sizeText + "\n" + plan.connectionText + "\n")
+ var decision = decideCopy(plan)
+ if decision == .waitForCable {
+ log(fmt("shell.copyWaiting", deviceName) + "\n")
+ waiting(true)
+ while !waitCancelled() {
+ Thread.sleep(forTimeInterval: pollInterval)
+ link = connection()
+ if link == .wired { break }
+ }
+ waiting(false)
+ decision = link == .wired && !waitCancelled() ? .copy : .skip
+ }
+ guard decision == .copy else {
+ outcome.copySkipped = true
+ outcome.message = fmt("dev.copySkipped", deviceName)
+ return outcome
+ }
+ let copyName = fmt("dev.copyStage", deviceName)
+ begin(Self.copyStageID, copyName)
+ for (i, path) in missing.enumerated() {
+ stage(ShellStage(id: Self.copyStageID, name: copyName, state: .running, detail: "\(i + 1)/\(missing.count)",
+ percent: Double(i) / Double(missing.count) * 100))
+ let r = run(ShellInstall.copyCommand(xcrun: xcrun, device: device, bundleID: bundleID, titleID: titleID,
+ source: archive + "/" + path, relativePath: path),
+ env: nil, label: copyName, step: BuildModel.installStep)
+ if r.status != 0 {
+ let why = r.lastError ?? fmt("msg.exitCode", r.status)
+ end(Self.copyStageID, copyName, ok: false, detail: why)
+ // The file that failed may be on the device in part. The next listing sees its size is not the local one and copies it
+ // again, so a Retry finishes the data. Nothing here marks the game as ready.
+ return Outcome(ok: false, message: fmt("shell.copyIncomplete", deviceName, why), appPath: app, bundleID: bundleID, copied: i,
+ failure: .shellDataIncomplete)
+ }
+ outcome.copied = i + 1
+ }
+ end(Self.copyStageID, copyName, ok: true)
+ return outcome
+ }
+
+ private func copyPlan(files: Int, bytes: Int64, connection: ShellInstall.Connection) -> ShellCopyPlan {
+ let connectionText: String
+ switch connection {
+ case .network:
+ let e = ShellInstall.wifiEstimate(bytes: bytes)
+ let size = ShellInstall.sizeText(bytes)
+ connectionText = e.high == 1 ? fmt("shell.copyWifiMinute", size)
+ : e.low == e.high ? fmt("shell.copyWifiOne", size, e.low) : fmt("shell.copyWifi", size, e.low, e.high)
+ case .notConnected, .notPaired: connectionText = fmt("shell.copyNotConnected", deviceName)
+ case .wired, .other: connectionText = fmt("shell.copyWired", deviceName)
+ }
+ return ShellCopyPlan(files: files, bytes: bytes, connection: connection, deviceName: deviceName,
+ sizeText: fmt("shell.copySize", ShellInstall.sizeText(bytes), files), connectionText: connectionText)
+ }
+
+ private func begin(_ id: Int, _ name: String) { stage(ShellStage(id: id, name: name, state: .running)) }
+ private func end(_ id: Int, _ name: String, ok: Bool, detail: String = "") {
+ stage(ShellStage(id: id, name: name, state: ok ? .done : .failed, detail: detail, percent: ok ? 100 : nil))
+ }
+
+ /// One tool, blocking: its output lines go to `log`, the last error line is kept. `env` nil is the plain tool environment of the
+ /// per-game install (xcodebuild, devicectl).
+ private func run(_ command: [String], env: [String: String]?, label: String,
+ step: (String) -> (detail: String, percent: Double?)?) -> ToolResult {
+ log("[\(label)] \(command.joined(separator: " "))\n")
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: command[0])
+ p.arguments = Array(command.dropFirst())
+ p.environment = env ?? ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": NSHomeDirectory(), "USER": NSUserName(), "LANG": "en_US.UTF-8"]
+ p.standardInput = FileHandle.nullDevice
+ if ownGroup { BuildModel.inOwnGroup(p, python: python) }
+ let pipe = Pipe(); p.standardOutput = pipe; p.standardError = pipe
+ do { try p.run() } catch { return ToolResult(status: 127, output: error.localizedDescription, lastError: error.localizedDescription) }
+ processStarted(p)
+ var output = "", pending = "", lastError: String?
+ func consume(_ line: String) {
+ log(line + "\n")
+ output += line + "\n"
+ if line.contains("error:") || line.hasPrefix("ERROR:") { lastError = line.trimmingCharacters(in: .whitespaces) }
+ }
+ let handle = pipe.fileHandleForReading
+ while true {
+ let data = handle.availableData
+ if data.isEmpty { break }
+ pending += String(decoding: data, as: UTF8.self)
+ while let nl = pending.firstIndex(of: "\n") {
+ consume(String(pending[..<nl]))
+ pending = String(pending[pending.index(after: nl)...])
+ }
+ }
+ if !pending.isEmpty { consume(pending) }
+ p.waitUntilExit()
+ processEnded(p)
+ return ToolResult(status: p.terminationStatus, output: output, lastError: lastError)
+ }
+}
+
+/// `NSPortBuilder --install-shell ...`: steps 3 to 7 without a window and without questions, for a terminal or a script.
+enum ShellCLI {
+ static let usage = "NSPortBuilder --install-shell --framework <path> --archive <games/TITLEID folder> --title-id <id> --name <name> "
+ + "--device <udid> --team <team> --repo <repo> [--shell-root <dir>] [--python <path>]"
+
+ /// The options as a dictionary, nil when an option has no value.
+ static func parse(_ args: [String]) -> [String: String]? {
+ var options: [String: String] = [:]
+ var i = 0
+ while i < args.count {
+ let a = args[i]
+ if a == "--install-shell" { i += 1; continue }
+ guard a.hasPrefix("--"), i + 1 < args.count else { return nil }
+ options[String(a.dropFirst(2))] = args[i + 1]
+ i += 2
+ }
+ return options
+ }
+
+ /// Exit status: 0 installed, 1 failed (or wrong usage). `out` gets every line, stage lines and tool output alike.
+ /// `--xcrun` is for the tests, which stand in for xcodebuild and devicectl.
+ static func run(_ args: [String], defaults: UserDefaults = .standard, out: @escaping (String) -> Void = { fputs($0, stdout); fflush(stdout) }) -> Int32 {
+ let required = ["framework", "archive", "title-id", "name", "device", "team", "repo"]
+ guard let o = parse(args), required.allSatisfy({ !(o[$0] ?? "").isEmpty }) else {
+ out("usage: " + usage + "\n")
+ return 1
+ }
+ let archive = o["archive"]!
+ let root = o["shell-root"] ?? ShellLibrary.resolveRoot(
+ defaults: defaults, parent: ((archive as NSString).deletingLastPathComponent as NSString).deletingLastPathComponent)
+ let python = o["python"] ?? BuildModel.findPython().path
+ var installer = ShellInstaller(xcrun: o["xcrun"] ?? "/usr/bin/xcrun", repo: o["repo"]!, python: python, root: root,
+ device: o["device"]!, team: o["team"]!)
+ installer.deviceName = o["device"]!
+ installer.toolPath = BuildModel.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: python)
+ installer.log = out
+ installer.stage = { s in
+ switch s.state {
+ case .running: if s.detail.isEmpty { out("==> \(s.name)\n") }
+ case .done: out("==> \(s.name): done\n")
+ case .failed: out("==> \(s.name): FAILED \(s.detail)\n")
+ case .pending: break
+ }
+ }
+ let result = installer.install(framework: o["framework"]!, titleID: o["title-id"]!, name: o["name"]!, archive: archive)
+ out((result.ok ? "OK: " : "FAIL: ") + result.message + "\n")
+ return result.ok ? 0 : 1
+ }
+}
diff --git a/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift b/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift
index 2204aa89..be5ab7ab 100644
--- a/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift
@@ -37,7 +37,7 @@ final class BuildFailureTests: XCTestCase {
}
/// The rows that no log line sets: the launcher's own state (a drive, a team) or the step that failed (the install).
- static let stateKinds: Set<BuildFailureKind> = [.driveMissing, .teamTaken, .noSigningAccount, .deviceTransfer, .engineOffline, .engineSync]
+ static let stateKinds: Set<BuildFailureKind> = [.driveMissing, .teamTaken, .noSigningAccount, .deviceTransfer, .devicePairing, .shellDataIncomplete, .engineOffline, .engineSync]
/// A bump of the pin or a patch that rewords a message must fail here, not turn a hint into the raw last line.
func testTheEnginesScriptsStillSayWhatThePatternsExpect() throws {
diff --git a/frontend/Tests/NSPortBuilderTests/ShellInstallTests.swift b/frontend/Tests/NSPortBuilderTests/ShellInstallTests.swift
new file mode 100644
index 00000000..2de3dbff
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/ShellInstallTests.swift
@@ -0,0 +1,776 @@
+import XCTest
+import Combine
+@testable import NSPortBuilder
+
+/// Route C: one app on the device for several games. The commands and parsers are checked as pure functions, and the whole path
+/// after the build runs headless against a stand-in `xcrun` that models devicectl on a folder (a fake device container): an install
+/// keeps the container, a copy to a file creates the parents, and `--remove-existing-content true` wipes the destination's siblings,
+/// as it does on a real device. No test reaches a device or a real game.
+final class ShellInstallTests: XCTestCase {
+ private var temporary: URL!
+ private let fm = FileManager.default
+ private let titleID = "0100535012974000"
+ private let device = "00008150-AAAA"
+ private let team = "TEAM123456"
+
+ override func setUpWithError() throws {
+ temporary = fm.temporaryDirectory.appendingPathComponent("nspb-shell-" + UUID().uuidString)
+ try fm.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws { try fm.removeItem(at: temporary) }
+
+ private func path(_ parts: String...) -> String { parts.reduce(temporary.path) { $0 + "/" + $1 } }
+ private func write(_ file: String, _ text: String) throws {
+ try fm.createDirectory(atPath: (file as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
+ try text.write(toFile: file, atomically: true, encoding: .utf8)
+ }
+
+ // ---- the state file ----
+
+ func testLibraryCreateAddReplaceDropAndKeepBundleID() throws {
+ let root = path("shell")
+ XCTAssertEqual(ShellLibrary.load(root: root), ShellLibrary()) // no file yet
+ var library = ShellLibrary.load(root: root)
+ XCTAssertEqual(library.bundleID, "org.nxnative.shell")
+ let one = path("one.framework"), two = path("two.framework"), gone = path("gone.framework")
+ for f in [one, two] { try fm.createDirectory(atPath: f, withIntermediateDirectories: true) }
+ library.team = team
+ library.add(.init(titleID: "A", name: "One", framework: one))
+ library.add(.init(titleID: "B", name: "Two", framework: two))
+ library.add(.init(titleID: "C", name: "Gone", framework: gone))
+ library.bundleID = "org.nxnative.shell." + team
+ try library.save(root: root)
+ XCTAssertEqual(ShellLibrary.load(root: root), library)
+
+ var again = ShellLibrary.load(root: root)
+ again.add(.init(titleID: "A", name: "One again", framework: two)) // the same title ID replaces
+ XCTAssertEqual(again.games.count, 3)
+ XCTAssertEqual(again.games.first?.name, "One again")
+ again.dropMissing()
+ XCTAssertEqual(again.games.map(\.titleID), ["A", "B"])
+ try again.save(root: root)
+ XCTAssertEqual(ShellLibrary.load(root: root).bundleID, "org.nxnative.shell." + team) // the bundle ID stays
+ let json = try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: root + "/shell.json"))) as? [String: Any]
+ XCTAssertEqual(Set(json?.keys.map { $0 } ?? []), ["bundleID", "team", "games"])
+ }
+
+ func testShellRootIsDerivedOnceAndKept() throws {
+ let defaults = UserDefaults(suiteName: "nspb-shell-" + UUID().uuidString)!
+ XCTAssertEqual(ShellLibrary.resolveRoot(defaults: defaults, parent: "/Volumes/A"), "/Volumes/A/NX2Apple-shell")
+ XCTAssertEqual(ShellLibrary.resolveRoot(defaults: defaults, parent: "/Volumes/B"), "/Volumes/A/NX2Apple-shell")
+ }
+
+ // ---- the commands ----
+
+ func testCommandsAreExact() {
+ let root = "/R/NX2Apple-shell"
+ XCTAssertEqual(ShellInstall.buildArguments(workDir: "/W", team: "T"), ["--shell-framework", "/W/shell-framework", "--team-id", "T"])
+ XCTAssertEqual(ShellInstall.frameworkPath(workDir: "/W", titleID: "01"), "/W/shell-framework/DmGame01.framework")
+ XCTAssertEqual(ShellInstall.projectCommand(repo: "/repo"), ["/bin/bash", "/repo/dm/ios/tools/build_shell.sh", "--prepare-xcode"])
+ let env = ShellInstall.projectEnvironment(root: root, frameworks: ["/f/a", "/f/b"], bundleID: "org.nxnative.shell", team: "T",
+ python: "/py", path: "/opt/homebrew/bin:/usr/bin", home: "/h", user: "u")
+ XCTAssertEqual(env, ["SHELL_DIR": root + "/project", "DM_SHELL_FRAMEWORKS": "/f/a\n/f/b", "DM_BUNDLE_ID": "org.nxnative.shell",
+ "DM_TEAM_ID": "T", "DM_XCODE_DERIVED_DATA": root + "/derived-data", "FONT_PY": "/py",
+ "PATH": "/opt/homebrew/bin:/usr/bin", "HOME": "/h", "USER": "u", "LANG": "en_US.UTF-8"])
+ let build = ["/x", "xcodebuild", "-project", root + "/project/DmShell.xcodeproj", "-scheme", "DmShell", "-configuration", "Release",
+ "-destination", "id=D", "-derivedDataPath", root + "/derived-data", "-allowProvisioningUpdates", "DEVELOPMENT_TEAM=T"]
+ XCTAssertEqual(ShellInstall.buildCommand(xcrun: "/x", root: root, device: "D", team: "T", bundleID: "org.nxnative.shell"),
+ build + ["PRODUCT_BUNDLE_IDENTIFIER=org.nxnative.shell", "build"])
+ XCTAssertEqual(ShellInstall.buildCommand(xcrun: "/x", root: root, device: "D", team: "T", bundleID: ShellLibrary.teamVariant(team: "T")),
+ build + ["PRODUCT_BUNDLE_IDENTIFIER=org.nxnative.shell.T", "build"])
+ XCTAssertEqual(ShellInstall.installCommand(xcrun: "/x", device: "D", app: ShellInstall.appPath(root: root)),
+ ["/x", "devicectl", "device", "install", "app", "--device", "D",
+ root + "/derived-data/Build/Products/Release-iphoneos/DmShell.app"])
+ let list = ShellInstall.listCommand(xcrun: "/x", device: "D", bundleID: "b", titleID: "01", json: "/t.json")
+ XCTAssertEqual(list, ["/x", "devicectl", "device", "info", "files", "--device", "D", "--domain-type", "appDataContainer",
+ "--domain-identifier", "b", "--subdirectory", "Documents/games/01", "--json-output", "/t.json"])
+ let copy = ShellInstall.copyCommand(xcrun: "/x", device: "D", bundleID: "b", titleID: "01", source: "/a/aoc/1.img", relativePath: "aoc/1.img")
+ XCTAssertEqual(copy, ["/x", "devicectl", "device", "copy", "to", "--device", "D", "--source", "/a/aoc/1.img",
+ "--destination", "Documents/games/01/aoc/1.img", "--domain-type", "appDataContainer", "--domain-identifier", "b"])
+ for command in [build, list, copy, ShellInstall.projectCommand(repo: "/r"), ShellInstall.installCommand(xcrun: "/x", device: "D", app: "/a")] {
+ XCTAssertFalse(command.contains("--remove-existing-content"))
+ }
+ }
+
+ func testShellAppPathsForAResign() {
+ let app = "/Volumes/NX/NX2Apple-shell/derived-data/Build/Products/Release-iphoneos/DmShell.app"
+ let paths = ShellInstall.paths(ofApp: app)
+ XCTAssertEqual(paths?.root, "/Volumes/NX/NX2Apple-shell")
+ XCTAssertEqual(paths?.project, "/Volumes/NX/NX2Apple-shell/project/DmShell.xcodeproj")
+ XCTAssertEqual(paths?.derived, "/Volumes/NX/NX2Apple-shell/derived-data")
+ XCTAssertNil(ShellInstall.paths(ofApp: "/x/0100_build/xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app"))
+ }
+
+ // ---- the listing ----
+
+ func testListingParserOnTheRealShapeAndOnTheErrorJSON() {
+ let listing = """
+ {"info": {"outcome": "success"}, "result": {"files": [
+ {"name": "aoc", "relativePath": "aoc", "metadata": {"size": 96}, "resources": {"isDirectory": true}},
+ {"name": "aoc/1.img", "relativePath": "aoc/1.img", "metadata": {"size": 4}, "resources": {"isDirectory": false}},
+ {"name": "romfs.img", "relativePath": "romfs.img", "metadata": {"size": 10000000000}, "resources": {"isDirectory": false}}]}}
+ """
+ XCTAssertEqual(ShellInstall.parseListing(Data(listing.utf8)), ["aoc/1.img": 4, "romfs.img": 10_000_000_000])
+ let failed = #"{"error": {"code": 6, "domain": "NSCocoaErrorDomain"}, "info": {"outcome": "failed"}}"#
+ XCTAssertEqual(ShellInstall.parseListing(Data(failed.utf8)), [:])
+ XCTAssertEqual(ShellInstall.parseListing(nil), [:])
+ XCTAssertEqual(ShellInstall.parseListing(Data("not json".utf8)), [:])
+ }
+
+ func testBannerGoesIntoTheFrameworkAndTheCacheStaysUntouched() throws {
+ let cache = path("artwork"), fw = path("DmGame\(titleID).framework"), picked = path("mine.png")
+ try write(cache + "/\(titleID).jpg", "jpeg")
+ try fm.createDirectory(atPath: fw, withIntermediateDirectories: true)
+ let banners = URL(fileURLWithPath: cache)
+ XCTAssertEqual(ShellInstall.placeBanner(titleID: titleID, framework: fw, banners: banners, picked: nil), cache + "/\(titleID).jpg")
+ XCTAssertEqual(try String(contentsOfFile: fw + "/banner.jpg", encoding: .utf8), "jpeg")
+ XCTAssertTrue(fm.fileExists(atPath: cache + "/\(titleID).jpg"), "the cache is only read")
+ try write(picked, "png")
+ XCTAssertEqual(ShellInstall.placeBanner(titleID: titleID, framework: fw, banners: banners, picked: picked), picked, "the player's own picture wins")
+ XCTAssertTrue(fm.fileExists(atPath: fw + "/banner.png"))
+ XCTAssertFalse(fm.fileExists(atPath: fw + "/banner.jpg"), "one banner, the older one goes")
+ XCTAssertNil(ShellInstall.placeBanner(titleID: "0100000000000000", framework: fw, banners: banners, picked: nil))
+ XCTAssertFalse(fm.fileExists(atPath: fw + "/banner.png"), "no picture: the library falls back to the icon")
+ }
+
+ func testDiffByPathAndSizeSkippingDotFiles() throws {
+ let archive = path("games", titleID)
+ try write(archive + "/romfs.img", "0123456789")
+ try write(archive + "/aoc/1.img", "abcd")
+ try write(archive + "/.packstamp", "stamp")
+ let local = ShellInstall.localFiles(in: archive)
+ XCTAssertEqual(local, ["romfs.img": 10, "aoc/1.img": 4])
+ XCTAssertEqual(ShellInstall.filesToCopy(local: local, device: [:]), ["aoc/1.img", "romfs.img"])
+ XCTAssertEqual(ShellInstall.filesToCopy(local: local, device: ["romfs.img": 10, "aoc/1.img": 4, "extra.bin": 1]), [])
+ XCTAssertEqual(ShellInstall.filesToCopy(local: local, device: ["romfs.img": 10, "aoc/1.img": 5]), ["aoc/1.img"])
+ }
+
+ func testScriptFailurePrefersTheRedLine() {
+ let out = "[12:00:00] checking\n[RED] games of different profiles in one shell: A (x), B (y)\n[12:00:01] FAIL: the frameworks in DM_SHELL_FRAMEWORKS (above)\n"
+ XCTAssertEqual(ShellInstall.scriptFailure(out), "games of different profiles in one shell: A (x), B (y)")
+ XCTAssertEqual(ShellInstall.scriptFailure("[12:00:01] FAIL: mkdir x\n"), "mkdir x")
+ XCTAssertEqual(ShellInstall.scriptFailure("boom\n"), "boom")
+ }
+
+ func testEveryLanguageHasTheShellTexts() {
+ for key in ["build.shell", "build.shellNote", "shell.projectStage", "shell.projectFailed", "shell.checkStage", "shell.dataAlready",
+ "shell.noFramework", "shell.needsDevice", "shell.copySize", "shell.copyWired", "shell.copyWifi", "shell.copyWifiOne",
+ "shell.copyWifiMinute", "shell.copyNotConnected", "shell.copyWaiting", "shell.copyTitle", "shell.copyContinue",
+ "shell.copyWaitCable", "shell.copySkip", "shell.copyStopWaiting", "shell.retry", "shell.notPaired",
+ "shell.copyIncomplete", "fail.devicePairing.what", "fail.devicePairing.next", "fail.shellDataIncomplete.what",
+ "fail.shellDataIncomplete.next"] {
+ let both = L10n.table[key]
+ XCTAssertNotNil(both, key)
+ XCTAssertNotNil(L10n.sv[key], key)
+ for text in [both?.zh, both?.en, L10n.sv[key]].compactMap({ $0 }) {
+ XCTAssertFalse(text.contains(";") || text.contains(";"), key)
+ }
+ }
+ XCTAssertEqual(L10n.string("build.shell", .en), "iPhone or iPad (one app for all games)")
+ }
+
+ // ---- the stand-ins ----
+
+ /// A fake device: `container/<bundle ID>/...` is the app data container of each app.
+ private var container: String { path("device") }
+ private var state: String { path("state") }
+
+ /// xcodebuild and devicectl as one script. `state/taken` makes the plain bundle ID "registered to another team".
+ private func makeXcrun() throws -> String {
+ try fm.createDirectory(atPath: state, withIntermediateDirectories: true)
+ let xcrun = path("xcrun")
+ try """
+ #!/usr/bin/python3
+ import sys, os, json, shutil
+ a = sys.argv[1:]
+ CONT, STATE = '\(container)', '\(state)'
+ open(STATE + '/calls.txt', 'a').write(' '.join(a) + '\\n')
+ def val(flag): return a[a.index(flag) + 1] if flag in a else None
+ if a[0] == 'xcodebuild':
+ bundle = [x.split('=', 1)[1] for x in a if x.startswith('PRODUCT_BUNDLE_IDENTIFIER=')][0]
+ if os.path.exists(STATE + '/taken') and bundle == 'org.nxnative.shell':
+ print('error: The app identifier "' + bundle + '" cannot be registered to your development team because it is not available. Change your bundle identifier to a unique string to try again.', flush=True)
+ sys.exit(65)
+ if os.path.exists(STATE + '/nomemory') and not os.path.exists(os.path.dirname(val('-project')) + '/entitlements-empty'):
+ print('error: Provisioning profile iOS Team Provisioning Profile: ' + bundle + ' doesn\\'t include the Increased Memory Limit capability.', flush=True)
+ sys.exit(65)
+ app = val('-derivedDataPath') + '/Build/Products/Release-iphoneos/DmShell.app'
+ os.makedirs(app, exist_ok=True)
+ open(app + '/bundle.txt', 'w').write(bundle)
+ print('CodeSign ' + app, flush=True)
+ elif a[:3] == ['devicectl', 'list', 'devices']:
+ n = (int(open(STATE + '/list-count').read()) if os.path.exists(STATE + '/list-count') else 0) + 1
+ open(STATE + '/list-count', 'w').write(str(n))
+ after = int(open(STATE + '/switch-after').read()) if os.path.exists(STATE + '/switch-after') else None
+ src = STATE + ('/devices-wired.json' if after is not None and n > after else '/devices.json')
+ if not os.path.exists(src): src = STATE + '/devices-default.json'
+ shutil.copyfile(src, val('--json-output'))
+ elif a[:4] == ['devicectl', 'device', 'copy', 'from']:
+ src = CONT + '/' + val('--domain-identifier') + '/' + val('--source')
+ if not os.path.exists(src):
+ print('ERROR: The file couldn\\'t be opened because there is no such file. (NSCocoaErrorDomain error 260)', flush=True)
+ sys.exit(1)
+ shutil.copyfile(src, val('--destination'))
+ elif a[:3] == ['devicectl', 'device', 'install']:
+ app = a[-1]
+ bundle = open(app + '/bundle.txt').read()
+ os.makedirs(CONT + '/' + bundle + '/Documents', exist_ok=True) # an existing container is kept as it is
+ print('45%', flush=True); print('App installed', flush=True)
+ elif a[:4] == ['devicectl', 'device', 'copy', 'to']:
+ dest = CONT + '/' + val('--domain-identifier') + '/' + val('--destination')
+ src = val('--source')
+ if val('--remove-existing-content') == 'true': # a real device deletes the destination's siblings too
+ parent = os.path.dirname(dest)
+ for e in (os.listdir(parent) if os.path.isdir(parent) else []):
+ p = parent + '/' + e
+ shutil.rmtree(p) if os.path.isdir(p) else os.remove(p)
+ if os.path.exists(STATE + '/fail-on') and dest.endswith(open(STATE + '/fail-on').read().strip()):
+ os.makedirs(os.path.dirname(dest), exist_ok=True) # a locked device: half of the file is there, then the copy stops
+ data = open(src, 'rb').read()
+ open(dest, 'wb').write(data[:len(data) // 2])
+ print('ERROR: The device is locked. (com.apple.dt.CoreDeviceError error 1)', flush=True)
+ sys.exit(1)
+ if os.path.isdir(src):
+ os.makedirs(dest, exist_ok=True)
+ shutil.copytree(src, dest, dirs_exist_ok=True) # merged into the destination
+ else:
+ os.makedirs(os.path.dirname(dest), exist_ok=True) # a file destination makes the parents and names the file
+ shutil.copyfile(src, dest)
+ print('60%', flush=True); print('Copied', flush=True)
+ elif a[:4] == ['devicectl', 'device', 'info', 'files']:
+ base = CONT + '/' + val('--domain-identifier') + '/' + val('--subdirectory')
+ out = val('--json-output')
+ if not os.path.isdir(base):
+ json.dump({'error': {'code': 6}, 'info': {'outcome': 'failed'}}, open(out, 'w'))
+ print('ERROR: The file couldn\\'t be opened because there is no such file. (NSCocoaErrorDomain error 260)', flush=True)
+ sys.exit(1)
+ files = []
+ for root, dirs, names in os.walk(base):
+ for n in dirs + names:
+ full = root + '/' + n; rel = os.path.relpath(full, base)
+ files.append({'name': rel, 'relativePath': rel, 'metadata': {'size': os.path.getsize(full)},
+ 'resources': {'isDirectory': os.path.isdir(full)}})
+ json.dump({'info': {'outcome': 'success'}, 'result': {'files': files}}, open(out, 'w'))
+ """.write(toFile: xcrun, atomically: true, encoding: .utf8)
+ try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: xcrun)
+ return xcrun
+ }
+
+ /// A checkout with a stand-in build_shell.sh: it records its environment, makes the project folder, and refuses when asked to.
+ private func makeRepo() throws -> String {
+ let repo = path("repo")
+ try write(repo + "/dm/ios/tools/build_shell.sh", """
+ #!/bin/bash
+ [ "$1" = "--prepare-xcode" ] || { echo "FAIL: no --prepare-xcode"; exit 1; }
+ if [ -f "\(state)/refuse" ]; then
+ echo "[RED] games of different profiles in one shell: A (x), B (y)"
+ echo "[12:00:01] FAIL: the frameworks in DM_SHELL_FRAMEWORKS (above)"
+ exit 1
+ fi
+ mkdir -p "$SHELL_DIR/DmShell.xcodeproj"
+ env | sort > "\(state)/shell-env.txt"
+ if [ "${DM_ENTITLEMENTS+set}" = set ] && [ -z "$DM_ENTITLEMENTS" ]; then touch "$SHELL_DIR/entitlements-empty"; else rm -f "$SHELL_DIR/entitlements-empty"; fi
+ """)
+ return repo
+ }
+
+ private struct Fixture {
+ var xcrun: String, repo: String, framework: String, archive: String, root: String
+ func args(name: String = "Test Game", extra: [String] = []) -> [String] {
+ ["--install-shell", "--framework", framework, "--archive", archive, "--title-id", "0100535012974000", "--name", name,
+ "--device", "00008150-AAAA", "--team", "TEAM123456", "--repo", repo, "--shell-root", root,
+ "--python", "/usr/bin/python3", "--xcrun", xcrun] + extra
+ }
+ }
+
+ private func makeFixture() throws -> Fixture {
+ guard fm.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("System Python is required for the process fixture") }
+ let framework = path("work/shell-framework/DmGame\(titleID).framework")
+ try write(framework + "/game.manifest.json", "{}")
+ let archive = path("out/games", titleID)
+ try write(archive + "/romfs.img", "0123456789")
+ try write(archive + "/aoc/1.img", "abcd")
+ try write(archive + "/.packstamp", "stamp")
+ let made = Fixture(xcrun: try makeXcrun(), repo: try makeRepo(), framework: framework, archive: archive, root: path("NX2Apple-shell"))
+ try writeDevices(state + "/devices-default.json", [(device, "wired")])
+ return made
+ }
+
+ /// `devicectl list devices` output in its real shape: transportType is "wired" (cable) or "localNetwork" (Wi-Fi), and absent
+ /// for a device that is not connected.
+ private func writeDevices(_ file: String, _ entries: [(udid: String, transport: String?)]) throws {
+ let list: [[String: Any]] = entries.map { e in
+ var connection: [String: Any] = ["pairingState": "paired", "tunnelState": e.transport == nil ? "unavailable" : "connected"]
+ if let t = e.transport { connection["transportType"] = t }
+ return ["hardwareProperties": ["udid": e.udid, "reality": "physical", "platform": "iOS", "marketingName": "iPhone 17 Pro"],
+ "deviceProperties": ["name": "Z", "osVersionNumber": "27.0"], "connectionProperties": connection]
+ }
+ try JSONSerialization.data(withJSONObject: ["info": ["outcome": "success"], "result": ["devices": list]]).write(to: URL(fileURLWithPath: file))
+ }
+
+ private func installer(_ f: Fixture) -> ShellInstaller {
+ var i = ShellInstaller(xcrun: f.xcrun, repo: f.repo, python: "/usr/bin/python3", root: f.root, device: device, team: team)
+ i.deviceName = "Z"
+ i.pollInterval = 0.02
+ return i
+ }
+
+ private func install(_ i: ShellInstaller, _ f: Fixture) -> ShellInstaller.Outcome {
+ i.install(framework: f.framework, titleID: titleID, name: "Test Game", archive: f.archive)
+ }
+
+ private func run(_ f: Fixture, _ extra: [String] = []) -> (status: Int32, output: String) {
+ var output = ""
+ let defaults = UserDefaults(suiteName: "nspb-shell-" + UUID().uuidString)!
+ let status = ShellCLI.run(f.args(extra: extra), defaults: defaults) { output += $0 }
+ return (status, output)
+ }
+
+ private var calls: [String] { ((try? String(contentsOfFile: state + "/calls.txt", encoding: .utf8)) ?? "").split(separator: "\n").map(String.init) }
+ private func copies() -> [String] { calls.filter { $0.hasPrefix("devicectl device copy to") } }
+
+ func testTheFakeDeviceWipesSiblingsWithRemoveExistingContent() throws {
+ let f = try makeFixture()
+ try write(container + "/b/Documents/games/X/old.bin", "old")
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: f.xcrun)
+ p.arguments = ["devicectl", "device", "copy", "to", "--device", "D", "--source", f.archive + "/romfs.img", "--destination", "Documents/games/X/romfs.img",
+ "--domain-type", "appDataContainer", "--domain-identifier", "b", "--remove-existing-content", "true"]
+ try p.run(); p.waitUntilExit()
+ XCTAssertFalse(fm.fileExists(atPath: container + "/b/Documents/games/X/old.bin"))
+ XCTAssertTrue(fm.fileExists(atPath: container + "/b/Documents/games/X/romfs.img"))
+ }
+
+ // ---- the headless install, end to end ----
+
+ func testHeadlessInstallCopiesOnlyWhatTheDeviceLacksAndKeepsTheSave() throws {
+ let f = try makeFixture()
+ let bundle = "org.nxnative.shell"
+ let save = container + "/\(bundle)/Documents/save/slot1.bin"
+ try write(save, "my save") // the app is on the device already, with a save
+
+ // first run: the game's folder does not exist on the device (error JSON), so both files go
+ var r = run(f)
+ XCTAssertEqual(r.status, 0, r.output)
+ XCTAssertTrue(r.output.contains("OK: Installed on"), r.output)
+ let games = container + "/\(bundle)/Documents/games/\(titleID)"
+ XCTAssertEqual(try String(contentsOfFile: games + "/romfs.img"), "0123456789")
+ XCTAssertEqual(try String(contentsOfFile: games + "/aoc/1.img"), "abcd")
+ XCTAssertFalse(fm.fileExists(atPath: games + "/.packstamp"))
+ XCTAssertEqual(copies().count, 2)
+ XCTAssertEqual(try String(contentsOfFile: save), "my save")
+ let env = try String(contentsOfFile: state + "/shell-env.txt")
+ for line in ["DM_BUNDLE_ID=org.nxnative.shell", "DM_SHELL_FRAMEWORKS=\(f.framework)", "DM_TEAM_ID=TEAM123456",
+ "SHELL_DIR=\(f.root)/project", "DM_XCODE_DERIVED_DATA=\(f.root)/derived-data", "FONT_PY=/usr/bin/python3"] {
+ XCTAssertTrue(env.contains(line), line)
+ }
+ let library = ShellLibrary.load(root: f.root)
+ XCTAssertEqual(library.games, [.init(titleID: titleID, name: "Test Game", framework: f.framework)])
+ XCTAssertEqual(library.team, team)
+
+ // second run, same data: nothing is copied
+ r = run(f)
+ XCTAssertEqual(r.status, 0, r.output)
+ XCTAssertEqual(copies().count, 2)
+ XCTAssertTrue(r.output.contains("the game data was already on the device"), r.output)
+ XCTAssertEqual(try String(contentsOfFile: save), "my save")
+
+ // a file with another size: only that one is copied
+ try write(f.archive + "/aoc/1.img", "abcdef")
+ r = run(f)
+ XCTAssertEqual(r.status, 0, r.output)
+ XCTAssertEqual(copies().count, 3)
+ XCTAssertTrue(copies().last?.contains("--destination Documents/games/\(titleID)/aoc/1.img") ?? false)
+ XCTAssertEqual(try String(contentsOfFile: games + "/aoc/1.img"), "abcdef")
+ XCTAssertEqual(try String(contentsOfFile: games + "/romfs.img"), "0123456789")
+ XCTAssertEqual(try String(contentsOfFile: save), "my save")
+
+ XCTAssertFalse(calls.contains { $0.contains("--remove-existing-content") })
+ XCTAssertEqual(calls.filter { $0.hasPrefix("devicectl device install app") }.count, 3)
+ }
+
+ func testTeamVariantRetryStoresTheBundleIDAndTheNextRunUsesIt() throws {
+ let f = try makeFixture()
+ try write(state + "/taken", "")
+ let variant = "org.nxnative.shell." + team
+ let save = container + "/\(variant)/Documents/save/slot1.bin"
+ try write(save, "my save")
+
+ var r = run(f)
+ XCTAssertEqual(r.status, 0, r.output)
+ XCTAssertEqual(ShellLibrary.load(root: f.root).bundleID, variant)
+ var builds = calls.filter { $0.hasPrefix("xcodebuild") }
+ XCTAssertEqual(builds.count, 2)
+ XCTAssertTrue(builds[0].contains("PRODUCT_BUNDLE_IDENTIFIER=org.nxnative.shell build"))
+ XCTAssertTrue(builds[1].contains("PRODUCT_BUNDLE_IDENTIFIER=\(variant) build"))
+ XCTAssertEqual(try String(contentsOfFile: container + "/\(variant)/Documents/games/\(titleID)/romfs.img"), "0123456789")
+
+ r = run(f) // the plain identifier is not tried again
+ XCTAssertEqual(r.status, 0, r.output)
+ builds = calls.filter { $0.hasPrefix("xcodebuild") }
+ XCTAssertEqual(builds.count, 3)
+ XCTAssertTrue(builds[2].contains("PRODUCT_BUNDLE_IDENTIFIER=\(variant) build"))
+ XCTAssertEqual(copies().count, 2)
+ XCTAssertEqual(try String(contentsOfFile: save), "my save")
+ XCTAssertFalse(calls.contains { $0.contains("--remove-existing-content") })
+ }
+
+ func testAFailingProjectScriptReachesThePlayer() throws {
+ let f = try makeFixture()
+ try write(state + "/refuse", "")
+ let r = run(f)
+ XCTAssertEqual(r.status, 1)
+ XCTAssertTrue(r.output.contains("FAIL: The shared app could not be prepared: games of different profiles in one shell: A (x), B (y)"), r.output)
+ XCTAssertFalse(calls.contains { $0.hasPrefix("xcodebuild") || $0.hasPrefix("devicectl device") }) // nothing was signed or installed
+ }
+
+ func testCLIChecksItsArguments() throws {
+ var output = ""
+ XCTAssertEqual(ShellCLI.run(["--install-shell", "--framework", "/x"], defaults: UserDefaults(suiteName: "nspb-shell-" + UUID().uuidString)!) { output += $0 }, 1)
+ XCTAssertTrue(output.hasPrefix("usage: NSPortBuilder --install-shell"))
+ let f = try makeFixture()
+ output = ""
+ XCTAssertEqual(ShellCLI.run(f.args(extra: ["--framework", path("missing.framework")]),
+ defaults: UserDefaults(suiteName: "nspb-shell-" + UUID().uuidString)!) { output += $0 }, 1)
+ XCTAssertTrue(output.contains("framework was not found"), output)
+ }
+
+ // ---- the lead's three: memory capability, free space, the shell's log ----
+
+ func testMemoryCapabilityFreeSpaceAndLogCommand() {
+ XCTAssertTrue(ShellInstall.memoryCapabilityMissing("error: Provisioning profile \"x\" doesn't include the Increased Memory Limit capability."))
+ XCTAssertTrue(ShellInstall.memoryCapabilityMissing("doesn't include the com.apple.developer.kernel.increased-memory-limit entitlement"))
+ XCTAssertFalse(ShellInstall.memoryCapabilityMissing("error: No profiles for 'org.nxnative.shell' were found"))
+ XCTAssertEqual(ShellInstall.shellLogCommand(xcrun: "/x", device: "D", bundleID: "b", destination: "/t.txt"),
+ ["/x", "devicectl", "device", "copy", "from", "--device", "D", "--domain-type", "appDataContainer",
+ "--domain-identifier", "b", "--source", "Documents/shell-log.txt", "--destination", "/t.txt"])
+ XCTAssertEqual(ShellInstall.freeSpace(inShellLog: "shell: start\nshell: free space 123 bytes\nshell: free space 4567 bytes\nother\n"), 4567)
+ XCTAssertNil(ShellInstall.freeSpace(inShellLog: "shell: start\n"))
+ XCTAssertNil(ShellInstall.freeSpace(inShellLog: nil))
+ XCTAssertNil(ShellInstall.freeSpace(inShellLog: "shell: free space -1 bytes\n"))
+ XCTAssertEqual(ShellInstall.freeSpaceMargin, 2_000_000_000)
+ }
+
+ func testNoSpaceRefusesTheCopyAndALaterRunWithRoomCopies() throws {
+ let f = try makeFixture()
+ let log = container + "/org.nxnative.shell/Documents/shell-log.txt"
+ try write(log, "shell: free space 9999999999 bytes\nshell: free space 5 bytes\n") // the last line counts
+ var r = install(installer(f), f)
+ XCTAssertFalse(r.ok)
+ XCTAssertTrue(r.message.hasPrefix("Not enough space on Z"), r.message)
+ XCTAssertNil(r.failure)
+ XCTAssertTrue(copies().isEmpty)
+ try write(log, "shell: free space 100000000000 bytes\n")
+ r = install(installer(f), f)
+ XCTAssertTrue(r.ok, r.message)
+ XCTAssertEqual(copies().count, 2)
+ }
+
+ func testMissingMemoryCapabilityFallsBackToASecondSignWithoutEntitlements() throws {
+ let f = try makeFixture()
+ try write(state + "/nomemory", "")
+ let r = install(installer(f), f)
+ XCTAssertTrue(r.ok, r.message)
+ XCTAssertTrue(r.noMemoryCapability)
+ XCTAssertEqual(calls.filter { $0.hasPrefix("xcodebuild") }.count, 2)
+ XCTAssertTrue(try String(contentsOfFile: state + "/shell-env.txt").contains("DM_ENTITLEMENTS=\n"))
+ XCTAssertEqual(copies().count, 2)
+ try fm.removeItem(atPath: state + "/nomemory")
+ XCTAssertFalse(install(installer(f), f).noMemoryCapability) // a team that can carry it signs with it
+ }
+
+ // ---- the connection ----
+
+ func testConnectionFromTheRealDeviceList() throws {
+ let real = """
+ {"info": {"outcome": "success"}, "result": {"devices": [
+ {"hardwareProperties": {"udid": "CABLE", "reality": "physical", "platform": "iOS"}, "deviceProperties": {"name": "A"},
+ "connectionProperties": {"pairingState": "paired", "transportType": "wired", "tunnelState": "connected"}},
+ {"hardwareProperties": {"udid": "WIFI", "reality": "physical", "platform": "iOS"}, "deviceProperties": {"name": "B"},
+ "connectionProperties": {"pairingState": "paired", "transportType": "localNetwork", "tunnelState": "connected"}},
+ {"hardwareProperties": {"udid": "AWAY", "reality": "physical", "platform": "iOS"}, "deviceProperties": {"name": "C"},
+ "connectionProperties": {"pairingState": "paired", "tunnelState": "unavailable"}},
+ {"hardwareProperties": {"udid": "NEW", "reality": "physical", "platform": "iOS"}, "deviceProperties": {"name": "D"},
+ "connectionProperties": {"pairingState": "unpaired", "tunnelState": "unavailable"}}]}}
+ """
+ let devices = DeviceTools.parseDevices(Data(real.utf8))
+ XCTAssertEqual(devices.first { $0.id == "CABLE" }?.transport, "wired")
+ XCTAssertEqual(devices.first { $0.id == "AWAY" }?.transport, "")
+ XCTAssertEqual(ShellInstall.connection(of: "CABLE", in: devices), .wired)
+ XCTAssertEqual(ShellInstall.connection(of: "WIFI", in: devices), .network)
+ XCTAssertEqual(ShellInstall.connection(of: "AWAY", in: devices), .notConnected)
+ XCTAssertEqual(ShellInstall.connection(of: "NEW", in: devices), .notPaired) // listed unpaired
+ XCTAssertEqual(ShellInstall.connection(of: "NOPE", in: devices), .notPaired) // not listed at all
+ XCTAssertEqual(ShellInstall.wifiEstimate(bytes: 15_000_000_000).low, 10)
+ XCTAssertEqual(ShellInstall.wifiEstimate(bytes: 15_000_000_000).high, 15)
+ XCTAssertEqual(ShellInstall.wifiEstimate(bytes: 5).low, 1)
+ }
+
+ func testOverACableTheNoteSaysToKeepTheDeviceUnlockedAndTheCopyStarts() throws {
+ let f = try makeFixture()
+ var plans: [ShellCopyPlan] = []
+ var i = installer(f)
+ i.decideCopy = { plans.append($0); return .copy }
+ var lines = ""
+ i.log = { lines += $0 }
+ let r = install(i, f)
+ XCTAssertTrue(r.ok, r.message)
+ XCTAssertEqual(plans.count, 1)
+ XCTAssertEqual(plans.first?.connection, .wired)
+ XCTAssertEqual(plans.first?.connectionText, "Keep Z unlocked until the copy finishes.")
+ XCTAssertEqual(plans.first?.files, 2)
+ XCTAssertEqual(plans.first?.canWaitForCable, false)
+ XCTAssertTrue(lines.contains("Keep Z unlocked"), "the terminal prints the same note")
+ XCTAssertEqual(copies().count, 2)
+ }
+
+ func testOverWiFiTheHintHasTheEstimateAndNotNowCopiesNothing() throws {
+ let f = try makeFixture()
+ try writeDevices(state + "/devices.json", [(device, "localNetwork")])
+ var plans: [ShellCopyPlan] = []
+ var i = installer(f)
+ i.decideCopy = { plans.append($0); return .skip }
+ let r = install(i, f)
+ XCTAssertTrue(r.ok && r.copySkipped, r.message)
+ XCTAssertEqual(plans.first?.connection, .network)
+ XCTAssertEqual(plans.first?.canWaitForCable, true)
+ XCTAssertTrue(plans.first?.connectionText.hasPrefix("Connected over Wi-Fi: copying 1 KB takes about a minute") ?? false, plans.first?.connectionText ?? "")
+ XCTAssertTrue(plans.first?.connectionText.hasSuffix("A cable is faster.") ?? false)
+ XCTAssertTrue(copies().isEmpty)
+ }
+
+ func testWaitForACableStartsTheCopyWhenTheDeviceShowsUpWired() throws {
+ let f = try makeFixture()
+ try writeDevices(state + "/devices.json", [(device, "localNetwork")])
+ try writeDevices(state + "/devices-wired.json", [(device, "wired")])
+ try write(state + "/switch-after", "3") // the precheck, the plan and the first poll still see Wi-Fi
+ var i = installer(f)
+ var waits: [Bool] = []
+ i.decideCopy = { _ in .waitForCable }
+ i.waiting = { waits.append($0) }
+ let r = install(i, f)
+ XCTAssertTrue(r.ok && !r.copySkipped, r.message)
+ XCTAssertEqual(waits, [true, false])
+ XCTAssertEqual(copies().count, 2)
+ XCTAssertEqual(try String(contentsOfFile: container + "/org.nxnative.shell/Documents/games/\(titleID)/romfs.img"), "0123456789")
+ }
+
+ func testCancellingTheWaitCopiesNothing() throws {
+ let f = try makeFixture()
+ try writeDevices(state + "/devices.json", [(device, "localNetwork")]) // never wired
+ var i = installer(f)
+ var waits: [Bool] = [], polls = 0
+ i.decideCopy = { _ in .waitForCable }
+ i.waiting = { waits.append($0) }
+ i.waitCancelled = { polls += 1; return polls > 3 }
+ let r = install(i, f)
+ XCTAssertTrue(r.ok && r.copySkipped, r.message)
+ XCTAssertEqual(waits, [true, false])
+ XCTAssertTrue(copies().isEmpty)
+ }
+
+ func testAnUnknownDeviceGetsThePairingStepsBeforeAnythingIsBuilt() throws {
+ let f = try makeFixture()
+ try writeDevices(state + "/devices-default.json", [("00008150-OTHER", "wired")])
+ let r = install(installer(f), f)
+ XCTAssertFalse(r.ok)
+ XCTAssertEqual(r.failure, .devicePairing)
+ XCTAssertTrue(r.message.contains("Connect it with a cable, tap Trust on the device and enter its passcode"), r.message)
+ XCTAssertFalse(fm.fileExists(atPath: state + "/shell-env.txt"), "build_shell.sh did not run")
+ XCTAssertFalse(calls.contains { $0.hasPrefix("xcodebuild") || $0.hasPrefix("devicectl device") })
+ var output = ""
+ XCTAssertEqual(ShellCLI.run(f.args(), defaults: UserDefaults(suiteName: "nspb-shell-" + UUID().uuidString)!) { output += $0 }, 1)
+ XCTAssertTrue(output.contains("FAIL: ") && output.contains("tap Trust"), output)
+ }
+
+ // ---- a copy that fails midway ----
+
+ func testAFailedCopyIsIncompleteAndRetryCopiesOnlyWhatIsMissingOrShort() throws {
+ let f = try makeFixture()
+ let games = container + "/org.nxnative.shell/Documents/games/\(titleID)"
+ try write(state + "/fail-on", "romfs.img")
+ var r = install(installer(f), f)
+ XCTAssertFalse(r.ok)
+ XCTAssertEqual(r.failure, .shellDataIncomplete)
+ XCTAssertTrue(r.message.contains("The game data on Z is incomplete: ERROR: The device is locked."), r.message)
+ XCTAssertTrue(r.message.hasSuffix("Retry finishes it."), r.message)
+ XCTAssertEqual(try String(contentsOfFile: games + "/aoc/1.img"), "abcd")
+ XCTAssertEqual(try String(contentsOfFile: games + "/romfs.img"), "01234") // a short file on the device
+ let signs = calls.filter { $0.hasPrefix("xcodebuild") }.count, installs = calls.filter { $0.hasPrefix("devicectl device install") }.count
+
+ try fm.removeItem(atPath: state + "/fail-on")
+ let before = copies().count
+ r = installer(f).installData(titleID: titleID, archive: f.archive)
+ XCTAssertTrue(r.ok, r.message)
+ XCTAssertEqual(copies().count - before, 1, "only the short romfs.img")
+ XCTAssertTrue(copies().last?.contains("Documents/games/\(titleID)/romfs.img") ?? false)
+ XCTAssertEqual(try String(contentsOfFile: games + "/romfs.img"), "0123456789")
+ XCTAssertEqual(calls.filter { $0.hasPrefix("xcodebuild") }.count, signs, "Retry does not sign again")
+ XCTAssertEqual(calls.filter { $0.hasPrefix("devicectl device install") }.count, installs, "or install again")
+
+ try write(games + "/aoc/1.img", "ab") // a file that is short on the device is copied again
+ let again = copies().count
+ r = installer(f).installData(titleID: titleID, archive: f.archive)
+ XCTAssertTrue(r.ok, r.message)
+ XCTAssertEqual(copies().count - again, 1)
+ XCTAssertTrue(copies().last?.contains("aoc/1.img") ?? false)
+ XCTAssertEqual(installer(f).installData(titleID: titleID, archive: f.archive).message, "Installed on Z, the game data was already on the device")
+ }
+
+ // ---- through the model: the build with the third target, and the re-sign ----
+
+ @MainActor func testBuildWithTheShellTargetInstallsAndResignsTheSharedApp() throws {
+ let f = try makeFixture()
+ let keysSaved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam", "shellRoot"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
+ defer { for (key, value) in keysSaved { UserDefaults.standard.set(value, forKey: key) } }
+ UserDefaults.standard.set(f.root, forKey: "shellRoot")
+ let model = BuildModel()
+ model.repoPath = f.repo
+ model.target = "ios-shell"
+ model.outDir = path("out")
+ 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 = device
+ model.signingTeam = team
+ model.xcrunPath = f.xcrun
+ try write(f.repo + "/dm/tools/nx_extract/Program.cs", "")
+ for tool in BuildModel.requiredTools.filter({ $0 != BuildModel.buildScript }) { try write(f.repo + "/" + tool, "") }
+ // the packer stand-in writes the image from the extracted RomFS
+ try write(f.repo + "/dm/tools/romfs_image.py", "import sys\nopen(sys.argv[3], 'wb').write(b'image')\n")
+ try write(f.repo + "/scripts/build_ipa_from_nsp.py", """
+ import sys, json, pathlib
+ open('\(state)/script.txt', 'w').write(' '.join(sys.argv[1:]))
+ work = pathlib.Path(sys.argv[sys.argv.index('--work-dir') + 1])
+ fw = pathlib.Path(sys.argv[sys.argv.index('--shell-framework') + 1]) / 'DmGame\(titleID).framework'
+ fw.mkdir(parents=True); (fw / 'game.manifest.json').write_text('{}')
+ (work / 'extract/v0/RomFS').mkdir(parents=True); (work / 'extract/v0/RomFS/data.bin').write_bytes(b'game')
+ print(json.dumps(dict(ev='stage', k=1, n=1, name='framework')), flush=True)
+ print(json.dumps(dict(ev='stage_end', k=1, name='framework', ok=True, summary='', elapsed=1)), flush=True)
+ """)
+ 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]
+ try fm.removeItem(atPath: f.archive) // the build's own archive step makes it
+
+ let finished = expectation(description: "Installed")
+ let token = model.$done.filter { $0 }.prefix(1).sink { _ in finished.fulfill() }
+ let asked = model.$shellCopy.compactMap { $0 }.prefix(1).sink { _ in model.answerShellCopy(.copy) }
+ model.startBuild()
+ wait(for: [finished], timeout: 30)
+ withExtendedLifetime(token) {}; withExtendedLifetime(asked) {}
+
+ let script = try String(contentsOfFile: state + "/script.txt")
+ XCTAssertTrue(script.contains("--shell-framework \(temporary.path)/out/\(titleID)_build/shell-framework --team-id \(team)"), script)
+ XCTAssertFalse(script.contains("--prepare-xcode"))
+ XCTAssertEqual(model.installedOn, device)
+ XCTAssertEqual(model.installedAppPath, f.root + "/derived-data/Build/Products/Release-iphoneos/DmShell.app")
+ XCTAssertFalse(model.running)
+ let games = container + "/org.nxnative.shell/Documents/games/\(titleID)"
+ XCTAssertTrue(fm.fileExists(atPath: games + "/romfs.img"))
+ XCTAssertEqual(ShellLibrary.load(root: f.root).games.map(\.titleID), [titleID])
+
+ // the re-sign after seven days: same project, same identifier, same app
+ try write(container + "/org.nxnative.shell/Documents/save/slot1.bin", "my save")
+ let before = calls.count
+ let resigned = expectation(description: "Re-signed")
+ model.resignOnDevice(app: model.installedAppPath, device: device) { resigned.fulfill() }
+ wait(for: [resigned], timeout: 30)
+ let log = Array(calls.dropFirst(before))
+ let build = try XCTUnwrap(log.first { $0.hasPrefix("xcodebuild") })
+ XCTAssertTrue(build.contains("-project \(f.root)/project/DmShell.xcodeproj -scheme DmShell"), build)
+ XCTAssertTrue(build.contains("PRODUCT_BUNDLE_IDENTIFIER=org.nxnative.shell build"), build)
+ XCTAssertEqual(log.filter { $0.hasPrefix("devicectl device install app") }.count, 1)
+ XCTAssertTrue(log.allSatisfy { !$0.contains("--remove-existing-content") })
+ XCTAssertEqual(try String(contentsOfFile: container + "/org.nxnative.shell/Documents/save/slot1.bin"), "my save")
+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.resigned"), "iPhone"))
+ }
+
+ @MainActor private func makeModel(_ f: Fixture) throws -> BuildModel {
+ let model = BuildModel()
+ model.repoPath = f.repo
+ model.target = "ios-shell"
+ model.outDir = path("out")
+ 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 = device
+ model.signingTeam = team
+ model.xcrunPath = f.xcrun
+ try write(f.repo + "/dm/tools/nx_extract/Program.cs", "")
+ for tool in BuildModel.requiredTools.filter({ $0 != BuildModel.buildScript }) { try write(f.repo + "/" + tool, "") }
+ try write(f.repo + "/scripts/build_ipa_from_nsp.py", "open('\(state)/script.txt', 'w').write('ran')\n")
+ 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]
+ return model
+ }
+
+ /// An unknown device stops the build before the script runs: no hour of building for a device that cannot be installed on.
+ @MainActor func testUnknownDeviceStopsTheBuildBeforeTheScriptRuns() throws {
+ let f = try makeFixture()
+ try writeDevices(state + "/devices-default.json", [("00008150-OTHER", "wired")])
+ 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 = try makeModel(f)
+ model.startBuild()
+ let stopped = expectation(description: "Checked")
+ let token = model.$running.dropFirst().filter { !$0 }.prefix(1).sink { _ in stopped.fulfill() }
+ wait(for: [stopped], timeout: 20)
+ withExtendedLifetime(token) {}
+ XCTAssertEqual(model.failure?.kind, .devicePairing)
+ XCTAssertTrue(model.doneNote.contains("tap Trust on the device"), model.doneNote)
+ XCTAssertFalse(fm.fileExists(atPath: state + "/script.txt"), "the build script did not start")
+ }
+
+ /// The copy card's answer and the failure row: a copy that fails midway says the data is incomplete, and Retry runs only the data step.
+ @MainActor func testFailedCopyShowsTheIncompleteRowAndRetryFinishesIt() throws {
+ let f = try makeFixture()
+ let saved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam", "shellRoot"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
+ defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
+ UserDefaults.standard.set(f.root, forKey: "shellRoot")
+ let model = try makeModel(f)
+ try write(state + "/fail-on", "romfs.img")
+ var plans: [ShellCopyPlan] = []
+ let asked = model.$shellCopy.compactMap { $0 }.sink { plans.append($0); model.answerShellCopy(.copy) }
+ func finish(_ start: () -> Void) {
+ let ended = expectation(description: "Ended")
+ let token = model.$running.dropFirst().filter { !$0 }.prefix(1).sink { _ in ended.fulfill() }
+ start()
+ wait(for: [ended], timeout: 30)
+ withExtendedLifetime(token) {}
+ }
+ finish { model.installShell(framework: f.framework, titleID: titleID, name: "Test Game", archive: f.archive) }
+ XCTAssertEqual(model.failure?.kind, .shellDataIncomplete)
+ XCTAssertTrue(model.doneNote.contains("incomplete"), model.doneNote)
+ XCTAssertFalse(model.done)
+ XCTAssertEqual(plans.count, 1)
+ XCTAssertEqual(plans.first?.connection, .wired)
+
+ try fm.removeItem(atPath: state + "/fail-on")
+ let signs = calls.filter { $0.hasPrefix("xcodebuild") }.count
+ finish { model.fixBuildFailure(.shellDataIncomplete) }
+ withExtendedLifetime(asked) {}
+ XCTAssertNil(model.failure)
+ XCTAssertTrue(model.done, model.doneNote)
+ XCTAssertEqual(model.installedOn, device)
+ XCTAssertEqual(calls.filter { $0.hasPrefix("xcodebuild") }.count, signs)
+ XCTAssertEqual(try String(contentsOfFile: container + "/org.nxnative.shell/Documents/games/\(titleID)/romfs.img"), "0123456789")
+ }
+
+ @MainActor func testShellTargetWithoutDeviceStopsBeforeBuilding() throws {
+ let saved = ["repoPath", "buildTarget", "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
+ try write(temporary.path + "/dm/tools/nx_extract/Program.cs", "")
+ model.target = "ios-shell"
+ model.installDevice = ""
+ model.startBuild()
+ XCTAssertFalse(model.running)
+ XCTAssertEqual(model.doneNote, model.t("shell.needsDevice"))
+ }
+}