Skip to content

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

Merge origin/main into v0lumehi/build-store

v0lumehicc8a6ffc4f14
diff --cc frontend/Sources/NXCore/ShellInstall.swift
index 1da8cc06,43eaf8b3..aacc35a0
--- a/frontend/Sources/NXCore/ShellInstall.swift
+++ b/frontend/Sources/NXCore/ShellInstall.swift
@@@ -56,29 -52,60 +56,60 @@@ package struct ShellLibrary: Codable, E
try encoder.encode(self).write(to: URL(fileURLWithPath: Self.stateFile(root: root)), options: .atomic)
}
+ /// The folder a shell root may live in: an absolute path that is not the root of a volume. `""` (no game or output
+ /// folder chosen yet) and `/` both gave `/NX2Apple-shell` on the read-only system volume (#492); `home` stands in.
- static func parentFolder(_ parent: String, home: String = NSHomeDirectory()) -> String {
++ package static func parentFolder(_ parent: String, home: String = NSHomeDirectory()) -> String {
+ let path = (parent as NSString).expandingTildeInPath
+ return path.hasPrefix("/") && path != "/" ? path : home
+ }
+
+ /// Whether a saved root can be used as it is: an absolute path below a volume root. `/NX2Apple-shell` came from an
+ /// empty parent and is repaired instead of used (#492).
- static func rootIsUsable(_ root: String) -> Bool {
++ package static func rootIsUsable(_ root: String) -> Bool {
+ root.hasPrefix("/") && (root as NSString).pathComponents.filter { $0 != "/" }.count >= 2
+ }
+
+ /// The root the next install would use, without saving it. The Settings page shows it before any game is chosen,
+ /// and that look must not decide where builds save (#492).
- static func previewRoot(defaults: UserDefaults = .standard, parent: String, home: String = NSHomeDirectory()) -> String {
++ package static func previewRoot(defaults: UserDefaults = .standard, parent: String, home: String = NSHomeDirectory()) -> String {
+ if let saved = defaults.string(forKey: "shellRoot"), rootIsUsable(saved) { return saved }
+ return parentFolder(parent, home: home) + "/NX2Apple-shell"
+ }
+
/// 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.
- package 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"
+ /// stays where it was first made, whatever output folder a later build uses. A saved root at a volume root is repaired.
- static func resolveRoot(defaults: UserDefaults = .standard, parent: String, home: String = NSHomeDirectory()) -> String {
++ package static func resolveRoot(defaults: UserDefaults = .standard, parent: String, home: String = NSHomeDirectory()) -> String {
+ if let saved = defaults.string(forKey: "shellRoot"), rootIsUsable(saved) { return saved }
+ let root = parentFolder(parent, home: home) + "/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"
+package enum ShellInstall {
+ package static let appName = "DmShell.app"
+ package static let scheme = "DmShell"
+ package static let projectName = "DmShell.xcodeproj"
- static func projectFolder(root: String) -> String { root + "/project" }
+ package static func projectFolder(root: String) -> String { root + "/project" }
+
+ /// Whether the shell root can be written, checked before an hour of building: a folder on a read-only volume (or a
+ /// file where the folder goes) only failed at the last step otherwise (#492).
- static func canWriteRoot(_ root: String, fm: FileManager = .default) -> Bool {
++ package static func canWriteRoot(_ root: String, fm: FileManager = .default) -> Bool {
+ var isDir: ObjCBool = false
+ if fm.fileExists(atPath: root, isDirectory: &isDir) { return isDir.boolValue && fm.isWritableFile(atPath: root) }
+ let parent = (root as NSString).deletingLastPathComponent
+ guard fm.fileExists(atPath: parent, isDirectory: &isDir), isDir.boolValue else { return false }
+ return fm.isWritableFile(atPath: parent)
+ }
+
- static func derivedData(root: String) -> String { root + "/derived-data" }
- static func appPath(root: String) -> String { derivedData(root: root) + "/Build/Products/Release-iphoneos/" + appName }
+ package static func derivedData(root: String) -> String { root + "/derived-data" }
+ package static func appPath(root: String) -> String { derivedData(root: root) + "/Build/Products/Release-iphoneos/" + appName }
/// The folder that mirrors every game's framework inside the shell folder: a game survives its build folder's deletion here.
- static func frameworksMirror(root: String) -> String { root + "/frameworks" }
- static func mirroredFramework(root: String, titleID: String) -> String {
+ package static func frameworksMirror(root: String) -> String { root + "/frameworks" }
+ package static func mirroredFramework(root: String, titleID: String) -> String {
frameworksMirror(root: root) + "/DmGame\(titleID).framework"
}
diff --cc frontend/Sources/NXModel/BuildStore+Run.swift
index 78b92a39,00000000..f1f2b9d3
mode 100644,000000..100644
--- a/frontend/Sources/NXModel/BuildStore+Run.swift
+++ b/frontend/Sources/NXModel/BuildStore+Run.swift
@@@ -1,263 -1,0 +1,266 @@@
+import Foundation
+import Combine
+import NXCore
+
+// The build run: the script's arguments and environment, the process, and what happens when it ends (LNPANDY/NX2Apple#387).
+
+extension BuildStore {
+ package 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 != BuildTarget.mac, !shellDeviceChecked {
+ guard installsDirectly else { doneNote = t("shell.needsDevice"); done = false; return }
+ verifyShellDevice()
+ return
+ }
+ shellDeviceChecked = false
+ if target != BuildTarget.mac, askAboutStaleFrameworks() { return } // StaleFrameworksPrompt.swift (#449)
+ stopping = false
+ running = true; done = false; doneNote = ""; stages = []; log.clear(); chainNoteShown = false
+ failure = nil; confirmingOverride = nil
+ let override = takeOverrideFlag() // for this build only: the next one asks again
+ installedOn = ""; installedAppPath = ""
+ guard repo.isRepo else {
+ fail(repo.path.isEmpty ? t("msg.repoInvalidEmpty") : String(format: t("msg.repoInvalid"), shortPath(repo.path)))
+ return
+ }
+ // Resolve the interpreter here if the dependency check has not landed yet. checkDeps()
+ // runs on a background queue and startBuild() can beat it — for a moment deps.pythonPath is
+ // empty, and the old fallback was Apple's /usr/bin/python3 (3.9), which the script then
+ // rejected with "require Python 3.12 or newer" whatever the machine actually had (#53).
+ let py = deps.pythonPath.isEmpty ? Toolchain.findPython().path : deps.pythonPath
+ // engine/ is the only engine and is stale or missing (#214): make it, then start again
+ if EngineLayout.needsSyncBeforeBuild(repo.path) {
+ _ = engine.syncEngine { ok in
+ self.running = false
+ if ok && !EngineLayout.needsSyncBeforeBuild(self.repo.path) { self.startBuild() }
+ else { self.fail(String(format: self.t("msg.toolsOld"), "engine/ (python3 tools/engine.py sync, see the log)")) }
+ }
+ return
+ }
+ // The tools this app runs, before a build that takes an hour finds one missing at its last step (#87)
+ let missing = RepoLayout.missingTools(in: repo.path)
+ if !missing.isEmpty {
+ fail(String(format: t("msg.toolsOld"), missing.joined(separator: ", ")))
+ return
+ }
+
+ // One folder when everything lives together; otherwise a staging folder of symlinks. A folder
+ // that holds other games too (a ROMs folder with one file per game) is staged as well: the
+ // script takes one game per folder and refuses one with several ("more than one game in the
+ // folder"), even when only the base game was picked (issue #58; ufooer's PR #31).
+ let baseDir = (basePath as NSString).deletingLastPathComponent
+ let allPaths = [basePath, updatePath] + dlcPaths
+ let dirs = Set(allPaths.filter { !$0.isEmpty }.map { ($0 as NSString).deletingLastPathComponent })
+ let picked = Set(allPaths.filter { !$0.isEmpty }.map { ($0 as NSString).lastPathComponent })
+ let unpicked = ((try? FileManager.default.contentsOfDirectory(atPath: baseDir)) ?? []).filter {
+ ["nsp", "xci", "nsz", "xcz"].contains(($0 as NSString).pathExtension.lowercased()) && !picked.contains($0)
+ }
+ // Staged, the folder's own update and add-on content would be left behind, where the script
+ // used to find them unpicked: bring along those whose file name carries this game's title ID
+ // exactly as build_ipa_from_nsp.py:445 reads it: the low 12 bits are 0x000 for a base game,
+ // 0x800 for its update, and anything else is add-on content below the base.
+ var staged = allPaths
+ if let base = TitleID.parse((basePath as NSString).lastPathComponent) {
+ let app = base & ~0xFFF
+ for f in unpicked {
+ guard let tid = TitleID.parse(f) else { continue }
+ let low = tid & 0xFFF
+ let owner = low == 0 ? tid : (low == 0x800 ? tid & ~0xFFF : (tid & ~0xFFF) - 0x1000)
+ guard owner == app else { continue }
+ if low == 0x800 && !updatePath.isEmpty { continue } // the update was picked already
+ if low != 0 && low != 0x800 && tid <= app { continue } // add-on content sits above its base
+ staged.append(baseDir + "/" + f)
+ }
+ }
+ let tidHex = TitleID.buildKey(basePath)
+ let workDir = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + "_build"
+ // The build's signing step refuses the attributes a cloud folder adds, after the long steps: stop here instead.
+ if cloudFolderCheck(workDir) {
+ failure = BuildFailure(kind: .cloudFolder, gameName: nil, detail: workDir)
+ fail(failureWhat(failure!))
+ return
+ }
++ // The shared app's own folder is decided before the long steps too: one on a read-only volume (a saved
++ // /NX2Apple-shell, a DMG chosen as Save to) failed at the last step after the whole build (#492).
++ if target != BuildTarget.mac, let why = shellRootProblem() { fail(why); return }
+ var inputDir = baseDir
+ if dirs.count > 1 || !unpicked.isEmpty {
+ // A stable folder per game (#132): the script's fingerprints name its files and its profile path.
+ let tmp = InputStaging.folder(workDir: workDir)
+ let linked = InputStaging.sync(files: staged, into: tmp)
+ if linked == 0 { fail(t("msg.stagingFailed")); return }
+ staging = tmp; inputDir = tmp
+ if !unpicked.isEmpty {
+ say(String(format: t("msg.stagedFromSharedFolder"), (basePath as NSString).lastPathComponent))
+ }
+ } else { staging = nil }
+
+ // This fork's --work-dir keeps the build folder (extracted files, shader cache, the romfs
+ // archive) outside the NSPs' folder. An upstream checkout or an older ZIP does not have the
+ // option and would stop with "unrecognized arguments" (issue #5), so ask the script; without
+ // it the script's own default (<input>/<title ID>_build) is used and the archive step follows
+ // whatever folder the build reports.
+ let hasWorkDir = RepoLayout.supportsWorkDir(repo.path)
+ if !hasWorkDir {
+ say(t("msg.noWorkDir"))
+ }
+ // A compressed dump (NSZ / XCZ) needs nsz in the interpreter the build runs under; it is not
+ // part of the dependency probe (most builds never see one), so install it here, once, only
+ // when such a file is actually selected — otherwise the build stops with "pip install nsz".
+ let compressed = ([basePath, updatePath] + dlcPaths).contains {
+ let e = ($0 as NSString).pathExtension.lowercased()
+ return e == "nsz" || e == "xcz"
+ }
+ if compressed, !Toolchain.runOK(py, ["-c", "import nsz"]) {
+ say(t("msg.installingNsz"))
+ let r = runner.runCaptured([py, "-m", "pip", "install", "nsz"],
+ env: ["PATH": BuildCommands.toolPath(python: py),
+ "HOME": NSHomeDirectory()].merging(BundledTools.environment(for: py)) { $1 }) { @Sendable line in
+ hop { self.append(line + "\n") }
+ }
+ if !r {
+ fail(String(format: t("msg.nszFailed"), py))
+ return
+ }
+ }
+ let engine = EngineLayout.root(repo.path) // the checkout's engine/ (#214)
+ var args = [engine + "/" + RepoLayout.buildScript, inputDir, "-k", keysPath,
+ "--progress", "json"]
+ // A compatibility switch the player turned on: written to a small env file the pipeline
+ // copies into the app bundle (main.m sets one variable per line at boot). Only for an iPhone or iPad build;
+ // a Mac app runs on this Mac's GPU, which always has BC support.
+ if bcOnCPU && target != BuildTarget.mac {
+ let envPath = NSTemporaryDirectory() + "nspb-env-\(UUID().uuidString.prefix(8)).txt"
+ do {
+ try "DM_TEX_BC_CPU=1\n".write(toFile: envPath, atomically: true, encoding: .utf8)
+ args += ["--env-file", envPath]
+ say(t("msg.bcOn"))
+ } catch {
+ say(String(format: t("msg.bcEnvFailed"), error.localizedDescription))
+ }
+ }
+ if hasWorkDir { args += ["--work-dir", workDir] }
+ let macApp = target == BuildTarget.mac
+ if macApp {
+ // -o names the .app; the RomFS goes inside it, so the archive step is skipped below.
+ args += ["--platform", "mac-app"]
+ macAppPath = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + ".app"
+ args += ["-o", macAppPath]
+ } else {
+ // Only the game's framework: the one shared app is made and signed after the script (installShell)
+ args += ShellInstall.buildArguments(workDir: workDir, team: devices.signingTeam)
+ }
+ // The archive step packs whatever folder the build reported; without --work-dir that is the
+ // script's default, which is the same workDir unless a separate output folder was chosen.
+ effectiveWorkDir = hasWorkDir ? workDir : (inputDir as NSString).appendingPathComponent(tidHex + "_build")
+ args = BuildFailureClassifier.arguments(args, adding: override)
+ if let override { say(String(format: t("fail.override.note"), override)) }
+ say(String(format: t("msg.running"), py) + " " + args.joined(separator: " "))
+ lastBuildCommand = [py] + args
+
+ // The root of the runtime the apphost looks for: derived from the detected installation,
+ // not assumed to be ~/.dotnet (Homebrew keeps it in …/opt/dotnet/libexec). Only set when the
+ // derivation actually answered — a wrong root is worse than none, and the pipeline derives
+ // and verifies its own (DOTNET_ROOT, build_ipa_from_nsp.py) when this is absent.
+ // TMPDIR as well: .NET 10 on macOS keeps the named mutex its first-run configure takes
+ // (NuGet-Migrations) under $TMPDIR/.dotnet/shm, and with no TMPDIR it stats "" and dies with
+ // 'NuGet-Migrations' + lstat("") == ENOENT before any project is read. NSTemporaryDirectory()
+ // is the per-user temp folder whether or not the app's own environment carries one.
+ var denv: [String: String] = ["PATH": BuildCommands.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: py),
+ "USER": NSUserName(), "HOME": NSHomeDirectory(), "LANG": "en_US.UTF-8",
+ "TMPDIR": NSTemporaryDirectory()]
+ if let droot = Toolchain.dotnetRoot(for: deps.dotnetPath.isEmpty ? "dotnet" : deps.dotnetPath) {
+ denv["DOTNET_ROOT"] = droot // both variables carry the same root, as the apphost checks the arch-specific one first
+ denv["DOTNET_ROOT_ARM64"] = droot
+ }
+ // The bundled Python lives inside the signed app: a .pyc written there would change what the signature seals
+ // (the packages are compiled at bundle time), and a user site must not shadow its pinned packages.
+ denv.merge(BundledTools.environment(for: py)) { $1 }
+ let launch = ProcessLaunch(executable: py, arguments: args, environment: denv, directory: engine, groupPython: py)
+ let onExit: @Sendable (Int32) -> Void = { [weak self] status in
+ hop {
+ guard let self else { return }
+ self.running = false
+ self.flushLines()
+ if self.stopping {
+ self.stopping = false
+ self.resetProgress()
+ self.doneNote = self.t("msg.stopped")
+ self.cleanupStaging()
+ return
+ }
+ if status == 0 {
+ self.markAllDone()
+ if self.target == BuildTarget.mac {
+ // The .app is self-contained (its RomFS is inside), and the marker file
+ // beside it (.nx2apple-library, a dot file the Finder hides) tells the
+ // game's launcher that this folder is a library: its saves and log live
+ // here, and they follow the folder if it moves. No image copy — the .app
+ // already carries one, and a second multi-GB file was pure duplication.
+ let made = !self.macAppPath.isEmpty &&
+ FileManager.default.fileExists(atPath: self.macAppPath)
+ self.done = made
+ self.doneNote = self.t(made ? "msg.macAppDone" : "msg.macAppMissing")
+ if made {
+ try? Data().write(to: URL(fileURLWithPath:
+ (self.macAppPath as NSString).deletingLastPathComponent +
+ "/.nx2apple-library"))
+ }
+ self.running = false
+ self.cleanupStaging()
+ } else {
+ // The game's archive, then its framework into the one shared app on the device
+ let tid = TitleID.buildKey(self.basePath)
+ let name = ((self.basePath as NSString).lastPathComponent as NSString).deletingPathExtension
+ let fw = ShellInstall.frameworkPath(workDir: self.effectiveWorkDir, titleID: tid)
+ self.packArchive(workDir: self.effectiveWorkDir) {
+ self.installShell(framework: fw, titleID: tid, name: name, archive: $0)
+ }
+ }
+ } else {
+ if let i = self.stages.lastIndex(where: { $0.state == .running }) {
+ self.stages[i].state = .failed
+ self.stages[i].detail = String(format: self.t("msg.exitCode"), status)
+ self.noteFailure()
+ } else {
+ // The last real line says more than the exit code alone, and the message
+ // points at the log: "Build failed (exit code 1)" with nothing else sent a
+ // reporter looking for a log that a short window had below the fold (#52)
+ self.doneNote = String(format: self.t("msg.buildFailed"), status)
+ if let last = BuildProgress.lastMeaningfulLine(self.logTail) {
+ self.doneNote = String(format: self.t("msg.buildFailedReason"), last)
+ }
+ self.noteFailure()
+ }
+ self.cleanupStaging()
+ }
+ }
+ }
+ do {
+ proc = try runner.start(launch, onOutput: { @Sendable [weak self] d in
+ guard let s = String(data: d, encoding: .utf8) else { return }
+ hop { self?.ingest(s) }
+ }, onExit: onExit)
+ } catch { fail(String(format: t("msg.launchFailed"), error.localizedDescription)) }
+ }
+
+ /// Looks the device up in `devicectl list devices` (in the background), then starts the build, or says how to pair it.
+ package func verifyShellDevice() {
+ running = true; done = false; doneNote = ""; failure = nil; stages = []
+ let xcrun = devices.xcrun, device = devices.installDevice, runner = runner
+ DispatchQueue.global(qos: .userInitiated).async {
+ let link = ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20, runner: runner))
+ hop {
+ self.running = false
+ if link == .notPaired {
+ self.failure = BuildFailure(kind: .devicePairing, gameName: nil)
+ self.doneNote = String(format: self.t("shell.notPaired"), self.devices.deviceName(device))
+ return
+ }
+ self.shellDeviceChecked = true
+ self.startBuild()
+ }
+ }
+ }
+}
diff --cc frontend/Sources/NXModel/BuildStore+ShellRoot.swift
index 00000000,e68f33ab..128aa712
mode 000000,100644..100644
--- a/frontend/Sources/NXModel/BuildStore+ShellRoot.swift
+++ b/frontend/Sources/NXModel/BuildStore+ShellRoot.swift
@@@ -1,0 -1,21 +1,22 @@@
+ import Foundation
++import NXCore
+
+ // Where the shared app's folder lives (#492). The Settings row shows it before a game or output folder is chosen, so a
+ // look only previews the root; a build saves it. An empty parent, "/" or a relative one would have put it at
+ // /NX2Apple-shell, the root of the read-only system volume, where the write failed after the whole build; a saved value
+ // like that is repaired. A build also checks the folder before its long steps, not at the end.
+
-extension BuildModel {
++extension BuildStore {
+ /// The shell folder the cache row shows: the frameworks' mirror, shell.json and the banner cache live here.
- var shellCachePath: String { ShellLibrary.previewRoot(parent: shellRootParent) }
++ package var shellCachePath: String { ShellLibrary.previewRoot(defaults: defaults, parent: shellRootParent) }
+ /// The folder a first shell root would sit in: the output folder, else the game's folder.
- var shellRootParent: String { outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir }
++ package var shellRootParent: String { outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir }
+ /// The shell folder of the install: the saved one, else next to the output folder (or the game's folder).
- var shellRoot: String { ShellLibrary.resolveRoot(parent: shellRootParent) }
++ package var shellRoot: String { ShellLibrary.resolveRoot(defaults: defaults, parent: shellRootParent) }
+
+ /// Why the shell folder cannot be written (`nil`: it can), before an hour of building rather than at the last step.
- func shellRootProblem() -> String? {
++ package func shellRootProblem() -> String? {
+ let root = shellRoot
+ return ShellInstall.canWriteRoot(root) ? nil : String(format: t("shell.rootUnwritable"), shortPath(root))
+ }
+ }
diff --cc frontend/Sources/NXModel/BuildStore.swift
index b58c123d,00000000..1560da75
mode 100644,000000..100644
--- a/frontend/Sources/NXModel/BuildStore.swift
+++ b/frontend/Sources/NXModel/BuildStore.swift
@@@ -1,316 -1,0 +1,313 @@@
+import Foundation
+import Combine
+import NXCore
+
+/// A file picker request: what the store asks the app's open panel for (`BuildStore.choosePaths`).
+package struct FilePick: Equatable {
+ package var allowsMultiple: Bool
+ package var fileTypes: [String]
+ package var message: String?
+ package var prompt: String?
+
+ package init(allowsMultiple: Bool, fileTypes: [String], message: String? = nil, prompt: String? = nil) {
+ self.allowsMultiple = allowsMultiple; self.fileTypes = fileTypes; self.message = message; self.prompt = prompt
+ }
+}
+
+/// What the build asks of the engine sync: make `engine/` of the checkout current, and tell when it is done.
+@MainActor package protocol EngineSyncing: AnyObject {
+ func syncEngine(then: ((Bool) -> Void)?) -> Task<Void, Never>
+}
+
+/// What the build asks of the dependency store besides its status: the rows, and the install the card's fix buttons run.
+@MainActor package protocol DependencyInstalling: DependencyStatus {
+ func isInstalling(_ id: String) -> Bool
+ func install(_ dep: Dep) -> Task<Void, Never>
+}
+
+/// What the build reads from the device store: the device and the team to install on, the names, the listing of the teams, and the
+/// copy flow the install blocks on (its queue is not the main one, so those four are `nonisolated`).
+@MainActor package protocol InstallTarget: AnyObject {
+ var installDevice: String { get }
+ /// The paired devices the last listing found.
+ var devices: [AppleDevice] { get }
+ var signingTeam: String { get }
+ var xcrun: String { get }
+ var readTeams: @Sendable () -> [SigningTeam] { get }
+ func deviceName(_ udid: String) -> String
+ nonisolated func askCopy(_ plan: ShellCopyPlan) -> ShellCopyDecision
+ nonisolated func setWaiting(_ on: Bool)
+ nonisolated var waitCancelled: Bool { get }
+ func copyEnded()
+}
+
+extension DeviceStore: InstallTarget {}
+extension DependencyStore: DependencyInstalling {}
+extension EngineSyncStore: EngineSyncing {}
+
+/// Runs `body` on the main actor, from a queue that is not the main one: the pipe's callbacks and the background install land here.
+func hop(_ body: @escaping @MainActor () -> Void) {
+ DispatchQueue.main.async { MainActor.assumeIsolated(body) }
+}
+
+/// The build (LNPANDY/NX2Apple#387, step 7, the last store): the inputs (the four rows, the output folder), the target, the stages
+/// and whether a build runs, the script's JSON events, the run itself with its archive step and its hand-off to the device, the
+/// failure the card shows and "Build anyway". It follows `AppUpdateStore` (`frontend/ARCHITECTURE.md`, "Stores").
+///
+/// - What it works with comes through `init`: the `Localizer`, a `ProcessRunner`, the `BuildLog`, and three narrow views of the other
+/// stores: `RepoLocation` (where the checkout is), `DependencyInstalling` (the tools: `DependencyStatus` and the install the fix
+/// buttons run), `EngineSyncing` (the sync a stale `engine/` needs before a build) and `InstallTarget` (the device, the team and
+/// the copy flow). The app wires them.
+/// - AppKit reaches it as closures: the file and folder pickers (`choosePaths`, `chooseFolder`, `chooseSaveLocation`), the notice
+/// (`showNotice`), the Finder (`revealFolder`, `openApp`), and `targetChanged`, which the app answers with a new dependency check.
+/// - It checks the conditions for its own actions: `canBuild` and the start of a build (`startBuild`).
+/// - The pieces live in the `BuildStore+` files: `Inputs`, `Run`, `Failure`, `Archive`, `Install`, `Stale`, `DropFiles`.
+@MainActor package final class BuildStore: ObservableObject {
+ nonisolated package static let outputKey = "buildOutputDirectory"
+ nonisolated package static let targetKey = "buildTarget"
+ nonisolated package static let bcOnCPUKey = "bcOnCPU"
+
+ @Published package var gameDir = ""
+ @Published package var slots: [Slot] = [
+ Slot(id: "base", kind: .base, title: "data.base", optional: false),
+ Slot(id: "update", kind: .update, title: "data.update", optional: true),
+ Slot(id: "dlc", kind: .dlc, title: "data.dlc", optional: true),
+ Slot(id: "keys", kind: .keys, title: "data.keys", optional: false),
+ ]
+ @Published package var outDir: String {
+ didSet { defaults.set(outDir, forKey: Self.outputKey) }
+ }
+ @Published package var stages: [Stage] = []
+ var chainNoteShown = false // the shader-chain notice shows once per build
+ @Published package var running = false
+ @Published package var staleFrameworks: [StaleFrameworks.Entry] = [] // the prompt of StaleFrameworksPrompt.swift (#449)
- /// The shell folder the cache row shows: the frameworks' mirror, shell.json and the banner cache live here.
- package var shellCachePath: String { shellRoot }
- /// The shell folder of the install and of the cache row: the saved one, else next to the output folder (or the game's folder).
- package var shellRoot: String { ShellLibrary.resolveRoot(defaults: defaults, parent: outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir) }
++ // The shell folder (shellCachePath, shellRoot, shellRootProblem): BuildStore+ShellRoot.swift.
+ @Published package var stopping = false
+ /// The build log. Not published: only `BuildLogView` observes it (#387), so a log line redraws the log and nothing else.
+ package let log: BuildLog
+ package var logTail: String {
+ get { log.text }
+ set { log.set(newValue) }
+ }
+ @Published package var done = false
+ @Published package var doneNote = ""
+ /// What the NSP script stopped on, when it is one of the known early stops (BuildFailureClassifier). nil for a build that
+ /// succeeded, is running, or failed some other way (the note then shows the last line of the log, as it always did).
+ @Published package var failure: BuildFailure?
+ /// "Build anyway" asked for this stop and waiting for the confirmation dialog.
+ @Published package var confirmingOverride: BuildFailureKind?
+ /// The one-off `--allow-*` of a confirmed "Build anyway": taken by the next build and never stored.
+ package var armedOverride: BuildFailureKind?
+ @Published package var macAppPath = "" // --platform mac-app: the .app this build produced
+ /// BuildTarget.ios = the game's framework in the one shared app on an iPhone or iPad; BuildTarget.mac = a double-clickable
+ /// Mac app (upstream's --platform mac-app). A Mac app is a different output of the same pipeline, not a
+ /// different pipeline: same extraction, rewrite and shaders, then dm/mac/pack_app.py.
+ @Published package var target: String {
+ didSet {
+ defaults.set(target, forKey: Self.targetKey)
+ if oldValue != target { targetChanged() }
+ }
+ }
+ /// Decode BC-compressed textures on the CPU. Only relevant for GPUs without BC support
+ /// (A15/A16 and older): on a device that has it the GPU path is always better, so the switch
+ /// is a compatibility option and defaults off. Passed as DM_TEX_BC_CPU through --env-file,
+ /// which the host reads at start-up — no rebuild of the host needed.
+ @Published package var bcOnCPU: Bool {
+ didSet { defaults.set(bcOnCPU, forKey: Self.bcOnCPUKey) }
+ }
+ @Published package var archivePath = "" // the romfs folder the pack wrote
+ /// Where this build's folder actually is: --work-dir when the checkout has it, else the script's
+ /// default under the input folder (issue #5 — an upstream checkout has no --work-dir).
+ package var effectiveWorkDir = ""
+ package var lastBuildCommand: [String] = [] // this session's last build, for Copy diagnostics (Diagnostics.swift)
+
+ // ---- Installing on an iPhone or iPad (Xcode with a development certificate) ----
+ // Optional: with a paired device and a signing team chosen, the script prepares the game's Xcode project
+ // (--prepare-xcode, the route its README gives developers), xcodebuild signs it for that device with the
+ // team (Xcode makes the provisioning profile) without the game files, devicectl installs it and copies the game's
+ // folder (romfs.img, aoc/) into its Documents, as a sideloaded copy has it. Without a device or a team the build stays an unsigned IPA, as before.
+ @Published package var installedOn = "" // the device the last build went to (its UDID)
+ @Published package var installedAppPath = "" // the signed app that went there
+ var shellRetry: (framework: String, titleID: String, name: String, archive: String)?
+ var shellDeviceChecked = false
+
+ // ---- The app's side: AppKit and the wiring, as closures ----
+ package var chooseKeys: (() -> Void)? // tests stand in for the file picker
+ /// The open panel: the paths the player picked, none when they cancelled.
+ package var choosePaths: (FilePick) -> [String] = { _ in [] }
+ /// The folder panel of "Save to": the folder's path, nil when they cancelled.
+ package var chooseFolder: () -> String? = { nil }
+ /// The save panel of "Save IPA" (title, the name offered): where to write, nil when they cancelled.
+ package var chooseSaveLocation: (String, String) -> URL? = { _, _ in nil }
+ /// A notice the player must see (the shader chain changed): an alert.
+ package var showNotice: (String) -> Void = { _ in }
+ package var revealFolder: (URL) -> Void = { _ in }
+ package var openApp: (URL) -> Void = { _ in }
+ /// Whether the build folder is in a cloud folder. Tests stand in for the system's answer.
+ package var cloudFolderCheck: (String) -> Bool = { CloudFolder.contains($0) }
+ /// The target changed: the app checks the tools again when a Mac-only setup now needs, or no longer needs, the iOS SDK.
+ package var targetChanged: () -> Void
+
+ // ---- What it works with ----
+ package let localizer: Localizer
+ package let runner: ProcessRunner
+ package let repo: RepoLocation
+ package let deps: DependencyInstalling
+ package let engine: EngineSyncing
+ package let devices: InstallTarget
+ package let volumesRoot: String
+ let defaults: UserDefaults
+
+ var proc: RunningProcess?
+ var staging: String?
+
+ /// - Parameters:
+ /// - volumesRoot: where external drives are mounted (the failure classifier reads it).
+ /// - targetChanged: see the property of the same name.
+ package init(localizer: Localizer, runner: ProcessRunner, log: BuildLog = BuildLog(), repo: RepoLocation, deps: DependencyInstalling,
+ engine: EngineSyncing, devices: InstallTarget, defaults: UserDefaults = .standard, volumesRoot: String = "/Volumes",
+ targetChanged: @escaping () -> Void = {}) {
+ self.localizer = localizer
+ self.runner = runner
+ self.log = log
+ self.repo = repo
+ self.deps = deps
+ self.engine = engine
+ self.devices = devices
+ self.defaults = defaults
+ self.volumesRoot = volumesRoot
+ self.targetChanged = targetChanged
+ outDir = defaults.string(forKey: Self.outputKey) ?? ""
+ target = BuildTarget.saved(defaults)
+ bcOnCPU = defaults.bool(forKey: Self.bcOnCPUKey)
+ }
+
+ /// The language and the text this store writes itself: views take strings from the environment.
+ package var lang: Lang { get { localizer.lang } set { localizer.lang = newValue } }
+ package func t(_ key: String) -> String { localizer.t(key) }
+
+ /// This iPhone build goes straight to a device.
+ package var installsDirectly: Bool { target != BuildTarget.mac && !devices.installDevice.isEmpty && !devices.signingTeam.isEmpty }
+
+ /// Home shown as ~ (shorter in a one-line row, and it keeps the account name out of screenshots).
+ package func shortPath(_ path: String) -> String { RepoLayout.shortPath(path) }
+
+ package var basePath: String { slot("base").paths.first ?? "" }
+ package var keysPath: String { slot("keys").paths.first ?? "" }
+ package var updatePath: String { slot("update").paths.first ?? "" }
+ package var dlcPaths: [String] { slot("dlc").paths }
+
+ package func slot(_ id: String) -> Slot { slots.first { $0.id == id } ?? slots[0] }
+ package func updateSlot(_ id: String, _ body: (inout Slot) -> Void) {
+ if let i = slots.firstIndex(where: { $0.id == id }) { body(&slots[i]) }
+ }
+
+ /// A build may start: the repository is usable, the base game and the keys are there, the tools are all present and none runs.
+ package var canBuild: Bool { repo.isRepo && slot("base").ok && slot("keys").ok && deps.allPresent && !running }
+
+ /// A line for the build card's note, from a store that has no card of its own (the dependency store's failed install).
+ package func note(_ text: String) { doneNote = text }
+
+ // MARK: Ending a build
+
+ package func fail(_ why: String) { running = false; doneNote = why; say("✗ " + why); cleanupStaging() }
+
+ package func stop() {
+ guard running, !stopping, let proc, proc.isRunning else { return }
+ stopping = true
+ ProcessGroups.endGroup(proc.processIdentifier) // the script and every tool it started
+ }
+
+ package func cleanupStaging() {
+ staging = nil // the folder stays for the next build of this game (#132, InputStaging)
+ }
+
+ /// A stopped build leaves no half-finished stages behind: the progress starts empty again.
+ package func resetProgress() { stages = []; log.clear() }
+
+ package func markAllDone() { for i in stages.indices where stages[i].state != .failed { stages[i].state = .done } }
+
+ // MARK: Output parsing
+
+ package func say(_ s: String) { append(s + "\n") }
+ package func append(_ s: String) { log.append(s) }
+
+ /// Split into lines (the pipe delivers arbitrary chunks) and turn the script's progress into the stage list.
+ /// `--progress json` writes one event per line (stage, step, progress with done / total / frac / eta, stage_end,
+ /// say), a count change at most every half second; anything else on the pipe (a tool's traceback) is log text.
+ /// The older `--progress lines` form is still understood:
+ /// [12:00:01] [2/7] extract v720896 …
+ /// [12:00:20] ✓ [2/7] extract v720896 (0:19): 30,000 files, 3.4 GB
+ package func ingest(_ chunk: String) {
+ for line in log.feed(chunk) { handle(line) }
+ }
+
+ package func flushLines() {
+ if let rest = log.flush() { handle(rest) }
+ }
+
+ package func handle(_ line: String) {
+ if line.hasPrefix("{"), let data = line.data(using: .utf8),
+ let event = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], let kind = event["ev"] as? String {
+ return handleEvent(kind, event)
+ }
+ append(line + "\n")
+ noteChainChange(line)
+ guard let s = BuildProgress.parseStage(line) else { return }
+ if let i = stages.firstIndex(where: { $0.id == s.k }) {
+ if !s.name.isEmpty { stages[i].name = Stage.localizedName(s.name, t) }
+ if s.state != .pending { stages[i].state = s.state }
+ if !s.detail.isEmpty { stages[i].detail = s.detail }
+ stages[i].percent = s.percent
+ } else if s.state != .pending {
+ stages.append(Stage(id: s.k, name: Stage.localizedName(s.name, t), state: s.state, detail: s.detail, percent: s.percent, started: Date()))
+ stages.sort { $0.id < $1.id }
+ }
+ }
+
+ /// The script marks a shader-chain bump with this tag: the cached libraries cannot be
+ /// reused and this build recompiles them. An alert, not a log line — the report's question
+ /// ("why is it building shaders again, the artifacts are on the drive") came from exactly
+ /// this moment passing unnoticed. Once per build: the pipe delivers arbitrary chunks.
+ /// (A plain line, or the message of a `say` event in `--progress json`.)
+ package func noteChainChange(_ text: String) {
+ guard text.contains("[NOTE] chain-changed"), !chainNoteShown else { return }
+ chainNoteShown = true
+ showNotice(t("msg.chainChanged"))
+ }
+
+ /// One event of `--progress json`: the stage list follows it, and the log gets a readable line (no count updates).
+ package func handleEvent(_ kind: String, _ e: [String: Any]) {
+ let k = (e["k"] as? NSNumber)?.intValue ?? 0
+ func stage(_ update: (inout Stage) -> Void) {
+ if let i = stages.firstIndex(where: { $0.id == k }) { update(&stages[i]) }
+ else { var s = Stage(id: k, name: Stage.localizedName(e["name"] as? String ?? "", t)); update(&s); stages.append(s); stages.sort { $0.id < $1.id } }
+ }
+ switch kind {
+ case "stage":
+ let name = e["name"] as? String ?? "", step = e["step"] as? String ?? ""
+ let n = (e["n"] as? NSNumber)?.intValue ?? 0
+ append("[\(k)/\(n)] \(name)" + (step.isEmpty ? "" : " · \(step)") + " …\n")
+ stage { $0.name = Stage.localizedName(name, t); $0.state = .running; $0.detail = step; $0.percent = nil; $0.started = Date(); $0.eta = nil }
+ case "step":
+ let step = e["step"] as? String ?? ""
+ append(" · \(step)\n")
+ stage { $0.detail = step; $0.percent = nil; $0.eta = nil }
+ case "progress":
+ let fraction = (e["frac"] as? NSNumber)?.doubleValue
+ let detail = BuildProgress.progressDetail(e)
+ let eta = (e["eta"] as? NSNumber)?.doubleValue
+ stage { $0.percent = fraction.map { $0 * 100 }; $0.detail = detail; $0.eta = eta; $0.etaAt = eta == nil ? nil : Date() }
+ case "stage_end":
+ let ok = e["ok"] as? Bool ?? true, summary = e["summary"] as? String ?? ""
+ let elapsed = BuildProgress.duration((e["elapsed"] as? NSNumber)?.doubleValue ?? 0)
+ append("\(ok ? "✓" : "✗") \(e["name"] as? String ?? "") (\(elapsed))" + (summary.isEmpty ? "" : ": \(summary)") + "\n")
+ stage { $0.state = ok ? .done : .failed; $0.detail = summary; $0.percent = ok ? 100 : $0.percent; $0.eta = nil }
+ case "say":
+ let msg = e["msg"] as? String ?? ""
+ append(msg + "\n")
+ noteChainChange(msg)
+ default: break
+ }
+ }
+}
diff --cc frontend/Tests/NX2AppleTests/ShellInstallTests.swift
index 62ca961d,a2c1ed95..22e5405e
--- a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
+++ b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
@@@ -852,7 -891,12 +892,12 @@@ import NXMode
}
finish { model.installShell(framework: f.framework, titleID: titleID, name: "Test Game", archive: f.archive) }
XCTAssertEqual(model.failure?.kind, .shellDataIncomplete)
- XCTAssertTrue(model.doneNote.hasPrefix(String(format: model.t("shell.copyIncomplete"), modelStores.deviceStore.deviceName(modelStores.deviceStore.installDevice), "").components(separatedBy: ": ").first ?? "-"), model.doneNote)
+ // The sentence before the tool's error, in every language: it used to split the English template on ": ", which
+ // never matches a full-width colon (a Chinese macOS ran this test red on main).
+ let marker = "\u{1}"
- let prefix = String(format: model.t("shell.copyIncomplete"), model.deviceName(model.installDevice), marker)
++ let prefix = String(format: model.t("shell.copyIncomplete"), modelStores.deviceStore.deviceName(modelStores.deviceStore.installDevice), marker)
+ .components(separatedBy: marker).first ?? "-"
+ XCTAssertTrue(model.doneNote.hasPrefix(prefix), model.doneNote)
XCTAssertFalse(model.done)
XCTAssertEqual(plans.count, 1)
XCTAssertEqual(plans.first?.connection, .wired)