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
Console mode starts a game from a window that left full screen
v0lumehi82a2c51c2d99
diff --git a/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift b/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swiftindex dd176832..31f582ad 100644--- a/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift+++ b/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift@@ -4,13 +4,18 @@ import AppKit/// Enters and leaves the console mode: the window content switches (RootView, with a short calm transition) and the window goes/// full screen for the mode, then back to what it was. A window that was already full screen is left that way. The two animations/// are sequenced so they do not fight: on entering, the content switches after the window has finished going full screen, and on-/// leaving, the console fades out first and the window leaves full screen after.+/// leaving, the console fades out first and the window leaves full screen after. A game is started from a window that has left full+/// screen: a game opened from an app in its own full screen Space can come up as a window, so the window goes back to full screen+/// once the game has quit.@MainActor final class ConsoleCoordinator: ObservableObject {@Published private(set) var active = false/// The launcher is showing (not the guided setup), so the mode can be entered.@Published var available = falseprivate var enteredFullScreen = falseprivate var entering = false+ private var leftForGame = false+ private var activationObserver: NSObjectProtocol?+ private let appIsActive: () -> Boolprivate let window: () -> NSWindow?/// Changes the window's full screen state and calls `done` when that animation has finished.private let setFullScreen: @MainActor (NSWindow, Bool, @escaping () -> Void) -> Void@@ -20,7 +25,9 @@ import AppKitinit(window: @escaping () -> NSWindow? = { NSApp.keyWindow ?? NSApp.windows.first { $0.canBecomeMain } },setFullScreen: @escaping @MainActor (NSWindow, Bool, @escaping () -> Void) -> Void = ConsoleCoordinator.toggleFullScreen,- fadeSeconds: TimeInterval = ConsoleCoordinator.transitionSeconds + 0.05) {+ fadeSeconds: TimeInterval = ConsoleCoordinator.transitionSeconds + 0.05,+ appIsActive: @escaping () -> Bool = { NSApp?.isActive ?? true }) {+ self.appIsActive = appIsActiveself.window = windowself.setFullScreen = setFullScreenself.fadeSeconds = fadeSeconds@@ -58,6 +65,35 @@ import AppKit}func toggle() { active ? exit() : enter() }++ /// Takes the window out of full screen and then calls `launch`, which starts the game. A window that is not full screen calls it at once.+ func leaveFullScreenForGame(then launch: @escaping () -> Void) {+ guard active, let w = window(), w.styleMask.contains(.fullScreen) else { launch(); return }+ leftForGame = true+ setFullScreen(w, false) { launch() }+ }++ /// The game has quit or did not start: the window goes back to full screen if it left for the game and the console is still showing.+ /// A launcher that is not the active app waits until it is, so it does not pull the player into a Space from behind another app.+ func resumeFullScreenAfterGame() {+ guard leftForGame else { return }+ leftForGame = false+ guard active else { return }+ if appIsActive() { returnToFullScreen(); return }+ if let activationObserver { NotificationCenter.default.removeObserver(activationObserver) }+ activationObserver = NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in+ MainActor.assumeIsolated {+ guard let self else { return }+ if let token = self.activationObserver { NotificationCenter.default.removeObserver(token) }+ self.activationObserver = nil+ if self.active { self.returnToFullScreen() }+ }+ }+ }++ private func returnToFullScreen() {+ if let w = window(), !w.styleMask.contains(.fullScreen) { setFullScreen(w, true) {} }+ }}/// The calm switch between the desktop and the console: opacity with a little scale, blur or movement. Reduce Motion gets a plain fade.diff --git a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swiftindex fb2efc35..82f2989c 100644--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift@@ -111,6 +111,10 @@ struct ConsolePadSnapshot: Equatable {clock = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.state.time = Date(); self?.refreshControllers(announce: false) } } // the battery has no change callback: it is read again each tick}private var devicePads = false+ /// Runs before the game is opened and calls its argument when the launch may go on (the window leaves full screen first,+ /// see ConsoleCoordinator). `gameEnded` runs when the game quit or did not start.+ var prepareLaunch: (@escaping () -> Void) -> Void = { $0() }+ var gameEnded: () -> Void = {}deinit {observers.forEach { NotificationCenter.default.removeObserver($0); NSWorkspace.shared.notificationCenter.removeObserver($0) }@@ -219,11 +223,19 @@ struct ConsolePadSnapshot: Equatable {let environment = GameStart.environment(for: game, library: library, controls: controls, repo: repo(), labels: labels, fullscreen: true).merging(FrameTimes.recordingEnvironment(for: game, library: library.folder)) { $1 } // a frame-time recording, as the desktop Play adds (FrameTimes.swift)state.starting = .preparing+ prepareLaunch { [weak self] in+ guard let self else { return }+ guard self.state.startingGameID == gameID else { self.gameEnded(); return }+ self.openGame(game, environment: environment, gameID: gameID)+ }+ }++ private func openGame(_ game: LibraryGame, environment: [String: String], gameID: String) {launch(game, environment) { [weak self] pid, error inDispatchQueue.main.async {MainActor.assumeIsolated {guard let self, self.state.startingGameID == gameID else { return }- if let error { self.state.returnFromGame(); self.showToast(error.localizedDescription); return }+ if let error { self.state.returnFromGame(); self.gameEnded(); self.showToast(error.localizedDescription); return }self.launchedPID = pidif let pid { GameReturnWatcher.shared.didStart(pid: pid) { [weak self] in self?.gameDidTerminate(pid: pid) } } // the launcher's one watcher and its switch (ReturnAfterPlay.swift)self.state.starting = .opening@@ -260,6 +272,7 @@ struct ConsolePadSnapshot: Equatable {launchedPID = niltimeoutTask?.cancel()state.returnFromGame()+ gameEnded()}// MARK: Optionsdiff --git a/frontend/Sources/NSPortBuilder/OnboardingRoot.swift b/frontend/Sources/NSPortBuilder/OnboardingRoot.swiftindex 533cc1c3..4a315ebb 100644--- a/frontend/Sources/NSPortBuilder/OnboardingRoot.swift+++ b/frontend/Sources/NSPortBuilder/OnboardingRoot.swift@@ -44,7 +44,11 @@ struct RootView: View {.background(LauncherPalette.background).preferredColorScheme(.dark).frame(minWidth: 900, idealWidth: 1280, minHeight: 680, idealHeight: 900)- .task { await decide() }+ .task {+ shared.console.prepareLaunch = { [console] launch in console.leaveFullScreenForGame(then: launch) }+ shared.console.gameEnded = { [console] in console.resumeFullScreenAfterGame() }+ await decide()+ }.onChange(of: mode) { console.available = $0 == .launcher }}diff --git a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swiftindex a46edeac..25144709 100644--- a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift+++ b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift@@ -174,6 +174,62 @@ import SwiftUIcoordinator.toggle()}+ func testAGameStartsFromAWindowThatLeftFullScreenAndFullScreenReturnsAfterIt() throws {+ var calls: [Bool] = []+ var active = true+ final class FakeWindow: NSWindow {+ var isFull = true+ override var styleMask: NSWindow.StyleMask {+ get { isFull ? super.styleMask.union(.fullScreen) : super.styleMask }+ set { super.styleMask = newValue.subtracting(.fullScreen) }+ }+ }+ let window = FakeWindow(contentRect: .zero, styleMask: [.titled], backing: .buffered, defer: true)+ let coordinator = ConsoleCoordinator(window: { window }, setFullScreen: { _, on, done in+ calls.append(on)+ window.isFull = on+ done()+ }, fadeSeconds: 0.05, appIsActive: { active })+ coordinator.available = true+ coordinator.enter()+ XCTAssertTrue(coordinator.active, "the window was full screen already")+ var launched = 0+ coordinator.leaveFullScreenForGame { launched += 1 }+ XCTAssertEqual(calls, [false], "the window leaves full screen first")+ XCTAssertEqual(launched, 1, "the game starts after that")+ active = false+ coordinator.resumeFullScreenAfterGame()+ XCTAssertEqual(calls, [false], "a launcher behind another app waits")+ NotificationCenter.default.post(name: NSApplication.didBecomeActiveNotification, object: nil)+ XCTAssertEqual(calls, [false, true], "full screen is back once the launcher is active")+ coordinator.leaveFullScreenForGame { launched += 1 }+ coordinator.exit()+ coordinator.resumeFullScreenAfterGame()+ XCTAssertEqual(calls, [false, true, false], "a console that was left is not put back into full screen")+ var windowed = 0+ coordinator.leaveFullScreenForGame { windowed += 1 }+ XCTAssertEqual(windowed, 1, "a window that is not full screen starts the game at once")+ XCTAssertEqual(calls, [false, true, false])+ }++ func testPlayWaitsForTheLaunchHookAndReportsTheEnd() async throws {+ var launches: [Launch] = []+ let (driver, _, _) = try makeDriver { launches.append($0) }+ var release: (() -> Void)?+ var ended = 0+ driver.prepareLaunch = { release = $0 }+ driver.gameEnded = { ended += 1 }+ let id = try XCTUnwrap(driver.state.games.first?.id)+ driver.play(id)+ XCTAssertTrue(launches.isEmpty, "the game is not opened before the hook says so")+ XCTAssertEqual(driver.state.starting, .preparing)+ release?()+ XCTAssertEqual(launches.count, 1)+ for _ in 0..<50 where driver.state.starting != .opening { try await Task.sleep(nanoseconds: 20_000_000) }+ driver.gameDidTerminate(pid: 4242)+ XCTAssertEqual(ended, 1)+ }+func testControllerPromptOncePerSessionAndSetting() {XCTAssertTrue(ConsolePrompt.shouldShow(enabled: true, shown: false))XCTAssertFalse(ConsolePrompt.shouldShow(enabled: true, shown: true))