Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Console mode: player output on connect, idempotent notifications, calm enter and leave

v0lumehi82b934fbfc4e
diff --git a/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift b/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift
index d11e180d..dd176832 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift
@@ -1,38 +1,84 @@
import SwiftUI
import AppKit
-/// Enters and leaves the console mode: the window content switches (RootView) 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.
+/// 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.
@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 = false
private var enteredFullScreen = false
+ private var entering = false
private let window: () -> NSWindow?
- private let setFullScreen: (NSWindow, Bool) -> Void
+ /// Changes the window's full screen state and calls `done` when that animation has finished.
+ private let setFullScreen: @MainActor (NSWindow, Bool, @escaping () -> Void) -> Void
+ private let fadeSeconds: TimeInterval
+
+ nonisolated static let transitionSeconds: TimeInterval = 0.4
init(window: @escaping () -> NSWindow? = { NSApp.keyWindow ?? NSApp.windows.first { $0.canBecomeMain } },
- setFullScreen: @escaping (NSWindow, Bool) -> Void = { w, _ in w.toggleFullScreen(nil) }) {
+ setFullScreen: @escaping @MainActor (NSWindow, Bool, @escaping () -> Void) -> Void = ConsoleCoordinator.toggleFullScreen,
+ fadeSeconds: TimeInterval = ConsoleCoordinator.transitionSeconds + 0.05) {
self.window = window
self.setFullScreen = setFullScreen
+ self.fadeSeconds = fadeSeconds
+ }
+
+ /// The system toggle, with `done` called when AppKit reports the window has entered or left full screen (or after 1.5 seconds).
+ static func toggleFullScreen(_ window: NSWindow, _ enter: Bool, _ done: @escaping () -> Void) {
+ var finished = false
+ var token: NSObjectProtocol?
+ let finish = { if !finished { finished = true; if let token { NotificationCenter.default.removeObserver(token) }; done() } }
+ token = NotificationCenter.default.addObserver(forName: enter ? NSWindow.didEnterFullScreenNotification : NSWindow.didExitFullScreenNotification,
+ object: window, queue: .main) { _ in finish() }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { finish() }
+ window.toggleFullScreen(nil)
}
func enter() {
- guard available, !active else { return }
- active = true
- if let w = window(), !w.styleMask.contains(.fullScreen) { enteredFullScreen = true; setFullScreen(w, true) }
+ guard available, !active, !entering else { return }
+ if let w = window(), !w.styleMask.contains(.fullScreen) {
+ entering = true
+ enteredFullScreen = true
+ setFullScreen(w, true) { [weak self] in self?.entering = false; self?.active = true } // the content follows the window
+ } else { active = true }
}
func exit() {
guard active else { return }
- active = false
- if enteredFullScreen, let w = window(), w.styleMask.contains(.fullScreen) { setFullScreen(w, false) }
+ active = false // the console fades out first
+ let leave = enteredFullScreen
enteredFullScreen = false
+ guard leave else { return }
+ DispatchQueue.main.asyncAfter(deadline: .now() + fadeSeconds) { [weak self] in
+ if let w = self?.window(), w.styleMask.contains(.fullScreen) { self?.setFullScreen(w, false) {} }
+ }
}
func toggle() { active ? exit() : enter() }
}
+/// The calm switch between the desktop and the console: opacity with a little scale, blur or movement. Reduce Motion gets a plain fade.
+struct CalmTransition: ViewModifier {
+ var scale: CGFloat = 1
+ var blur: CGFloat = 0
+ var offset: CGFloat = 0
+ var opacity: Double = 1
+ func body(content: Content) -> some View {
+ content.scaleEffect(scale).blur(radius: blur).offset(y: offset).opacity(opacity)
+ }
+ static var reduceMotion: Bool { NSWorkspace.shared.accessibilityDisplayShouldReduceMotion }
+ /// The console arrives from a soft blur, a few points low. The desktop settles back from 0.97.
+ static var console: AnyTransition {
+ reduceMotion ? .opacity : .modifier(active: CalmTransition(blur: 8, offset: 10, opacity: 0), identity: CalmTransition())
+ }
+ static var desktop: AnyTransition {
+ reduceMotion ? .opacity : .modifier(active: CalmTransition(scale: 0.97, opacity: 0), identity: CalmTransition())
+ }
+}
+
/// The controller-connect prompt: once per session, and never when the player turned it off in Settings.
enum ConsolePrompt {
static let defaultsKey = "consolePrompt"
diff --git a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
index 70d9e0c9..5801699a 100644
--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
@@ -80,7 +80,8 @@ struct ConsolePadSnapshot: Equatable {
init(library: GameLibrary, controls: ControlLayout, repo: @escaping () -> String, lang: @escaping () -> Lang, labels: @escaping (String) -> String,
pads: (() -> [ConsolePadSnapshot])? = nil,
launch: ((LibraryGame, [String: String], @escaping (Int32?, Error?) -> Void) -> Void)? = nil,
- artwork: ((LibraryGame, String) -> NSImage?)? = nil, startingTimeout: TimeInterval = 20, observeSystem: Bool = true) {
+ artwork: ((LibraryGame, String) -> NSImage?)? = nil, startingTimeout: TimeInterval = 20, observeSystem: Bool = true, playerOutput: ((String, Int) -> Void)? = nil) {
+ self.sendPlayerOutput = playerOutput
self.library = library; self.controls = controls; self.repo = repo; self.lang = lang; self.labels = labels
self.startingTimeout = startingTimeout
self.pads = pads ?? { [] }
@@ -92,6 +93,7 @@ struct ConsolePadSnapshot: Equatable {
controls.$padMerge.sink { [weak self] merged in self?.state.padMerge = merged }.store(in: &cancellables)
refresh()
refreshControllers(announce: false)
+ announced = Set(state.controllers.map(\.id)) // controllers there at launch are not announced again by a repeated notification
if observeSystem { scheduleBatteryRereads() } // a controller there at launch may not have its battery yet either
guard observeSystem else { return }
let center = NotificationCenter.default
@@ -422,6 +424,50 @@ struct ConsolePadSnapshot: Equatable {
private static let hidLog = Logger(subsystem: "NX2Apple", category: "console.controllers")
private var remembered: [String: Int] = [:]
+ /// The player each controller was last told about (player lights and light bar), so the output is sent once per assignment.
+ private var primedPlayer: [String: Int] = [:]
+ /// Writes the player to a controller: its player lights and, when it has one, its light bar. Tests replace it.
+ var sendPlayerOutput: ((String, Int) -> Void)?
+
+ /// A calm colour per player for the light bar: blue, red, green, amber.
+ static func playerLightColor(_ player: Int) -> (red: Float, green: Float, blue: Float) {
+ switch player {
+ case 1: return (0.25, 0.55, 1.0)
+ case 2: return (1.0, 0.35, 0.35)
+ case 3: return (0.3, 0.85, 0.5)
+ default: return (1.0, 0.75, 0.3)
+ }
+ }
+
+ /// A DualShock 4 over Bluetooth (and the pads that copy it) only sends the report that carries its battery after the host has
+ /// sent it an output report, so every connected controller is sent one harmless one: its player. It also shows the player on the
+ /// controller. The battery is read again shortly after (and the key-value observer catches it). No rumble.
+ private func primeOutputs(_ pads: [ConsolePadSnapshot]) {
+ primedPlayer = primedPlayer.filter { key, _ in pads.contains { $0.id == key } }
+ var sent = false
+ for pad in pads {
+ guard let player = pad.playerIndex, primedPlayer[pad.id] != player else { continue }
+ primedPlayer[pad.id] = player
+ sent = true
+ if let sendPlayerOutput { sendPlayerOutput(pad.id, player); continue }
+ guard let device = devices[pad.id] else { continue }
+ device.playerIndex = GCControllerPlayerIndex(rawValue: player - 1) ?? .indexUnset
+ if let light = device.light {
+ let c = Self.playerLightColor(player)
+ light.color = GCColor(red: c.red, green: c.green, blue: c.blue)
+ }
+ Self.hidLog.debug("player output to \(pad.name, privacy: .public): player \(player), light bar \(device.light != nil)")
+ }
+ if sent {
+ Task { [weak self] in
+ for seconds in [0.5, 1.5] {
+ try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
+ self?.refreshControllers(announce: false)
+ }
+ }
+ }
+ }
+
private var batteryWatchers: [String: (object: ObjectIdentifier, watcher: KeyValueWatcher)] = [:]
/// A battery's level and state are key-value observable: a change refreshes the list at once instead of waiting for the next read.
@@ -445,15 +491,27 @@ struct ConsolePadSnapshot: Equatable {
Self.hidLog.debug("\(connected ? "connect" : "disconnect") \(self.stamp(), privacy: .public): vendor \(pad.vendorName ?? "?", privacy: .public), category \(pad.productCategory, privacy: .public), extendedGamepad \(pad.extendedGamepad != nil), battery \(pad.battery != nil)")
if !connected { tearDown(pad) }
}
- let name = pad.map { $0.vendorName ?? $0.productCategory } ?? ""
- controllerListChanged(connectedName: connected ? name : nil, disconnectedName: connected ? nil : name, including: connected ? pad : nil, excluding: connected ? nil : pad)
- guard pad != nil else { return }
- guard connected else { showToast(String(format: t("console.disconnected"), name)); return }
- let id = pad.map { String(UInt(bitPattern: ObjectIdentifier($0).hashValue), radix: 16) } ?? ""
+ guard let pad else { controllerListChanged(connectedName: nil, disconnectedName: nil); return }
+ let id = String(UInt(bitPattern: ObjectIdentifier(pad).hashValue), radix: 16)
+ handleConnection(id: id, name: pad.vendorName ?? pad.productCategory, connected: connected, including: connected ? pad : nil, excluding: connected ? nil : pad)
+ }
+
+ private var announced = Set<String>()
+
+ /// One connect or disconnect of one controller instance. GameController posts the notification two or three times for a single
+ /// connect (and twice for a disconnect), so the list is rebuilt every time (harmless, it is keyed by instance) but the toast, the
+ /// battery re-reads and the rest only happen on the first. Returns whether this was the first.
+ @discardableResult
+ func handleConnection(id: String, name: String, connected: Bool, including: GCController? = nil, excluding: GCController? = nil) -> Bool {
+ let first = connected ? announced.insert(id).inserted : announced.remove(id) != nil
+ controllerListChanged(connectedName: connected ? name : nil, disconnectedName: connected ? nil : name, including: including, excluding: excluding)
+ guard first else { Self.hidLog.debug("repeated \(connected ? "connect" : "disconnect") for \(id, privacy: .public) ignored"); return false }
+ guard connected else { showToast(String(format: t("console.disconnected"), name)); return true }
if let player = state.padMerge ? 1 : state.controllers.first(where: { $0.id == id })?.player {
showToast(String(format: t("console.connected"), name, player))
} else { showToast(t("console.noFreePlayer"), glyph: ConsoleGlyphs.current().glyph(for: .controllers)) }
scheduleBatteryRereads()
+ return true
}
/// The part of a connect or disconnect that does not need a GCController, so tests can drive it.
@@ -469,6 +527,7 @@ struct ConsolePadSnapshot: Equatable {
devices[id] = nil
overrides[id] = nil
batteryWatchers[id] = nil
+ primedPlayer[id] = nil
Self.hidLog.debug("torn down \(id, privacy: .public)")
}
@@ -516,6 +575,7 @@ struct ConsolePadSnapshot: Equatable {
devices[new.id]?.playerIndex = GCControllerPlayerIndex(rawValue: (new.playerIndex ?? 1) - 1) ?? .indexUnset
}
for pad in assigned { if let p = pad.playerIndex { remembered[Self.memoryKey(pad)] = p } }
+ primeOutputs(assigned)
let list = assigned.map(\.controller)
if list != state.controllers {
Self.hidLog.debug("publish \(list.count) controllers at \(self.stamp(), privacy: .public): \(list.map { "\($0.name)" }.joined(separator: ", "), privacy: .public)")
diff --git a/frontend/Sources/NSPortBuilder/OnboardingRoot.swift b/frontend/Sources/NSPortBuilder/OnboardingRoot.swift
index e04644a7..533cc1c3 100644
--- a/frontend/Sources/NSPortBuilder/OnboardingRoot.swift
+++ b/frontend/Sources/NSPortBuilder/OnboardingRoot.swift
@@ -27,13 +27,18 @@ struct RootView: View {
case .onboarding:
if let driver { OnboardingView(driver: driver, lang: model.lang, gamepad: gamepad) }
case .launcher:
- if console.active {
- ConsoleView(driver: shared.console, lang: model.lang, onExit: { console.exit(); shared.console.returnFromGame() })
- .onAppear { shared.console.reloadCovers() }
- } else {
- ContentView(model: model, library: library, onRunSetup: runSetupAgain, enterConsole: { console.enter() },
- controllerDriver: AnyConsoleDriver(shared.console), controls: shared.controls)
+ ZStack {
+ if console.active {
+ ConsoleView(driver: shared.console, lang: model.lang, onExit: { console.exit(); shared.console.returnFromGame() })
+ .onAppear { shared.console.reloadCovers() }
+ .transition(CalmTransition.console)
+ } else {
+ ContentView(model: model, library: library, onRunSetup: runSetupAgain, enterConsole: { console.enter() },
+ controllerDriver: AnyConsoleDriver(shared.console), controls: shared.controls)
+ .transition(CalmTransition.desktop)
+ }
}
+ .animation(.easeInOut(duration: CalmTransition.reduceMotion ? 0.25 : ConsoleCoordinator.transitionSeconds), value: console.active)
}
}
.background(LauncherPalette.background)
diff --git a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
index c53a0efe..e0e6b7c9 100644
--- a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
@@ -137,22 +137,26 @@ import SwiftUI
XCTAssertNotNil(driver.state.toast, "a Bluetooth controller cannot be dropped by an app: the toast says where")
}
- func testEnteringAndLeavingConsoleModeRestoresTheWindow() {
+ func testEnteringAndLeavingConsoleModeRestoresTheWindowInOrder() async throws {
var calls: [Bool] = []
+ var finishEntering: (() -> Void)?
let window = NSWindow(contentRect: .zero, styleMask: [.titled], backing: .buffered, defer: true)
- let coordinator = ConsoleCoordinator(window: { window }, setFullScreen: { _, on in calls.append(on) })
+ let coordinator = ConsoleCoordinator(window: { window }, setFullScreen: { _, on, done in calls.append(on); if on { finishEntering = done } else { done() } }, fadeSeconds: 0.05)
coordinator.enter()
XCTAssertFalse(coordinator.active, "not while the guided setup shows")
coordinator.available = true
coordinator.enter()
- XCTAssertTrue(coordinator.active)
- XCTAssertEqual(calls, [true])
+ XCTAssertEqual(calls, [true], "the window starts going full screen")
+ XCTAssertFalse(coordinator.active, "the console fades in only after the window finished")
coordinator.enter()
XCTAssertEqual(calls, [true], "entering twice does nothing")
+ finishEntering?()
+ XCTAssertTrue(coordinator.active)
coordinator.exit()
- XCTAssertFalse(coordinator.active)
+ XCTAssertFalse(coordinator.active, "the console fades out first")
+ XCTAssertEqual(calls, [true], "the window has not left full screen yet")
+ try await Task.sleep(nanoseconds: 150_000_000)
coordinator.toggle()
- XCTAssertTrue(coordinator.active)
}
func testControllerPromptOncePerSessionAndSetting() {
@@ -476,4 +480,52 @@ import SwiftUI
for _ in 0..<50 where driver.state.controllers.first?.batteryPercent != 62 { try await Task.sleep(nanoseconds: 20_000_000) }
XCTAssertEqual(driver.state.controllers.first?.batteryPercent, 62)
}
+
+ /// The pad reports no battery until the host sends it an output (the DS4 Bluetooth protocol): the driver sends the player once per
+ /// assignment right after connecting, and the battery is known on the next read.
+ func testPlayerOutputOnConnectMakesTheBatteryAppear() async throws {
+ var wroteOutput = false
+ var sent: [(String, Int)] = []
+ let driver = LiveConsoleDriver(library: GameLibrary(file: temporary.appendingPathComponent("library.json")),
+ controls: ControlLayout(defaults: UserDefaults(suiteName: "ConsoleLiveTests-" + UUID().uuidString)!),
+ repo: { "" }, lang: { .en }, labels: { $0 },
+ pads: { [ConsolePadSnapshot(id: "g7", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil, battery: wroteOutput ? 0.72 : nil)] },
+ artwork: { _, _ in nil }, observeSystem: false,
+ playerOutput: { id, player in sent.append((id, player)); wroteOutput = true }) // the fake pad only reports a battery after an output
+ XCTAssertEqual(sent.map(\.1), [1], "the player is written once, right on connect")
+ XCTAssertNil(driver.state.controllers.first?.battery, "unknown until the output has been sent")
+ for _ in 0..<80 where driver.state.controllers.first?.batteryPercent != 72 { try await Task.sleep(nanoseconds: 25_000_000) }
+ XCTAssertEqual(driver.state.controllers.first?.batteryPercent, 72, "known on the read after the output")
+ driver.refreshControllers(announce: false)
+ XCTAssertEqual(sent.count, 1, "not sent again for the same assignment")
+ XCTAssertEqual(LiveConsoleDriver.playerLightColor(1).blue, 1.0)
+ XCTAssertNotEqual(LiveConsoleDriver.playerLightColor(2).red, LiveConsoleDriver.playerLightColor(3).red)
+ }
+
+ /// GameController posts the connect notification two or three times for one connect, and the disconnect twice: one entry, one
+ /// toast, one set of light writes, one reassignment.
+ func testRepeatedConnectAndDisconnectNotificationsAreIdempotent() {
+ var list: [ConsolePadSnapshot] = []
+ var writes: [(String, Int)] = []
+ let driver = LiveConsoleDriver(library: GameLibrary(file: temporary.appendingPathComponent("library.json")),
+ controls: ControlLayout(defaults: UserDefaults(suiteName: "ConsoleLiveTests-" + UUID().uuidString)!),
+ repo: { "" }, lang: { .en }, labels: { $0 }, pads: { list }, artwork: { _, _ in nil }, observeSystem: false,
+ playerOutput: { writes.append(($0, $1)) })
+ list = [ConsolePadSnapshot(id: "pad", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil)]
+ XCTAssertTrue(driver.handleConnection(id: "pad", name: "DUALSHOCK 4 Wireless Controller", connected: true), "the first connect counts")
+ let toast = driver.state.toast
+ XCTAssertNotNil(toast)
+ XCTAssertFalse(driver.handleConnection(id: "pad", name: "DUALSHOCK 4 Wireless Controller", connected: true))
+ XCTAssertFalse(driver.handleConnection(id: "pad", name: "DUALSHOCK 4 Wireless Controller", connected: true))
+ XCTAssertEqual(driver.state.toast, toast, "no second toast")
+ XCTAssertEqual(driver.state.controllers.map(\.id), ["pad"], "one entry")
+ XCTAssertEqual(driver.state.controllers.map(\.player), [1], "assigned once")
+ XCTAssertEqual(writes.count, 1, "one light and player write")
+ list = []
+ XCTAssertTrue(driver.handleConnection(id: "pad", name: "DUALSHOCK 4 Wireless Controller", connected: false))
+ let gone = driver.state.toast
+ XCTAssertFalse(driver.handleConnection(id: "pad", name: "DUALSHOCK 4 Wireless Controller", connected: false))
+ XCTAssertEqual(driver.state.toast, gone, "no second disconnect toast")
+ XCTAssertTrue(driver.state.controllers.isEmpty)
+ }
}