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: GameController only, the prompt dims the whole window

v0lumehid72f5143f682
diff --git a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
index 4a0f7913..f5c07db9 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
@@ -137,8 +137,8 @@ struct ConsoleControllerChips: View {
chip(id: controller.id, label: controller.name + ", " + t(controller.kind.labelKey) + ", " + ((merged ? 1 : controller.player).map { String(format: t("console.player"), $0) } ?? t("console.unassigned")) + (controller.batteryPercent.map { ", " + String(format: t(controller.charging ? "console.batteryCharging" : "console.batteryLevel"), $0) } ?? "")) {
HStack(spacing: compact ? 5 : 8) {
Image(systemName: controller.kind.symbol).accessibilityHidden(true)
- if controller.connecting { Text("\u{2026}") } else { Text((merged ? 1 : controller.player).map { String(format: t("console.playerShort"), $0) } ?? "\u{2014}") } // the full "Unassigned" is in the Controllers list
- if !controller.connecting { ConsoleBattery(controller: controller, lang: lang, compact: compact) }
+ Text((merged ? 1 : controller.player).map { String(format: t("console.playerShort"), $0) } ?? "\u{2014}") // the full "Unassigned" is in the Controllers list
+ ConsoleBattery(controller: controller, lang: lang, compact: compact)
}
}
}
@@ -263,10 +263,8 @@ struct ConsoleToastView: View {
Image(systemName: controller.kind.symbol).font(.system(size: compact ? 26 : 34)).frame(width: 42).accessibilityHidden(true)
VStack(alignment: .leading, spacing: 6) {
Text(controller.name).font(.manrope(compact ? 18 : 23, .semibold))
- if controller.connecting { Text(t("console.connecting")).font(.manrope(compact ? 14 : 17)).foregroundStyle(.secondary) }
- else { Text(t(controller.kind.labelKey) + " \u{00b7} " + playerLabel(controller)).font(.manrope(compact ? 14 : 17)).foregroundStyle(.secondary) }
- if controller.connecting {}
- else if controller.wired { HStack(spacing: 6) { ConsoleBattery(controller: controller, lang: lang); Text(t("console.wired")).font(.manrope(13)).foregroundStyle(.secondary) } }
+ do { Text(t(controller.kind.labelKey) + " \u{00b7} " + playerLabel(controller)).font(.manrope(compact ? 14 : 17)).foregroundStyle(.secondary) }
+ if controller.wired { HStack(spacing: 6) { ConsoleBattery(controller: controller, lang: lang); Text(t("console.wired")).font(.manrope(13)).foregroundStyle(.secondary) } }
else if controller.battery == nil { Text(t("console.batteryUnknown")).font(.manrope(13)).foregroundStyle(.secondary) }
else { ConsoleBattery(controller: controller, lang: lang) }
if controller.charging { Text(t("console.charging")).font(.manrope(13)).foregroundStyle(.secondary) }
@@ -274,11 +272,11 @@ struct ConsoleToastView: View {
Spacer(minLength: 0)
}
// Three equal tiles: the icon above a label that wraps between words only (and shrinks a little rather than break a word).
- if !controller.connecting { HStack(spacing: 10) {
+ HStack(spacing: 10) {
if controller.canIdentify { tile(id: controller.id + ".identify", label: t(state.identifyingControllerID == controller.id ? "console.identifying" : "console.identify"), symbol: "wave.3.right") { driver.identify(controllerID: controller.id) } }
tile(id: controller.id + ".assign", label: t("console.assign"), symbol: "person.crop.circle.badge.plus") { driver.requestAssignment(controllerID: controller.id) }
tile(id: controller.id + ".disconnect", label: t("console.disconnect"), symbol: "xmark.circle") { driver.disconnect(controllerID: controller.id) }
- } }
+ }
if state.isPreview, state.assigningPlayer != nil, state.assigningControllerID == nil || state.assigningControllerID == controller.id {
action(id: controller.id + ".press", label: t("console.mockPress"), symbol: "hand.tap") {
driver.assignPlayer(controllerID: controller.id, player: state.assigningPlayer ?? 1)
diff --git a/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
index d4e6868d..a01ba7b5 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
@@ -41,7 +41,7 @@ struct ConsoleConnectionPrompt: View {
private var glyphs: ConsoleGlyphs { .current() }
var body: some View {
ZStack {
- Color.black.opacity(0.65)
+ Color.black.opacity(0.65).ignoresSafeArea() // the whole window, the area behind the hidden title bar too
VStack(alignment: .leading, spacing: 14) {
Label(t("console.connectionTitle"), systemImage: "gamecontroller").font(.manrope(22, .bold))
Text(t("console.connectionNote")).font(.manrope(14)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
diff --git a/frontend/Sources/NSPortBuilder/ConsoleState.swift b/frontend/Sources/NSPortBuilder/ConsoleState.swift
index dbe291b2..e7004004 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleState.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleState.swift
@@ -72,8 +72,6 @@ struct ConsoleController: Identifiable, Equatable {
var canIdentify = true
/// No battery object at all: a controller like that is powered by its cable.
var wired = false
- /// Plugged in or switched on according to the hardware, not yet reported by GameController.
- var connecting = false
var batteryPercent: Int? { battery.map { Int((min(max($0.isFinite ? $0 : 0, 0), 1) * 100).rounded()) } }
}
diff --git a/frontend/Sources/NSPortBuilder/HIDControllerWatcher.swift b/frontend/Sources/NSPortBuilder/HIDControllerWatcher.swift
deleted file mode 100644
index 9039ac89..00000000
--- a/frontend/Sources/NSPortBuilder/HIDControllerWatcher.swift
+++ /dev/null
@@ -1,110 +0,0 @@
-import Foundation
-import IOKit
-import os
-
-/// Tells the launcher when a game pad, joystick or multi-axis controller is plugged in or removed, straight from the IOKit registry
-/// (matching notifications on IOHIDDevice with the Generic Desktop usages GamePad, Joystick and MultiAxisController). It only watches
-/// the registry: no device is opened or seized, so games and the system are unaffected and no permission is asked. It exists because
-/// GameController can report a controller seconds after the hardware appears, and sometimes not on a re-plug. The launcher shows a
-/// "Connecting" placeholder from this and replaces it when GameController reports the controller.
-final class HIDControllerWatcher {
- struct Event: Equatable {
- enum Kind { case attach, detach }
- var kind: Kind
- var id: UInt64
- var name: String
- }
-
- private static let log = Logger(subsystem: "NX2Apple", category: "console.controllers")
- private var port: IONotificationPortRef?
- private var iterators: [io_iterator_t] = []
- private var seen = Set<UInt64>()
- private let handler: (Event) -> Void
-
- init(handler: @escaping (Event) -> Void) {
- self.handler = handler
- port = IONotificationPortCreate(kIOMainPortDefault)
- guard let port else { return }
- CFRunLoopAddSource(CFRunLoopGetMain(), IONotificationPortGetRunLoopSource(port).takeUnretainedValue(), .defaultMode)
- let refcon = Unmanaged.passUnretained(self).toOpaque()
- for usage in [5, 4, 8] { // GamePad, Joystick, MultiAxisController
- for (notification, attach) in [(kIOFirstMatchNotification, true), (kIOTerminatedNotification, false)] {
- let matching = IOServiceMatching("IOHIDDevice") as NSMutableDictionary
- matching["DeviceUsagePage"] = 1
- matching["DeviceUsage"] = usage
- var iterator: io_iterator_t = 0
- let status = IOServiceAddMatchingNotification(port, notification, matching, attach ? Self.attachCallback : Self.detachCallback, refcon, &iterator)
- if status == KERN_SUCCESS {
- iterators.append(iterator)
- drain(iterator, attach: attach) // arms the notification and reports what is already there
- }
- }
- }
- }
-
- private static let attachCallback: IOServiceMatchingCallback = { refcon, iterator in
- guard let refcon else { return }
- Unmanaged<HIDControllerWatcher>.fromOpaque(refcon).takeUnretainedValue().drain(iterator, attach: true)
- }
- private static let detachCallback: IOServiceMatchingCallback = { refcon, iterator in
- guard let refcon else { return }
- Unmanaged<HIDControllerWatcher>.fromOpaque(refcon).takeUnretainedValue().drain(iterator, attach: false)
- }
-
- private func drain(_ iterator: io_iterator_t, attach: Bool) {
- while case let service = IOIteratorNext(iterator), service != 0 {
- defer { IOObjectRelease(service) }
- var id: UInt64 = 0
- IORegistryEntryGetRegistryEntryID(service, &id)
- let name = (IORegistryEntryCreateCFProperty(service, "Product" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? String) ?? ""
- if attach { guard seen.insert(id).inserted else { continue } } else { guard seen.remove(id) != nil else { continue } }
- Self.log.debug("hid \(attach ? "attach" : "detach", privacy: .public) \(name, privacy: .public) id \(id) at \(Date().timeIntervalSince1970, format: .fixed(precision: 3))")
- handler(Event(kind: attach ? .attach : .detach, id: id, name: name))
- }
- }
-
- deinit {
- iterators.forEach { IOObjectRelease($0) }
- if let port { IONotificationPortDestroy(port) }
- }
-}
-
-/// Which controllers the launcher shows while the hardware and GameController disagree: a "Connecting" placeholder from a plug-in
-/// until GameController reports it (or ten seconds pass), and a controller hidden from its unplug until GameController lets go of it.
-/// Names are compared loosely (the HID product is often a part of GameController's vendor name).
-struct HIDPresence {
- struct Pending: Equatable { var id: UInt64; var name: String; var since: Date }
- private(set) var pending: [Pending] = []
- private(set) var detached: [String] = []
- static let timeout: TimeInterval = 10
-
- static func matches(_ a: String, _ b: String) -> Bool {
- let x = a.lowercased(), y = b.lowercased()
- return !x.isEmpty && !y.isEmpty && (x.contains(y) || y.contains(x))
- }
-
- mutating func attached(id: UInt64, name: String, at now: Date = Date()) {
- detached.removeAll { Self.matches($0, name) } // plugged in again: GameController's old object, if any, shows again
- if !pending.contains(where: { $0.id == id }) { pending.append(Pending(id: id, name: name, since: now)) }
- }
-
- mutating func detached(id: UInt64, name: String) {
- let hadPlaceholder = pending.contains { $0.id == id }
- pending.removeAll { $0.id == id }
- if hadPlaceholder { return } // GameController never knew it: nothing to hide
- if !name.isEmpty, !detached.contains(where: { Self.matches($0, name) }) { detached.append(name) }
- }
-
- /// GameController reported a controller: its placeholder (the one with a matching name, else the oldest) is replaced.
- /// Without a name match the oldest placeholder goes, only when `orOldest` (a connect notification, not a list read).
- mutating func gcConnected(name: String, orOldest: Bool = true) {
- if let i = pending.firstIndex(where: { Self.matches($0.name, name) }) ?? (orOldest ? pending.indices.first : nil) { pending.remove(at: i) }
- }
-
- /// GameController let go of a controller: it no longer needs hiding.
- mutating func gcDisconnected(name: String) { detached.removeAll { Self.matches($0, name) } }
-
- mutating func expire(now: Date = Date()) { pending.removeAll { now.timeIntervalSince($0.since) >= Self.timeout } }
-
- func isHidden(_ gcName: String) -> Bool { detached.contains { Self.matches($0, gcName) } }
-}
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index c9d1281a..bf3b2107 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -57,7 +57,8 @@ struct ContentView: View {
init(model: BuildModel? = nil, library: GameLibrary? = nil, initialPage: LauncherPage = .library,
activeBuildID: UUID? = nil, performStartupChecks: Bool = true, search: String? = nil, olderTools: Set<UUID> = [],
manageOpen: Bool = false, padRing: Bool = false, onRunSetup: (() -> Void)? = nil,
- enterConsole: (() -> Void)? = nil, controllerDriver: AnyConsoleDriver? = nil, controls sharedControls: ControlLayout? = nil) {
+ enterConsole: (() -> Void)? = nil, controllerDriver: AnyConsoleDriver? = nil, controls sharedControls: ControlLayout? = nil, qaPrompt: Bool = false) {
+ _consolePrompt = State(initialValue: qaPrompt) // visual QA: the connect prompt open at launch
self.onRunSetup = onRunSetup
let layout = sharedControls ?? ControlLayout()
_controls = StateObject(wrappedValue: layout)
diff --git a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
index 1d95bea6..1986b9a3 100644
--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
@@ -72,7 +72,7 @@ struct ConsolePadSnapshot: Equatable {
/// When a controller was first seen without a battery object. GameController can hand one over a moment after the connect, so
/// "wired" is only decided after the object has been missing for several reads.
private var noBatterySince: [String: Date] = [:]
- static let wiredAfter: TimeInterval = 6
+ static let wiredAfter: TimeInterval = 4.5 // the 5 second read is the one that decides
private var cancellables = Set<AnyCancellable>()
private var observers: [NSObjectProtocol] = []
private var refreshQueued = false
@@ -87,7 +87,7 @@ 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, watchHardware: Bool = true, now: @escaping () -> Date = Date.init) {
+ artwork: ((LibraryGame, String) -> NSImage?)? = nil, startingTimeout: TimeInterval = 20, observeSystem: Bool = true, now: @escaping () -> Date = Date.init) {
self.now = now
self.library = library; self.controls = controls; self.repo = repo; self.lang = lang; self.labels = labels
self.startingTimeout = startingTimeout
@@ -102,7 +102,6 @@ struct ConsolePadSnapshot: Equatable {
refreshControllers(announce: false)
if observeSystem { scheduleBatteryRereads() } // a controller there at launch may not have its battery yet either
guard observeSystem else { return }
- if watchHardware { hidWatcher = HIDControllerWatcher { [weak self] event in MainActor.assumeIsolated { self?.hidEvent(event) } } }
let center = NotificationCenter.default
observers = [
center.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { [weak self] note in
@@ -430,10 +429,7 @@ struct ConsolePadSnapshot: Equatable {
static func memoryKey(_ pad: ConsolePadSnapshot) -> String { pad.name + "|" + (pad.category ?? "") }
private static let hidLog = Logger(subsystem: "NX2Apple", category: "console.controllers")
- private var presence = HIDPresence()
- private var hidWatcher: HIDControllerWatcher?
private var remembered: [String: Int] = [:]
- private var pollTask: Task<Void, Never>?
private func stamp() -> String { String(format: "%.3f", Date().timeIntervalSince1970) }
@@ -460,8 +456,6 @@ struct ConsolePadSnapshot: Equatable {
/// The part of a connect or disconnect that does not need a GCController, so tests can drive it.
func controllerListChanged(connectedName: String?, disconnectedName: String?, including: GCController? = nil, excluding: GCController? = nil) {
- if let connectedName { presence.gcConnected(name: connectedName) }
- if let disconnectedName { presence.gcDisconnected(name: disconnectedName) }
refreshControllers(announce: false, including: including, excluding: excluding)
}
@@ -478,44 +472,14 @@ struct ConsolePadSnapshot: Equatable {
/// Right after a connect GameController may still report 0 or an unknown battery (a Bluetooth reconnect): read it again soon.
private func scheduleBatteryRereads() {
Task { [weak self] in
- for seconds in [2.0, 3.0, 3.0] { // reads at 2, 5 and 8 seconds, then the 20 second tick
+ for seconds in [2.0, 3.0] { // reads at 2 and 5 seconds after a connect, then the 20 second tick
try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
self?.refreshControllers(announce: false)
}
}
}
- // MARK: Hardware (IOKit registry) events
-
- func hidEvent(_ event: HIDControllerWatcher.Event) {
- Self.hidLog.debug("hid \(event.kind == .attach ? "attach" : "detach", privacy: .public) \(event.name, privacy: .public) at \(self.stamp(), privacy: .public)")
- switch event.kind {
- case .attach:
- // GameController already lists it (a controller there at launch): no placeholder
- if state.controllers.contains(where: { !$0.connecting && HIDPresence.matches($0.name, event.name) }) {
- Self.hidLog.debug("hid attach \(event.name, privacy: .public): already listed by GameController")
- } else { presence.attached(id: event.id, name: event.name); watchForGameController() }
- case .detach: presence.detached(id: event.id, name: event.name)
- }
- refreshControllers(announce: false)
- }
-
- /// GameController can lag the hardware by seconds, and has been seen missing a re-plug: after a plug-in, look at its list every half
- /// second for ten seconds, and drop the placeholder when the time is up.
- private func watchForGameController() {
- pollTask?.cancel()
- pollTask = Task { [weak self] in
- for _ in 0..<21 {
- try? await Task.sleep(nanoseconds: 500_000_000)
- guard !Task.isCancelled, let self else { return }
- self.refreshControllers(announce: false)
- if self.presence.pending.isEmpty { return }
- }
- }
- }
-
func refreshControllers(announce: Bool, including: GCController? = nil, excluding: GCController? = nil) {
- let before = Set(state.controllers.filter { !$0.connecting }.map(\.id))
var snapshots = pads()
if devicePads {
devices = [:]
@@ -543,8 +507,6 @@ struct ConsolePadSnapshot: Equatable {
if now().timeIntervalSince(since) < Self.wiredAfter { snapshots[i].hasBattery = true } // too early to call it wired: unknown for now
}
noBatterySince = noBatterySince.filter { key, _ in snapshots.contains { $0.id == key } }
- presence.expire()
- snapshots = snapshots.filter { !presence.isHidden($0.name) } // unplugged according to the hardware, GameController not told yet
let live = Set(snapshots.map(\.id))
overrides = overrides.filter { live.contains($0.key) }
snapshots = snapshots.map { snap in
@@ -557,12 +519,9 @@ 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 } }
- // a controller GameController reports that the hardware watch has a placeholder for replaces it (also without a notification)
- for pad in assigned where !before.contains(pad.id) { presence.gcConnected(name: pad.name, orOldest: false) }
- var list = assigned.map(\.controller)
- for p in presence.pending { list.append(ConsoleController(id: "hid." + String(p.id), name: p.name.isEmpty ? t("console.connecting") : p.name, player: nil, kind: .gamepad, canIdentify: false, connecting: true)) }
+ 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)\($0.connecting ? " (connecting)" : "")" }.joined(separator: ", "), privacy: .public)")
+ Self.hidLog.debug("publish \(list.count) controllers at \(self.stamp(), privacy: .public): \(list.map { "\($0.name)" }.joined(separator: ", "), privacy: .public)")
state.controllers = list
}
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 094480a5..9b7911e3 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -170,7 +170,6 @@ enum L10n {
"console.assignCancelled": ("\u{5df2}\u{53d6}\u{6d88}\u{5206}\u{914d}\u{73a9}\u{5bb6}\u{3002}", "Player assignment cancelled."),
"console.assignTimeout": ("\u{6ca1}\u{6709}\u{6309}\u{952e}\u{3002}\u{8bf7}\u{91cd}\u{65b0}\u{9009}\u{62e9}\u{73a9}\u{5bb6}\u{518d}\u{8bd5}\u{4e00}\u{6b21}\u{3002}", "No button was pressed. Choose a player to try again."),
"console.wired": ("\u{6709}\u{7ebf}\u{8fde}\u{63a5}", "Wired"),
- "console.connecting": ("\u{6b63}\u{5728}\u{8fde}\u{63a5}\u{2026}", "Connecting\u{2026}"),
"console.mergeEach": ("\u{6bcf}\u{4e2a}\u{624b}\u{67c4}\u{5bf9}\u{5e94}\u{4e00}\u{4f4d}\u{73a9}\u{5bb6}", "Each controller is its own player"),
"console.mockPress": ("\u{6a21}\u{62df}\u{6309}\u{4e0b}\u{6309}\u{94ae}", "Simulate a button press"),
"console.connectedUnassigned": ("%@ \u{5df2}\u{8fde}\u{63a5}", "%@ connected"),
diff --git a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
index d0601d7d..b1d62082 100644
--- a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
@@ -260,7 +260,7 @@ import SwiftUI
var current = [ConsolePadSnapshot(id: "first", name: "First", category: "DualShock 4", playerIndex: nil)]
let library = GameLibrary(file: temporary.appendingPathComponent("library.json"))
let driver = LiveConsoleDriver(library: library, controls: ControlLayout(defaults: UserDefaults(suiteName: "ConsoleLiveTests-" + UUID().uuidString)!),
- repo: { "" }, lang: { .en }, labels: { $0 }, pads: { current }, artwork: { _, _ in nil }, observeSystem: true, watchHardware: false)
+ repo: { "" }, lang: { .en }, labels: { $0 }, pads: { current }, artwork: { _, _ in nil }, observeSystem: true)
XCTAssertEqual(driver.state.controllers.map(\.id), ["first"])
XCTAssertEqual(driver.state.controllers.map(\.player), [1])
current.append(ConsolePadSnapshot(id: "second", name: "Second", category: "Wired", playerIndex: nil))
@@ -376,46 +376,8 @@ import SwiftUI
repo: { "" }, lang: { .en }, labels: { $0 }, pads: pads, artwork: { _, _ in nil }, observeSystem: false)
}
- func testPlaceholderFromThePlugInUntilGameControllerReports() {
- var list: [ConsolePadSnapshot] = []
- let driver = liveDriver { list }
- driver.hidEvent(.init(kind: .attach, id: 7, name: "Wireless Controller"))
- XCTAssertEqual(driver.state.controllers.map(\.connecting), [true], "a Connecting chip from the hardware attach")
- XCTAssertEqual(driver.state.controllers.first?.name, "Wireless Controller")
- list = [ConsolePadSnapshot(id: "gc1", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil)]
- driver.controllerListChanged(connectedName: "DUALSHOCK 4 Wireless Controller", disconnectedName: nil)
- XCTAssertEqual(driver.state.controllers.map(\.connecting), [false], "replaced by the real controller")
- XCTAssertEqual(driver.state.controllers.map(\.player), [1])
- }
- func testPlaceholderIsRemovedOnUnplugAndGameControllerLateDisconnectIsHandled() {
- var list: [ConsolePadSnapshot] = []
- let driver = liveDriver { list }
- driver.hidEvent(.init(kind: .attach, id: 1, name: "Pad"))
- driver.hidEvent(.init(kind: .detach, id: 1, name: "Pad"))
- XCTAssertTrue(driver.state.controllers.isEmpty, "unplugged before GameController ever reported it")
- // a real one that the hardware drops first: hidden at once, GameController lets go later
- list = [ConsolePadSnapshot(id: "gc1", name: "Pad", category: nil, playerIndex: nil)]
- driver.controllerListChanged(connectedName: "Pad", disconnectedName: nil)
- XCTAssertEqual(driver.state.controllers.count, 1)
- driver.hidEvent(.init(kind: .detach, id: 2, name: "Pad"))
- XCTAssertTrue(driver.state.controllers.isEmpty, "removed on the hardware detach, before GameController's disconnect")
- list = []
- driver.controllerListChanged(connectedName: nil, disconnectedName: "Pad")
- XCTAssertTrue(driver.state.controllers.isEmpty)
- }
-
- func testPresenceExpiresAfterTenSecondsAndMatchesNamesLoosely() {
- var presence = HIDPresence()
- let start = Date()
- presence.attached(id: 1, name: "Wireless Controller", at: start)
- presence.expire(now: start.addingTimeInterval(9))
- XCTAssertEqual(presence.pending.count, 1)
- presence.expire(now: start.addingTimeInterval(10.5))
- XCTAssertTrue(presence.pending.isEmpty, "GameController never reported it")
- XCTAssertTrue(HIDPresence.matches("DUALSHOCK 4 Wireless Controller", "Wireless Controller"))
- XCTAssertFalse(HIDPresence.matches("Xbox Wireless Controller", ""))
- }
+
/// Connect, disconnect, connect the same controller again as a new instance: it is listed again with its player, and the battery
/// comes from the new instance (unknown first, then the real level).
@@ -442,26 +404,7 @@ import SwiftUI
XCTAssertEqual(driver.state.controllers.first { $0.id == "second" }?.batteryPercent, 64, "the next read picks up the real level")
}
- func testNoPlaceholderForAControllerGameControllerAlreadyListsAtLaunch() {
- let list = [ConsolePadSnapshot(id: "gc", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil)]
- let driver = liveDriver { list }
- driver.refreshControllers(announce: false)
- driver.hidEvent(.init(kind: .attach, id: 1, name: "DUALSHOCK 4 Wireless Controller"))
- XCTAssertEqual(driver.state.controllers.map(\.connecting), [false], "its hardware attach at launch adds nothing")
- driver.hidEvent(.init(kind: .attach, id: 2, name: "GamePad-1"))
- XCTAssertEqual(driver.state.controllers.map(\.connecting), [false, true], "a device GameController has not reported shows as connecting")
- }
- func testAnotherDevicesPlaceholderSurvivesAControllerAppearing() {
- var list: [ConsolePadSnapshot] = []
- let driver = liveDriver { list }
- driver.hidEvent(.init(kind: .attach, id: 1, name: "GamePad-1"))
- driver.hidEvent(.init(kind: .attach, id: 2, name: "DUALSHOCK 4 Wireless Controller"))
- list = [ConsolePadSnapshot(id: "gc", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil)]
- driver.controllerListChanged(connectedName: "DUALSHOCK 4 Wireless Controller", disconnectedName: nil)
- XCTAssertEqual(driver.state.controllers.map(\.name), ["DUALSHOCK 4 Wireless Controller", "GamePad-1"])
- XCTAssertEqual(driver.state.controllers.map(\.connecting), [false, true], "the unreported device keeps its placeholder")
- }
/// GameController can give a controller its battery object a moment after the connect: not wired at first, then 65 percent.
func testBatteryObjectArrivingLateIsNotWired() {
@@ -493,4 +436,37 @@ import SwiftUI
driver.refreshControllers(announce: false)
XCTAssertEqual(driver.state.controllers.first?.wired, true, "missing for more than six seconds: powered by its cable")
}
+
+ /// The Xbox and DualShock 4 together: both listed from the start with their own player, each with its own battery. One is unplugged
+ /// and plugged in again (a new instance) while the other stays, and neither loses its battery or player.
+ func testTwoControllersTogetherAndOneReconnects() {
+ var clock = Date()
+ var list = [ConsolePadSnapshot(id: "ds4", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil, battery: nil, hasBattery: false),
+ ConsolePadSnapshot(id: "xbox", name: "Xbox Wireless Controller", category: "Xbox One", playerIndex: nil, battery: 0.8)]
+ 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, now: { clock })
+ XCTAssertEqual(driver.state.controllers.map(\.id), ["ds4", "xbox"], "both appear together")
+ XCTAssertEqual(driver.state.controllers.map(\.player), [1, 2])
+ XCTAssertEqual(driver.state.controllers.map(\.wired), [false, false], "no battery object at 0 s is not wired yet")
+ clock = clock.addingTimeInterval(2)
+ list[0].hasBattery = true; list[0].battery = 0.65 // the DualShock's battery arrives on the 2 second read
+ driver.refreshControllers(announce: false)
+ XCTAssertEqual(driver.state.controllers.map(\.batteryPercent), [65, 80])
+ // the DualShock goes away and comes back as a new instance, the Xbox stays
+ let xbox = list[1]
+ list = [xbox]
+ driver.controllerListChanged(connectedName: nil, disconnectedName: "DUALSHOCK 4 Wireless Controller")
+ XCTAssertEqual(driver.state.controllers.map(\.id), ["xbox"])
+ XCTAssertEqual(driver.state.controllers.first?.batteryPercent, 80, "the other controller is untouched")
+ list = [ConsolePadSnapshot(id: "ds4-again", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil, battery: nil), xbox]
+ driver.controllerListChanged(connectedName: "DUALSHOCK 4 Wireless Controller", disconnectedName: nil)
+ XCTAssertEqual(Set(driver.state.controllers.map(\.id)), ["ds4-again", "xbox"], "both listed again")
+ XCTAssertEqual(driver.state.controllers.first { $0.id == "ds4-again" }?.player, 1, "its old player is back")
+ XCTAssertNil(driver.state.controllers.first { $0.id == "ds4-again" }?.battery, "nothing carried over from the old instance")
+ XCTAssertEqual(driver.state.controllers.first { $0.id == "xbox" }?.batteryPercent, 80)
+ list[0].battery = 0.64
+ driver.refreshControllers(announce: false)
+ XCTAssertEqual(driver.state.controllers.first { $0.id == "ds4-again" }?.batteryPercent, 64)
+ }
}
diff --git a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
index 3a7943ab..4c2b8293 100644
--- a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
@@ -202,6 +202,7 @@ final class ConsolePadTests: XCTestCase {
for width: CGFloat in [1280, 900] {
try shot(AnyView(ContentView(model: BuildModel(), library: library, performStartupChecks: false, enterConsole: {})), "desktop-bar-\(Int(width))", width, 720)
}
+ try shot(AnyView(ContentView(model: BuildModel(), library: library, performStartupChecks: false, enterConsole: {}, qaPrompt: true)), "prompt-windowed", 1000, 720)
for lang in [Lang.en, .zh] {
try shot(AnyView(ConsoleConnectionPrompt(lang: lang, enterConsole: {}, dismissPrompt: {}).environmentObject(PadFocus()).preferredColorScheme(.dark)), "prompt-\(lang.rawValue)", 900, 500)
}