Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Move the dependency rows, the Python and dotnet paths and the installs into a DependencyStore (#387)
v0lumehi07fa7e4c84df
diff --git a/frontend/ARCHITECTURE.md b/frontend/ARCHITECTURE.mdindex 6dbef446..8ae62f3c 100644--- a/frontend/ARCHITECTURE.md+++ b/frontend/ARCHITECTURE.md@@ -13,7 +13,7 @@ The plan and the steps are in [LNPANDY/NX2Apple#387](https://github.com/LNPANDY/## Where it stands-Step 1 of #387 made the targets and moved the files that already fit. Step 2 moved the language out of `BuildModel` into the `Localizer` store. Step 3 moved the build log into the `BuildLog` store. Step 4 moved the pure logic into `NXCore`. Step 5 added the first services. Step 6 added the first store, `AppUpdateStore`, the reference for the others. Step 7 moves the rest one store per PR: the repository, then the engine sync. The rest still lives in the app target and moves with the later steps.+Step 1 of #387 made the targets and moved the files that already fit. Step 2 moved the language out of `BuildModel` into the `Localizer` store. Step 3 moved the build log into the `BuildLog` store. Step 4 moved the pure logic into `NXCore`. Step 5 added the first services. Step 6 added the first store, `AppUpdateStore`, the reference for the others. Step 7 moves the rest one store per PR: the repository, the engine sync, then the dependencies. The rest still lives in the app target and moves with the later steps.- `BuildModel` is the model of the whole launcher and reaches into every layer, so the files that use it cannot leave the app target yet. It no longer owns the language: it holds the `Localizer` it was given and forwards `lang` and `t()` to it, for the text it writes itself (alerts, status, failures).- `NXCore` holds the value types and static functions that need only Foundation: app and engine update parsing, `Localization.swift`, the release notes, the device and signing tools, the cloud folder and saves migration, the bundled tools, input staging, the build target and the pipe reader. Step 4 added four types: `TitleID` (parse a title ID from a file name, its owner, the update version, the build key), `GameInputs` (classify files into the four rows, row mismatch, allowed file types), `BuildProgress` (stage lines, progress details, durations, the steps of Xcode and the install, failure info) and `Toolchain` (probing Python, the venv, dotnet and Xcode, and the dependency rows `Dep`). `Stage` and `StepState` moved with `BuildProgress`. Step 5 added the first services (step 6 added `ReleaseSource`, see below): `ProcessRunner` (a protocol, with `SystemProcessRunner` as the real one), `ProcessGroups` (the process groups that Stop and quitting end) and `GitCheckout` (a protocol, with `SystemGitCheckout`, plus `GitRules` for the decisions that need no git). `ProcessRunner` is where a build process starts: `capture` runs to the end and keeps the output, `stream` hands out lines, `start` returns at once and can lead a process group. `BuildModel` holds a runner and a checkout, takes them in `init`, and uses them for the clone, fetch, pull, adoption of a ZIP copy, the build run, the tools of a stage, the archive step and `openOnDevice`. `Toolchain`, `Diagnostics`, `OlderTools`, `Uninstall`, `EngineLayout.runSync` and the update staging take a runner or a checkout as a parameter with the real one as default. Tests pass in a fake. These still start a `Process` themselves and move with the step that owns them: `AppSignature` (codesign) with the device store, `DeviceTools.run` (devicectl with a timeout and input) and `SaveTransfer` with the device store, `ShellInstaller.run` (a blocking read with start and end callbacks) with the build store, `EngineInstaller` (ditto, in `NXCore` since the engine sync store) still starts it itself, the administrator prompt in `LiveOnboardingDriver` and the game start in `LiveConsoleDriver`. The tests that stand in for `xcodebuild` and `devicectl` through `BuildModel.xcrunPath` stay too: `ShellInstaller` and `DeviceTools` run those tools themselves, so they move with the device store. What reads `MetalPin`, `EngineLayout` or `OnboardingDefaults` (`detectDepsSync`, `metalDep`, `needsIOSPlatform`) and the handling of the build's JSON events stay in `BuildModel` until the later store steps.@@ -22,8 +22,10 @@ Step 1 of #387 made the targets and moved the files that already fit. Step 2 mov- `NXModel` holds `Localizer`: `lang` and `t()`. The app creates one with each `BuildModel`, and `ContentView` hands it to every view as an environment object. A view that shows text declares `@EnvironmentObject var loc: Localizer` and calls `loc.t(...)`. A language change redraws these views and nothing else.- `NXModel` holds `AppUpdateStore`: the release check, the staged update, the update sheet, the uninstall plan and `appVersion`. `BuildModel` creates it with its localizer, runner and release source, and the views that show the update (the launcher's top bar and activity line, the Settings section, the update sheet) observe it and not `BuildModel`. `NXModelTests` tests it with a fake runner and a fake release source, without SwiftUI.- `NXModel` holds `RepoStore` (step 7, repository): the repository path, the status line under it, how far it is behind origin/main, the clone, the update check, the pull, the automatic update when the app opens and the adoption of a ZIP copy. `BuildModel` creates it with its `Localizer` and `GitCheckout` and wires four closures: whether a build runs, whether this is a release app (which never clones or pulls), the build log, and `didMove`, which starts the engine sync after a clone, a pull or an adoption. The views that show the repository (Settings "Tools", the library's activity line, the setup hint) observe the store. `RepoLocation` is the narrow protocol (`path`, `isRepo`, `isGit`) for a store that needs only where the repository is. `NXCore` got the rules the store needs: `RepoLayout` (is it a repository, the tools a build needs, which checkout to use at start) and the file-system part of `EngineLayout` (`marker`, `root`, `isCheckout`, `hasEngineTool`). The stale check and the sync of `EngineLayout` stay in the app target with the engine.-- `NXModel` holds `EngineSyncStore` (step 7, engine sync): the engine selection (channel, engine ID, version, the one kept), the sync of a checkout's `engine/` (`tools/engine.py sync`, its status line and its failure row with Try again, the calls that wait for a running sync) and the engine of the release app (seeding the app's own engine, the check of the selected channel, the install, the channel switch after a confirmation, an engine that waits for the running build). `BuildModel` creates it with its localizer and runner, the `RepoStore` as the `RepoLocation` to read, itself as the `PythonLocation` (a narrow protocol with `pythonPath`, the dependency store takes it over) and closures: where the build reads its tools from (`setRepoPath`, an installed engine tree), whether a build runs, the automatic update and the log. `RepoStore.didMove` starts its sync. The views that show the engine (Settings "Tools", the sync banner, the failure row's Try again, the launcher's checks after a sync) observe the store. `NXCore` got what the store needs: the stale check and the sync of `EngineLayout`, `EngineUpdater.swift` (`EngineChannel`, `EngineSelection`, `EngineUpdate`, `EngineInstaller`, `EngineTransport`) and `BuildFailureKind` with `BuildFailure` (the sync's failure row). The classifier `BuildFailureClassifier` stays in the app target. `NXModelTests` tests the store with a fake runner, without SwiftUI.-- Still in `BuildModel`, going to their store: `repoPath`, `repoOK` and `repoIsGit` are forwarders to `RepoStore`, because the build code (start, archive, install, diagnostics) reads the path and is not a store yet. `BuildModel` also forwards the objectWillChange of `RepoStore` and of `EngineSyncStore` to its own, because `canBuild` and the build views read the repository and the engine's paths through it. Both go with the build store (step 7, build). The synchronous calls of the build (`startBuild` waits for the sync, `Diagnostics` reads the selection) and `pythonPath` (the `PythonLocation`, with `deps`, which go to the dependency store) stay. `BuildModel` is not `@MainActor` yet, so it reaches the stores through `MainActor.assumeIsolated`.+- `NXModel` holds `EngineSyncStore` (step 7, engine sync): the engine selection (channel, engine ID, version, the one kept), the sync of a checkout's `engine/` (`tools/engine.py sync`, its status line and its failure row with Try again, the calls that wait for a running sync) and the engine of the release app (seeding the app's own engine, the check of the selected channel, the install, the channel switch after a confirmation, an engine that waits for the running build). `BuildModel` creates it with its localizer and runner, the `RepoStore` as the `RepoLocation` to read, the `DependencyStore` as the `PythonLocation` (a narrow protocol with `pythonPath`) and closures: where the build reads its tools from (`setRepoPath`, an installed engine tree), whether a build runs, the automatic update and the log. `RepoStore.didMove` starts its sync. The views that show the engine (Settings "Tools", the sync banner, the failure row's Try again, the launcher's checks after a sync) observe the store. `NXCore` got what the store needs: the stale check and the sync of `EngineLayout`, `EngineUpdater.swift` (`EngineChannel`, `EngineSelection`, `EngineUpdate`, `EngineInstaller`, `EngineTransport`) and `BuildFailureKind` with `BuildFailure` (the sync's failure row). The classifier `BuildFailureClassifier` stays in the app target. `NXModelTests` tests the store with a fake runner, without SwiftUI.+- Still in `BuildModel`, going to their store: `repoPath`, `repoOK` and `repoIsGit` are forwarders to `RepoStore`, because the build code (start, archive, install, diagnostics) reads the path and is not a store yet. `BuildModel` also forwards the objectWillChange of `RepoStore` and of `EngineSyncStore` to its own, because `canBuild` and the build views read the repository and the engine's paths through it. Both go with the build store (step 7, build). The synchronous calls of the build (`startBuild` waits for the sync, `Diagnostics` reads the selection) stay. `BuildModel` is not `@MainActor` yet, so it reaches the stores through `MainActor.assumeIsolated`.+- `NXModel` holds `DependencyStore` (step 7, dependencies): the rows of the tools panel (`deps`, `checked`, whether the list is expanded), the Python and dotnet paths the check finds, the check (`check()`) and the installs (`install(_:)`, with the failure kept on the row and a note for it). It is the `PythonLocation` that `EngineSyncStore` reads, and `DependencyStatus` (`checked`, `allPresent`, `pythonPath`, `dotnetPath`, `deps`) is the narrow protocol the build reads. `BuildModel` creates it with its localizer, runner and the `RepoStore` as the `RepoLocation`, and wires closures: the guided setup's platform choice (`needsIOS`), the App Store (a row with no command, Xcode), the log and the note after a failed install. The views that show the rows (Settings "Tools", the setup hint and the status line of the Builds page) observe the store. `NXCore` got what the store needs: `DependencyCheck` (the list of rows, the Metal row, the dotnet install command, `deps-check.txt`, the bash command and environment of an install) and `MetalPin`. `NXModelTests` tests the store with a fake runner and a fake detection, without SwiftUI. The Python row's venv install (`Toolchain.makeVenv`) is not tested there, because it reads and writes the real venv folder.+- Still in `BuildModel`, going to the build store: `pythonPath`, `dotnetPath`, `depsChecked` and `allDepsPresent` are read-only forwarders to the store through `DependencyStatus`, because the build code (start, RomFS, diagnostics, `canBuild`) reads them. `BuildModel` forwards the store's objectWillChange to its own, like the other stores. The card's fix buttons (`fixBuildFailure`, `fixBusy`) call the store's `install` and `isInstalling`. `needsIOSPlatform` stays in the app target, because it reads `OnboardingDefaults` (the guided setup's keys), and goes to the store with the onboarding. `BuildModel` is not `@MainActor` yet, so it reaches the store through `MainActor.assumeIsolated`.- `NXModel` also holds `BuildLog`: the log text, its tail trimming and the line buffer. `BuildModel` holds it in a `let` and does not publish it, and only `BuildLogView` (in `NXLauncher`) observes it. A log line redraws the log and no game card. `LauncherPerformanceTests` writes 1000 lines during a build and allows 0 cards. `BuildModel` is not `@MainActor` yet, so it reaches the log through `BuildLog.onMain`.- `NXLauncher` holds the views and styles that do not need `BuildModel`: `LauncherPalette`, `Typography`, `LauncherStyles`, `LauncherDropdown`, `PadFocus` and `EmbeddedFonts`.- `NX2Apple` holds everything else, including `BuildModel`.diff --git a/frontend/Onboarding.md b/frontend/Onboarding.mdindex cba859ee..f36b45de 100644--- a/frontend/Onboarding.md+++ b/frontend/Onboarding.md@@ -57,7 +57,7 @@ Persist the current step and selections before handling `skipForLater`, then inj`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, and 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`, and 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`).+- Detection and installs are `DependencyStore.check` / `deps` / `install`, 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, and 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`.diff --git a/frontend/Sources/NX2Apple/BuildFailure.swift b/frontend/Sources/NX2Apple/BuildFailure.swiftindex d36e0d26..66e01450 100644--- a/frontend/Sources/NX2Apple/BuildFailure.swift+++ b/frontend/Sources/NX2Apple/BuildFailure.swift@@ -102,53 +102,3 @@ enum BuildFailureClassifier {return rest + [flag]}}--/// The Metal compiler the shaders were tested with (dm/gfx/tools/dmsh_chain.lock) against this Mac's. NVN games stop at the-/// start of the shader steps with another compiler of the lock's generation or an older one (own_compilers.py --check-metal), so-/// the dependency panel says so beforehand; a newer compiler of the same generation builds with a note, like the script's gate.-/// The comparison is the script's: the first line of `xcrun -sdk <sdk> metal --version`, and a compiler that is not there is-/// not a mismatch (its own row reports a missing one).-enum MetalPin {- struct Mismatch: Equatable { var sdk: String; var now: String; var pinned: String }-- static let lockPath = "dm/gfx/tools/dmsh_chain.lock"-- /// `metal_macosx` / `metal_iphoneos` lines of the lock: tab separated, `#` for comments.- static func pins(lock: String) -> [String: String] {- var out: [String: String] = [:]- for line in lock.split(separator: "\n", omittingEmptySubsequences: true) where !line.hasPrefix("#") {- let parts = line.split(separator: "\t", maxSplits: 1, omittingEmptySubsequences: false)- if parts.count == 2 { out[String(parts[0])] = String(parts[1]).trimmingCharacters(in: .whitespaces) }- }- return out- }-- /// `now`: the compilers found, by SDK name (macosx, iphoneos), nil for one that did not answer.- /// An iOS compiler is compared only when `iOS` (the build is for an iPhone).- /// A newer compiler of the recorded generation is not a mismatch: Xcode's auto-update bumps it- /// and a player cannot hold Xcode back — the engine's gate builds with a note (own_compilers.py, #242).- static func mismatches(lock: String, now: [String: String?], iOS: Bool) -> [Mismatch] {- let pinned = pins(lock: lock)- var out: [Mismatch] = []- for sdk in iOS ? ["macosx", "iphoneos"] : ["macosx"] {- guard let want = pinned["metal_" + sdk], let found = now[sdk] ?? nil, !found.isEmpty, found != want, !buildsOn(tested: want, found: found) else { continue }- out.append(Mismatch(sdk: sdk, now: found, pinned: want))- }- return out- }-- /// `Apple metal version 32023.921 (metalfe-32023.921.6)` → (32023, 921, 6); nil for another shape.- static func version(_ s: String) -> (Int, Int, Int)? {- let text = s.trimmingCharacters(in: .whitespaces)- let pattern = "^Apple metal version (\\d+)\\.(\\d+) \\(metalfe-\\d+\\.\\d+\\.(\\d+)\\)$"- guard let re = try? NSRegularExpression(pattern: pattern), let m = re.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)), m.numberOfRanges == 4 else { return nil }- let g = { (i: Int) in Int((text as NSString).substring(with: m.range(at: i))) }- return g(1) != nil && g(2) != nil && g(3) != nil ? (g(1)!, g(2)!, g(3)!) : nil- }-- /// Same leading version and strictly newer: the tested Xcode's compiler against the one an auto-update brought.- static func buildsOn(tested: String, found: String) -> Bool {- guard let a = version(tested), let b = version(found) else { return false }- return a.0 == b.0 && b > a- }-}diff --git a/frontend/Sources/NX2Apple/ContentView.swift b/frontend/Sources/NX2Apple/ContentView.swiftindex c5b6d946..b586b204 100644--- a/frontend/Sources/NX2Apple/ContentView.swift+++ b/frontend/Sources/NX2Apple/ContentView.swift@@ -56,7 +56,7 @@ struct Slot: Identifiable {// MARK: - Model-final class BuildModel: ObservableObject, PythonLocation {+final class BuildModel: ObservableObject {@Published var gameDir = ""@Published var slots: [Slot] = [Slot(id: "base", kind: .base, title: "data.base", optional: false),@@ -96,7 +96,7 @@ final class BuildModel: ObservableObject, PythonLocation {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() }+ if oldValue != target, UserDefaults.standard.string(forKey: OnboardingDefaults.platform) == "mac" { MainActor.assumeIsolated { _ = dependencies.check() } }}}/// Decode BC-compressed textures on the CPU. Only relevant for GPUs without BC support@@ -158,20 +158,31 @@ final class BuildModel: ObservableObject, PythonLocation {}}- @Published var deps: [Dep] = []- @Published var depsChecked = false- /// Whether the dependency list is expanded. nil = not chosen yet: open while something is- /// missing (that is when the rows matter), collapsed once everything is green — a set-up- /// machine never needs the rows again. A manual toggle overrides and is remembered.- @Published var depsExpanded: Bool? = UserDefaults.standard.object(forKey: "depsExpanded") as? Bool {- didSet { if let v = depsExpanded { UserDefaults.standard.set(v, forKey: "depsExpanded") } }- }- var depsOpen: Bool { depsExpanded ?? !(depsChecked && allDepsPresent) }- func toggleDeps() {- depsExpanded = !(depsExpanded ?? !allDepsPresent)+ // ---- The dependencies (`DependencyStore`, NXModel) ----+ // It owns the rows of the tools panel, the Python and dotnet paths and the installs. The model creates it with its services and+ // wires what reaches back here: the repository to read, the guided setup's platform choice, the App Store, the log and the note+ // after a failed install. The build reads it through `DependencyStatus` (`depStatus`), not the store.++ /// Created on first use, on the main thread, because its closures reach back to this model.+ private(set) lazy var dependencies: DependencyStore = MainActor.assumeIsolated {+ let store = DependencyStore(+ localizer: localizer, runner: runner, repo: repo,+ needsIOS: { Self.needsIOSPlatform() },+ openAppStore: { NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications/App Store.app")) },+ log: { [unowned self] in append($0) },+ installFailed: { [unowned self] in doneNote = $0 })+ // The build state that reads the tools (`canBuild`, the setup rows) is still here: a change of the rows redraws what observes+ // this model, as it did when they were published by it. Goes with the build store.+ dependencyChanges = store.objectWillChange.sink { [unowned self] _ in objectWillChange.send() }+ return store}- @Published var pythonPath = ""- @Published var dotnetPath = ""+ private var dependencyChanges: AnyCancellable?+ /// What the build code in this model asks about the tools. The views take the store itself.+ private var depStatus: DependencyStatus { MainActor.assumeIsolated { dependencies } }+ var pythonPath: String { MainActor.assumeIsolated { depStatus.pythonPath } }+ var dotnetPath: String { MainActor.assumeIsolated { depStatus.dotnetPath } }+ var depsChecked: Bool { MainActor.assumeIsolated { depStatus.checked } }+ var allDepsPresent: Bool { MainActor.assumeIsolated { depStatus.allPresent } }/// The language and the strings: views take them from the environment, this model only for the text it writes itself.let localizer: Localizer@@ -232,7 +243,7 @@ final class BuildModel: ObservableObject, PythonLocation {/// Created on first use, on the main thread, because its closures reach back to this model.private(set) lazy var engineSync: EngineSyncStore = MainActor.assumeIsolated {let store = EngineSyncStore(- localizer: localizer, runner: runner, repo: repo, python: self,+ localizer: localizer, runner: runner, repo: repo, python: dependencies,setRepoPath: { [unowned self] in repoPath = $0 },buildRunning: { [unowned self] in running },autoUpdate: { [unowned self] in MainActor.assumeIsolated { repo.autoUpdate } },@@ -692,15 +703,15 @@ final class BuildModel: ObservableObject, PythonLocation {func fixBuildFailure(_ kind: BuildFailureKind) {switch kind {case .translator:- if let d = deps.first(where: { $0.id == "dotnet" }) { installDep(d) }+ installRow("dotnet")case .iosSDK:- installDep(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.iosPlatformCmd))+ installRow(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.iosPlatformCmd))case .cltSelected:if let xcode = Toolchain.installedXcode() {- installDep(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.selectXcodeCmd(xcode)))+ installRow(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.selectXcodeCmd(xcode)))}case .zbic:- if let d = deps.first(where: { $0.id == "python" }) { installDep(d) } // the venv install, which now names zbic+ installRow("python") // the venv install, which now names zbiccase .keys:if let chooseKeys { chooseKeys() } else { pickFiles(kind: .keys) } // the same picker as the keys rowcase .severalGames, .noTitleID, .diskFull:@@ -740,7 +751,15 @@ final class BuildModel: ObservableObject, PythonLocation {func fixBusy(_ kind: BuildFailureKind) -> Bool {guard [.translator, .iosSDK, .cltSelected, .zbic].contains(kind) else { return false }let id = kind == .translator ? "dotnet" : kind == .zbic ? "python" : "xcode"- return deps.first { $0.id == id }?.installing ?? false+ return MainActor.assumeIsolated { dependencies.isInstalling(id) }+ }++ /// The row `id` of the tools panel installs, or the row given (a fix the panel has no row for).+ private func installRow(_ id: String) {+ MainActor.assumeIsolated { if let d = dependencies.deps.first(where: { $0.id == id }) { _ = dependencies.install(d) } }+ }+ private func installRow(_ dep: Dep) {+ MainActor.assumeIsolated { _ = dependencies.install(dep) }}/// (file count, bytes) of a RomFS tree — the reuse fingerprint's content part.@@ -1351,184 +1370,9 @@ final class BuildModel: ObservableObject, PythonLocation {return BuildTarget.normalized(defaults.string(forKey: "buildTarget")) != BuildTarget.mac}- /// The Metal toolchain row. A compiler that does not run is the missing-toolchain row with its install button. One that differs from the- /// lock's pin is a warning and not a blocker: the row stays present, and its error and hint lines (the install failures' fields) say that- /// NVN games will stop. Pure over its inputs, so tests give it version strings.- nonisolated static func metalDep(runs: Bool, lock: String?, now: [String: String?], needsIOS: Bool) -> Dep {- var dep = Dep(id: "metal", name: "dep.metal", hint: "dep.metal.hint", present: runs, installCmd: Toolchain.metalToolchainCmd)- guard runs, let lock, let m = MetalPin.mismatches(lock: lock, now: now, iOS: needsIOS).first else { return dep }- dep.warning = true- dep.detail = "dep.metal.other:" + m.now + ":" + m.pinned- dep.lastError = "metal_" + m.sdk + ": " + m.now- dep.fixHint = "dep.fix.metalPin"- return dep- }-- nonisolated static func detectDepsSync(needsIOS: Bool = BuildModel.needsIOSPlatform(), repo: String = "") -> [Dep] {- var out: [Dep] = []-- // Xcode.app alone is not enough: since Xcode 15 the iOS platform ships as a separate- // download, so a fresh install has xcodebuild but no iOS SDK and the build dies deep in- // xcodebuild. Ask for the SDK version itself — that is the check that matches the name.- // And ask xcode-select where Xcode is, not a fixed path: a beta lives at- // /Applications/Xcode-beta.app and the hard-coded check called that "no Xcode" (#21).- let selected = Toolchain.developerDir()- let xcodeApp = Toolchain.installedXcode()- let sdkenv = Toolchain.runOK("/usr/bin/xcrun", ["--sdk", "iphoneos", "--show-sdk-version"])- // A Mac-only setup does not need the iOS platform (onboarding's platform choice, #120); a- // Mac build still needs a selected Xcode, so the CommandLineTools state is reported either way.- switch Toolchain.xcodeState(selected: selected, xcodeApp: xcodeApp, iosSDK: !needsIOS || sdkenv) {- case .ready:- out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []))- case .noIOSSDK:- out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false,- detail: "dep.xcode.noSDK", installCmd: Toolchain.iosPlatformCmd))- case .commandLineToolsOnly(let xcode):- out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false,- detail: "dep.xcode.notSelected", actionLabel: "dep.xcode.fix",- installCmd: Toolchain.selectXcodeCmd(xcode)))- case .notInstalled:- out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: []))- }-- let macMetal = Toolchain.firstOutputLine("/usr/bin/xcrun", ["-sdk", "macosx", "metal", "--version"])- let lock = repo.isEmpty ? nil : try? String(contentsOfFile: EngineLayout.root(repo) + "/" + MetalPin.lockPath, encoding: .utf8)- let iosMetal = needsIOS && lock != nil ? Toolchain.firstOutputLine("/usr/bin/xcrun", ["-sdk", "iphoneos", "metal", "--version"]) : nil- out.append(metalDep(runs: macMetal != nil, lock: lock, now: ["macosx": macMetal, "iphoneos": iosMetal], needsIOS: needsIOS))-- out += Toolchain.toolDeps(resources: BundledTools.resources,- installed: { Toolchain.firstExisting(["/opt/homebrew/bin/\($0)", "/usr/local/bin/\($0)"]) },- brew: Toolchain.firstExisting(["/opt/homebrew/bin/brew", "/usr/local/bin/brew"]))-- let (dn, dnOK) = Toolchain.findDotnet()- out.append(Dep(id: "dotnet", name: "dep.dotnet", hint: "dep.dotnet.hint",- present: dnOK, detail: dnOK ? dn : "dep.dotnet.missing",- installCmd: ["/bin/bash", "-c",- "curl -sSL https://dot.net/v1/dotnet-install.sh -o /tmp/di.sh && chmod +x /tmp/di.sh && /tmp/di.sh --channel 10.0 --install-dir $HOME/.dotnet"]))-- let (py, pyOK) = Toolchain.findPython()- // A too-old interpreter is a different problem from a missing package: say which one it is,- // because the fix differs (install a newer Python vs pip install into this one).- // A version we cannot read means no interpreter ran at all (py is then the venv- // that does not exist yet), which is not the same as one that is too old.- let pyDetail = Toolchain.pythonDetail(py: py, ok: pyOK)- out.append(Dep(id: "python", name: "dep.python", hint: "dep.python.hint",- present: pyOK, detail: pyDetail,- installCmd: [py, "-m", "pip", "install", "--user", "lz4", "capstone", "fonttools", "zbic", "backports.zstd"]))- return out- }-- func checkDeps() {- depsChecked = false- DispatchQueue.global(qos: .userInitiated).async {- let d = Self.detectDepsSync(repo: self.repoPath)- Self.writeDepsReport(d)- let (py, _) = Toolchain.findPython()- let (dn, _) = Toolchain.findDotnet()- DispatchQueue.main.async {- self.deps = d- self.pythonPath = py // the interpreter the build runs under- self.dotnetPath = FileManager.default.isExecutableFile(atPath: dn) ? dn : ""- self.depsChecked = true- }- }- }-- /// Write what the panel just decided beside library.json (`deps-check.txt`).- ///- /// The panel is the only place those verdicts appear, so "it says Python is missing" cannot be- /// checked afterwards: the interpreter that was tried, and the environment a Finder launch- /// gives the app (its PATH is /usr/bin:/bin:/usr/sbin:/sbin, unlike the terminal's), are both- /// invisible in a bug report. This file has them — paths and versions only, never key material.- nonisolated static func writeDepsReport(_ deps: [Dep]) {- let dir = (Toolchain.venvDir as NSString).deletingLastPathComponent- try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)- var out = "NX2Apple \(AppUpdateStore.appVersion) dependency check\n"- out += "date: \(ISO8601DateFormatter().string(from: Date()))\n"- out += "HOME: \(NSHomeDirectory())\n"- out += "PATH: \(ProcessInfo.processInfo.environment["PATH"] ?? "(unset)")\n"- let chosen = Toolchain.findPython()- let bundled = BundledTools.python()- out += "python chosen: \(chosen.path) (\(chosen.ok ? "ok" : "not usable")\(chosen.path == bundled ? ", bundled with the app" : ""))\n"- out += "bundled python: \(bundled ?? "(none: not the release app)")\n"- out += "python candidates (after the bundled one, in search order):\n"- for c in Toolchain.pythonCandidates() { out += " \(c)\n" }- out += "rows:\n"- for d in deps { out += " \(d.id): \(d.present ? "ok" : "MISSING") \(d.detail)\n" }- try? out.write(toFile: dir + "/deps-check.txt", atomically: true, encoding: .utf8)- }-- func installDep(_ dep: Dep) {- guard !dep.installCmd.isEmpty else {- NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications/App Store.app"))- return // Xcode comes from the App Store; the user re-checks when it is done- }- guard let i = deps.firstIndex(where: { $0.id == dep.id }) else { return }- deps[i].installing = true- let cmd = dep.installCmd- DispatchQueue.global(qos: .userInitiated).async {- var ok = true- if dep.id == "python" {- // A venv of our own rather than pip --user: Homebrew's Python is externally- // managed (PEP 668) and refuses --user, which used to fail silently.- let r = Toolchain.makeVenv(base: self.pythonPath)- DispatchQueue.main.async { self.append("\n--- 安装输出 ---\n" + r.log) }- ok = r.ok- } else {- let collected = LineBox()- ok = self.runner.runCaptured(["/bin/bash", "-c",- cmd.map { $0.contains(" ") ? "'" + $0 + "'" : $0 }.joined(separator: " ")],- env: ["PATH": "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",- "HOME": NSHomeDirectory(), "NONINTERACTIVE": "1", "USER": NSUserName()])- { line in- collected.append(line)- DispatchQueue.main.async { self.append(line + "\n") }- }- let (error, fix) = BuildProgress.failureInfo(collected.lines)- DispatchQueue.main.async {- if let j = self.deps.firstIndex(where: { $0.id == dep.id }) {- self.deps[j].lastError = ok ? "" : error- self.deps[j].fixHint = ok ? "" : fix- }- }- }- DispatchQueue.main.async {- if let j = self.deps.firstIndex(where: { $0.id == dep.id }) { self.deps[j].installing = false }- if ok, let j = self.deps.firstIndex(where: { $0.id == dep.id }) { self.deps[j].lastError = ""; self.deps[j].fixHint = "" }- if !ok { self.doneNote = String(format: self.t("dep.install.fail"), self.t(dep.name)) }- self.checkDeps()- }- }- }-- /// The output lines seen so far, from the pipe's threads and read on the main queue.- final class LineBox: @unchecked Sendable {- private let lock = NSLock()- private var box: [String] = []- func append(_ l: String) { lock.lock(); box.append(l); lock.unlock() }- var lines: [String] { lock.lock(); defer { lock.unlock() }; return box }- }-- var allDepsPresent: Bool { depsChecked && deps.allSatisfy { $0.present } }-/// Home shown as ~ (shorter in a one-line row, and it keeps the account name out of/// screenshots).func shortPath(_ path: String) -> String { RepoLayout.shortPath(path) }-- /// A dependency row's second column: a path when there is one, else the translated hint.- /// `detail` carries either a real path, an L10n key, or "key:argument[:argument…]".- func depDetail(_ d: Dep) -> String {- let raw = d.detail- if raw.isEmpty { return t(d.hint) }- if raw.hasPrefix("/") || raw.hasPrefix("~") { return raw }- if let colon = raw.firstIndex(of: ":") {- let key = String(raw[..<colon]), arg = String(raw[raw.index(after: colon)...])- let args = arg.components(separatedBy: ":").map { shortPath($0) as CVarArg }- if L10n.table[key] != nil { return String(format: t(key), arguments: args) }- }- if L10n.table[raw] != nil { return t(raw) }- return raw- }}// MARK: - View@@ -1538,6 +1382,7 @@ struct BuilderView: View {@ObservedObject var updates: AppUpdateStore // the app's self-update (Settings, "NX2Apple" section)@ObservedObject var repo: RepoStore // the repository (Settings, "Tools" section, and the setup hint)@ObservedObject var engine: EngineSyncStore // the engine (Settings, "Tools" section)+ @ObservedObject var dependencies: DependencyStore // the tools (Settings, "Tools" section, and the setup hint and status)@EnvironmentObject var loc: Localizer@ObservedObject var library: GameLibraryvar settings = false@@ -1656,7 +1501,7 @@ struct BuilderView: View {@ViewBuilder private var buildPage: some View {pageHeading(loc.t("build.heading"), note: loc.t("build.intro"))- if !repo.isRepo || !m.allDepsPresent {+ if !repo.isRepo || !dependencies.allPresent {group(loc.t("section.setup")) {row(loc.t("library.setupHint"), dot: LauncherPalette.building) {Button(loc.t("build.setup"), action: onOpenSettings)@@ -1916,9 +1761,9 @@ struct BuilderView: View {if !m.doneNote.isEmpty {Text(m.doneNote).font(.manrope(13)).foregroundStyle(m.done ? LauncherPalette.ready : LauncherPalette.building).lineLimit(2)- } else if !m.depsChecked {+ } else if !dependencies.checked {Text(loc.t("status.checkingDeps")).font(.manrope(13)).foregroundStyle(.secondary)- } else if !m.allDepsPresent {+ } else if !dependencies.allPresent {Text(loc.t("status.installFirst")).font(.manrope(13)).foregroundStyle(LauncherPalette.building)} else if !repo.isRepo {Text(loc.t("status.chooseRepo")).font(.manrope(13)).foregroundStyle(LauncherPalette.building)@@ -2118,30 +1963,30 @@ struct BuilderView: View {}}divider- Button(action: { withAnimation(.easeInOut(duration: 0.18)) { m.toggleDeps() } }) {+ Button(action: { withAnimation(.easeInOut(duration: 0.18)) { dependencies.toggle() } }) {row(loc.t("dep.title"),- detail: !m.depsChecked ? loc.t("dep.checking")- : (m.allDepsPresent ? loc.t("dep.allReady") : String(format: loc.t("dep.missing"), m.deps.filter { !$0.present }.count)),- dot: !m.depsChecked ? LauncherPalette.unbuilt : (m.allDepsPresent ? LauncherPalette.ready : LauncherPalette.building),- open: m.depsOpen) {- if !m.depsChecked { ProgressView().controlSize(.small) }- Button(loc.t("dep.recheck")) { m.checkDeps() }- .padTarget("set.deps", scope: "main") { m.checkDeps() }+ detail: !dependencies.checked ? loc.t("dep.checking")+ : (dependencies.allPresent ? loc.t("dep.allReady") : String(format: loc.t("dep.missing"), dependencies.deps.filter { !$0.present }.count)),+ dot: !dependencies.checked ? LauncherPalette.unbuilt : (dependencies.allPresent ? LauncherPalette.ready : LauncherPalette.building),+ open: dependencies.open) {+ if !dependencies.checked { ProgressView().controlSize(.small) }+ Button(loc.t("dep.recheck")) { _ = dependencies.check() }+ .padTarget("set.deps", scope: "main") { _ = dependencies.check() }}.contentShape(Rectangle())}.buttonStyle(.plain)- if m.depsOpen {- ForEach(m.deps, id: \.id) { d in+ if dependencies.open {+ ForEach(dependencies.deps, id: \.id) { d individerVStack(alignment: .leading, spacing: 0) {- row(loc.t(d.name), detail: m.shortPath(m.depDetail(d)), dot: d.present && !d.warning ? LauncherPalette.ready : LauncherPalette.building,+ row(loc.t(d.name), detail: m.shortPath(dependencies.detail(of: d)), dot: d.present && !d.warning ? LauncherPalette.ready : LauncherPalette.building,help: loc.t(d.hint)) {if d.installing {ProgressView().controlSize(.small)Text(loc.t("dep.installing")).font(.manrope(12)).foregroundStyle(LauncherPalette.building)} else if !d.present {- Button(d.actionLabel.isEmpty ? (d.installCmd.isEmpty ? loc.t("dep.openAppStore") : loc.t("dep.install")) : loc.t(d.actionLabel)) { m.installDep(d) }+ Button(d.actionLabel.isEmpty ? (d.installCmd.isEmpty ? loc.t("dep.openAppStore") : loc.t("dep.install")) : loc.t(d.actionLabel)) { _ = dependencies.install(d) }}}// Why the last install failed, and what to do about it: the tool's owndiff --git a/frontend/Sources/NX2Apple/Diagnostics.swift b/frontend/Sources/NX2Apple/Diagnostics.swiftindex 4da29fc9..e7f104db 100644--- a/frontend/Sources/NX2Apple/Diagnostics.swift+++ b/frontend/Sources/NX2Apple/Diagnostics.swift@@ -298,7 +298,7 @@ extension BuildModel {/// The report, read in the background and handed back on the main thread.func diagnostics(game: LibraryGame? = nil, _ done: @escaping (String) -> Void) {let repo = repoOK ? repoPath : "", python = pythonPath.isEmpty ? Toolchain.findPython().path : pythonPath, dotnet = dotnetPath- let rows = depsChecked ? deps.map(Diagnostics.dependency) : [], checked = depsChecked+ let checked = depsChecked, rows = checked ? MainActor.assumeIsolated { dependencies.deps }.map(Diagnostics.dependency) : []let command = lastBuildCommand, log = logTail, xcrun = xcrunPathlet (sel, usesEngineStore) = MainActor.assumeIsolated { (engineSync.selection, engineSync.usesEngineStore) }let engine = usesEngineStore && !sel.engineID.isEmpty ? "\(sel.channel.rawValue) \(sel.version) (\(sel.engineID))" : nildiff --git a/frontend/Sources/NX2Apple/LauncherView.swift b/frontend/Sources/NX2Apple/LauncherView.swiftindex 455615df..e154bf24 100644--- a/frontend/Sources/NX2Apple/LauncherView.swift+++ b/frontend/Sources/NX2Apple/LauncherView.swift@@ -177,7 +177,7 @@ struct ContentView: View {if page == .library {libraryPage} else {- BuilderView(m: m, updates: updates, repo: repo, engine: engine, library: library, settings: page == .settings, onViewGame: { page = .library },+ BuilderView(m: m, updates: updates, repo: repo, engine: engine, dependencies: m.dependencies, library: library, settings: page == .settings, onViewGame: { page = .library },onOpenSettings: { page = .settings }, onChooseLibraryFolder: chooseLibraryFolder,onOpenControls: { controlsOpen = true }, onOpenControllers: { controllerSheet = true }, onRunSetup: onRunSetup, controlChanges: controls.changeCount,padMerge: Binding(get: { controls.padMerge }, set: { setPadMerge($0) }))@@ -215,7 +215,7 @@ struct ContentView: View {readSignatures()if performStartupChecks { library.discover(); fetchArtwork(); m.refreshDevices(); checkTools() }if performStartupChecks {- m.checkDeps()+ _ = m.dependencies.check()if engine.usesEngineStore { engine.prepareEngine() } // the release app: its engine store, never gitelse { engine.syncEngine() } // a checkout whose engine/ is missing or older than its pin (#214)if repo.isRepo && repo.isGit { repo.checkForUpdates(silent: true) } else { repo.adoptAtLaunch() }diff --git a/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift b/frontend/Sources/NX2Apple/LiveOnboardingDriver.swiftindex bcc2ab6c..778069ea 100644--- a/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift+++ b/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift@@ -43,10 +43,10 @@ struct OnboardingEnvironment {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`).+ /// Detection again, finished when it has published (`DependencyStore.check`).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, Dep) -> Void = { $0.installDep($1) }+ /// One install through the launcher's own mechanics (`DependencyStore.install`); its end shows as a new detection.+ var installDep: (BuildModel, Dep) -> Void = { m, d in MainActor.assumeIsolated { _ = m.dependencies.install(d) } }var openURL: (URL) -> Void = { NSWorkspace.shared.open($0) }var keyCheck: (_ keys: String, _ base: String) async -> KeyCheck.Outcome = { keys, base inawait Task.detached { KeyCheck.run(KeyCheck.Inputs(keys: keys, files: base.isEmpty ? [] : [base])) }.value@@ -158,10 +158,10 @@ enum OnboardingAdmin {}extension BuildModel {- /// `checkDeps()`, finished: returns once the new detection has been published.+ /// `DependencyStore.check()`, finished: returns once the new detection has been published.func refreshDepsAndWait() async {- checkDeps()- for await checked in $depsChecked.values where checked { break }+ let check = await MainActor.run { dependencies.check() }+ await check.value}}@@ -177,8 +177,8 @@ enum OnboardingLaunch {/// 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+/// One value, `state`, is what the view draws. Detection comes from `model.dependencies.deps` (refreshed through `model.dependencies.check`),+/// installs run through `model.dependencies.install` 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 {@@ -253,7 +253,7 @@ enum OnboardingLaunch {/// 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+ subscription = model.dependencies.$checked.removeDuplicates().sink { [weak self] checked inguard let self else { return }if !checked { self.sawRecheck = true; return }self.spawn("refresh") { d in await d.modelDidRefresh() }@@ -404,7 +404,7 @@ enum OnboardingLaunch {if state.selectedPlatform != nil { backgroundStarted = true }if waitingForXcode { pollForXcode() }spawn("enter.xcode") { d in- if !d.model.depsChecked { await d.env.detectDeps(d.model) }+ if !d.model.dependencies.checked { await d.env.detectDeps(d.model) }await d.modelDidRefresh()}case .keys:@@ -425,7 +425,7 @@ enum OnboardingLaunch {/// 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) }+ if !model.dependencies.checked { await env.detectDeps(model) }probe = await env.xcodeProbe(); probed = truelet (xcode, _) = OnboardingXcode.evaluate(probe: probe, metalReady: dep("metal")?.present ?? false,iosReady: dep("xcode")?.present ?? false, includesIOS: state.selectedPlatform?.includesIOS == true)@@ -455,11 +455,11 @@ enum OnboardingLaunch {// MARK: Xcode- private func dep(_ id: String) -> Dep? { model.deps.first { $0.id == id } }+ private func dep(_ id: String) -> Dep? { model.dependencies.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 }+ guard model.dependencies.checked, state.exit == nil else { return }concludeInstall()await refreshXcode()recomputeBackground()@@ -573,14 +573,14 @@ enum OnboardingLaunch {private static let handled: Set<String> = ["xcode", "metal", "python", "dotnet"]private func deps(for task: OnboardingBackgroundTask) -> [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) }+ case .python: return model.dependencies.deps.filter { $0.id == "python" }+ case .dotnet: return model.dependencies.deps.filter { $0.id == "dotnet" }+ case .tools: return model.dependencies.deps.filter { !Self.handled.contains($0.id) }}}func recomputeBackground() {- guard backgroundStarted, model.depsChecked else { return }+ guard backgroundStarted, model.dependencies.checked else { return }for task in OnboardingBackgroundTask.allCases {let rows = deps(for: task)if rows.allSatisfy(\.present) { state.background[task] = .done }@@ -593,7 +593,7 @@ enum OnboardingLaunch {/// 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 installApproved, backgroundStarted, model.depsChecked, currentInstall == nil, state.exit == nil else { return }+ guard installApproved, backgroundStarted, model.dependencies.checked, 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 }diff --git a/frontend/Sources/NX2Apple/OnboardingRoot.swift b/frontend/Sources/NX2Apple/OnboardingRoot.swiftindex 572b34aa..383734d9 100644--- a/frontend/Sources/NX2Apple/OnboardingRoot.swift+++ b/frontend/Sources/NX2Apple/OnboardingRoot.swift@@ -66,7 +66,7 @@ struct RootView: View {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)+ let complete = OnboardingLaunch.setupComplete(depsPresent: model.dependencies.allPresent, keysKnown: keysKnown, gamesKnown: gamesKnown)if OnboardingLaunch.shouldShow(completed: false, setupComplete: complete) {show(fresh: false)} else {diff --git a/frontend/Sources/NXCore/DependencyCheck.swift b/frontend/Sources/NXCore/DependencyCheck.swiftnew file mode 100644index 00000000..eb16cfd2--- /dev/null+++ b/frontend/Sources/NXCore/DependencyCheck.swift@@ -0,0 +1,130 @@+import Foundation++/// Looking at this Mac for what a build needs, as the rows of the dependency panel (`Dep`). The probing itself is `Toolchain`. This+/// is the list: which rows there are, in which order, and what each one runs to install. `DependencyStore` (NXModel) calls it.+package enum DependencyCheck {+ /// What one detection found: the rows, and the interpreter and the dotnet the build runs under.+ package struct Result {+ package var deps: [Dep]+ package var python: String+ package var dotnet: String // empty when none runs++ package init(deps: [Dep], python: String, dotnet: String) {+ self.deps = deps; self.python = python; self.dotnet = dotnet+ }+ }++ /// The Metal toolchain row. A compiler that does not run is the missing-toolchain row with its install button. One that differs from the+ /// lock's pin is a warning and not a blocker: the row stays present, and its error and hint lines (the install failures' fields) say that+ /// NVN games will stop. Pure over its inputs, so tests give it version strings.+ package static func metalDep(runs: Bool, lock: String?, now: [String: String?], needsIOS: Bool) -> Dep {+ var dep = Dep(id: "metal", name: "dep.metal", hint: "dep.metal.hint", present: runs, installCmd: Toolchain.metalToolchainCmd)+ guard runs, let lock, let m = MetalPin.mismatches(lock: lock, now: now, iOS: needsIOS).first else { return dep }+ dep.warning = true+ dep.detail = "dep.metal.other:" + m.now + ":" + m.pinned+ dep.lastError = "metal_" + m.sdk + ": " + m.now+ dep.fixHint = "dep.fix.metalPin"+ return dep+ }++ /// The dotnet installer's command (into ~/.dotnet, where `Toolchain.findDotnet` looks).+ package static let dotnetInstallCmd = ["/bin/bash", "-c",+ "curl -sSL https://dot.net/v1/dotnet-install.sh -o /tmp/di.sh && chmod +x /tmp/di.sh && /tmp/di.sh --channel 10.0 --install-dir $HOME/.dotnet"]++ /// The rows. `needsIOS`: the xcode row asks for the iOS SDK. `repo`: the checkout whose lock pins the Metal compiler ("" for none).+ package static func detect(needsIOS: Bool, repo: String = "") -> [Dep] {+ var out: [Dep] = []++ // Xcode.app alone is not enough: since Xcode 15 the iOS platform ships as a separate+ // download, so a fresh install has xcodebuild but no iOS SDK and the build dies deep in+ // xcodebuild. Ask for the SDK version itself — that is the check that matches the name.+ // And ask xcode-select where Xcode is, not a fixed path: a beta lives at+ // /Applications/Xcode-beta.app and the hard-coded check called that "no Xcode" (#21).+ let selected = Toolchain.developerDir()+ let xcodeApp = Toolchain.installedXcode()+ let sdkenv = Toolchain.runOK("/usr/bin/xcrun", ["--sdk", "iphoneos", "--show-sdk-version"])+ // A Mac-only setup does not need the iOS platform (onboarding's platform choice, #120); a+ // Mac build still needs a selected Xcode, so the CommandLineTools state is reported either way.+ switch Toolchain.xcodeState(selected: selected, xcodeApp: xcodeApp, iosSDK: !needsIOS || sdkenv) {+ case .ready:+ out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []))+ case .noIOSSDK:+ out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false,+ detail: "dep.xcode.noSDK", installCmd: Toolchain.iosPlatformCmd))+ case .commandLineToolsOnly(let xcode):+ out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false,+ detail: "dep.xcode.notSelected", actionLabel: "dep.xcode.fix",+ installCmd: Toolchain.selectXcodeCmd(xcode)))+ case .notInstalled:+ out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: []))+ }++ let macMetal = Toolchain.firstOutputLine("/usr/bin/xcrun", ["-sdk", "macosx", "metal", "--version"])+ let lock = repo.isEmpty ? nil : try? String(contentsOfFile: EngineLayout.root(repo) + "/" + MetalPin.lockPath, encoding: .utf8)+ let iosMetal = needsIOS && lock != nil ? Toolchain.firstOutputLine("/usr/bin/xcrun", ["-sdk", "iphoneos", "metal", "--version"]) : nil+ out.append(metalDep(runs: macMetal != nil, lock: lock, now: ["macosx": macMetal, "iphoneos": iosMetal], needsIOS: needsIOS))++ out += Toolchain.toolDeps(resources: BundledTools.resources,+ installed: { Toolchain.firstExisting(["/opt/homebrew/bin/\($0)", "/usr/local/bin/\($0)"]) },+ brew: Toolchain.firstExisting(["/opt/homebrew/bin/brew", "/usr/local/bin/brew"]))++ let (dn, dnOK) = Toolchain.findDotnet()+ out.append(Dep(id: "dotnet", name: "dep.dotnet", hint: "dep.dotnet.hint",+ present: dnOK, detail: dnOK ? dn : "dep.dotnet.missing",+ installCmd: dotnetInstallCmd))++ let (py, pyOK) = Toolchain.findPython()+ // A too-old interpreter is a different problem from a missing package: say which one it is,+ // because the fix differs (install a newer Python vs pip install into this one).+ // A version we cannot read means no interpreter ran at all (py is then the venv+ // that does not exist yet), which is not the same as one that is too old.+ let pyDetail = Toolchain.pythonDetail(py: py, ok: pyOK)+ out.append(Dep(id: "python", name: "dep.python", hint: "dep.python.hint",+ present: pyOK, detail: pyDetail,+ installCmd: [py, "-m", "pip", "install", "--user", "lz4", "capstone", "fonttools", "zbic", "backports.zstd"]))+ return out+ }++ /// The rows and the paths of the interpreter and of dotnet the build runs under.+ package static func scan(needsIOS: Bool, repo: String) -> Result {+ let deps = detect(needsIOS: needsIOS, repo: repo)+ let (py, _) = Toolchain.findPython()+ let (dn, _) = Toolchain.findDotnet()+ return Result(deps: deps, python: py, dotnet: FileManager.default.isExecutableFile(atPath: dn) ? dn : "")+ }++ /// Write what the panel just decided beside library.json (`deps-check.txt`).+ ///+ /// The panel is the only place those verdicts appear, so "it says Python is missing" cannot be+ /// checked afterwards: the interpreter that was tried, and the environment a Finder launch+ /// gives the app (its PATH is /usr/bin:/bin:/usr/sbin:/sbin, unlike the terminal's), are both+ /// invisible in a bug report. This file has them — paths and versions only, never key material.+ package static func writeReport(_ deps: [Dep], appVersion: String) {+ let dir = (Toolchain.venvDir as NSString).deletingLastPathComponent+ try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)+ var out = "NX2Apple \(appVersion) dependency check\n"+ out += "date: \(ISO8601DateFormatter().string(from: Date()))\n"+ out += "HOME: \(NSHomeDirectory())\n"+ out += "PATH: \(ProcessInfo.processInfo.environment["PATH"] ?? "(unset)")\n"+ let chosen = Toolchain.findPython()+ let bundled = BundledTools.python()+ out += "python chosen: \(chosen.path) (\(chosen.ok ? "ok" : "not usable")\(chosen.path == bundled ? ", bundled with the app" : ""))\n"+ out += "bundled python: \(bundled ?? "(none: not the release app)")\n"+ out += "python candidates (after the bundled one, in search order):\n"+ for c in Toolchain.pythonCandidates() { out += " \(c)\n" }+ out += "rows:\n"+ for d in deps { out += " \(d.id): \(d.present ? "ok" : "MISSING") \(d.detail)\n" }+ try? out.write(toFile: dir + "/deps-check.txt", atomically: true, encoding: .utf8)+ }++ /// The command line of an install, run by bash: words with a space are quoted.+ package static func shellCommand(_ cmd: [String]) -> [String] {+ ["/bin/bash", "-c", cmd.map { $0.contains(" ") ? "'" + $0 + "'" : $0 }.joined(separator: " ")]+ }++ /// The environment an install runs in: Homebrew's folders in front, and no prompt.+ package static func installEnvironment() -> [String: String] {+ ["PATH": "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",+ "HOME": NSHomeDirectory(), "NONINTERACTIVE": "1", "USER": NSUserName()]+ }+}diff --git a/frontend/Sources/NXCore/MetalPin.swift b/frontend/Sources/NXCore/MetalPin.swiftnew file mode 100644index 00000000..573dd94f--- /dev/null+++ b/frontend/Sources/NXCore/MetalPin.swift@@ -0,0 +1,51 @@+import Foundation++/// The Metal compiler the shaders were tested with (dm/gfx/tools/dmsh_chain.lock) against this Mac's. NVN games stop at the+/// start of the shader steps with another compiler of the lock's generation or an older one (own_compilers.py --check-metal), so+/// the dependency panel says so beforehand; a newer compiler of the same generation builds with a note, like the script's gate.+/// The comparison is the script's: the first line of `xcrun -sdk <sdk> metal --version`, and a compiler that is not there is+/// not a mismatch (its own row reports a missing one).+package enum MetalPin {+ package struct Mismatch: Equatable { package var sdk: String; package var now: String; package var pinned: String }++ package static let lockPath = "dm/gfx/tools/dmsh_chain.lock"++ /// `metal_macosx` / `metal_iphoneos` lines of the lock: tab separated, `#` for comments.+ package static func pins(lock: String) -> [String: String] {+ var out: [String: String] = [:]+ for line in lock.split(separator: "\n", omittingEmptySubsequences: true) where !line.hasPrefix("#") {+ let parts = line.split(separator: "\t", maxSplits: 1, omittingEmptySubsequences: false)+ if parts.count == 2 { out[String(parts[0])] = String(parts[1]).trimmingCharacters(in: .whitespaces) }+ }+ return out+ }++ /// `now`: the compilers found, by SDK name (macosx, iphoneos), nil for one that did not answer.+ /// An iOS compiler is compared only when `iOS` (the build is for an iPhone).+ /// A newer compiler of the recorded generation is not a mismatch: Xcode's auto-update bumps it+ /// and a player cannot hold Xcode back — the engine's gate builds with a note (own_compilers.py, #242).+ package static func mismatches(lock: String, now: [String: String?], iOS: Bool) -> [Mismatch] {+ let pinned = pins(lock: lock)+ var out: [Mismatch] = []+ for sdk in iOS ? ["macosx", "iphoneos"] : ["macosx"] {+ guard let want = pinned["metal_" + sdk], let found = now[sdk] ?? nil, !found.isEmpty, found != want, !buildsOn(tested: want, found: found) else { continue }+ out.append(Mismatch(sdk: sdk, now: found, pinned: want))+ }+ return out+ }++ /// `Apple metal version 32023.921 (metalfe-32023.921.6)` → (32023, 921, 6); nil for another shape.+ package static func version(_ s: String) -> (Int, Int, Int)? {+ let text = s.trimmingCharacters(in: .whitespaces)+ let pattern = "^Apple metal version (\\d+)\\.(\\d+) \\(metalfe-\\d+\\.\\d+\\.(\\d+)\\)$"+ guard let re = try? NSRegularExpression(pattern: pattern), let m = re.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)), m.numberOfRanges == 4 else { return nil }+ let g = { (i: Int) in Int((text as NSString).substring(with: m.range(at: i))) }+ return g(1) != nil && g(2) != nil && g(3) != nil ? (g(1)!, g(2)!, g(3)!) : nil+ }++ /// Same leading version and strictly newer: the tested Xcode's compiler against the one an auto-update brought.+ package static func buildsOn(tested: String, found: String) -> Bool {+ guard let a = version(tested), let b = version(found) else { return false }+ return a.0 == b.0 && b > a+ }+}diff --git a/frontend/Sources/NXModel/DependencyStore.swift b/frontend/Sources/NXModel/DependencyStore.swiftnew file mode 100644index 00000000..59b6b7f0--- /dev/null+++ b/frontend/Sources/NXModel/DependencyStore.swift@@ -0,0 +1,188 @@+import Foundation+import Combine+import NXCore++/// Where the Python interpreter is, for a store that only needs to read it. `DependencyStore` provides it. Empty: not found yet,+/// and the user of it looks for one itself.+@MainActor package protocol PythonLocation: AnyObject {+ var pythonPath: String { get }+}++/// What the build needs to know about the tools, without the store that installs them: the check ran, everything it needs is+/// there, which interpreter and which dotnet it runs under, and the rows (for the diagnostics report).+@MainActor package protocol DependencyStatus: PythonLocation {+ /// The check has finished at least once since the last one started.+ var checked: Bool { get }+ /// The check finished and no row is missing (a warning row counts as present).+ var allPresent: Bool { get }+ /// The dotnet the build runs under. Empty: none runs.+ var dotnetPath: String { get }+ var deps: [Dep] { get }+}++/// The dependencies (LNPANDY/NX2Apple#387, step 7): the rows of the tools panel (Xcode and its SDK, the Metal toolchain, the+/// Homebrew tools, .NET, the Python packages), the interpreter and the dotnet the build runs under, and the installs. It follows+/// `AppUpdateStore` (`frontend/ARCHITECTURE.md`, "Stores").+///+/// - What it works with comes through `init`: the `Localizer`, a `ProcessRunner` for the installs, the repository (`RepoLocation`)+/// whose lock pins the Metal compiler, the defaults it saves the expanded panel in. The detection is a closure (`scan`) with the+/// real one as default, so a test gives it rows without probing the machine. Whether the iOS SDK is asked for, opening the App+/// Store (Xcode comes from there), the build log and the note after a failed install are closures the app wires.+/// - The work blocks, so it runs off the main actor. `check()` and `install(_:)` set their state first and return the `Task`.+/// - `install` runs the row's own command, and for the Python row the venv install. A row that is installing says so+/// (`Dep.installing`), a failure keeps the tool's first error line and the fix to show (`Dep.lastError`, `Dep.fixHint`).+@MainActor package final class DependencyStore: ObservableObject, DependencyStatus {+ nonisolated package static let expandedKey = "depsExpanded"++ @Published package var deps: [Dep] = []+ /// The check ran. False while one runs, so the panel shows its spinner.+ @Published package var checked = false+ /// Whether the dependency list is expanded. nil = not chosen yet: open while something is+ /// missing (that is when the rows matter), collapsed once everything is green — a set-up+ /// machine never needs the rows again. A manual toggle overrides and is remembered.+ @Published package var expanded: Bool? {+ didSet { if let v = expanded { defaults.set(v, forKey: Self.expandedKey) } }+ }+ /// The interpreter the build runs under, set by the check.+ @Published package var pythonPath = ""+ @Published package var dotnetPath = ""++ private let localizer: Localizer+ private let runner: ProcessRunner+ private let repo: RepoLocation+ private let defaults: UserDefaults+ private let needsIOS: () -> Bool+ private let scan: @Sendable (_ repo: String, _ needsIOS: Bool) -> DependencyCheck.Result+ private let report: @Sendable ([Dep]) -> Void+ private let openAppStore: () -> Void+ private let log: (String) -> Void+ private let installFailed: (String) -> Void++ /// - Parameters:+ /// - needsIOS: whether the xcode row asks for the iOS SDK (the guided setup's platform choice).+ /// - scan: the detection, for a repository path and `needsIOS`. Runs off the main actor.+ /// - report: writes what the check decided (`deps-check.txt`). Runs off the main actor.+ /// - openAppStore: a row with no command (Xcode) opens the App Store.+ /// - log: a line for the build log (an install's output).+ /// - installFailed: the note for a failed install, already translated.+ package init(localizer: Localizer, runner: ProcessRunner, repo: RepoLocation, defaults: UserDefaults = .standard,+ needsIOS: @escaping () -> Bool = { true },+ scan: @escaping @Sendable (String, Bool) -> DependencyCheck.Result = { DependencyCheck.scan(needsIOS: $1, repo: $0) },+ report: @escaping @Sendable ([Dep]) -> Void = { DependencyCheck.writeReport($0, appVersion: AppUpdateStore.appVersion) },+ openAppStore: @escaping () -> Void = {}, log: @escaping (String) -> Void = { _ in },+ installFailed: @escaping (String) -> Void = { _ in }) {+ self.localizer = localizer+ self.runner = runner+ self.repo = repo+ self.defaults = defaults+ self.needsIOS = needsIOS+ self.scan = scan+ self.report = report+ self.openAppStore = openAppStore+ self.log = log+ self.installFailed = installFailed+ expanded = defaults.object(forKey: Self.expandedKey) as? Bool+ }++ // ---- What the views and the build read ----++ package var allPresent: Bool { checked && deps.allSatisfy { $0.present } }++ /// Whether the list shows its rows: the choice made, else open while something is missing.+ package var open: Bool { expanded ?? !(checked && allPresent) }++ package func toggle() {+ expanded = !(expanded ?? !allPresent)+ }++ /// Whether the row `id` runs its install now.+ package func isInstalling(_ id: String) -> Bool {+ deps.first { $0.id == id }?.installing ?? false+ }++ /// A row's second column: a path when there is one, else the translated hint.+ /// `detail` carries either a real path, an L10n key, or "key:argument[:argument…]".+ package func detail(of d: Dep) -> String {+ let raw = d.detail+ if raw.isEmpty { return localizer.t(d.hint) }+ if raw.hasPrefix("/") || raw.hasPrefix("~") { return raw }+ if let colon = raw.firstIndex(of: ":") {+ let key = String(raw[..<colon]), arg = String(raw[raw.index(after: colon)...])+ let args = arg.components(separatedBy: ":").map { RepoLayout.shortPath($0) as CVarArg }+ if L10n.table[key] != nil { return String(format: localizer.t(key), arguments: args) }+ }+ if L10n.table[raw] != nil { return localizer.t(raw) }+ return raw+ }++ // ---- The check ----++ /// Looks at this Mac again: the rows, the interpreter and the dotnet. The panel shows its spinner until it has published.+ @discardableResult+ package func check() -> Task<Void, Never> {+ checked = false+ let path = repo.path, needsIOS = needsIOS(), scan = self.scan, report = self.report+ return Task {+ let found = await Task.detached { () -> DependencyCheck.Result in+ let r = scan(path, needsIOS)+ report(r.deps)+ return r+ }.value+ deps = found.deps+ pythonPath = found.python // the interpreter the build runs under+ dotnetPath = found.dotnet+ checked = true+ }+ }++ // ---- The installs ----++ /// Runs the row's install. The row is installing until it ends, a failure leaves the tool's first error line on it, and the+ /// check runs again at the end. A row with no command (Xcode) opens the App Store, and the player checks again when it is done.+ @discardableResult+ package func install(_ dep: Dep) -> Task<Void, Never> {+ guard !dep.installCmd.isEmpty else {+ openAppStore() // Xcode comes from the App Store; the user re-checks when it is done+ return Task {}+ }+ guard let i = deps.firstIndex(where: { $0.id == dep.id }) else { return Task {} }+ deps[i].installing = true+ let runner = self.runner, log = self.log, base = pythonPath+ let cmd = dep.installCmd, isPython = dep.id == "python"+ return Task {+ let outcome = await Task.detached { () -> (ok: Bool, failure: (error: String, fix: String)?, output: String?) in+ if isPython {+ // A venv of our own rather than pip --user: Homebrew's Python is externally+ // managed (PEP 668) and refuses --user, which used to fail silently.+ let r = Toolchain.makeVenv(base: base, runner: runner)+ return (r.ok, nil, r.log)+ }+ let collected = Lines()+ let ok = runner.runCaptured(DependencyCheck.shellCommand(cmd), env: DependencyCheck.installEnvironment()) { line in+ collected.append(line)+ DispatchQueue.main.async { log(line + "\n") }+ }+ return (ok, BuildProgress.failureInfo(collected.lines), nil)+ }.value+ if let output = outcome.output { log("\n--- 安装输出 ---\n" + output) }+ if let j = deps.firstIndex(where: { $0.id == dep.id }) {+ if let failure = outcome.failure {+ deps[j].lastError = outcome.ok ? "" : failure.error+ deps[j].fixHint = outcome.ok ? "" : failure.fix+ }+ deps[j].installing = false+ if outcome.ok { deps[j].lastError = ""; deps[j].fixHint = "" }+ }+ if !outcome.ok { installFailed(String(format: localizer.t("dep.install.fail"), localizer.t(dep.name))) }+ await check().value+ }+ }++ /// The output lines seen so far, from the pipe's threads and read after the run.+ private final class Lines: @unchecked Sendable {+ private let lock = NSLock()+ private var box: [String] = []+ func append(_ l: String) { lock.lock(); box.append(l); lock.unlock() }+ var lines: [String] { lock.lock(); defer { lock.unlock() }; return box }+ }+}diff --git a/frontend/Sources/NXModel/EngineSyncStore.swift b/frontend/Sources/NXModel/EngineSyncStore.swiftindex 99cac3be..13eae98d 100644--- a/frontend/Sources/NXModel/EngineSyncStore.swift+++ b/frontend/Sources/NXModel/EngineSyncStore.swift@@ -2,12 +2,6 @@ import Foundationimport Combineimport NXCore-/// Where the Python interpreter is, for a store that only needs to read it. `BuildModel` provides it today, the dependency-/// store takes it over. Empty: not found yet, and the user of it looks for one itself.-package protocol PythonLocation: AnyObject {- var pythonPath: String { get }-}-/// The engine (LNPANDY/NX2Apple#387, step 7): which engine the launcher builds with and how it gets it. It follows/// `AppUpdateStore` (`frontend/ARCHITECTURE.md`, "Stores").///diff --git a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift b/frontend/Tests/NX2AppleTests/BuildFailureTests.swiftindex 2e14fc27..08a6a9af 100644--- a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift+++ b/frontend/Tests/NX2AppleTests/BuildFailureTests.swift@@ -199,7 +199,7 @@ final class BuildFailureTests: XCTestCase {}func testTheTestedCompilerIsNoWarning() {- let dep = BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.pinned, "iphoneos": Self.pinned], needsIOS: true)+ let dep = DependencyCheck.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.pinned, "iphoneos": Self.pinned], needsIOS: true)XCTAssertTrue(dep.present)XCTAssertFalse(dep.warning)XCTAssertTrue(dep.lastError.isEmpty)@@ -207,7 +207,7 @@ final class BuildFailureTests: XCTestCase {func testANewerCompilerOfTheGenerationIsNoWarning() { // Xcode 27.2's auto-update: the engine's gate builds with a note, so the row stays greenXCTAssertTrue(MetalPin.mismatches(lock: Self.lock, now: ["macosx": Self.newer, "iphoneos": Self.newer], iOS: true).isEmpty)- XCTAssertFalse(BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.newer], needsIOS: true).warning)+ XCTAssertFalse(DependencyCheck.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.newer], needsIOS: true).warning)}func testAnOlderOrForeignGenerationStaysAWarning() {@@ -224,7 +224,7 @@ final class BuildFailureTests: XCTestCase {}func testAnotherCompilerIsAWarningAndNotABlocker() {- let dep = BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other, "iphoneos": nil], needsIOS: false)+ let dep = DependencyCheck.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other, "iphoneos": nil], needsIOS: false)XCTAssertTrue(dep.present, "a warning never blocks")XCTAssertTrue(dep.warning)XCTAssertEqual(dep.fixHint, "dep.fix.metalPin")@@ -234,29 +234,29 @@ final class BuildFailureTests: XCTestCase {func testTheIPhoneCompilerCountsOnlyForAnIPhoneBuild() {let now: [String: String?] = ["macosx": Self.pinned, "iphoneos": Self.other]- XCTAssertFalse(BuildModel.metalDep(runs: true, lock: Self.lock, now: now, needsIOS: false).warning)- let ios = BuildModel.metalDep(runs: true, lock: Self.lock, now: now, needsIOS: true)+ XCTAssertFalse(DependencyCheck.metalDep(runs: true, lock: Self.lock, now: now, needsIOS: false).warning)+ let ios = DependencyCheck.metalDep(runs: true, lock: Self.lock, now: now, needsIOS: true)XCTAssertTrue(ios.warning)XCTAssertTrue(ios.lastError.hasPrefix("metal_iphoneos:"))}func testAMissingCompilerKeepsTheInstallRow() {- let dep = BuildModel.metalDep(runs: false, lock: Self.lock, now: ["macosx": nil, "iphoneos": nil], needsIOS: true)+ let dep = DependencyCheck.metalDep(runs: false, lock: Self.lock, now: ["macosx": nil, "iphoneos": nil], needsIOS: true)XCTAssertFalse(dep.present)XCTAssertFalse(dep.warning)XCTAssertEqual(dep.installCmd, Toolchain.metalToolchainCmd)}func testWithoutALockThereIsNothingToCompare() {- XCTAssertFalse(BuildModel.metalDep(runs: true, lock: nil, now: ["macosx": Self.other], needsIOS: true).warning)+ XCTAssertFalse(DependencyCheck.metalDep(runs: true, lock: nil, now: ["macosx": Self.other], needsIOS: true).warning)XCTAssertTrue(MetalPin.mismatches(lock: "", now: ["macosx": Self.other], iOS: true).isEmpty)}- func testTheMetalRowsDetailReadsInTheLauncher() {+ @MainActor func testTheMetalRowsDetailReadsInTheLauncher() {let m = BuildModel()- let dep = BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other], needsIOS: false)- XCTAssertTrue(m.depDetail(dep).contains(Self.other), m.depDetail(dep))- XCTAssertTrue(m.depDetail(dep).contains(Self.pinned), m.depDetail(dep))+ let dep = DependencyCheck.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other], needsIOS: false)+ XCTAssertTrue(m.dependencies.detail(of: dep).contains(Self.other), m.dependencies.detail(of: dep))+ XCTAssertTrue(m.dependencies.detail(of: dep).contains(Self.pinned), m.dependencies.detail(of: dep))}/// Opt-in native rendering for pull request screenshots (NX_LAUNCHER_CAPTURE_DIR), the way LibraryTests renders the launcher.@@ -294,9 +294,9 @@ final class BuildFailureTests: XCTestCase {}let m = BuildModel()m.lang = .en- m.depsChecked = true- m.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []),- BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other, "iphoneos": Self.other], needsIOS: true)]+ MainActor.assumeIsolated { m.dependencies.checked = true }+ MainActor.assumeIsolated { m.dependencies.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []),+ DependencyCheck.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other, "iphoneos": Self.other], needsIOS: true)] }try capture("deps-metal-warning", width: 760, height: 260, ZStack(alignment: .top) {LauncherPalette.backgroundMetalRowPreview(m: m).padding(24)@@ -309,12 +309,12 @@ private struct MetalRowPreview: View {@ObservedObject var m: BuildModelvar body: some View {VStack(alignment: .leading, spacing: 0) {- ForEach(m.deps, id: \.id) { d in+ ForEach(m.dependencies.deps, id: \.id) { d inHStack(alignment: .top, spacing: 12) {Circle().fill(d.present && !d.warning ? LauncherPalette.ready : LauncherPalette.building).frame(width: 7, height: 7).padding(.top, 6)VStack(alignment: .leading, spacing: 3) {Text(m.t(d.name)).font(.manrope(14, .semibold))- Text(m.depDetail(d)).font(.manrope(12.5)).foregroundStyle(.secondary)+ Text(m.dependencies.detail(of: d)).font(.manrope(12.5)).foregroundStyle(.secondary)if !d.lastError.isEmpty {Text(d.lastError).font(.mono(11)).foregroundStyle(LauncherPalette.building)Text(m.t(d.fixHint)).font(.manrope(11.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)diff --git a/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift b/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swiftindex e210f60b..7e88deff 100644--- a/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift+++ b/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift@@ -59,8 +59,8 @@ final class BuildNotificationsTests: XCTestCase {defer { try? FileManager.default.removeItem(at: temporary) }let model = BuildModel()model.lang = CaptureLanguage.current(.en)- model.depsChecked = true- model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]+ MainActor.assumeIsolated { model.dependencies.checked = true }+ MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))let host = NSHostingView(rootView: ContentView(model: model, library: library, initialPage: .settings, performStartupChecks: false))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1440, height: 1500), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)diff --git a/frontend/Tests/NX2AppleTests/CheatFilesTests.swift b/frontend/Tests/NX2AppleTests/CheatFilesTests.swiftindex 31728828..e5adb188 100644--- a/frontend/Tests/NX2AppleTests/CheatFilesTests.swift+++ b/frontend/Tests/NX2AppleTests/CheatFilesTests.swift@@ -375,8 +375,8 @@ final class CheatFilesTests: XCTestCase {let model = BuildModel()model.lang = .en- model.depsChecked = true- model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]+ MainActor.assumeIsolated { model.dependencies.checked = true }+ MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))let id = try library.addApp(app)library.recordCompletedIOS(archive: "", app: ios.path, device: "00008150-AAAA", for: id)diff --git a/frontend/Tests/NX2AppleTests/DropFilesTests.swift b/frontend/Tests/NX2AppleTests/DropFilesTests.swiftindex bfb55b3e..3329a1ef 100644--- a/frontend/Tests/NX2AppleTests/DropFilesTests.swift+++ b/frontend/Tests/NX2AppleTests/DropFilesTests.swift@@ -134,11 +134,11 @@ final class DropFilesTests: XCTestCase {let model = BuildModel()model.lang = CaptureLanguage.current(.en)model.outDir = temporary.path- model.depsChecked = true- model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]+ MainActor.assumeIsolated { model.dependencies.checked = true }+ MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))// the page as a drag shows it: the highlight drawn over the Builds page- let page = BuilderView(m: model, updates: model.appUpdates, repo: model.repo, engine: model.engineSync, library: library).environmentObject(PadFocus()).environmentObject(model.localizer)+ let page = BuilderView(m: model, updates: model.appUpdates, repo: model.repo, engine: model.engineSync, dependencies: model.dependencies, library: library).environmentObject(PadFocus()).environmentObject(model.localizer).modifier(GameFilesDrop(enabled: true, label: model.t("drop.hint"), targeted: true) { _ in }).frame(width: 1100, height: 760).background(LauncherPalette.background).environment(\.colorScheme, .dark)let host = NSHostingView(rootView: page)diff --git a/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift b/frontend/Tests/NX2AppleTests/EngineLayoutTests.swiftindex 83fb68d6..4d481d3a 100644--- a/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift+++ b/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift@@ -112,7 +112,7 @@ import XCTesttry touch("tools/engine.py", script)let m = BuildModel()m.repoPath = repo- m.pythonPath = "/usr/bin/python3"+ m.dependencies.pythonPath = "/usr/bin/python3"return m}diff --git a/frontend/Tests/NX2AppleTests/KeyCheckTests.swift b/frontend/Tests/NX2AppleTests/KeyCheckTests.swiftindex 6dc4cd43..e94fdba4 100644--- a/frontend/Tests/NX2AppleTests/KeyCheckTests.swift+++ b/frontend/Tests/NX2AppleTests/KeyCheckTests.swift@@ -173,8 +173,8 @@ final class KeyCheckTests: XCTestCase {let model = BuildModel()model.lang = CaptureLanguage.current(.en)model.outDir = temporary.path- model.depsChecked = true- model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]+ MainActor.assumeIsolated { model.dependencies.checked = true }+ MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))let base = try pfs0([("a.nca", ncaHeader(generation: 0x0C))], name: "Metroid Dread [010093801237C000].nsp")let update = try pfs0([("b.nca", ncaHeader(generation: 0x13))], name: "Metroid Dread [010093801237C800][v327680].nsp")diff --git a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swiftindex 71aa39ae..3d7950cd 100644--- a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift+++ b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift@@ -84,8 +84,8 @@ final class LauncherControlWidthTests: XCTestCase {Scenario(name: "settings with a ZIP copy and a library folder", page: .settings, atLeast: 6) { m, library, directory inm.repoPath = try self.makeRepo(directory, git: false)MainActor.assumeIsolated { m.appUpdates.installability = .ok }- m.depsChecked = true- m.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: [])]+ MainActor.assumeIsolated { m.dependencies.checked = true }+ MainActor.assumeIsolated { m.dependencies.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: [])] }library.setFolder(directory)},Scenario(name: "settings with a clone that is behind and an app update", page: .settings, atLeast: 6) { m, _, directory in@@ -101,9 +101,9 @@ final class LauncherControlWidthTests: XCTestCase {},Scenario(name: "settings with every kind of missing tool", page: .settings, atLeast: 6) { m, _, directory inm.repoPath = try self.makeRepo(directory, git: true)- m.depsChecked = true- m.deps = [missing("a"), missing("b", command: ["brew", "install", "x"]), missing("c", action: "dep.xcode.fix", command: ["x"])]- m.depsExpanded = true+ MainActor.assumeIsolated { m.dependencies.checked = true }+ MainActor.assumeIsolated { m.dependencies.deps = [missing("a"), missing("b", command: ["brew", "install", "x"]), missing("c", action: "dep.xcode.fix", command: ["x"])] }+ MainActor.assumeIsolated { m.dependencies.expanded = true }},Scenario(name: "builds without a repository", page: .builds, atLeast: 4) { m, _, _ inm.repoPath = ""diff --git a/frontend/Tests/NX2AppleTests/LibraryTests.swift b/frontend/Tests/NX2AppleTests/LibraryTests.swiftindex 2ee0bca0..677285b8 100644--- a/frontend/Tests/NX2AppleTests/LibraryTests.swift+++ b/frontend/Tests/NX2AppleTests/LibraryTests.swift@@ -292,10 +292,10 @@ final class LibraryTests: XCTestCase {model.repoPath = temporary.pathmodel.target = "mac-app"model.outDir = temporary.path- model.pythonPath = "/usr/bin/python3"- model.dotnetPath = "/usr/bin/true"- model.depsChecked = true- model.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]+ MainActor.assumeIsolated { model.dependencies.pythonPath = "/usr/bin/python3" }+ MainActor.assumeIsolated { model.dependencies.dotnetPath = "/usr/bin/true" }+ MainActor.assumeIsolated { model.dependencies.checked = true }+ MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])] }let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)try Data().write(to: marker)@@ -575,10 +575,10 @@ final class LibraryTests: XCTestCase {model.repoPath = temporary.pathmodel.target = "mac-app"model.outDir = temporary.path- model.pythonPath = "/usr/bin/python3"- model.dotnetPath = "/usr/bin/true"- model.depsChecked = true- model.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]+ MainActor.assumeIsolated { model.dependencies.pythonPath = "/usr/bin/python3" }+ MainActor.assumeIsolated { model.dependencies.dotnetPath = "/usr/bin/true" }+ MainActor.assumeIsolated { model.dependencies.checked = true }+ MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])] }let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)try Data().write(to: marker)@@ -664,8 +664,8 @@ final class LibraryTests: XCTestCase {let model = BuildModel()model.repoPath = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().pathmodel.lang = .en- model.depsChecked = true- model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]+ MainActor.assumeIsolated { model.dependencies.checked = true }+ MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }for game in real_.games.sorted(by: { $0.name < $1.name }) {let name = game.name.replacingOccurrences(of: #"\s*\([0-9.]+ GB\)"#, with: "", options: .regularExpression)if game.titleID == botw { _ = try library.addApp(makeApp(botw, name: name)) }@@ -771,8 +771,8 @@ final class LibraryTests: XCTestCase {model.repoPath = repomodel.lang = CaptureLanguage.current(.en)model.outDir = temporary.path- model.depsChecked = true- model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]+ MainActor.assumeIsolated { model.dependencies.checked = true }+ MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))let examples = [(titleID, "Hades"), ("01007EF00011E000", "The Legend of Zelda: Breath of the Wild"),("0100000000010000", "Super Mario Odyssey"), ("010093801237C000", "Metroid Dread")]diff --git a/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift b/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swiftindex e9918f5c..cce58f12 100644--- a/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift+++ b/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift@@ -43,7 +43,7 @@ import XCTestif 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+ model.dependencies.deps = deps; model.dependencies.checked = truevar env = OnboardingEnvironment()env.defaults = defaultsenv.home = home.path@@ -57,7 +57,7 @@ import XCTestenv.detectDeps = { m in fake.onDetect(m) }env.installDep = { m, d infake.installed.append(d.id)- if let i = m.deps.firstIndex(where: { $0.id == d.id }) { m.deps[i].installing = true }+ if let i = m.dependencies.deps.firstIndex(where: { $0.id == d.id }) { m.dependencies.deps[i].installing = true }}env.openURL = { fake.opened.append($0) }env.keyCheck = { _, _ in fake.keyOutcome }@@ -198,7 +198,7 @@ import XCTestlet (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 changefake.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 } }+ if !fake.commands.isEmpty { for i in m.dependencies.deps.indices { m.dependencies.deps[i].present = true } }}await driver.refreshXcode()driver.finishXcodeSetup()@@ -215,7 +215,7 @@ import XCTestlet (driver, _) = make(fake, deps: [dep("metal", present: false), dep("xcode", present: true)], step: .xcode, platform: .mac)fake.onDetect = { m infake.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 } }+ if !fake.commands.isEmpty { for i in m.dependencies.deps.indices { m.dependencies.deps[i].present = true } }}await driver.refreshXcode()driver.finishXcodeSetup()@@ -290,9 +290,9 @@ import XCTestawait 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+ model.dependencies.checked = false+ for i in model.dependencies.deps.indices { model.dependencies.deps[i].installing = false; if model.dependencies.deps[i].id == id { model.dependencies.deps[i].present = true } }+ model.dependencies.checked = trueawait driver.settle()}await finish("python"); XCTAssertEqual(fake.installed, ["python", "dotnet"])@@ -322,9 +322,9 @@ import XCTestdep("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+ model.dependencies.checked = false+ for i in model.dependencies.deps.indices { model.dependencies.deps[i].installing = false } // python's install ended, still missing+ model.dependencies.checked = trueawait 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)))diff --git a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift b/frontend/Tests/NX2AppleTests/ShellInstallTests.swiftindex c40ed307..d5fa303b 100644--- a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift+++ b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift@@ -775,10 +775,10 @@ final class ShellInstallTests: XCTestCase {model.repoPath = f.repomodel.target = "ios"model.outDir = path("out")- model.pythonPath = "/usr/bin/python3"- model.dotnetPath = "/usr/bin/true"- model.depsChecked = true- model.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]+ model.dependencies.pythonPath = "/usr/bin/python3"+ model.dependencies.dotnetPath = "/usr/bin/true"+ model.dependencies.checked = true+ model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]model.installDevice = devicemodel.signingTeam = teammodel.xcrunPath = f.xcrun@@ -839,10 +839,10 @@ final class ShellInstallTests: XCTestCase {model.repoPath = f.repomodel.target = "ios"model.outDir = path("out")- model.pythonPath = "/usr/bin/python3"- model.dotnetPath = "/usr/bin/true"- model.depsChecked = true- model.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]+ model.dependencies.pythonPath = "/usr/bin/python3"+ model.dependencies.dotnetPath = "/usr/bin/true"+ model.dependencies.checked = true+ model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]model.installDevice = devicemodel.signingTeam = teammodel.xcrunPath = f.xcrundiff --git a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift b/frontend/Tests/NX2AppleTests/SourceSizeTests.swiftindex 977b62bd..46289ccf 100644--- a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift+++ b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift@@ -7,7 +7,7 @@ final class SourceSizeTests: XCTestCase {/// Path under frontend/Sources → its line count when the limit came in. Lower the number when the file shrinks.private static let aboveTheLimit: [String: Int] = [- "NX2Apple/ContentView.swift": 2228,+ "NX2Apple/ContentView.swift": 2073,"NX2Apple/LauncherView.swift": 967,"NXCore/Localization.swift": 4237,]diff --git a/frontend/Tests/NXModelTests/DependencyStoreTests.swift b/frontend/Tests/NXModelTests/DependencyStoreTests.swiftnew file mode 100644index 00000000..7512c312--- /dev/null+++ b/frontend/Tests/NXModelTests/DependencyStoreTests.swift@@ -0,0 +1,234 @@+import XCTest+@testable import NXModel+@testable import NXCore++/// `DependencyStore` without SwiftUI: the detection is a closure that answers from the test, a fake `ProcessRunner` stands in for+/// brew and xcodebuild, and the defaults are a suite of their own. Nothing probes this Mac and nothing is installed. The Python row's+/// venv install is not run here: `Toolchain.makeVenv` reads and writes the real venv folder.+@MainActor final class DependencyStoreTests: XCTestCase {+ private final class FakeRepo: RepoLocation {+ var path = "/repo"+ var isRepo = true+ var isGit = true+ }++ /// What the detection was asked, and what it answers.+ private final class Scanner: @unchecked Sendable {+ private let lock = NSLock()+ private var asked: [(repo: String, needsIOS: Bool)] = []+ private var written: [[Dep]] = []+ var result = DependencyCheck.Result(deps: [], python: "", dotnet: "")+ var questions: [(repo: String, needsIOS: Bool)] { lock.lock(); defer { lock.unlock() }; return asked }+ var reports: [[Dep]] { lock.lock(); defer { lock.unlock() }; return written }+ func scan(_ repo: String, _ needsIOS: Bool) -> DependencyCheck.Result {+ lock.lock(); asked.append((repo, needsIOS)); lock.unlock()+ return result+ }+ func report(_ deps: [Dep]) { lock.lock(); written.append(deps); lock.unlock() }+ }++ private var suite: String!+ private var defaults: UserDefaults!+ private let runner = FakeProcessRunner()+ private let localizer = Localizer(.en)+ private let repo = FakeRepo()+ private let scanner = Scanner()+ private var log: [String] = []+ private var notes: [String] = []+ private var appStoreOpened = 0+ private var iOS = true++ override func setUpWithError() throws {+ suite = "nxmodel-dependency-tests-" + UUID().uuidString+ defaults = UserDefaults(suiteName: suite)+ }++ override func tearDownWithError() throws {+ defaults.removePersistentDomain(forName: suite)+ }++ private func makeStore() -> DependencyStore {+ let scanner = self.scanner+ return DependencyStore(localizer: localizer, runner: runner, repo: repo, defaults: defaults,+ needsIOS: { [unowned self] in iOS },+ scan: { scanner.scan($0, $1) }, report: { scanner.report($0) },+ openAppStore: { [unowned self] in appStoreOpened += 1 },+ log: { [unowned self] in log.append($0) }, installFailed: { [unowned self] in notes.append($0) })+ }++ private func dep(_ id: String, present: Bool, cmd: [String] = ["brew", "install", "x"], warning: Bool = false) -> Dep {+ Dep(id: id, name: "dep." + id, hint: "dep." + id + ".hint", present: present, warning: warning, installCmd: cmd)+ }++ // ---- The check ----++ func testTheCheckPublishesTheRowsAndThePathsAfterTheSpinner() async {+ scanner.result = DependencyCheck.Result(deps: [dep("xcode", present: true), dep("dotnet", present: true)],+ python: "/opt/py/bin/python3", dotnet: "/opt/dotnet/dotnet")+ let store = makeStore()+ XCTAssertFalse(store.checked)+ let task = store.check()+ XCTAssertFalse(store.checked, "the panel shows its spinner until the rows are in")+ await task.value+ XCTAssertTrue(store.checked)+ XCTAssertEqual(store.deps.map(\.id), ["xcode", "dotnet"])+ XCTAssertEqual(store.pythonPath, "/opt/py/bin/python3")+ XCTAssertEqual(store.dotnetPath, "/opt/dotnet/dotnet")+ }++ func testTheCheckReadsTheRepositoryAndThePlatformChoiceAndWritesTheReport() async {+ repo.path = "/somewhere/checkout"+ iOS = false+ scanner.result = DependencyCheck.Result(deps: [dep("xcode", present: false)], python: "", dotnet: "")+ let store = makeStore()+ await store.check().value+ XCTAssertEqual(scanner.questions.map(\.repo), ["/somewhere/checkout"])+ XCTAssertEqual(scanner.questions.map(\.needsIOS), [false])+ XCTAssertEqual(scanner.reports.map { $0.map(\.id) }, [["xcode"]])+ iOS = true+ await store.check().value+ XCTAssertEqual(scanner.questions.map(\.needsIOS), [false, true], "asked again at every check")+ }++ func testEverythingIsPresentOnlyAfterACheckWithNoMissingRow() async {+ let store = makeStore()+ XCTAssertFalse(store.allPresent, "before the first check")+ scanner.result = DependencyCheck.Result(deps: [dep("xcode", present: true), dep("metal", present: false)], python: "", dotnet: "")+ await store.check().value+ XCTAssertFalse(store.allPresent)+ scanner.result = DependencyCheck.Result(deps: [dep("xcode", present: true), dep("metal", present: true, warning: true)], python: "", dotnet: "")+ await store.check().value+ XCTAssertTrue(store.allPresent, "a warning row is present")+ _ = store.check()+ XCTAssertFalse(store.allPresent, "not while a check runs")+ }++ func testTheBuildReadsTheStoreThroughDependencyStatus() async {+ scanner.result = DependencyCheck.Result(deps: [dep("xcode", present: true)], python: "/py", dotnet: "/dn")+ let store = makeStore()+ await store.check().value+ let status: DependencyStatus = store+ XCTAssertTrue(status.checked)+ XCTAssertTrue(status.allPresent)+ XCTAssertEqual(status.pythonPath, "/py")+ XCTAssertEqual(status.dotnetPath, "/dn")+ XCTAssertEqual(status.deps.map(\.id), ["xcode"])+ let python: PythonLocation = store+ XCTAssertEqual(python.pythonPath, "/py", "the engine sync reads the interpreter through the narrow protocol")+ }++ // ---- The list's state ----++ func testTheListIsOpenWhileSomethingIsMissingAndFoldsWhenAllIsGreen() async {+ let store = makeStore()+ XCTAssertTrue(store.open, "not checked yet")+ scanner.result = DependencyCheck.Result(deps: [dep("xcode", present: false)], python: "", dotnet: "")+ await store.check().value+ XCTAssertTrue(store.open)+ scanner.result = DependencyCheck.Result(deps: [dep("xcode", present: true)], python: "", dotnet: "")+ await store.check().value+ XCTAssertFalse(store.open, "a set-up machine never needs the rows again")+ }++ func testAToggleOverridesAndIsRemembered() async {+ scanner.result = DependencyCheck.Result(deps: [dep("xcode", present: true)], python: "", dotnet: "")+ let store = makeStore()+ await store.check().value+ XCTAssertNil(store.expanded)+ store.toggle()+ XCTAssertEqual(store.expanded, true)+ XCTAssertTrue(store.open)+ XCTAssertEqual(defaults.object(forKey: DependencyStore.expandedKey) as? Bool, true)+ let again = makeStore()+ XCTAssertEqual(again.expanded, true, "the choice comes back with the next launch")+ again.toggle()+ XCTAssertEqual(again.expanded, false)+ XCTAssertFalse(again.open)+ }++ func testARowsDetailIsAPathAKeyWithArgumentsOrTheHint() {+ let store = makeStore()+ var d = dep("dotnet", present: true)+ XCTAssertEqual(store.detail(of: d), localizer.t("dep.dotnet.hint"), "no detail: the hint")+ d.detail = "/opt/dotnet/dotnet"+ XCTAssertEqual(store.detail(of: d), "/opt/dotnet/dotnet")+ d.detail = "dep.metal.other:32023.1:32023.2"+ XCTAssertTrue(store.detail(of: d).contains("32023.1"))+ XCTAssertTrue(store.detail(of: d).contains("32023.2"))+ d.detail = "dep.dotnet.missing"+ XCTAssertEqual(store.detail(of: d), localizer.t("dep.dotnet.missing"))+ d.detail = "3.9.6 is too old"+ XCTAssertEqual(store.detail(of: d), "3.9.6 is too old", "free text stays as it is")+ }++ // ---- The installs ----++ private func storeWithRows(_ rows: [Dep]) async -> DependencyStore {+ scanner.result = DependencyCheck.Result(deps: rows, python: "", dotnet: "")+ let store = makeStore()+ await store.check().value+ return store+ }++ func testAnInstallRunsTheRowsCommandThroughBashAndChecksAgain() async throws {+ let store = await storeWithRows([dep("zstd", present: false, cmd: ["/opt/homebrew/bin/brew", "install", "zstd"])])+ runner.streamAnswer = { _ in (["==> Installing zstd"], true) }+ scanner.result = DependencyCheck.Result(deps: [dep("zstd", present: true)], python: "", dotnet: "")+ let task = store.install(store.deps[0])+ XCTAssertTrue(store.isInstalling("zstd"), "the row says so from the call on")+ await task.value+ XCTAssertFalse(store.isInstalling("zstd"))+ XCTAssertTrue(store.allPresent, "the check after the install found it")+ let launch = try XCTUnwrap(runner.launches.first)+ XCTAssertEqual(launch.executable, "/bin/bash")+ XCTAssertEqual(launch.arguments, ["-c", "/opt/homebrew/bin/brew install zstd"])+ XCTAssertEqual(launch.environment?["NONINTERACTIVE"], "1")+ XCTAssertTrue(launch.environment?["PATH"]?.hasPrefix("/opt/homebrew/bin:") ?? false)+ try await Task.sleep(nanoseconds: 50_000_000) // the lines reach the log through the main queue+ XCTAssertTrue(log.contains("==> Installing zstd\n"))+ XCTAssertTrue(notes.isEmpty)+ }++ func testAWordWithASpaceIsQuotedForBash() async {+ let store = await storeWithRows([dep("x", present: false, cmd: ["/bin/echo", "two words"])])+ await store.install(store.deps[0]).value+ XCTAssertEqual(runner.launches.first?.arguments, ["-c", "/bin/echo 'two words'"])+ }++ func testAFailedInstallKeepsTheToolsErrorLineOnTheRowAndSaysSo() async {+ let store = await storeWithRows([dep("zstd", present: false)])+ runner.streamAnswer = { _ in (["==> Fetching zstd", "Error: zstd: no bottle available"], false) }+ scanner.result = DependencyCheck.Result(deps: [dep("zstd", present: false)], python: "", dotnet: "")+ let rows = store.deps+ await store.install(rows[0]).value+ XCTAssertEqual(notes, [String(format: localizer.t("dep.install.fail"), localizer.t("dep.zstd"))])+ XCTAssertFalse(store.isInstalling("zstd"))+ XCTAssertTrue(store.checked, "the check ran again")+ }++ func testTheErrorLineAndTheFixSitOnTheRowUntilTheNextCheck() async {+ let store = await storeWithRows([dep("zstd", present: false)])+ runner.streamAnswer = { _ in (["Error: zstd: no bottle available"], false) }+ // The check at the end of the install replaces the rows, so look at the row while it still runs the install.+ let task = store.install(store.deps[0])+ scanner.result = DependencyCheck.Result(deps: [dep("zstd", present: false)], python: "", dotnet: "")+ XCTAssertTrue(store.isInstalling("zstd"))+ await task.value+ XCTAssertEqual(notes.count, 1)+ }++ func testARowWithoutACommandOpensTheAppStoreAndInstallsNothing() async {+ let store = await storeWithRows([dep("xcode", present: false, cmd: [])])+ await store.install(store.deps[0]).value+ XCTAssertEqual(appStoreOpened, 1)+ XCTAssertTrue(runner.launches.isEmpty)+ XCTAssertFalse(store.isInstalling("xcode"))+ }++ func testARowTheListDoesNotHoldIsNotInstalled() async {+ let store = await storeWithRows([dep("xcode", present: true)])+ await store.install(dep("zstd", present: false)).value+ XCTAssertTrue(runner.launches.isEmpty)+ XCTAssertTrue(notes.isEmpty)+ }+}