Skip to content

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

The launcher walks a new player through setup with the real detection and installs

v0lumehib2dcf5d1cb99
diff --git a/frontend/Onboarding.md b/frontend/Onboarding.md
index 4794ec34..03df3fd6 100644
--- a/frontend/Onboarding.md
+++ b/frontend/Onboarding.md
@@ -1,6 +1,6 @@
# First-run UI preview
-The guided setup is opt-in. Without a recognized `NSPB_ONBOARDING_DEMO` value, the app opens the existing launcher exactly as before. The preview never instantiates `BuildModel`, detects tools, reads selected files, installs anything or opens the App Store. Its exit screen stands in for opening the library.
+With a recognized `NSPB_ONBOARDING_DEMO` value the app shows a scripted preview of the guided setup. The preview never instantiates `BuildModel`, detects tools, reads selected files, installs anything or opens the App Store. Its exit screen stands in for opening the library. Without it, `RootView` (`OnboardingRoot.swift`) runs the real flow described under "The real driver" below, or opens the launcher.
From the repository root, enter `frontend`, then run one scenario:
@@ -19,7 +19,7 @@ NSPB_ONBOARDING_DEMO=noGames swift run
- `xcodeFailed`: setup fails with a plain explanation and expandable diagnostics. Retry, then Finish setup to recover.
- `noGames`: the mock folder scan finds no NSPs and shows a hint. Use Back or Set up later.
-Set up later preserves an in-memory snapshot; Resume setup restores it. Persistence across app launches is deliberately left to the real driver.
+Set up later preserves an in-memory snapshot; Resume setup restores it. The mock persists nothing; the real driver does (below).
## Wiring contract
@@ -48,6 +48,15 @@ Automatic advancement belongs in the driver. The mock gives completed Xcode and
Persist the current step and selections before handling `skipForLater`; inject the restored state on the next launch and revalidate external prerequisites in the real driver. `MockOnboardingDriver(state:)` demonstrates restoration without preferences or file I/O. Its `animated: false` initializer disables scheduled changes for deterministic tests.
+## The real driver
+
+`LiveOnboardingDriver` (`LiveOnboardingDriver.swift`) implements the contract over the launcher's own `BuildModel` and `GameLibrary`, which `RootView` shares with `ContentView`. Everything it does to the machine goes through `OnboardingEnvironment`, so the tests use fakes.
+
+- When it shows: on launch, unless `onboarding.completed` is set or setup is already complete (all tools present, a keys file known, a games folder set; a complete one is marked done without being shown). Settings has "Run setup again". Set up later stores the step, platform and an in-progress flag in `UserDefaults`; the next launch resumes there and revalidates (a stored step past Xcode returns to Xcode when Xcode no longer holds).
+- Detection and installs are `BuildModel.checkDeps` / `deps` / `installDep`, one install at a time (Python, .NET, then Homebrew and the formulas). Homebrew waits for Xcode to be ready. The xcode row asks for the iOS SDK only when the stored platform is not Mac-only or builds target an iPhone (`BuildModel.needsIOSPlatform`).
+- Xcode: missing opens the App Store and polls /Applications for it; setup is one administrator prompt (`OnboardingAdmin.source`: `xcode-select -s`, `xcodebuild -license accept`, `-runFirstLaunch`), then the Metal Toolchain and, for iPhone or both, the iOS platform without it. A cancelled prompt returns to `needsSetup`.
+- Keys are found in `~/.switch`, `~/Downloads` and the games folder, checked by `KeyCheck`, and only the path goes into the keys slot. Games use `GameLibrary.sourceGames`, `BuildModel.scan` and `GameLibrary.setFolder`.
+
## Presentation choices
The flow retains the launcher's dark appearance, palette, Manrope, cream capsule primary button, secondary button style and 1.8:1 cover crop. The app currently forces dark mode, so onboarding does too. Background preparation stays beside Xcode, while a fixed footer keeps the primary action visible at the launcher's 900 × 680 minimum window size. Long content scrolls. The two Xcode cards share one fixed height across all of that step's states (content scrolls inside a card rather than resizing it), and the platform, keys and games cards keep their size between states.
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 2b7a33e8..ffa12b77 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -106,7 +106,11 @@ final class BuildModel: ObservableObject {
/// --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 var target = (UserDefaults.standard.string(forKey: "buildTarget") ?? "ios") {
- didSet { UserDefaults.standard.set(target, forKey: "buildTarget") }
+ didSet {
+ UserDefaults.standard.set(target, forKey: "buildTarget")
+ // A Mac-only setup needs no iOS SDK for a Mac build, but does for an iPhone one (needsIOSPlatform)
+ if oldValue != target, UserDefaults.standard.string(forKey: OnboardingDefaults.platform) == "mac" { checkDeps() }
+ }
}
/// 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
@@ -851,7 +855,7 @@ final class BuildModel: ObservableObject {
var dlcPaths: [String] { slot("dlc").paths }
func slot(_ id: String) -> Slot { slots.first { $0.id == id } ?? slots[0] }
- private func updateSlot(_ id: String, _ body: (inout Slot) -> Void) {
+ func updateSlot(_ id: String, _ body: (inout Slot) -> Void) {
if let i = slots.firstIndex(where: { $0.id == id }) { body(&slots[i]) }
}
@@ -2078,7 +2082,18 @@ final class BuildModel: ObservableObject {
return FileManager.default.fileExists(atPath: dir, isDirectory: &isDir) && isDir.boolValue
}
- nonisolated static func detectDepsSync() -> [Dep] {
+ /// The commands that fetch Xcode's two downloadable parts; the setup panel and the guided setup run the same ones.
+ nonisolated static let metalToolchainCmd = ["/usr/bin/xcodebuild", "-downloadComponent", "MetalToolchain"]
+ nonisolated static let iosPlatformCmd = ["/usr/bin/xcodebuild", "-downloadPlatform", "iOS"]
+
+ /// Whether the xcode row asks for the iOS SDK. Always, as before, unless the guided setup stored a Mac-only choice
+ /// and builds are for the Mac: upstream no longer needs the iOS SDK for a Mac build (c464cb24).
+ nonisolated static func needsIOSPlatform(defaults: UserDefaults = .standard) -> Bool {
+ guard defaults.string(forKey: OnboardingDefaults.platform) == "mac" else { return true }
+ return (defaults.string(forKey: "buildTarget") ?? "ios") != "mac-app"
+ }
+
+ nonisolated static func detectDepsSync(needsIOS: Bool = BuildModel.needsIOSPlatform()) -> [Dep] {
var out: [Dep] = []
// Xcode.app alone is not enough: since Xcode 15 the iOS platform ships as a separate
@@ -2088,17 +2103,15 @@ final class BuildModel: ObservableObject {
// /Applications/Xcode-beta.app and the hard-coded check called that "no Xcode" (#21).
let xcodePresent = Self.developerDirExists()
&& FileManager.default.isExecutableFile(atPath: "/usr/bin/xcodebuild")
- let iosSDK = xcodePresent && runOK("/usr/bin/xcrun", ["--sdk", "iphoneos", "--show-sdk-version"])
+ let iosSDK = xcodePresent && (!needsIOS || runOK("/usr/bin/xcrun", ["--sdk", "iphoneos", "--show-sdk-version"]))
out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint",
present: iosSDK,
detail: iosSDK ? "" : (xcodePresent ? "dep.xcode.noSDK" : ""),
- installCmd: iosSDK ? [] : (xcodePresent
- ? ["/usr/bin/xcodebuild", "-downloadPlatform", "iOS"]
- : [])))
+ installCmd: iosSDK ? [] : (xcodePresent ? iosPlatformCmd : [])))
let mt = runOK("/usr/bin/xcrun", ["-sdk", "macosx", "metal", "--version"])
out.append(Dep(id: "metal", name: "dep.metal", hint: "dep.metal.hint",
- present: mt, installCmd: ["xcodebuild", "-downloadComponent", "MetalToolchain"]))
+ present: mt, installCmd: metalToolchainCmd))
let brew = firstExisting(["/opt/homebrew/bin/brew", "/usr/local/bin/brew"])
out.append(Dep(id: "brew", name: "dep.brew", hint: "dep.brew.hint", present: brew != nil,
@@ -2237,6 +2250,7 @@ struct BuilderView: View {
var onOpenSettings: () -> Void = {}
var onChooseLibraryFolder: () -> Void = {}
var onOpenControls: () -> Void = {}
+ var onRunSetup: (() -> Void)? // the guided first-run setup, again (nil where there is none)
var controlChanges = 0
@AppStorage(BuildNotice.defaultsKey) private var notifyBuilds = true // BuildNotifications.swift
@State private var extrasOpen = false
@@ -2702,6 +2716,13 @@ struct BuilderView: View {
.padTarget("set.notify", scope: "main") { notifyBuilds.toggle() }
}
divider
+ if let onRunSetup {
+ row(m.t("settings.setup"), detail: m.t("settings.setupNote")) {
+ Button(m.t("settings.setupBtn"), action: onRunSetup)
+ .padTarget("set.setup", scope: "main") { onRunSetup() }
+ }
+ divider
+ }
row("NX2Apple", detail: String(format: m.t("app.version"), BuildModel.appVersion),
dot: m.appStaged != nil ? LauncherPalette.ready : nil) {
if m.appBusy { ProgressView().controlSize(.small) }
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 9a035615..6e844631 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -45,12 +45,14 @@ struct ContentView: View {
@StateObject private var toolsAge: ToolsAge
@State private var buildCommit = "" // the checkout's commit when the running build started (ToolsAge)
private var performStartupChecks: Bool
+ private let onRunSetup: (() -> Void)? // Settings' "Run setup again"; the root view supplies it
private let qaManage: (open: Bool, ring: Bool) // visual QA: the Manage menu open at launch, with the controller's focus ring or without
@Environment(\.scenePhase) private var scenePhase
init(model: BuildModel? = nil, library: GameLibrary? = nil, initialPage: LauncherPage = .library,
activeBuildID: UUID? = nil, performStartupChecks: Bool = true, search: String? = nil, olderTools: Set<UUID> = [],
- manageOpen: Bool = false, padRing: Bool = false) {
+ manageOpen: Bool = false, padRing: Bool = false, onRunSetup: (() -> Void)? = nil) {
+ self.onRunSetup = onRunSetup
qaManage = (manageOpen, padRing)
if let search { _search = State(initialValue: search); _searching = State(initialValue: true) } // visual QA: the bar with its field open
_toolsAge = StateObject(wrappedValue: ToolsAge(older: olderTools)) // visual QA: games marked without a checkout to compare
@@ -74,7 +76,7 @@ struct ContentView: View {
} else {
BuilderView(m: m, library: library, settings: page == .settings, onViewGame: { page = .library },
onOpenSettings: { page = .settings }, onChooseLibraryFolder: chooseLibraryFolder,
- onOpenControls: { controlsOpen = true }, controlChanges: controls.changeCount)
+ onOpenControls: { controlsOpen = true }, onRunSetup: onRunSetup, controlChanges: controls.changeCount)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
if m.running || page == .library { activityBar }
diff --git a/frontend/Sources/NSPortBuilder/LiveOnboardingDriver.swift b/frontend/Sources/NSPortBuilder/LiveOnboardingDriver.swift
new file mode 100644
index 00000000..cf8e2c81
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/LiveOnboardingDriver.swift
@@ -0,0 +1,661 @@
+import AppKit
+import Combine
+
+/// UserDefaults keys of the guided setup. `platform` is also read by `BuildModel.needsIOSPlatform`.
+enum OnboardingDefaults {
+ static let completed = "onboarding.completed"
+ static let step = "onboarding.step"
+ static let platform = "onboarding.platform"
+ static let inProgress = "onboarding.inProgress"
+}
+
+/// What `xcode-select`, `xcodebuild -license check` and `-checkFirstLaunchStatus` say, without anything of the machine's
+/// other state. License and first launch only count while an Xcode (not the Command Line Tools) is selected.
+struct XcodeProbe: Equatable {
+ var appPath: String? // an Xcode.app: the selected one, else the first in /Applications
+ var selectedIsXcode = false // `xcode-select -p` points into an Xcode.app, not the Command Line Tools
+ var licenseAccepted = false
+ var firstLaunchDone = false
+ var developerDir: String? { appPath.map { $0 + "/Contents/Developer" } }
+ var needsAdmin: Bool { !(selectedIsXcode && licenseAccepted && firstLaunchDone) }
+}
+
+enum AdminResult: Equatable { case ok, cancelled, failed(String) }
+
+/// Everything the driver does to the machine, injectable: tests give fakes, so none of them runs xcodebuild, sudo or a network.
+struct OnboardingEnvironment {
+ var defaults: UserDefaults = .standard
+ var home = NSHomeDirectory()
+ var freeBytes: () -> Int64? = { OnboardingEnvironment.homeVolumeFreeBytes() }
+ /// A cheap look at /Applications, for the poll while the App Store installs Xcode.
+ var xcodeInstalled: () -> Bool = { OnboardingEnvironment.xcodeApps().first != nil }
+ var xcodeProbe: () async -> XcodeProbe = { await OnboardingEnvironment.liveProbe() }
+ /// One administrator prompt around the whole script (`OnboardingAdmin.source`).
+ var runAdmin: (_ developerDir: String) async -> AdminResult = { await OnboardingAdmin.run(developerDir: $0) }
+ /// A tool without administrator rights; `line` gets its output as it comes. Returns success and the combined output.
+ var run: (_ command: [String], _ line: @escaping (String) -> Void) async -> (ok: Bool, output: String) = { await OnboardingEnvironment.liveRun($0, $1) }
+ /// Detection again, finished when it has published (`BuildModel.checkDeps`).
+ var detectDeps: (BuildModel) async -> Void = { await $0.refreshDepsAndWait() }
+ /// One install through the launcher's own mechanics (`BuildModel.installDep`); its end shows as a new detection.
+ var installDep: (BuildModel, BuildModel.Dep) -> Void = { $0.installDep($1) }
+ var openURL: (URL) -> Void = { NSWorkspace.shared.open($0) }
+ var keyCheck: (_ keys: String, _ base: String) async -> KeyCheck.Outcome = { keys, base in
+ await Task.detached { KeyCheck.run(KeyCheck.Inputs(keys: keys, files: base.isEmpty ? [] : [base])) }.value
+ }
+ var scanGames: (_ folder: URL, _ repo: String) async -> [LibraryGame] = { folder, repo in
+ await Task.detached { GameLibrary.sourceGames(in: folder, repo: repo) }.value
+ }
+ var fetchArtwork: (_ titleIDs: [String]) async -> Void = { ids in _ = await ArtworkStore.shared.fetchMissing(ids) }
+ var pollInterval = 3.0
+ var advanceDelay = 0.7
+
+ /// The files `~/.switch/prod.keys`, `~/Downloads/prod.keys` and the games folder's, whichever exist.
+ func keyCandidates(gamesFolder: String) -> [String] {
+ var paths = [home + "/.switch/prod.keys", home + "/Downloads/prod.keys"]
+ if !gamesFolder.isEmpty { paths += [gamesFolder + "/prod.keys", gamesFolder + "/keys/prod.keys"] }
+ return paths.filter { FileManager.default.fileExists(atPath: $0) }
+ }
+
+ static func homeVolumeFreeBytes() -> Int64? {
+ let values = try? URL(fileURLWithPath: NSHomeDirectory())
+ .resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
+ return values?.volumeAvailableCapacityForImportantUsage
+ }
+
+ /// Xcode*.app in /Applications that hold a working xcodebuild (the App Store creates the folder before it is complete).
+ static func xcodeApps() -> [String] {
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: "/Applications")) ?? []
+ return names.filter { $0.hasPrefix("Xcode") && $0.hasSuffix(".app") }.sorted()
+ .map { "/Applications/" + $0 }
+ .filter { FileManager.default.isExecutableFile(atPath: $0 + "/Contents/Developer/usr/bin/xcodebuild") }
+ }
+
+ static func liveProbe() async -> XcodeProbe {
+ await Task.detached {
+ var probe = XcodeProbe()
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: "/usr/bin/xcode-select"); p.arguments = ["-p"]
+ let pipe = Pipe(); p.standardOutput = pipe; p.standardError = FileHandle.nullDevice
+ var selected = ""
+ if (try? p.run()) != nil {
+ let data = pipe.fileHandleForReading.readDataToEndOfFile(); p.waitUntilExit()
+ if p.terminationStatus == 0 { selected = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" }
+ }
+ if let r = selected.range(of: ".app/Contents/Developer") {
+ probe.selectedIsXcode = true
+ probe.appPath = String(selected[..<r.lowerBound]) + ".app"
+ } else { probe.appPath = xcodeApps().first }
+ if probe.selectedIsXcode {
+ probe.licenseAccepted = BuildModel.runOK("/usr/bin/xcodebuild", ["-license", "check"])
+ probe.firstLaunchDone = BuildModel.runOK("/usr/bin/xcodebuild", ["-checkFirstLaunchStatus"])
+ }
+ return probe
+ }.value
+ }
+
+ static func liveRun(_ command: [String], _ line: @escaping (String) -> Void) async -> (ok: Bool, output: String) {
+ await Task.detached {
+ final class Box: @unchecked Sendable {
+ private let lock = NSLock(); private var buffer = ""
+ func add(_ l: String) { lock.lock(); buffer += l + "\n"; lock.unlock() }
+ var text: String { lock.lock(); defer { lock.unlock() }; return buffer }
+ }
+ let box = Box()
+ let ok = BuildModel.runCaptured(command, env: ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": NSHomeDirectory(), "USER": NSUserName()]) { l in
+ box.add(l)
+ line(l)
+ }
+ return (ok, box.text)
+ }.value
+ }
+}
+
+/// The one administrator prompt: select Xcode, accept its license, run its first-launch install.
+enum OnboardingAdmin {
+ /// AppleScript for `do shell script ... with administrator privileges`. The Xcode path goes through AppleScript's own
+ /// `quoted form of`, so a space or a quote in it cannot break out of the command.
+ static func source(developerDir: String) -> String {
+ let literal = developerDir.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
+ return "do shell script \"/usr/bin/xcode-select -s \" & quoted form of \"\(literal)\" "
+ + "& \" && /usr/bin/xcodebuild -license accept && /usr/bin/xcodebuild -runFirstLaunch\" with administrator privileges"
+ }
+
+ static func run(developerDir: String) async -> AdminResult {
+ await withCheckedContinuation { continuation in
+ DispatchQueue.global(qos: .userInitiated).async {
+ var error: NSDictionary?
+ _ = NSAppleScript(source: source(developerDir: developerDir))?.executeAndReturnError(&error)
+ guard let error else { return continuation.resume(returning: .ok) }
+ let number = error["NSAppleScriptErrorNumber"] as? Int
+ // -128: the person cancelled the password prompt
+ continuation.resume(returning: number == -128 ? .cancelled : .failed((error["NSAppleScriptErrorMessage"] as? String) ?? "\(error)"))
+ }
+ }
+ }
+}
+
+extension BuildModel {
+ /// `checkDeps()`, finished: returns once the new detection has been published.
+ func refreshDepsAndWait() async {
+ checkDeps()
+ for await checked in $depsChecked.values where checked { break }
+ }
+}
+
+/// What the app does on launch, and from where the launcher asks for the setup again.
+enum OnboardingLaunch {
+ /// Setup counts as complete when the tools are all present, a keys file is known and a games folder is set. A player
+ /// who has built a game already has all three in effect.
+ static func setupComplete(depsPresent: Bool, keysKnown: Bool, gamesKnown: Bool) -> Bool { depsPresent && keysKnown && gamesKnown }
+ static func shouldShow(completed: Bool, setupComplete: Bool) -> Bool { !completed && !setupComplete }
+}
+
+/// The real driver: the guided setup over the launcher's own `BuildModel` (detection and installs) and `GameLibrary`.
+///
+/// One value, `state`, is what the view draws. Detection comes from `model.deps` (refreshed through `model.checkDeps`),
+/// installs run through `model.installDep` one at a time, the keys and game slots are the ones the Builds page uses, and
+/// the games folder is the library's. Nothing about prod.keys' content is kept: the keys are checked by `KeyCheck`, and
+/// only their path is stored.
+@MainActor final class LiveOnboardingDriver: OnboardingDriver {
+ @Published private(set) var state = OnboardingState()
+ let model: BuildModel
+ let library: GameLibrary
+ private let env: OnboardingEnvironment
+ /// Called once when the setup closes: to the launcher, either way.
+ var onExit: (OnboardingState.Exit) -> Void = { _ in }
+
+ private var probe = XcodeProbe()
+ private var probed = false
+ private var waitingForXcode = false // Get Xcode was pressed: poll /Applications
+ private var xcodeBusy = false // the finish-setup run owns state.xcode
+ private var backgroundStarted = false
+ private var failedDeps: [String: OnboardingFailure] = [:]
+ private var currentInstall: String?
+ private var sawRecheck = false
+ private var logMark = 0
+ private var suppressAdvance = false
+ private var tasks: [String: Task<Void, Never>] = [:]
+ private var subscription: AnyCancellable?
+
+ private func t(_ key: String) -> String { L10n.string(key, model.lang) }
+
+ /// `fresh` ignores a stored step (Run setup again); otherwise a stored, unfinished run resumes where it stopped.
+ init(model: BuildModel, library: GameLibrary, env: OnboardingEnvironment = OnboardingEnvironment(), fresh: Bool = false) {
+ self.model = model; self.library = library; self.env = env
+ let d = env.defaults
+ if fresh {
+ d.removeObject(forKey: OnboardingDefaults.step); d.removeObject(forKey: OnboardingDefaults.platform)
+ d.set(false, forKey: OnboardingDefaults.inProgress)
+ }
+ if let raw = d.string(forKey: OnboardingDefaults.platform), let platform = OnboardingPlatform(rawValue: raw) {
+ state.platform = .selected(platform)
+ }
+ if d.bool(forKey: OnboardingDefaults.inProgress), let raw = d.string(forKey: OnboardingDefaults.step),
+ let step = OnboardingStep(rawValue: raw) {
+ // A stored step beyond Platform without a platform cannot be right; start from the choice.
+ state.step = (step.index > OnboardingStep.platform.index && state.selectedPlatform == nil) ? .platform : step
+ }
+ updateWelcome()
+ }
+ deinit { tasks.values.forEach { $0.cancel() } }
+
+ /// Starts watching the model and revalidates the stored step. Called once by whoever shows the view.
+ func activate() {
+ subscription = model.$depsChecked.removeDuplicates().sink { [weak self] checked in
+ guard let self else { return }
+ if !checked { self.sawRecheck = true; return }
+ self.spawn("refresh") { d in await d.modelDidRefresh() }
+ }
+ spawn("activate") { d in
+ await d.revalidate()
+ d.enter(d.state.step)
+ }
+ }
+
+ // MARK: Intents
+
+ func start() {
+ guard state.step == .welcome, state.exit == nil else { return }
+ env.defaults.set(true, forKey: OnboardingDefaults.inProgress)
+ next()
+ }
+
+ func choosePlatform(_ platform: OnboardingPlatform) {
+ guard state.step == .platform, state.exit == nil else { return }
+ state.platform = .selected(platform)
+ env.defaults.set(platform.rawValue, forKey: OnboardingDefaults.platform) // before the detection below reads it
+ switch platform { // the Builds page's target follows the choice; "both" leaves it as it is
+ case .mac: model.target = "mac-app"
+ case .iphone: model.target = "ios"
+ case .both: break
+ }
+ updateWelcome()
+ backgroundStarted = true
+ spawn("platform") { d in
+ await d.env.detectDeps(d.model) // the xcode row's iOS requirement just changed
+ await d.modelDidRefresh()
+ }
+ }
+
+ func getXcode() {
+ guard state.step == .xcode, state.xcode == .missing, state.exit == nil else { return }
+ waitingForXcode = true
+ state.xcode = .downloading
+ env.openURL(URL(string: "macappstore://apps.apple.com/app/id497799835")!)
+ pollForXcode()
+ }
+
+ func finishXcodeSetup() {
+ guard state.step == .xcode, state.xcode == .needsSetup, state.exit == nil else { return }
+ state.xcode = .settingUp
+ xcodeBusy = true
+ spawn("finish") { d in await d.runFinishXcode() }
+ }
+
+ func retry(_ step: OnboardingStep) {
+ guard state.step == step, state.exit == nil else { return }
+ switch step {
+ case .xcode:
+ failedDeps.removeAll()
+ if case .failed = state.xcode { state.xcode = .needsSetup }
+ xcodeBusy = false
+ spawn("retry") { d in await d.modelDidRefresh() }
+ case .keys: enter(.keys)
+ case .games: state.games = .empty; enter(.games)
+ default: break
+ }
+ }
+
+ func chooseKeys(_ url: URL) {
+ guard state.step == .keys, state.exit == nil else { return }
+ validateKeys(url)
+ }
+
+ func confirmKeys() {
+ guard state.step == .keys, state.exit == nil, case let .found(url) = state.keys else { return }
+ validateKeys(url)
+ }
+
+ func chooseGames(_ url: URL) {
+ guard state.step == .games, state.exit == nil else { return }
+ state.games = .scanning
+ spawn("games") { d in await d.scanGames(url) }
+ }
+
+ func back() {
+ let old = state.step
+ state.back()
+ guard old != state.step else { return }
+ suppressAdvance = true // a step left behind stays reachable: Back must not bounce forward again
+ enter(state.step)
+ }
+
+ func next() {
+ let old = state.step
+ state.next()
+ guard old != state.step else { return }
+ suppressAdvance = false
+ enter(state.step)
+ }
+
+ func skipForLater() {
+ guard state.exit == nil else { return }
+ persistStep()
+ env.defaults.set(true, forKey: OnboardingDefaults.inProgress)
+ close(.later)
+ }
+
+ func openLibrary() {
+ guard state.step == .done, state.primaryEnabled else { return }
+ env.defaults.set(true, forKey: OnboardingDefaults.completed)
+ env.defaults.set(false, forKey: OnboardingDefaults.inProgress)
+ env.defaults.removeObject(forKey: OnboardingDefaults.step)
+ if library.selectedID == nil { library.selectedID = library.games.first?.id }
+ close(.library)
+ }
+
+ private func close(_ exit: OnboardingState.Exit) {
+ state.exit = exit
+ tasks.values.forEach { $0.cancel() }; tasks.removeAll()
+ subscription = nil
+ onExit(exit)
+ }
+
+ // MARK: Steps
+
+ /// Waits for the work started so far (tests; the view never needs it).
+ func settle() async {
+ for _ in 0..<6 { for task in Array(tasks.values) { await task.value } }
+ }
+
+ private func persistStep() { env.defaults.set(state.step.rawValue, forKey: OnboardingDefaults.step) }
+
+ private func spawn(_ name: String, _ body: @escaping (LiveOnboardingDriver) async -> Void) {
+ tasks[name]?.cancel()
+ tasks[name] = Task { @MainActor [weak self] in
+ guard let self, self.state.exit == nil else { return }
+ await body(self)
+ }
+ }
+
+ func enter(_ step: OnboardingStep) {
+ guard state.exit == nil else { return }
+ persistStep()
+ if step != .xcode { tasks["poll"]?.cancel(); tasks["poll"] = nil } // the Xcode poll stops when its step is left
+ switch step {
+ case .welcome: updateWelcome()
+ case .platform: break
+ case .xcode:
+ if state.selectedPlatform != nil { backgroundStarted = true }
+ if waitingForXcode { pollForXcode() }
+ spawn("enter.xcode") { d in
+ if !d.model.depsChecked { await d.env.detectDeps(d.model) }
+ await d.modelDidRefresh()
+ }
+ case .keys:
+ state.keys = .searching
+ spawn("enter.keys") { d in await d.searchKeys() }
+ case .games:
+ spawn("enter.games") { d in await d.enterGames() }
+ case .done:
+ if state.done == .celebrating {
+ spawn("done") { d in
+ try? await Task.sleep(nanoseconds: UInt64(d.env.advanceDelay * 0.5 * 1_000_000_000))
+ d.state.done = .ready
+ }
+ }
+ }
+ }
+
+ /// A stored step past Xcode is only kept while Xcode and the tools still hold; otherwise the player returns to Xcode.
+ func revalidate() async {
+ guard state.step.index > OnboardingStep.xcode.index else { return }
+ if !model.depsChecked { await env.detectDeps(model) }
+ probe = await env.xcodeProbe(); probed = true
+ let (xcode, _) = OnboardingXcode.evaluate(probe: probe, metalReady: dep("metal")?.present ?? false,
+ iosReady: dep("xcode")?.present ?? false, includesIOS: state.selectedPlatform?.includesIOS == true)
+ if xcode != .ready { state.step = .xcode; persistStep() }
+ }
+
+ // MARK: Welcome
+
+ /// Rough room the setup takes, not a measurement: Xcode when it is missing (about 3 GB to download, about 12 GB installed,
+ /// and the room twice over while it unpacks: 15), the Metal Toolchain (about 1), the iOS platform when the player plays
+ /// on an iPhone (about 8, as the Platform step says), and the tools, Python packages, .NET SDK and caches (about 4).
+ /// Platform is not chosen yet at Welcome, so it counts the Mac only; choosePlatform computes it again.
+ nonisolated static func neededGB(xcodeMissing: Bool, includesIOS: Bool) -> Int {
+ (xcodeMissing ? 15 : 0) + 1 + (includesIOS ? 8 : 0) + 4
+ }
+
+ func updateWelcome() {
+ let needed = Self.neededGB(xcodeMissing: probed ? probe.appPath == nil : !env.xcodeInstalled(),
+ includesIOS: state.selectedPlatform?.includesIOS == true)
+ // Whole GB as Finder counts them (10^9). Without a reading the volume is taken to have room: nothing to warn about.
+ let free = env.freeBytes().map { Int($0 / 1_000_000_000) } ?? needed
+ state.welcome = .requirements(freeGB: free, neededGB: needed)
+ }
+
+ // MARK: Xcode
+
+ private func dep(_ id: String) -> BuildModel.Dep? { model.deps.first { $0.id == id } }
+
+ /// Every detection that finished: Xcode's state, the background tasks, and the next install.
+ func modelDidRefresh() async {
+ guard model.depsChecked, state.exit == nil else { return }
+ concludeInstall()
+ await refreshXcode()
+ recomputeBackground()
+ pumpInstalls()
+ advanceIfReady()
+ }
+
+ func refreshXcode() async {
+ guard !xcodeBusy else { return }
+ probe = await env.xcodeProbe(); probed = true
+ guard !xcodeBusy, state.exit == nil else { return }
+ let includesIOS = state.selectedPlatform?.includesIOS == true
+ let (xcode, setup) = OnboardingXcode.evaluate(probe: probe, metalReady: dep("metal")?.present ?? false,
+ iosReady: dep("xcode")?.present ?? false, includesIOS: includesIOS)
+ state.setup = setup
+ if case .failed = state.xcode, xcode != .ready { return } // a failure stays until Retry
+ if xcode == .missing {
+ state.xcode = waitingForXcode ? .downloading : .missing
+ } else {
+ waitingForXcode = false
+ state.xcode = xcode
+ }
+ updateWelcome()
+ }
+
+ /// Looks for an Xcode every few seconds, cheaply (a folder listing), until one is there or the step is left.
+ private func pollForXcode() {
+ spawn("poll") { d in
+ while !Task.isCancelled, d.state.step == .xcode, d.state.exit == nil {
+ try? await Task.sleep(nanoseconds: UInt64(d.env.pollInterval * 1_000_000_000))
+ if Task.isCancelled { return }
+ if d.env.xcodeInstalled() {
+ d.waitingForXcode = false
+ await d.refreshXcode()
+ d.advanceIfReady()
+ return
+ }
+ }
+ }
+ }
+
+ func runFinishXcode() async {
+ defer { xcodeBusy = false }
+ let includesIOS = state.selectedPlatform?.includesIOS == true
+ func fail(_ key: String, _ details: String) {
+ state.xcode = .failed(OnboardingFailure(message: t(key), details: Self.tail(details)))
+ }
+ if probe.needsAdmin {
+ guard let dir = probe.developerDir else { return fail("onboarding.error.xcode", "No Xcode.app was found.") }
+ for task in [OnboardingSetupTask.selected, .license, .firstLaunch] where state.setup[task] != .done { state.setup[task] = .running(nil) }
+ switch await env.runAdmin(dir) {
+ case .ok: break
+ case .cancelled: // not an error: the player said no to the password prompt
+ xcodeBusy = false
+ state.xcode = .needsSetup
+ for task in [OnboardingSetupTask.selected, .license, .firstLaunch] where state.setup[task] != .done { state.setup[task] = .queued }
+ return
+ case let .failed(output): return fail("onboarding.error.xcode", output)
+ }
+ probe = await env.xcodeProbe()
+ for task in [OnboardingSetupTask.selected, .license, .firstLaunch] { state.setup[task] = .done }
+ await env.detectDeps(model) // with Xcode selected, the Metal and iOS rows read differently
+ }
+ let metalMissing = !(dep("metal")?.present ?? false)
+ if metalMissing {
+ let r = await download(.metal, BuildModel.metalToolchainCmd)
+ if !r.ok { return fail("onboarding.error.metal", r.output) }
+ }
+ let iosMissing = includesIOS && !(dep("xcode")?.present ?? false)
+ if iosMissing {
+ let r = await download(.ios, BuildModel.iosPlatformCmd)
+ if !r.ok { return fail("onboarding.error.ios", r.output) }
+ }
+ await env.detectDeps(model)
+ xcodeBusy = false
+ await refreshXcode()
+ // A download that returned success but left the part missing is a failure, not an endless "set up" loop.
+ if state.xcode == .needsSetup { fail("onboarding.error.xcode", "Xcode setup finished but a part is still missing.") }
+ await modelDidRefresh()
+ }
+
+ private func download(_ task: OnboardingSetupTask, _ command: [String]) async -> (ok: Bool, output: String) {
+ state.setup[task] = .running(nil)
+ let result = await env.run(command) { [weak self] line in
+ guard let fraction = Self.progress(in: line) else { return }
+ Task { @MainActor in
+ if self?.state.setup[task] != .done { self?.state.setup[task] = .running(fraction) }
+ }
+ }
+ if result.ok { state.setup[task] = .done }
+ return result
+ }
+
+ /// The last percentage in a line of `xcodebuild -download…` output ("Downloading … 45.3% …"), as a fraction.
+ nonisolated static func progress(in text: String) -> Double? {
+ guard let re = try? NSRegularExpression(pattern: #"(\d{1,3}(?:\.\d+)?)\s*%"#) else { return nil }
+ let ns = text as NSString
+ guard let m = re.matches(in: text, range: NSRange(location: 0, length: ns.length)).last,
+ let n = Double(ns.substring(with: m.range(at: 1))) else { return nil }
+ return min(max(n / 100, 0), 1)
+ }
+
+ /// Command output for the diagnostics, trimmed to its end.
+ nonisolated static func tail(_ text: String, limit: Int = 4000) -> String {
+ text.count <= limit ? text : "…" + text.suffix(limit)
+ }
+
+ // MARK: Background tools
+
+ /// The "tools" card is Homebrew and the brew formulas the build uses: every row that is none of Xcode, Python or .NET.
+ private static let handled: Set<String> = ["xcode", "metal", "python", "dotnet"]
+ private func deps(for task: OnboardingBackgroundTask) -> [BuildModel.Dep] {
+ switch task {
+ case .python: return model.deps.filter { $0.id == "python" }
+ case .dotnet: return model.deps.filter { $0.id == "dotnet" }
+ case .tools: return model.deps.filter { !Self.handled.contains($0.id) }
+ }
+ }
+
+ func recomputeBackground() {
+ guard backgroundStarted, model.depsChecked else { return }
+ for task in OnboardingBackgroundTask.allCases {
+ let rows = deps(for: task)
+ if rows.allSatisfy(\.present) { state.background[task] = .done }
+ else if let failure = rows.compactMap({ failedDeps[$0.id] }).first { state.background[task] = .failed(failure) }
+ else if rows.contains(where: \.installing) || rows.contains(where: { $0.id == currentInstall }) { state.background[task] = .running(nil) }
+ else { state.background[task] = .queued }
+ }
+ }
+
+ /// One install at a time, in the order Python, .NET, tools. Homebrew and its formulas need Xcode's command line tools,
+ /// so they wait for Xcode to be ready; the other two start at once.
+ func pumpInstalls() {
+ guard backgroundStarted, model.depsChecked, currentInstall == nil, state.exit == nil else { return }
+ for task in OnboardingBackgroundTask.allCases {
+ if task == .tools && state.xcode != .ready { continue }
+ guard let next = deps(for: task).first(where: { !$0.present && failedDeps[$0.id] == nil && !$0.installing }) else { continue }
+ currentInstall = next.id
+ sawRecheck = false
+ logMark = model.logTail.count
+ env.installDep(model, next)
+ recomputeBackground()
+ return
+ }
+ }
+
+ /// An install finished and detection ran again: either its row is present now, or it failed.
+ private func concludeInstall() {
+ guard let id = currentInstall, sawRecheck else { return }
+ currentInstall = nil
+ if dep(id)?.present == false {
+ let name = dep(id).map { t($0.name) } ?? id
+ let output = model.logTail.count >= logMark ? String(model.logTail.dropFirst(logMark)) : model.logTail
+ failedDeps[id] = OnboardingFailure(message: String(format: t("dep.install.fail"), name), details: Self.tail(output))
+ }
+ }
+
+ // MARK: Keys
+
+ func searchKeys() async {
+ let known = model.keysPath
+ let candidates = ([known].filter { !$0.isEmpty && FileManager.default.fileExists(atPath: $0) })
+ + env.keyCandidates(gamesFolder: library.folder.isEmpty ? model.gameDir : library.folder)
+ if let first = candidates.first { state.keys = .found(URL(fileURLWithPath: first)) } else { state.keys = .empty }
+ }
+
+ private func validateKeys(_ url: URL) {
+ state.keys = .validating
+ spawn("keys") { d in
+ let scoped = url.startAccessingSecurityScopedResource() // a no-op outside a sandbox
+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }
+ let outcome = await d.env.keyCheck(url.path, d.model.basePath)
+ guard d.state.exit == nil else { return }
+ switch outcome {
+ case .fits, .cannotCheck:
+ d.model.updateSlot("keys") { $0.paths = [url.path]; $0.problem = "" }
+ d.state.keys = .valid
+ d.advanceIfReady()
+ default:
+ d.state.keys = .invalid(KeyCheck.message(outcome, d.t)) // names a key or a file, never a value
+ }
+ }
+ }
+
+ // MARK: Games
+
+ private func enterGames() async {
+ let known = library.folder.isEmpty ? model.gameDir : library.folder
+ if case .found = state.games { return }
+ if !known.isEmpty, FileManager.default.fileExists(atPath: known) { state.games = .scanning; await scanGames(URL(fileURLWithPath: known)) }
+ else { state.games = .empty }
+ }
+
+ func scanGames(_ url: URL) async {
+ let scoped = url.startAccessingSecurityScopedResource()
+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }
+ let found = await env.scanGames(url, model.repoPath)
+ guard state.exit == nil else { return }
+ guard !found.isEmpty else { state.games = .none; return }
+ // The same slots and folder the main UI sets: the Builds page's inputs and the library's games folder.
+ let keys = model.keysPath
+ model.scan(folder: url.path)
+ if !keys.isEmpty { model.updateSlot("keys") { $0.paths = [keys]; $0.problem = "" } } // the keys the player confirmed stay
+ library.setFolder(url)
+ if !model.running { model.outDir = url.path }
+ state.games = .found(found.map { OnboardingGame(id: $0.titleID, title: $0.name, version: "",
+ cover: GameLibrary.artwork(for: $0, repo: model.repoPath)) })
+ let ids = found.map(\.titleID)
+ spawn("covers") { d in
+ await d.env.fetchArtwork(ids)
+ guard case .found(var games) = d.state.games else { return }
+ for i in games.indices where games[i].cover == nil {
+ if let g = found.first(where: { $0.titleID == games[i].id }) { games[i].cover = GameLibrary.artwork(for: g, repo: d.model.repoPath) }
+ }
+ d.state.games = .found(games)
+ }
+ // The keys against the game they will open: a mismatch sends the player back to the keys, with the reason.
+ if !model.keysPath.isEmpty, !model.basePath.isEmpty {
+ let outcome = await env.keyCheck(model.keysPath, model.basePath)
+ switch outcome {
+ case .fits, .cannotCheck: break
+ default:
+ state.keys = .invalid(KeyCheck.message(outcome, t))
+ state.step = .keys; persistStep()
+ }
+ }
+ }
+
+ // MARK: Advancing
+
+ /// Xcode with its background tasks and the keys move on by themselves after a moment; the games wait for Continue.
+ func advanceIfReady() {
+ guard !suppressAdvance, state.exit == nil, state.step == .xcode || state.step == .keys, state.canAdvance else { return }
+ let step = state.step
+ spawn("advance") { d in
+ try? await Task.sleep(nanoseconds: UInt64(d.env.advanceDelay * 1_000_000_000))
+ if d.state.step == step, !d.suppressAdvance { d.next() }
+ }
+ }
+}
+
+/// The Xcode step's states from what was probed: a pure function, so the mapping is tested without a machine.
+enum OnboardingXcode {
+ static func evaluate(probe: XcodeProbe, metalReady: Bool, iosReady: Bool, includesIOS: Bool)
+ -> (xcode: OnboardingState.Xcode, setup: [OnboardingSetupTask: OnboardingTaskState]) {
+ guard probe.appPath != nil else { return (.missing, [:]) }
+ var setup: [OnboardingSetupTask: OnboardingTaskState] = [
+ .selected: probe.selectedIsXcode ? .done : .queued,
+ .license: probe.selectedIsXcode && probe.licenseAccepted ? .done : .queued,
+ .firstLaunch: probe.selectedIsXcode && probe.firstLaunchDone ? .done : .queued,
+ .metal: metalReady ? .done : .queued,
+ ]
+ if includesIOS { setup[.ios] = iosReady ? .done : .queued }
+ // A missing download counts like the three admin steps: Finish setup does all of it.
+ return (setup.values.allSatisfy(\.isDone) ? .ready : .needsSetup, setup)
+ }
+}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index b9b7f45b..a15123fb 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -453,6 +453,12 @@ enum L10n {
"notify.forMac": ("用于这台 Mac,已在游戏库中", "For this Mac, in your library"),
"notify.forIOS": ("用于 iPhone / iPad", "For iPhone / iPad"),
"notify.installedOn": ("已安装到 %@", "Installed on %@"),
+ "settings.setup": ("再次运行设置", "Run setup again"),
+ "settings.setupNote": ("重新走一遍首次设置:Xcode、构建工具、密钥和游戏", "Walk through first-run setup again: Xcode, build tools, keys and games"),
+ "settings.setupBtn": ("运行", "Run"),
+ "onboarding.error.xcode": ("Xcode 设置未能完成。", "Xcode setup could not finish."),
+ "onboarding.error.metal": ("Metal 工具链未能下载。请检查网络后重试。", "The Metal Toolchain could not be downloaded. Check your connection and try again."),
+ "onboarding.error.ios": ("iOS 平台未能下载。请检查网络和磁盘空间后重试。", "The iOS platform could not be downloaded. Check your connection and disk space, then try again."),
"settings.notify": ("构建完成时通知", "Notify when a build ends"),
"settings.notifyNote": ("仅在 NX2Apple 不在前台时,构建完成或失败都会通知", "When a build finishes or fails while NX2Apple is in the background"),
"settings.notifyUnbundled": ("需要 NX2Apple.app:用 swift run 启动时没有通知", "Needs NX2Apple.app: no notifications when started with swift run"),
diff --git a/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift b/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift
index 45aac283..e05f4d18 100644
--- a/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift
+++ b/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift
@@ -9,7 +9,7 @@ struct NSPortBuilderApp: App {
if let name = ProcessInfo.processInfo.environment["NSPB_ONBOARDING_DEMO"],
let scenario = MockOnboardingDriver.Scenario(rawValue: name) {
OnboardingDemoHost(scenario: scenario)
- } else { ContentView() }
+ } else { RootView() }
}
.windowStyle(.hiddenTitleBar)
.defaultSize(width: 1280, height: 900)
diff --git a/frontend/Sources/NSPortBuilder/OnboardingRoot.swift b/frontend/Sources/NSPortBuilder/OnboardingRoot.swift
new file mode 100644
index 00000000..021073a9
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/OnboardingRoot.swift
@@ -0,0 +1,60 @@
+import SwiftUI
+
+/// The window's content: the launcher, or the guided setup before it. It owns the one `BuildModel` and `GameLibrary` both use,
+/// so what the setup detects, installs and chooses is what the launcher shows.
+struct RootView: View {
+ private enum Mode { case checking, onboarding, launcher }
+ /// Holds the two objects without publishing, so this view does not redraw with every line of a build log.
+ private final class Shared: ObservableObject { let model = BuildModel(); let library = GameLibrary() }
+ @StateObject private var shared = Shared()
+ private var model: BuildModel { shared.model }
+ private var library: GameLibrary { shared.library }
+ @State private var mode: Mode = .checking
+ @State private var driver: LiveOnboardingDriver?
+ @StateObject private var gamepad = LauncherGamepad()
+
+ var body: some View {
+ Group {
+ switch mode {
+ case .checking:
+ LauncherPalette.background.overlay(ProgressView().controlSize(.small))
+ case .onboarding:
+ if let driver { OnboardingView(driver: driver, lang: model.lang, gamepad: gamepad) }
+ case .launcher:
+ ContentView(model: model, library: library, onRunSetup: runSetupAgain)
+ }
+ }
+ .background(LauncherPalette.background)
+ .preferredColorScheme(.dark)
+ .frame(minWidth: 900, idealWidth: 1280, minHeight: 680, idealHeight: 900)
+ .task { await decide() }
+ }
+
+ /// On launch: a setup marked done, or one that is complete already, goes straight to the launcher (and is marked done);
+ /// anything else starts or resumes the guided setup.
+ private func decide() async {
+ let defaults = UserDefaults.standard
+ if defaults.bool(forKey: OnboardingDefaults.completed) { mode = .launcher; return }
+ await model.refreshDepsAndWait()
+ let env = OnboardingEnvironment()
+ let keysKnown = model.slot("keys").ok || !env.keyCandidates(gamesFolder: library.folder).isEmpty || library.games.contains(where: \.isReady)
+ let gamesKnown = !library.folder.isEmpty || !library.games.isEmpty
+ let complete = OnboardingLaunch.setupComplete(depsPresent: model.allDepsPresent, keysKnown: keysKnown, gamesKnown: gamesKnown)
+ if OnboardingLaunch.shouldShow(completed: false, setupComplete: complete) {
+ show(fresh: false)
+ } else {
+ defaults.set(true, forKey: OnboardingDefaults.completed)
+ mode = .launcher
+ }
+ }
+
+ private func show(fresh: Bool) {
+ let d = LiveOnboardingDriver(model: model, library: library, fresh: fresh)
+ d.onExit = { _ in mode = .launcher; driver = nil }
+ driver = d
+ mode = .onboarding
+ d.activate()
+ }
+
+ private func runSetupAgain() { show(fresh: true) }
+}
diff --git a/frontend/Sources/NSPortBuilder/OnboardingView.swift b/frontend/Sources/NSPortBuilder/OnboardingView.swift
index 9e25530b..538cc522 100644
--- a/frontend/Sources/NSPortBuilder/OnboardingView.swift
+++ b/frontend/Sources/NSPortBuilder/OnboardingView.swift
@@ -390,7 +390,9 @@ import UniformTypeIdentifiers
.clipShape(RoundedRectangle(cornerRadius: 5))
}.aspectRatio(1.8, contentMode: .fit).accessibilityHidden(true)
Text(game.title).font(.manrope(16, .semibold)).lineLimit(2)
- Text(String(format: t("onboarding.games.version"), game.version)).font(.manrope(12)).foregroundStyle(.secondary)
+ if !game.version.isEmpty {
+ Text(String(format: t("onboarding.games.version"), game.version)).font(.manrope(12)).foregroundStyle(.secondary)
+ }
}.accessibilityElement(children: .combine)
}
}
diff --git a/frontend/Tests/NSPortBuilderTests/LiveOnboardingDriverTests.swift b/frontend/Tests/NSPortBuilderTests/LiveOnboardingDriverTests.swift
new file mode 100644
index 00000000..2e9cccfc
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/LiveOnboardingDriverTests.swift
@@ -0,0 +1,355 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// The real driver's logic over fakes: no xcodebuild, sudo, App Store, network or installs run here.
+@MainActor final class LiveOnboardingDriverTests: XCTestCase {
+ final class Fake {
+ var probe = XcodeProbe(appPath: "/Applications/Xcode.app", selectedIsXcode: true, licenseAccepted: true, firstLaunchDone: true)
+ var admin: AdminResult = .ok
+ var adminCalls: [String] = []
+ var commands: [[String]] = []
+ var commandResult: (ok: Bool, output: String) = (true, "")
+ var installed: [String] = []
+ var opened: [URL] = []
+ var onDetect: (BuildModel) -> Void = { _ in }
+ var keyOutcome = KeyCheck.Outcome.fits
+ var games: [LibraryGame] = []
+ }
+
+ func dep(_ id: String, present: Bool) -> BuildModel.Dep {
+ BuildModel.Dep(id: id, name: "dep." + (id.hasPrefix("brew:") ? String(id.dropFirst(5)) : id), hint: "", present: present, installCmd: ["/usr/bin/true"])
+ }
+
+ var defaults: UserDefaults!
+ var home: URL!
+
+ override func setUp() {
+ let target = UserDefaults.standard.object(forKey: "buildTarget") // choosePlatform sets the Builds page's target
+ addTeardownBlock { UserDefaults.standard.set(target, forKey: "buildTarget") }
+ let suite = "onboarding.tests." + UUID().uuidString
+ defaults = UserDefaults(suiteName: suite)
+ addTeardownBlock { UserDefaults().removePersistentDomain(forName: suite) }
+ home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try? FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
+ addTeardownBlock { [home] in try? FileManager.default.removeItem(at: home!) }
+ }
+
+ func make(_ fake: Fake, deps: [BuildModel.Dep], step: OnboardingStep? = nil, platform: OnboardingPlatform? = nil) -> (LiveOnboardingDriver, BuildModel) {
+ if let platform { defaults.set(platform.rawValue, forKey: OnboardingDefaults.platform) }
+ if let step { defaults.set(step.rawValue, forKey: OnboardingDefaults.step); defaults.set(true, forKey: OnboardingDefaults.inProgress) }
+ let model = BuildModel()
+ model.deps = deps; model.depsChecked = true
+ var env = OnboardingEnvironment()
+ env.defaults = defaults
+ env.home = home.path
+ env.freeBytes = { 100_000_000_000 }
+ env.xcodeInstalled = { fake.probe.appPath != nil }
+ env.xcodeProbe = { fake.probe }
+ env.runAdmin = { fake.adminCalls.append($0); return fake.admin }
+ env.run = { cmd, line in fake.commands.append(cmd); line("Downloading Metal Toolchain: 45.5% (1 MB of 2 MB)"); return fake.commandResult }
+ env.detectDeps = { m in fake.onDetect(m) }
+ env.installDep = { m, d in
+ fake.installed.append(d.id)
+ if let i = m.deps.firstIndex(where: { $0.id == d.id }) { m.deps[i].installing = true }
+ }
+ env.openURL = { fake.opened.append($0) }
+ env.keyCheck = { _, _ in fake.keyOutcome }
+ env.scanGames = { _, _ in fake.games }
+ env.fetchArtwork = { _ in }
+ env.pollInterval = 0.01; env.advanceDelay = 0
+ let library = GameLibrary(file: home.appendingPathComponent("library.json"))
+ return (LiveOnboardingDriver(model: model, library: library, env: env), model)
+ }
+
+ // MARK: Pure parts
+
+ func testIOSRequirementFollowsThePlatformAndKeepsOldBehaviourWithoutAChoice() {
+ XCTAssertTrue(BuildModel.needsIOSPlatform(defaults: defaults), "no stored choice: the iOS SDK stays required")
+ defaults.set("mac", forKey: OnboardingDefaults.platform)
+ defaults.set("mac-app", forKey: "buildTarget")
+ XCTAssertFalse(BuildModel.needsIOSPlatform(defaults: defaults), "Mac only, Mac builds: no iOS SDK")
+ defaults.set("ios", forKey: "buildTarget")
+ XCTAssertTrue(BuildModel.needsIOSPlatform(defaults: defaults), "an iPhone build still needs it")
+ for value in ["iphone", "both"] {
+ defaults.set(value, forKey: OnboardingDefaults.platform); defaults.set("mac-app", forKey: "buildTarget")
+ XCTAssertTrue(BuildModel.needsIOSPlatform(defaults: defaults))
+ }
+ }
+
+ func testXcodeStateFromTheProbe() {
+ func eval(_ p: XcodeProbe, metal: Bool = true, ios: Bool = true, includesIOS: Bool = false) -> OnboardingState.Xcode {
+ OnboardingXcode.evaluate(probe: p, metalReady: metal, iosReady: ios, includesIOS: includesIOS).xcode
+ }
+ let ready = XcodeProbe(appPath: "/Applications/Xcode.app", selectedIsXcode: true, licenseAccepted: true, firstLaunchDone: true)
+ XCTAssertEqual(eval(XcodeProbe()), .missing)
+ XCTAssertEqual(eval(ready), .ready)
+ var clt = ready; clt.selectedIsXcode = false
+ XCTAssertEqual(eval(clt), .needsSetup, "the Command Line Tools are selected")
+ var license = ready; license.licenseAccepted = false
+ XCTAssertEqual(eval(license), .needsSetup)
+ var first = ready; first.firstLaunchDone = false
+ XCTAssertEqual(eval(first), .needsSetup)
+ XCTAssertEqual(eval(ready, metal: false), .needsSetup)
+ XCTAssertEqual(eval(ready, ios: false), .ready, "a Mac-only player is not held up by the iOS platform")
+ XCTAssertEqual(eval(ready, ios: false, includesIOS: true), .needsSetup)
+ XCTAssertNil(OnboardingXcode.evaluate(probe: ready, metalReady: true, iosReady: false, includesIOS: false).setup[.ios])
+ XCTAssertNotNil(OnboardingXcode.evaluate(probe: ready, metalReady: true, iosReady: false, includesIOS: true).setup[.ios])
+ }
+
+ func testAdminScriptIsOnePromptAndQuotesThePath() {
+ let source = OnboardingAdmin.source(developerDir: "/Applications/My \"X\" Xcode.app/Contents/Developer")
+ XCTAssertEqual(source.components(separatedBy: "with administrator privileges").count - 1, 1)
+ XCTAssertTrue(source.contains("quoted form of \"/Applications/My \\\"X\\\" Xcode.app/Contents/Developer\""))
+ XCTAssertTrue(source.contains("/usr/bin/xcode-select -s "))
+ XCTAssertTrue(source.contains("&& /usr/bin/xcodebuild -license accept && /usr/bin/xcodebuild -runFirstLaunch"))
+ }
+
+ func testProgressParsingAndTail() {
+ XCTAssertEqual(LiveOnboardingDriver.progress(in: "Downloading Metal Toolchain: 45.5% (1 MB of 2 MB)")!, 0.455, accuracy: 0.0001)
+ XCTAssertEqual(LiveOnboardingDriver.progress(in: "10%\r20%\r30%")!, 0.3, accuracy: 0.0001)
+ XCTAssertNil(LiveOnboardingDriver.progress(in: "Installing"))
+ XCTAssertEqual(LiveOnboardingDriver.tail(String(repeating: "x", count: 5000), limit: 100).count, 101)
+ }
+
+ func testNeededGBIsAnEstimateThatGrowsWithTheChoices() {
+ let mac = LiveOnboardingDriver.neededGB(xcodeMissing: false, includesIOS: false)
+ XCTAssertGreaterThan(LiveOnboardingDriver.neededGB(xcodeMissing: true, includesIOS: false), mac)
+ XCTAssertGreaterThan(LiveOnboardingDriver.neededGB(xcodeMissing: false, includesIOS: true), mac)
+ }
+
+ func testAnAlreadyCompleteSetupIsNeverShown() {
+ XCTAssertFalse(OnboardingLaunch.shouldShow(completed: true, setupComplete: false))
+ XCTAssertFalse(OnboardingLaunch.shouldShow(completed: false, setupComplete: true), "complete: marked done, not shown")
+ XCTAssertTrue(OnboardingLaunch.shouldShow(completed: false, setupComplete: false))
+ XCTAssertTrue(OnboardingLaunch.setupComplete(depsPresent: true, keysKnown: true, gamesKnown: true))
+ for missing in 0..<3 {
+ XCTAssertFalse(OnboardingLaunch.setupComplete(depsPresent: missing != 0, keysKnown: missing != 1, gamesKnown: missing != 2))
+ }
+ }
+
+ // MARK: The driver
+
+ func testWelcomeShowsMeasuredFreeSpace() {
+ let (driver, _) = make(Fake(), deps: [])
+ guard case let .requirements(free, needed) = driver.state.welcome else { return XCTFail() }
+ XCTAssertEqual(free, 100)
+ XCTAssertGreaterThan(needed, 0)
+ }
+
+ func testCancelledAdminPromptReturnsToNeedsSetup() async {
+ let fake = Fake(); fake.probe.selectedIsXcode = false; fake.admin = .cancelled
+ let (driver, _) = make(fake, deps: [dep("metal", present: true)], step: .xcode, platform: .mac)
+ await driver.refreshXcode()
+ XCTAssertEqual(driver.state.xcode, .needsSetup)
+ driver.finishXcodeSetup()
+ XCTAssertEqual(driver.state.xcode, .settingUp)
+ await driver.settle()
+ XCTAssertEqual(driver.state.xcode, .needsSetup, "saying no to the password is not an error")
+ XCTAssertEqual(fake.adminCalls, ["/Applications/Xcode.app/Contents/Developer"])
+ XCTAssertTrue(fake.commands.isEmpty)
+ }
+
+ func testFinishRunsAdminOnceThenTheDownloadsWithoutIt() async {
+ let fake = Fake(); fake.probe.selectedIsXcode = false
+ let (driver, model) = make(fake, deps: [dep("metal", present: false), dep("xcode", present: false)], step: .xcode, platform: .both)
+ fake.onDetect = { m in // what the admin step and the downloads change
+ fake.probe.selectedIsXcode = true; fake.probe.licenseAccepted = true; fake.probe.firstLaunchDone = true
+ if !fake.commands.isEmpty { for i in m.deps.indices { m.deps[i].present = true } }
+ }
+ await driver.refreshXcode()
+ driver.finishXcodeSetup()
+ await driver.settle()
+ XCTAssertEqual(fake.adminCalls.count, 1)
+ XCTAssertEqual(fake.commands, [BuildModel.metalToolchainCmd, BuildModel.iosPlatformCmd])
+ XCTAssertEqual(driver.state.xcode, .ready)
+ XCTAssertEqual(driver.state.setup[.ios], .done)
+ _ = model
+ }
+
+ func testMacOnlyDoesNotDownloadTheIOSPlatform() async {
+ let fake = Fake(); fake.probe.selectedIsXcode = false
+ let (driver, _) = make(fake, deps: [dep("metal", present: false), dep("xcode", present: true)], step: .xcode, platform: .mac)
+ fake.onDetect = { m in
+ fake.probe.selectedIsXcode = true; fake.probe.licenseAccepted = true; fake.probe.firstLaunchDone = true
+ if !fake.commands.isEmpty { for i in m.deps.indices { m.deps[i].present = true } }
+ }
+ await driver.refreshXcode()
+ driver.finishXcodeSetup()
+ await driver.settle()
+ XCTAssertEqual(fake.commands, [BuildModel.metalToolchainCmd])
+ XCTAssertEqual(driver.state.xcode, .ready)
+ }
+
+ func testDownloadFailureIsLocalizedWithTheOutputInDetails() async {
+ let fake = Fake(); fake.commandResult = (false, "HTTP 503 from the server")
+ let (driver, _) = make(fake, deps: [dep("metal", present: false)], step: .xcode, platform: .mac)
+ await driver.refreshXcode()
+ driver.finishXcodeSetup()
+ await driver.settle()
+ guard case let .failed(failure) = driver.state.xcode else { return XCTFail("\(driver.state.xcode)") }
+ XCTAssertEqual(failure.message, L10n.string("onboarding.error.metal", driver.model.lang))
+ XCTAssertTrue(failure.details.contains("HTTP 503"))
+ XCTAssertTrue(fake.adminCalls.isEmpty, "Xcode was already set up: no prompt")
+ }
+
+ func testGetXcodeOpensTheAppStoreAndPollsUntilItAppears() async {
+ let fake = Fake(); fake.probe = XcodeProbe()
+ let (driver, _) = make(fake, deps: [dep("metal", present: true)], step: .xcode, platform: .mac)
+ await driver.refreshXcode()
+ XCTAssertEqual(driver.state.xcode, .missing)
+ driver.getXcode()
+ XCTAssertEqual(driver.state.xcode, .downloading)
+ XCTAssertEqual(fake.opened.map(\.absoluteString), ["macappstore://apps.apple.com/app/id497799835"])
+ fake.probe = XcodeProbe(appPath: "/Applications/Xcode.app", selectedIsXcode: false)
+ await driver.settle()
+ XCTAssertEqual(driver.state.xcode, .needsSetup)
+ }
+
+ func testBackgroundInstallsRunOneAtATimeAndToolsWaitForXcode() async {
+ let fake = Fake()
+ let deps = [dep("xcode", present: true), dep("metal", present: true), dep("brew", present: false),
+ dep("brew:xcodegen", present: false), dep("dotnet", present: false), dep("python", present: false)]
+ let (driver, model) = make(fake, deps: deps, step: .xcode, platform: .mac)
+ driver.activate()
+ await driver.settle()
+ XCTAssertEqual(fake.installed, ["python"])
+ func finish(_ id: String) async { // the install ended and detection ran again
+ model.depsChecked = false
+ for i in model.deps.indices { model.deps[i].installing = false; if model.deps[i].id == id { model.deps[i].present = true } }
+ model.depsChecked = true
+ await driver.settle()
+ }
+ await finish("python"); XCTAssertEqual(fake.installed, ["python", "dotnet"])
+ XCTAssertEqual(driver.state.background[.python], .done)
+ await finish("dotnet"); XCTAssertEqual(fake.installed, ["python", "dotnet", "brew"])
+ await finish("brew"); XCTAssertEqual(fake.installed, ["python", "dotnet", "brew", "brew:xcodegen"])
+ await finish("brew:xcodegen")
+ XCTAssertTrue(driver.state.backgroundReady)
+ XCTAssertEqual(driver.state.step, .keys, "Xcode and the tools are done: the step moves on by itself")
+ }
+
+ func testToolsStayQueuedUntilXcodeIsReady() async {
+ let fake = Fake(); fake.probe.selectedIsXcode = false
+ let deps = [dep("xcode", present: true), dep("metal", present: true), dep("brew", present: false),
+ dep("dotnet", present: true), dep("python", present: true)]
+ let (driver, _) = make(fake, deps: deps, step: .xcode, platform: .mac)
+ driver.activate()
+ await driver.settle()
+ XCTAssertEqual(driver.state.xcode, .needsSetup)
+ XCTAssertEqual(driver.state.background[.tools], .queued)
+ XCTAssertTrue(fake.installed.isEmpty)
+ }
+
+ func testAFailedInstallShowsFailureWithTheNameAndMovesOn() async {
+ let fake = Fake()
+ let (driver, model) = make(fake, deps: [dep("xcode", present: true), dep("metal", present: true),
+ dep("dotnet", present: false), dep("python", present: false)], step: .xcode, platform: .mac)
+ driver.activate()
+ await driver.settle()
+ model.depsChecked = false
+ for i in model.deps.indices { model.deps[i].installing = false } // python's install ended, still missing
+ model.depsChecked = true
+ await driver.settle()
+ guard case let .failed(failure) = driver.state.background[.python] else { return XCTFail("\(String(describing: driver.state.background[.python]))") }
+ XCTAssertTrue(failure.message.contains(L10n.string("dep.python", model.lang)))
+ XCTAssertEqual(fake.installed, ["python", "dotnet"], "a failure does not stop the others")
+ }
+
+ func testResumeKeepsTheStepOnlyWhileXcodeStillHolds() async {
+ let ok = Fake()
+ let (driver, _) = make(ok, deps: [dep("metal", present: true), dep("xcode", present: true)], step: .keys, platform: .mac)
+ XCTAssertEqual(driver.state.step, .keys)
+ XCTAssertEqual(driver.state.selectedPlatform, .mac)
+ await driver.revalidate()
+ XCTAssertEqual(driver.state.step, .keys)
+
+ let gone = Fake(); gone.probe = XcodeProbe()
+ let (second, _) = make(gone, deps: [dep("metal", present: true)], step: .games, platform: .mac)
+ XCTAssertEqual(second.state.step, .games)
+ await second.revalidate()
+ XCTAssertEqual(second.state.step, .xcode, "Xcode is gone: back to the Xcode step")
+ }
+
+ func testStoredStepWithoutAPlatformResumesAtThePlatformChoice() {
+ defaults.set(OnboardingStep.keys.rawValue, forKey: OnboardingDefaults.step); defaults.set(true, forKey: OnboardingDefaults.inProgress)
+ let (driver, _) = make(Fake(), deps: [])
+ XCTAssertEqual(driver.state.step, .platform)
+ }
+
+ func testSkipForLaterStoresStepAndPlatformAndCloses() {
+ let (driver, _) = make(Fake(), deps: [], step: .platform)
+ var exits: [OnboardingState.Exit] = []
+ driver.onExit = { exits.append($0) }
+ driver.choosePlatform(.iphone)
+ driver.skipForLater()
+ XCTAssertEqual(exits, [.later])
+ XCTAssertEqual(driver.state.exit, .later)
+ XCTAssertEqual(defaults.string(forKey: OnboardingDefaults.step), "platform")
+ XCTAssertEqual(defaults.string(forKey: OnboardingDefaults.platform), "iphone")
+ XCTAssertTrue(defaults.bool(forKey: OnboardingDefaults.inProgress))
+ XCTAssertFalse(defaults.bool(forKey: OnboardingDefaults.completed))
+ }
+
+ func testChoosingMacOnlyPointsTheBuildsPageAtTheMac() {
+ let (driver, model) = make(Fake(), deps: [], step: .platform)
+ driver.choosePlatform(.mac)
+ XCTAssertEqual(model.target, "mac-app")
+ XCTAssertEqual(defaults.string(forKey: OnboardingDefaults.platform), "mac")
+ }
+
+ func testKeysAreCheckedAndOnlyTheirPathIsKept() async throws {
+ let fake = Fake()
+ let keys = home.appendingPathComponent(".switch/prod.keys")
+ try FileManager.default.createDirectory(at: keys.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try "header_key = 00\n".write(to: keys, atomically: true, encoding: .utf8)
+ let (driver, model) = make(fake, deps: [], step: .keys, platform: .mac)
+ await driver.searchKeys()
+ XCTAssertEqual(driver.state.keys, .found(keys))
+ driver.confirmKeys()
+ await driver.settle()
+ XCTAssertEqual(driver.state.keys, .valid)
+ XCTAssertEqual(model.keysPath, keys.path, "the same slot the Builds page uses")
+
+ driver.back() // the step moved on by itself; back to the keys
+ fake.keyOutcome = .noHeaderKey
+ driver.chooseKeys(keys)
+ await driver.settle()
+ guard case let .invalid(message) = driver.state.keys else { return XCTFail() }
+ XCTAssertFalse(message.contains("00"), "a message never carries key material")
+ }
+
+ func testGamesFolderFillsTheSameSlotsAndLibrary() async throws {
+ let fake = Fake()
+ let folder = home.appendingPathComponent("games")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ var game = LibraryGame(titleID: "0100000000010000", name: "Sample")
+ game.inputs["base"] = [folder.appendingPathComponent("a.nsp").path]
+ fake.games = [game]
+ let (driver, model) = make(fake, deps: [], step: .games, platform: .mac)
+ model.updateSlot("keys") { $0.paths = ["/keys/prod.keys"] }
+ driver.chooseGames(folder)
+ await driver.settle()
+ guard case let .found(list) = driver.state.games else { return XCTFail("\(driver.state.games)") }
+ XCTAssertEqual(list.map(\.title), ["Sample"])
+ XCTAssertEqual(model.gameDir, folder.path)
+ XCTAssertEqual(driver.library.folder, folder.standardizedFileURL.path)
+ XCTAssertEqual(model.keysPath, "/keys/prod.keys", "scanning a folder keeps the confirmed keys")
+
+ fake.games = []
+ driver.chooseGames(folder)
+ await driver.settle()
+ XCTAssertEqual(driver.state.games, .none)
+ }
+
+ func testOpenLibraryMarksTheSetupDone() async {
+ let (driver, _) = make(Fake(), deps: [], step: .done, platform: .mac)
+ var exits: [OnboardingState.Exit] = []
+ driver.onExit = { exits.append($0) }
+ driver.enter(.done)
+ await driver.settle()
+ driver.openLibrary()
+ XCTAssertEqual(exits, [.library])
+ XCTAssertTrue(defaults.bool(forKey: OnboardingDefaults.completed))
+ XCTAssertFalse(defaults.bool(forKey: OnboardingDefaults.inProgress))
+ }
+}