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
Keep build progress and logs across launcher windows
thehobbit85cb633ca27db9
diff --git a/frontend/Sources/NX2Apple/NX2AppleApp.swift b/frontend/Sources/NX2Apple/NX2AppleApp.swiftindex 44367e4d..24d08351 100644--- a/frontend/Sources/NX2Apple/NX2AppleApp.swift+++ b/frontend/Sources/NX2Apple/NX2AppleApp.swift@@ -20,6 +20,7 @@ enum Entry {struct NX2AppleApp: App {@NSApplicationDelegateAdaptor private var delegate: AppDelegate@StateObject private var console = ConsoleCoordinator()+ @StateObject private var session = LauncherSession()var body: some Scene {WindowGroup("NX2Apple") {@@ -28,7 +29,7 @@ struct NX2AppleApp: App {OnboardingDemoHost(scenario: scenario)} else if let scenario = ProcessInfo.processInfo.environment["NSPB_CONSOLE_DEMO"].flatMap(MockConsoleDriver.Scenario.init(rawValue:)) {ConsoleDemoView(scenario: scenario)- } else { RootView(console: console) }+ } else { RootView(shared: session, console: console) }}.windowStyle(.hiddenTitleBar).defaultSize(width: 1280, height: 900)diff --git a/frontend/Sources/NX2Apple/OnboardingRoot.swift b/frontend/Sources/NX2Apple/OnboardingRoot.swiftindex cd2c28d4..280f2f15 100644--- a/frontend/Sources/NX2Apple/OnboardingRoot.swift+++ b/frontend/Sources/NX2Apple/OnboardingRoot.swift@@ -3,19 +3,26 @@ import NXCoreimport NXModelimport NXLauncher-/// The window's content: the launcher, or the guided setup before it. It owns the one `LauncherStores` and `GameLibrary` both use,-/// so what the setup detects, installs and chooses is what the launcher shows.+/// App-lifetime state shared by setup and every launcher window. A build and its log must outlive the window that started it.+/// Nothing is published here, so log output redraws only the views observing the individual stores.+@MainActor final class LauncherSession: ObservableObject {+ let stores: LauncherStores+ let library: GameLibrary+ let controls = ControlLayout()+ lazy var console = LiveConsoleDriver(library: library, controls: controls, repo: { [stores] in stores.repo.path }, lang: { [stores] in stores.localizer.lang },+ labels: { [stores] in stores.localizer.t($0) })++ init(stores: LauncherStores? = nil, library: GameLibrary? = nil) {+ self.stores = stores ?? LauncherStores()+ self.library = library ?? GameLibrary()+ }+}++/// The window's content: the launcher, or the guided setup before it. The app owns the shared session.struct RootView: View {private enum Mode { case checking, onboarding, launcher }- /// Holds the two objects without publishing, so this view does not redraw with every line of a build log.- @MainActor private final class Shared: ObservableObject {- let stores = LauncherStores(); let library = GameLibrary(); let controls = ControlLayout()- /// The console mode's driver over this window's model, library and controls.- lazy var console = LiveConsoleDriver(library: library, controls: controls, repo: { [stores] in stores.repo.path }, lang: { [stores] in stores.localizer.lang },- labels: { [stores] in stores.localizer.t($0) })- }- @StateObject private var shared = Shared()- private var stores: LauncherStores { shared.stores }+ @ObservedObject var shared: LauncherSession+ var stores: LauncherStores { shared.stores }private var library: GameLibrary { shared.library }@State private var mode: Mode = .checking@State private var driver: LiveOnboardingDriver?diff --git a/frontend/Tests/NX2AppleTests/BuildSessionTests.swift b/frontend/Tests/NX2AppleTests/BuildSessionTests.swiftnew file mode 100644index 00000000..1bb9afc1--- /dev/null+++ b/frontend/Tests/NX2AppleTests/BuildSessionTests.swift@@ -0,0 +1,83 @@+import XCTest+import Combine+@testable import NX2Apple+@testable import NXCore+@testable import NXModel++/// A real stand-in build stays alive while its window is replaced. No game or device is needed.+@MainActor final class BuildSessionTests: IsolatedDefaultsTestCase {+ func testRecreatedWindowKeepsTheRunningBuildItsLogAndStopControl() throws {+ let fm = FileManager.default+ let folder = fm.temporaryDirectory.appendingPathComponent("build-session-" + UUID().uuidString)+ try fm.createDirectory(at: folder, withIntermediateDirectories: true)+ defer { try? fm.removeItem(at: folder) }+ func write(_ path: String, _ text: String = "") throws {+ let url = folder.appendingPathComponent(path)+ try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try text.write(to: url, atomically: true, encoding: .utf8)+ }+ try write(EngineLayout.marker)+ try write(RepoLayout.romfsImageTool)+ try write(RepoLayout.buildScript, """+ import json, pathlib, time+ # '--work-dir' is supported by this stand-in.+ print(json.dumps(dict(ev='stage', k=1, n=1, name='Shaders')), flush=True)+ print(json.dumps(dict(ev='progress', k=1, frac=0.25)), flush=True)+ print('compiling before the window closes', flush=True)+ while not pathlib.Path('continue').exists():+ time.sleep(0.01)+ print(json.dumps(dict(ev='progress', k=1, frac=0.5)), flush=True)+ print('compiling after the window reopens', flush=True)+ while True:+ time.sleep(1)+ """)+ try write("Game [0100000000001000].nsp")+ try write("prod.keys")+ let stores = LauncherStores(defaults: testDefaults)+ stores.repo.path = folder.path+ stores.dependencies.pythonPath = "/usr/bin/python3"+ stores.dependencies.dotnetPath = "/usr/bin/true"+ stores.dependencies.checked = true+ stores.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]+ stores.build.target = BuildTarget.mac+ stores.build.appReplaceCheck = { _ in true }+ stores.build.cloudFolderCheck = { _ in false }+ stores.build.slots[0].paths = [folder.appendingPathComponent("Game [0100000000001000].nsp").path]+ stores.build.slots[3].paths = [folder.appendingPathComponent("prod.keys").path]+ let session = LauncherSession(stores: stores, library: GameLibrary(file: folder.appendingPathComponent("library.json")))+ let console = ConsoleCoordinator()+ var window: RootView? = RootView(shared: session, console: console)+ let before = expectation(description: "output before closing the window")+ let beforeToken = stores.build.log.$text.filter { $0.contains("compiling before") }.prefix(1).sink { _ in before.fulfill() }+ window?.stores.build.startBuild()+ defer { stores.build.stop() }+ wait(for: [before], timeout: 10)+ withExtendedLifetime(beforeToken) {}+ let process = try XCTUnwrap(stores.build.proc)+ XCTAssertTrue(process.isRunning)++ window = nil+ window = RootView(shared: session, console: console)+ let reopened = try XCTUnwrap(window)+ XCTAssertTrue(reopened.stores.build.running)+ XCTAssertFalse(reopened.stores.build.canBuild, "the new window cannot start a duplicate build")+ XCTAssertEqual(reopened.stores.build.stages.first?.name, "Shaders")+ XCTAssertEqual(reopened.stores.build.stages.first?.percent, 25)+ XCTAssertTrue(reopened.stores.build.log.text.contains("compiling before"))+ let after = expectation(description: "new window receives later output")+ let afterToken = reopened.stores.build.log.$text.filter { $0.contains("compiling after") }.prefix(1).sink { _ in after.fulfill() }+ try write("continue")+ wait(for: [after], timeout: 10)+ withExtendedLifetime(afterToken) {}+ XCTAssertTrue(process.isRunning)+ XCTAssertEqual(reopened.stores.build.stages.first?.percent, 50)+ XCTAssertEqual(reopened.stores.build.proc?.processIdentifier, process.processIdentifier)+ let stopped = expectation(description: "stop from the new window ends the build")+ let stopToken = reopened.stores.build.$running.filter { !$0 }.prefix(1).sink { _ in stopped.fulfill() }+ reopened.stores.build.stop()+ wait(for: [stopped], timeout: 10)+ withExtendedLifetime(stopToken) {}+ XCTAssertFalse(process.isRunning)+ XCTAssertEqual(reopened.stores.build.doneNote, stores.localizer.t("msg.stopped"))+ }+}