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
Show preparation feedback when launching shared iOS games
heza3259ffe20839
diff --git a/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstringsindex 80adb6e0..3751222c 100644--- a/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings+++ b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings@@ -1361,6 +1361,46 @@}}},+ "Preparing game…": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Spiel wird vorbereitet…"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Preparing game…"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Préparation du jeu…"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Preparazione del gioco…"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Förbereder spelet…"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "正在准备游戏…"+ }+ }+ }+ },"Quit": {"localizations": {"de": {diff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swiftindex 90939e30..5a78650d 100644--- a/frontend-ios/Sources/ShellHost/ShellHostModel.swift+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift@@ -57,6 +57,8 @@ public struct ShellHostConfig: Sendable {public var notice: String?/// The log the host view shows in a read-only sheet.public var log: LogPresentation?+ /// Play is preparing the game's resources or handing over to the engine.+ public private(set) var launchingGame = falsepublic private(set) var globalPadMap = PadMap()/// The last controller state, sent only while the button test is open.@@ -64,7 +66,6 @@ public struct ShellHostConfig: Sendable {@ObservationIgnored private let config: ShellHostConfig@ObservationIgnored private let launcher: any GameLauncher- @ObservationIgnored private var launchingGame = false@ObservationIgnored private let picker: any FolderPicker@ObservationIgnored private let adapter = GamepadAdapter()@ObservationIgnored private var dataStores: [String: BookmarkStore] = [:]@@ -501,7 +502,7 @@ public struct ShellHostConfig: Sendable {/// Starts reading GameController: the connected controllers become `controllers`, their buttons `input`.public func startControllers() {adapter.onInput = { [weak self] action, device in- guard let self else { return }+ guard let self, !self.launchingGame else { return }self.input = ShellInput(sequence: (self.input?.sequence ?? 0) + 1, action: action, device: device)}adapter.onControllersChange = { [weak self] connected indiff --git a/frontend-ios/Sources/ShellHost/ShellHostView.swift b/frontend-ios/Sources/ShellHost/ShellHostView.swiftindex 45802e41..b78e50d5 100644--- a/frontend-ios/Sources/ShellHost/ShellHostView.swift+++ b/frontend-ios/Sources/ShellHost/ShellHostView.swift@@ -18,6 +18,18 @@ public struct ShellHostView: View {LibraryView(games: model.details, controllers: model.controllers, actions: model.actions, input: model.input,initialSelection: initialSelection, initialDetailOpen: initialDetailOpen, globalPadMap: model.globalPadMap,padSnapshot: model.padSnapshot)+ .disabled(model.launchingGame)+ .overlay {+ if model.launchingGame {+ ZStack {+ Color.black.opacity(0.45).ignoresSafeArea()+ ProgressView { Text("Preparing game…", bundle: .module) }+ .padding(24)+ .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 20))+ .accessibilityIdentifier("launch.progress")+ }+ }+ }.sheet(item: $model.log) { LogView(log: $0) }.alert(Text(verbatim: hostText("Shell")), isPresented: Binding(get: { model.notice != nil }, set: { if !$0 { model.notice = nil } })) {Button(hostText("OK")) { model.notice = nil }diff --git a/frontend-ios/Tests/ShellHostTests/GameDeletionTests.swift b/frontend-ios/Tests/ShellHostTests/GameDeletionTests.swiftindex 9acf00b5..808a9028 100644--- a/frontend-ios/Tests/ShellHostTests/GameDeletionTests.swift+++ b/frontend-ios/Tests/ShellHostTests/GameDeletionTests.swift@@ -5,12 +5,15 @@ import Testing/// #559: deleting a game in the shell removes its folder in the app (the saves only when asked), never a folder the player/// picked, and keeps the game off the list until a new build of it or its game data comes again.@MainActor @Suite struct GameDeletionTests {- /// The orbit fixture's folder in the app with game data, add-on content, saves, a temp folder and a log.+ /// The orbit fixture's folder with game data, add-on content, saves, shader caches, a temp folder and a log.private func fill(_ box: Sandbox) throws -> URL {let dir = try box.giveAppData()for file in ["aoc/0.img", "save/0/file.bin", "save_device/0/file.bin", "save.work/0/file.bin", "temp/t.bin", "log.txt"] {try box.write("x", to: dir.appendingPathComponent(file))}+ for prefix in ["msl-", ".partial-"] {+ try box.write("shader", to: dir.appendingPathComponent(".shader-resources/" + prefix + UUID().uuidString + "/b-3f9a2c/example.metallib"))+ }return dir}private func names(_ dir: URL) -> [String] { ((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? []).sorted() }@@ -23,7 +26,7 @@ import Testinglet before = model.details.count#expect(listed(model))model.deleteGame(Fixtures.orbit, saves: false)- #expect(names(dir) == ["save", "save.work", "save_device"], "game data, add-on content, temp and log are gone, the saves stay")+ #expect(names(dir) == ["save", "save.work", "save_device"], "game data, shader caches, add-on content, temp and log are gone, the saves stay")#expect(!listed(model) && model.details.count == before - 1)#expect(model.notice == nil)#expect(!listed(ShellHostModel(config: box.config())), "still off the list when the app opens again")@@ -78,8 +81,8 @@ import Testing@Test func theRemovalsListNamesEverythingButTheSaves() throws {let box = try Sandbox()let dir = try fill(box)- #expect(GameDeletion.removals(in: dir, saves: false).map(\.lastPathComponent) == ["aoc", "log.txt", "romfs", "temp"])- #expect(GameDeletion.removals(in: dir, saves: true).count == 7)+ #expect(GameDeletion.removals(in: dir, saves: false).map(\.lastPathComponent) == [".shader-resources", "aoc", "log.txt", "romfs", "temp"])+ #expect(GameDeletion.removals(in: dir, saves: true).count == 8)#expect(GameDeletion.removals(in: dir.appendingPathComponent("missing"), saves: true).isEmpty)}}diff --git a/frontend-ios/Tests/ShellHostTests/LaunchCaptureTests.swift b/frontend-ios/Tests/ShellHostTests/LaunchCaptureTests.swiftnew file mode 100644index 00000000..ae44ec99--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/LaunchCaptureTests.swift@@ -0,0 +1,86 @@+#if os(macOS)+import AppKit+import SwiftUI+import XCTest+@testable import ShellHost+@testable import ShellUI++/// Opt-in visual QA of the real host before Play and while it prepares a launch. The fixture contains no game assets.+@MainActor+final class LaunchCaptureTests: XCTestCase {+ @MainActor private final class HeldLauncher: GameLauncher {+ private var continuation: CheckedContinuation<Void, Never>?+ private(set) var started = false++ func launch(_ game: LaunchableGame) async throws {+ await withCheckedContinuation { continuation in+ self.continuation = continuation+ started = true+ }+ }++ func finish() {+ continuation?.resume()+ continuation = nil+ }+ }++ func testCaptureBeforeAndDuringLaunch() async throws {+ guard let directory = ProcessInfo.processInfo.environment["NX_SHELL_CAPTURE_DIR"] else {+ throw XCTSkip("Set NX_SHELL_CAPTURE_DIR to capture the shell")+ }+ let language = ProcessInfo.processInfo.environment["NX_SHELL_CAPTURE_LANG"] ?? "en"+ let locale = language == "zh" ? "zh-Hans" : language+ if let path = ShellStrings.bundle.path(forResource: locale, ofType: "lproj") {+ ShellStrings.captureBundle = try XCTUnwrap(Bundle(path: path))+ }+ defer { ShellStrings.captureBundle = nil }+ let output = URL(fileURLWithPath: directory, isDirectory: true)+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)++ let box = try Sandbox()+ try box.giveAppData()+ // Keep one fictional, playable entry so both captures show the same library without unrelated error fixtures.+ for game in try FileManager.default.contentsOfDirectory(at: box.games, includingPropertiesForKeys: nil)+ where game.lastPathComponent != Fixtures.orbit {+ try FileManager.default.removeItem(at: game)+ }+ let suite = "shellhost.capture.\(UUID().uuidString)"+ let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))+ defer { defaults.removePersistentDomain(forName: suite) }+ let launcher = HeldLauncher()+ let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: ShellSettingsStore(defaults: defaults))+ let view = ShellHostView(model: model, initialSelection: Fixtures.orbit)+ .environment(\.locale, Locale(identifier: locale))+ try capture(view, to: output.appendingPathComponent("launch-before-\(language).png"))++ let launch = Task { await model.playNow(Fixtures.orbit) }+ defer { launcher.finish() }+ for _ in 0..<200 where !launcher.started { try await Task.sleep(for: .milliseconds(10)) }+ XCTAssertTrue(launcher.started, "The fixture launch must remain suspended while its loading state is captured")+ XCTAssertTrue(model.launchingGame)+ try capture(view, to: output.appendingPathComponent("launch-preparing-\(language).png"))+ launcher.finish()+ await launch.value+ XCTAssertFalse(model.launchingGame)+ }++ private func capture<V: View>(_ view: V, to file: URL) throws {+ NSApplication.shared.setActivationPolicy(.accessory)+ let host = NSHostingView(rootView: view.frame(width: 402, height: 874)+ .background(ShellPalette.background).environment(\.colorScheme, .dark))+ host.frame = NSRect(x: 0, y: 0, width: 402, height: 874)+ let window = NSWindow(contentRect: NSRect(x: -100_000, y: -100_000, width: 402, height: 874),+ styleMask: [.borderless], backing: .buffered, defer: false)+ window.isReleasedWhenClosed = false+ window.contentView = host+ window.orderFront(nil)+ defer { window.orderOut(nil); window.contentView = nil }+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))+ host.layoutSubtreeIfNeeded()+ let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))+ host.cacheDisplay(in: host.bounds, to: bitmap)+ try XCTUnwrap(bitmap.representation(using: .png, properties: [:])).write(to: file)+ }+}+#endifdiff --git a/frontend-ios/Tests/ShellHostTests/LauncherTests.swift b/frontend-ios/Tests/ShellHostTests/LauncherTests.swiftindex de06fa03..7bff9685 100644--- a/frontend-ios/Tests/ShellHostTests/LauncherTests.swift+++ b/frontend-ios/Tests/ShellHostTests/LauncherTests.swift@@ -1,4 +1,5 @@import Foundation+import Observationimport Testing@testable import ShellHost@@ -17,7 +18,50 @@ func sampleGame() throws -> LaunchableGame {appFolder: URL(fileURLWithPath: "/tmp/app"), environment: ["DM_OPMODE": "1"], cloudSavesURL: nil)}+@MainActor private final class WaitingLauncher: GameLauncher {+ private(set) var calls = 0+ private var entered: CheckedContinuation<Void, Never>?+ private var pending: CheckedContinuation<Void, any Error>?++ func launch(_ game: LaunchableGame) async throws {+ calls += 1+ try await withCheckedThrowingContinuation { pending = $0; entered?.resume(); entered = nil }+ }++ func waitForLaunch() async {+ if pending != nil { return }+ await withCheckedContinuation { entered = $0 }+ }++ func finish(failing: Bool) {+ let continuation = pending+ pending = nil+ if failing { continuation?.resume(throwing: Failure()) } else { continuation?.resume() }+ }+}+@MainActor @Suite struct LauncherTests {+ @Test(arguments: [false, true]) func launchStatusIsObservableAndClearsAfterSuccessOrFailure(failing: Bool) async throws {+ let box = try Sandbox()+ try box.giveAppData()+ let launcher = WaitingLauncher(), model = ShellHostModel(config: box.config(), launcher: launcher)+ let changes = LogBox()+ #expect(!model.launchingGame)+ withObservationTracking { _ = model.launchingGame } onChange: { changes.add("starting") }++ let play = Task { await model.playNow(Fixtures.orbit) }+ await launcher.waitForLaunch()+ #expect(model.launchingGame && changes.all == ["starting"])+ await model.playNow(Fixtures.orbit)+ #expect(launcher.calls == 1, "Play stays guarded while the loading indicator is visible")++ withObservationTracking { _ = model.launchingGame } onChange: { changes.add("finished") }+ launcher.finish(failing: failing)+ await play.value+ #expect(!model.launchingGame && changes.all == ["starting", "finished"])+ #expect((model.notice != nil) == failing)+ }+@Test func theStubLogsAndSaysItCannotLaunch() async throws {let box = LogBox()let launcher = StubGameLauncher(log: { box.add($0) })diff --git a/frontend-ios/Tests/ShellHostTests/ShaderResourcesTests.swift b/frontend-ios/Tests/ShellHostTests/ShaderResourcesTests.swiftindex 9523b2e3..a3ea489f 100644--- a/frontend-ios/Tests/ShellHostTests/ShaderResourcesTests.swift+++ b/frontend-ios/Tests/ShellHostTests/ShaderResourcesTests.swift@@ -28,6 +28,10 @@ import Testing@Test func playExtractsOnceAndRetriesAnInterruptedUpdate() async throws {let box = try Sandbox(), gameFolder = try box.giveAppData()+ let save = gameFolder.appendingPathComponent("save/progress.sav")+ let otherCache = box.appData.appendingPathComponent(Fixtures.chain + "/.shader-resources/msl-" + UUID().uuidString + "/" + shader)+ try box.write("player save", to: save)+ try box.write("other game shaders", to: otherCache)let launcher = RecordingLauncher(), model = ShellHostModel(config: box.config(), launcher: launcher)let framework = box.games.appendingPathComponent(Fixtures.orbit + "/DmGame.framework")let secondShader = "b-3f9a2c/large.metallib"@@ -55,6 +59,7 @@ import Testingtry complete.prefix(complete.count / 2).write(to: next) // Truncate the multi-block LZFSE stream.await model.playNow(Fixtures.orbit)#expect(model.notice != nil && launcher.launched.count == 2)+ #expect(!model.launchingGame)let cache = gameFolder.appendingPathComponent(".shader-resources")#expect(try FileManager.default.contentsOfDirectory(atPath: cache.path) == [firstCache.lastPathComponent])@@ -62,9 +67,13 @@ import Testingawait model.playNow(Fixtures.orbit)let updatedGame = try #require(launcher.launched.last), updated = try #require(updatedGame.shaderResourcesURL)#expect(launcher.launched.count == 3 && updated != firstCache)+ #expect(!model.launchingGame)#expect(try String(contentsOf: updated.appendingPathComponent(shader), encoding: .utf8) == "later")#expect(try String(contentsOf: updated.appendingPathComponent(secondShader), encoding: .utf8) == large)#expect(try FileManager.default.contentsOfDirectory(atPath: cache.path) == [updated.lastPathComponent])+ #expect(try String(contentsOf: save, encoding: .utf8) == "player save")+ #expect(try Data(contentsOf: gameFolder.appendingPathComponent("romfs/fixture.marker")).isEmpty)+ #expect(try String(contentsOf: otherCache, encoding: .utf8) == "other game shaders")}@Test func interruptedExtractionsAreRemovedBeforeRetryOrCacheHit() async throws {diff --git a/frontend/Tests/NX2AppleTests/ShellExportTests.swift b/frontend/Tests/NX2AppleTests/ShellExportTests.swiftindex c93793db..771f9781 100644--- a/frontend/Tests/NX2AppleTests/ShellExportTests.swift+++ b/frontend/Tests/NX2AppleTests/ShellExportTests.swift@@ -744,6 +744,39 @@ import NXModel// ---- step 3: the game data to a drive or folder ----+ func testDataResendIgnoresHiddenShaderCachesAndPreservesTheDestinationsOtherFiles() throws {+ let archive = try makeArchive(), destination = path("drive", titleID)+ let cache = ".shader-resources/msl-" + UUID().uuidString + "/b-3f9a2c/example.metallib"+ try write(archive + "/" + cache, "not transfer data")+ try write(destination + "/" + cache, "prepared shaders")+ try write(destination + "/save/progress.sav", "player save")+ try write(destination + "/romfs.img", "short")+ try write(destination + "/aoc/1.img", "abcd")+ let local = ShellInstall.localFiles(in: archive)+ XCTAssertEqual(local, ["romfs.img": 10, "aoc/1.img": 4])++ // A device listing may include the hidden cache. Only differing local game data is sent.+ let listing: [[String: Any]] = [+ ["relativePath": "romfs.img", "metadata": ["size": 5]],+ ["relativePath": "aoc/1.img", "metadata": ["size": 4]],+ ["relativePath": cache, "metadata": ["size": 16]],+ ["relativePath": "save/progress.sav", "metadata": ["size": 11]]+ ]+ let device = ShellInstall.parseListing(try JSONSerialization.data(withJSONObject: ["result": ["files": listing]]))+ XCTAssertEqual(ShellInstall.filesToCopy(local: local, device: device), ["romfs.img"])+ let command = ShellInstall.copyCommand(xcrun: "/xcrun", device: "fixture", bundleID: "org.nxnative.shell",+ titleID: titleID, source: archive + "/romfs.img", relativePath: "romfs.img")+ XCTAssertFalse(command.contains("--remove-existing-content"))++ // Exercise the real folder-copy path with the same transfer list, without a device or signing.+ var progress: [(Int64, Int64)] = []+ try DriveCopy.copy(archive: archive, files: local, to: destination) { progress.append(($0, $1)) }+ XCTAssertEqual(progress.last?.1, 10)+ XCTAssertEqual(try String(contentsOfFile: destination + "/romfs.img"), "0123456789")+ XCTAssertEqual(try String(contentsOfFile: destination + "/" + cache), "prepared shaders")+ XCTAssertEqual(try String(contentsOfFile: destination + "/save/progress.sav"), "player save")+ }+func testTheDriveGetsTheSameFilesAsTheDeviceUnderTheTitleIDFolder() throws {let archive = try makeArchive()try write(archive + "/.packstamp", "stamp") // a dot file is not game datadiff --git a/frontend/l10n/de.json b/frontend/l10n/de.jsonindex 37d9a174..0bcbdc71 100644--- a/frontend/l10n/de.json+++ b/frontend/l10n/de.json@@ -682,6 +682,7 @@"ios.host.padSameAsAllGames": "Wie alle Spiele","ios.host.padSwapAB": "A und B tauschen","ios.host.player": "Spieler %@",+ "ios.host.preparingGame": "Spiel wird vorbereitet…","ios.host.quitButton": "Beenden","ios.host.quitCancel": "Abbrechen","ios.host.quitHold": "Zum Beenden gedrückt halten",diff --git a/frontend/l10n/en.json b/frontend/l10n/en.jsonindex 69e6c2c1..d3420d54 100644--- a/frontend/l10n/en.json+++ b/frontend/l10n/en.json@@ -680,6 +680,7 @@"ios.host.padSameAsAllGames": "Same as all games","ios.host.padSwapAB": "Swap A and B","ios.host.player": "Player %@",+ "ios.host.preparingGame": "Preparing game…","ios.host.quitButton": "Quit","ios.host.quitCancel": "Cancel","ios.host.quitHold": "Keep holding to quit",diff --git a/frontend/l10n/fr.json b/frontend/l10n/fr.jsonindex 991be1c0..8fd5941b 100644--- a/frontend/l10n/fr.json+++ b/frontend/l10n/fr.json@@ -681,6 +681,7 @@"ios.host.padSameAsAllGames": "Comme tous les jeux","ios.host.padSwapAB": "Inverser A et B","ios.host.player": "Joueur %@",+ "ios.host.preparingGame": "Préparation du jeu…","ios.host.quitButton": "Quitter","ios.host.quitCancel": "Annuler","ios.host.quitHold": "Maintenez pour quitter",diff --git a/frontend/l10n/it.json b/frontend/l10n/it.jsonindex fdb5562e..bda5fcc2 100644--- a/frontend/l10n/it.json+++ b/frontend/l10n/it.json@@ -681,6 +681,7 @@"ios.host.padSameAsAllGames": "Come tutti i giochi","ios.host.padSwapAB": "Scambia A e B","ios.host.player": "Giocatore %@",+ "ios.host.preparingGame": "Preparazione del gioco…","ios.host.quitButton": "Esci","ios.host.quitCancel": "Annulla","ios.host.quitHold": "Tieni premuto per uscire",diff --git a/frontend/l10n/sv.json b/frontend/l10n/sv.jsonindex 35837f7e..68d4c666 100644--- a/frontend/l10n/sv.json+++ b/frontend/l10n/sv.json@@ -523,6 +523,7 @@"ios.host.padSameAsAllGames": "Som alla spel","ios.host.padSwapAB": "Byt A och B","ios.host.player": "Spelare %@",+ "ios.host.preparingGame": "Förbereder spelet…","ios.host.quitButton": "Avsluta","ios.host.quitCancel": "Avbryt","ios.host.quitHold": "Fortsätt hålla in för att avsluta",diff --git a/frontend/l10n/zh.json b/frontend/l10n/zh.jsonindex 8eb9283c..371846cf 100644--- a/frontend/l10n/zh.json+++ b/frontend/l10n/zh.json@@ -681,6 +681,7 @@"ios.host.padSameAsAllGames": "与所有游戏相同","ios.host.padSwapAB": "交换 A 和 B","ios.host.player": "玩家 %@",+ "ios.host.preparingGame": "正在准备游戏…","ios.host.quitButton": "退出","ios.host.quitCancel": "取消","ios.host.quitHold": "继续按住即可退出",