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
The launcher comes back to the front when a game it started quits
subyoung9a7dfb28a43a
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 4cedb251..a40745b8 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -2677,6 +2677,7 @@ struct BuilderView: View {var padMerge: Binding<Bool> = .constant(false) // "All controllers are player 1" (ControlLayout.padMerge)@AppStorage(ConsolePrompt.defaultsKey) private var consolePromptOn = true // ConsoleCoordinator.swift@AppStorage(BuildNotice.defaultsKey) private var notifyBuilds = true // BuildNotifications.swift+ @AppStorage(ReturnAfterPlay.defaultsKey) private var returnAfterPlay = true // ReturnAfterPlay.swift@State private var extrasOpen = false@State private var logOpen = false@State private var keyCheck: KeyCheck.Outcome? // prod.keys against the chosen files (KeyCheck.swift)@@ -3164,6 +3165,12 @@ struct BuilderView: View {}divider}+ // The launcher back in front when a game it started quits (ReturnAfterPlay.swift)+ row(m.t("settings.returnAfterPlay"), detail: m.t("settings.returnAfterPlayNote")) {+ Toggle("", isOn: $returnAfterPlay).toggleStyle(LauncherSwitchStyle()).labelsHidden()+ .padTarget("set.returnAfterPlay", scope: "main") { returnAfterPlay.toggle() }+ }+ dividerrow("NX2Apple", detail: String(format: m.t("app.version"), BuildModel.appVersion),dot: m.appStaged != nil ? LauncherPalette.ready : nil) {if m.appBusy { ProgressView().controlSize(.small) }diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 8d845969..04d08837 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -803,10 +803,14 @@ struct ContentView: View {// They stay launch overrides (the environment) for now: DM_KEYMAP and DM_PAD_MAP become saved choices only when seedds/nxnative#386 merges.let environment = GameStart.environment(for: game, library: library, controls: controls, repo: m.repoPath, labels: m.t) // GameStart.swift: the console mode starts games with the sameif !environment.isEmpty { configuration.environment = environment }- NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: game.appPath), configuration: configuration) { _, error in+ NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: game.appPath), configuration: configuration) { app, error in+ let pid = app?.processIdentifierDispatchQueue.main.async {- launching = false- if let error { launchError = error.localizedDescription }+ MainActor.assumeIsolated {+ launching = false+ if let error { launchError = error.localizedDescription }+ else if let pid { GameReturnWatcher.shared.didStart(pid: pid) } // ReturnAfterPlay.swift+ }}}} catch { launchError = error.localizedDescription }diff --git a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swiftindex 5801699a..d15e3ea4 100644--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift@@ -105,11 +105,6 @@ struct ConsolePadSnapshot: Equatable {MainActor.assumeIsolated { self?.padsChanged(connected: false, note: note) }},]- let workspace = NSWorkspace.shared.notificationCenter- observers.append(workspace.addObserver(forName: NSWorkspace.didTerminateApplicationNotification, object: nil, queue: .main) { [weak self] note in- let pid = (note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication)?.processIdentifier- MainActor.assumeIsolated { if let pid { self?.gameDidTerminate(pid: pid) } }- })observers.append(center.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { [weak self] _ inMainActor.assumeIsolated { self?.gameWindowAppeared() }})@@ -229,6 +224,7 @@ struct ConsolePadSnapshot: Equatable {guard let self, self.state.startingGameID == gameID else { return }if let error { self.state.returnFromGame(); self.showToast(error.localizedDescription); return }self.launchedPID = pid+ if 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 = .openingself.timeoutTask?.cancel()self.timeoutTask = Task { [weak self] in@@ -256,14 +252,13 @@ struct ConsolePadSnapshot: Equatable {state.returnFromGame()}- /// The game this console started quit: the console comes back to the front (PR #110's launcher-wide return does the same for the desktop).+ /// The game this console started quit (GameReturnWatcher, which then brings the launcher forward when Settings > App+ /// leaves that on, as for the desktop Play): Starting ends, the selected game is kept.func gameDidTerminate(pid: Int32) {guard pid == launchedPID else { return }launchedPID = niltimeoutTask?.cancel()state.returnFromGame()- NSApp.unhide(nil)- NSApp.activate(ignoringOtherApps: true)}// MARK: Optionsdiff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 36f8dbf2..71019df6 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -599,6 +599,8 @@ enum L10n {"settings.notify": ("构建完成时通知", "Notify when a build ends"),"settings.notifyNote": ("仅在 NX2Apple 不在前台时,构建完成或失败都会通知", "When a build finishes or fails while NX2Apple is in the background"),"settings.notifyUnbundled": ("需要 NX2Apple.app:用 swift run 启动时没有通知", "Needs NX2Apple.app: no notifications when started with swift run"),+ "settings.returnAfterPlay": ("游戏退出后回到启动器", "Come back when a game quits"),+ "settings.returnAfterPlayNote": ("从游戏库点 Play 或在主机模式里启动的游戏退出时,启动器回到前台,可以接着选下一个游戏", "When a game started with Play or in console mode quits, the launcher comes to the front to pick the next one"),"build.cancel": ("取消构建", "Cancel build"),"msg.macAppDone": ("Mac App 已生成,可在访达里双击运行", "Mac app ready — double-click it in the Finder"),"msg.macAppMissing": ("构建结束但没有找到 .app(仓库里缺 dm/mac/pack_app.py?)",@@ -971,6 +973,8 @@ enum L10n {"settings.language.zh": "Kinesiska","settings.language.en": "English","settings.language.sv": "Svenska",+ "settings.returnAfterPlay": "Kom tillbaka när ett spel avslutas",+ "settings.returnAfterPlayNote": "När ett spel som startats med Spela eller i konsolläget avslutas kommer startprogrammet fram, så att du kan välja nästa","settings.heading": "Inställningar","onboarding.welcome.title": "Välkommen.","onboarding.welcome.note": "Spela dina Switch-spel direkt på din Mac på ungefär 15 minuter.",diff --git a/frontend/Sources/NSPortBuilder/ReturnAfterPlay.swift b/frontend/Sources/NSPortBuilder/ReturnAfterPlay.swiftnew file mode 100644index 00000000..72cb7f84--- /dev/null+++ b/frontend/Sources/NSPortBuilder/ReturnAfterPlay.swift@@ -0,0 +1,55 @@+import AppKit++// The launcher comes back to the front when a game it started quits. Play opens the game's own app and the+// launcher stayed wherever it was: after a session (often played with a controller) there was nothing in front to+// pick the next game with, and the launcher had to be found in the Dock. One watcher serves both ways of starting a+// game, the desktop Play button (LauncherView) and console mode (LiveConsoleDriver), so they behave the same: each+// registers the process it opened, by its process ID (an app opened from Finder is left alone), and one Settings+// switch (Settings > App) decides whether the launcher comes forward.++enum ReturnAfterPlay {+ static let defaultsKey = "returnAfterPlay"++ /// On unless switched off in Settings.+ static var enabled: Bool { UserDefaults.standard.object(forKey: defaultsKey) as? Bool ?? true }++ /// The launcher's windows forward: unhidden, active, its main window in front.+ static func bringForward() {+ NSApp.unhide(nil)+ NSApp.activate(ignoringOtherApps: true)+ NSApp.windows.first { $0.canBecomeMain }?.makeKeyAndOrderFront(nil)+ }+}++/// The games the launcher started, by process ID, and what each start wants done when its game quits.+@MainActor final class GameReturnWatcher {+ static let shared = GameReturnWatcher()+ private var started: [Int32: () -> Void] = [:]+ private var observer: NSObjectProtocol?+ private let observesSystem: Bool++ /// `observesSystem` false: no NSWorkspace observer, `quit(pid:)` is called by hand (the tests).+ init(observesSystem: Bool = true) { self.observesSystem = observesSystem }++ /// Called once the game's app has been opened; `onQuit` is the caller's own bookkeeping (console mode ends its+ /// Starting state there), run whether or not the launcher comes forward.+ func didStart(pid: Int32, onQuit: @escaping () -> Void = {}) {+ started[pid] = onQuit+ guard observesSystem, observer == nil else { return }+ observer = NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didTerminateApplicationNotification,+ object: nil, queue: .main) { [weak self] note in+ let pid = (note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication)?.processIdentifier+ MainActor.assumeIsolated { if let pid { self?.quit(pid: pid) } }+ }+ }++ /// A process quit. Returns whether it was a game the launcher started: its `onQuit` ran, and the launcher came+ /// forward if the switch is on.+ @discardableResult+ func quit(pid: Int32, enabled: Bool = ReturnAfterPlay.enabled, bringForward: () -> Void = ReturnAfterPlay.bringForward) -> Bool {+ guard let onQuit = started.removeValue(forKey: pid) else { return false }+ onQuit()+ if enabled { bringForward() }+ return true+ }+}diff --git a/frontend/Tests/NSPortBuilderTests/ReturnAfterPlayTests.swift b/frontend/Tests/NSPortBuilderTests/ReturnAfterPlayTests.swiftnew file mode 100644index 00000000..c620b559--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/ReturnAfterPlayTests.swift@@ -0,0 +1,51 @@+import XCTest+@testable import NSPortBuilder++/// When the launcher comes back to the front after a game it started quits. Nothing here touches NSWorkspace.+@MainActor final class ReturnAfterPlayTests: XCTestCase {+ func testComesBackForAGameItStarted() {+ let watcher = GameReturnWatcher(observesSystem: false)+ var forward = 0, quit = 0+ watcher.didStart(pid: 4242) { quit += 1 }+ XCTAssertTrue(watcher.quit(pid: 4242, enabled: true) { forward += 1 })+ XCTAssertEqual(quit, 1, "the caller's bookkeeping ran")+ XCTAssertEqual(forward, 1, "the launcher came forward")+ XCTAssertFalse(watcher.quit(pid: 4242, enabled: true) { forward += 1 }, "only once per start")+ XCTAssertEqual(forward, 1)+ }++ func testStaysPutForOtherProcesses() {+ let watcher = GameReturnWatcher(observesSystem: false)+ var forward = 0+ watcher.didStart(pid: 4242)+ XCTAssertFalse(watcher.quit(pid: 1, enabled: true) { forward += 1 }, "a process the launcher did not start (a game opened from Finder)")+ XCTAssertEqual(forward, 0)+ }++ func testSwitchedOffStillRunsTheBookkeeping() {+ let watcher = GameReturnWatcher(observesSystem: false)+ var forward = 0, quit = 0+ watcher.didStart(pid: 4242) { quit += 1 }+ XCTAssertTrue(watcher.quit(pid: 4242, enabled: false) { forward += 1 })+ XCTAssertEqual(quit, 1, "console mode still ends its Starting state")+ XCTAssertEqual(forward, 0, "switched off in Settings: the launcher stays where it is")+ }++ func testOnUntilSwitchedOff() {+ let saved = UserDefaults.standard.object(forKey: ReturnAfterPlay.defaultsKey)+ defer { UserDefaults.standard.set(saved, forKey: ReturnAfterPlay.defaultsKey) }+ UserDefaults.standard.removeObject(forKey: ReturnAfterPlay.defaultsKey)+ XCTAssertTrue(ReturnAfterPlay.enabled)+ UserDefaults.standard.set(false, forKey: ReturnAfterPlay.defaultsKey)+ XCTAssertFalse(ReturnAfterPlay.enabled)+ }++ func testTheSettingIsInEveryLanguage() {+ for key in ["settings.returnAfterPlay", "settings.returnAfterPlayNote"] {+ XCTAssertNotEqual(L10n.string(key, .en), key)+ XCTAssertNotEqual(L10n.string(key, .zh), key)+ XCTAssertNotEqual(L10n.string(key, .en), L10n.string(key, .zh))+ XCTAssertNotEqual(L10n.string(key, .sv), L10n.string(key, .en), "a Swedish entry, not the English fallback")+ }+ }+}