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: wired controllers, instant plug-in detection, reconnects
v0lumehi3eb0a456c1a7
diff --git a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swiftindex 62a09fcb..4a0f7913 100644--- a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift+++ b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift@@ -75,6 +75,7 @@ struct BatteryIcon: View {RoundedRectangle(cornerRadius: g.innerRadius).fill(Self.isLow(level) && !charging ? Color.red : (charging ? LauncherPalette.ready : Color.white.opacity(0.9))).frame(width: g.fill.width, height: g.fill.height).offset(x: g.fill.minX, y: g.fill.minY)+ .animation(.easeInOut(duration: 0.6), value: g.fill.width) // a charging level grows smoothly between reads}if charging {Image(systemName: "bolt.fill").font(.system(size: height * 0.62, weight: .bold)).foregroundStyle(.black.opacity(0.75))@@ -104,7 +105,10 @@ struct ConsoleBattery: View {} else if controller.charging {HStack(spacing: 5) { BatteryIcon(level: nil, charging: true, height: compact ? 10 : 13) }.accessibilityElement(children: .ignore).accessibilityLabel(L10n.string("console.charging", lang))- } else if controller.kind != .keyboard { // a level not reported (yet): the outline alone, no percentage+ } else if controller.wired { // no battery object: the cable is its power+ Image(systemName: "powerplug").font(.system(size: compact ? 11 : 15, weight: .medium)).foregroundStyle(.white.opacity(0.7))+ .accessibilityElement(children: .ignore).accessibilityLabel(L10n.string("console.wired", lang)).help(L10n.string("console.wired", lang))+ } else if controller.kind != .keyboard { // a battery that reports no level (yet): the outline alone, no percentageBatteryIcon(level: nil, height: compact ? 10 : 13).accessibilityElement(children: .ignore).accessibilityLabel(L10n.string("console.batteryUnknown", lang))}@@ -133,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)- 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)+ 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) }}}}@@ -259,19 +263,22 @@ 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))- Text(t(controller.kind.labelKey) + " · " + playerLabel(controller)).font(.manrope(compact ? 14 : 17)).foregroundStyle(.secondary)- if controller.battery == nil { Text(t("console.batteryUnknown")).font(.manrope(13)).foregroundStyle(.secondary) }+ 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) } }+ 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) }}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).- HStack(spacing: 10) {+ if !controller.connecting { 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/ConsoleState.swift b/frontend/Sources/NSPortBuilder/ConsoleState.swiftindex f4242953..dbe291b2 100644--- a/frontend/Sources/NSPortBuilder/ConsoleState.swift+++ b/frontend/Sources/NSPortBuilder/ConsoleState.swift@@ -70,6 +70,10 @@ struct ConsoleController: Identifiable, Equatable {var charging = false/// Whether Identify can do anything on this controller (a player light, a light bar or a rumble). Hidden when it cannot.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 = falsevar batteryPercent: Int? { battery.map { Int((min(max($0.isFinite ? $0 : 0, 0), 1) * 100).rounded()) } }}diff --git a/frontend/Sources/NSPortBuilder/Gamepad.swift b/frontend/Sources/NSPortBuilder/Gamepad.swiftindex 8bb02bd3..34fff32f 100644--- a/frontend/Sources/NSPortBuilder/Gamepad.swift+++ b/frontend/Sources/NSPortBuilder/Gamepad.swift@@ -37,6 +37,7 @@ final class LauncherGamepad: ObservableObject {/// One press, one action, per controller: a button held on one controller never hides the same button on another.struct Edges {private var held: Set<String> = []+ mutating func reset(controller: String) { held = held.filter { !$0.hasPrefix(controller + "/") } }/// What changed for `controller` given the state of its buttons: pressed and released actions.mutating func changes(controller: String, state: [(String, Bool, Action)]) -> (pressed: [Action], released: [Action]) {var pressed: [Action] = [], released: [Action] = []@@ -59,6 +60,10 @@ final class LauncherGamepad: ObservableObject {observers = [NSNotification.Name.GCControllerDidConnect, .GCControllerDidDisconnect].map {center.addObserver(forName: $0, object: nil, queue: .main) { [weak self] note inif let pad = note.object as? GCController {+ if note.name == .GCControllerDidDisconnect { // nothing of the old instance is kept+ pad.physicalInputProfile.valueDidChangeHandler = nil+ self?.edges.reset(controller: String(UInt(bitPattern: ObjectIdentifier(pad).hashValue), radix: 16))+ }Self.log.debug("\(note.name.rawValue, privacy: .public): vendor \(pad.vendorName ?? "?", privacy: .public), category \(pad.productCategory, privacy: .public), extendedGamepad \(pad.extendedGamepad != nil), attached \(pad.isAttachedToDevice)")}self?.attach()diff --git a/frontend/Sources/NSPortBuilder/HIDControllerWatcher.swift b/frontend/Sources/NSPortBuilder/HIDControllerWatcher.swiftnew file mode 100644index 00000000..9039ac89--- /dev/null+++ b/frontend/Sources/NSPortBuilder/HIDControllerWatcher.swift@@ -0,0 +1,110 @@+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/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swiftindex 4163e38b..7cf37bb5 100644--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift@@ -25,6 +25,8 @@ struct ConsolePadSnapshot: Equatable {var battery: Double?var charging = falsevar canIdentify = true+ /// Whether GameController gives the controller a battery object at all. Without one it can only be powered by its cable.+ var hasBattery = true/// The level to show, or nil when the controller has not really reported one. GameController gives 0 with an unknown state for a/// DualShock 4 over Bluetooth and before the first report, and some pads over USB report no battery or an unknown one: those are@@ -46,7 +48,7 @@ struct ConsolePadSnapshot: Equatable {else if family == .nintendo { kind = .fullSize }else if family == .xbox { kind = .xbox }else { kind = .gamepad }- return ConsoleController(id: id, name: name, player: playerIndex, kind: kind, battery: battery, charging: charging, canIdentify: canIdentify)+ return ConsoleController(id: id, name: name, player: playerIndex, kind: kind, battery: battery, charging: charging, canIdentify: canIdentify, wired: !hasBattery && kind != .keyboard)}}@@ -80,7 +82,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) {+ artwork: ((LibraryGame, String) -> NSImage?)? = nil, startingTimeout: TimeInterval = 20, observeSystem: Bool = true, watchHardware: Bool = true) {self.library = library; self.controls = controls; self.repo = repo; self.lang = lang; self.labels = labelsself.startingTimeout = startingTimeoutself.pads = pads ?? { [] }@@ -93,6 +95,7 @@ struct ConsolePadSnapshot: Equatable {refresh()refreshControllers(announce: false)guard observeSystem else { return }+ if watchHardware { hidWatcher = HIDControllerWatcher { [weak self] event in MainActor.assumeIsolated { self?.hidEvent(event) } } }let center = NotificationCenter.defaultobservers = [center.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { [weak self] note in@@ -405,41 +408,113 @@ struct ConsolePadSnapshot: Equatable {func disconnect(controllerID: String) { showToast(t("console.disconnectHint")) }/// Controllers that have no player take the next free one, in the order they are listed, as a console does. A fifth has none.- static func autoAssigned(_ pads: [ConsolePadSnapshot]) -> [ConsolePadSnapshot] {+ static func autoAssigned(_ pads: [ConsolePadSnapshot], remembered: [String: Int] = [:]) -> [ConsolePadSnapshot] {var used = Set(pads.compactMap(\.playerIndex))return pads.map { pad in- guard pad.playerIndex == nil, let free = (1...4).first(where: { !used.contains($0) }) else { return pad }+ guard pad.playerIndex == nil else { return pad }+ // the same physical controller coming back takes its old player when that is free, else the next free one+ let free = remembered[Self.memoryKey(pad)].flatMap { used.contains($0) ? nil : $0 } ?? (1...4).first(where: { !used.contains($0) })+ guard let free else { return pad }used.insert(free)var assigned = pad; assigned.playerIndex = freereturn assigned}}+ static func memoryKey(_ pad: ConsolePadSnapshot) -> String { pad.name + "|" + (pad.category ?? "") }- /// A controller connected or disconnected: the list is rebuilt and published at once (not at the next battery tick), then the toast.+ 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) }++ /// A controller connected or disconnected: the list is rebuilt and published at once (no debounce, no polling), then the toast./// The notification's own controller is added when GameController's list does not have it yet, and left out when it still has it- /// on a disconnect, so a wired controller shows up the moment it is plugged in.+ /// on a disconnect, so a wired controller shows up the moment it is plugged in. A disconnect tears down everything kept for that+ /// instance: its input handler, its haptics engine and any Identify in progress.func padsChanged(connected: Bool, note: Notification) {let pad = note.object as? GCControllerif let pad {- Self.log.debug("\(connected ? "connect" : "disconnect"): vendor \(pad.vendorName ?? "?", privacy: .public), category \(pad.productCategory, privacy: .public), extendedGamepad \(pad.extendedGamepad != nil)")+ 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) }}- refreshControllers(announce: false, including: connected ? pad : nil, excluding: connected ? nil : pad)- guard let pad else { return }- let name = pad.vendorName ?? pad.productCategory+ 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 = String(UInt(bitPattern: ObjectIdentifier(pad).hashValue), radix: 16)+ let id = pad.map { String(UInt(bitPattern: ObjectIdentifier($0).hashValue), radix: 16) } ?? ""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()+ }++ /// 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)+ }++ private func tearDown(_ pad: GCController) {+ let id = String(UInt(bitPattern: ObjectIdentifier(pad).hashValue), radix: 16)+ pad.physicalInputProfile.valueDidChangeHandler = nil+ identifyEngines.removeValue(forKey: id)?.stop(completionHandler: nil)+ if state.identifyingControllerID == id { identifyTask?.cancel(); state.identifyingControllerID = nil }+ devices[id] = nil+ overrides[id] = nil+ Self.hidLog.debug("torn down \(id, privacy: .public)")+ }++ /// 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, 5.0] {+ 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 = [:]var all = GCController.controllers().filter { $0 !== excluding }if let including, !all.contains(where: { $0 === including }) { all.append(including) }- snapshots = all.compactMap { c in // every controller, whatever its vendor or profile+ snapshots = all.compactMap { c in // every controller, whatever its vendor or profile, read fresh from its own instancelet id = String(UInt(bitPattern: ObjectIdentifier(c).hashValue), radix: 16)devices[id] = clet reading = c.battery.map { b -> (level: Double?, charging: Bool) in@@ -449,9 +524,11 @@ struct ConsolePadSnapshot: Equatable {let index = c.playerIndex.rawValuereturn ConsolePadSnapshot(id: id, name: c.vendorName ?? c.productCategory, category: c.productCategory,playerIndex: (0...3).contains(index) ? index + 1 : nil, battery: reading?.level,- charging: reading?.charging ?? false, canIdentify: !Self.identifyActions(c).isEmpty)+ charging: reading?.charging ?? false, canIdentify: !Self.identifyActions(c).isEmpty, hasBattery: c.battery != nil)}}+ presence.expire()+ snapshots = snapshots.filter { !presence.isHidden($0.name) } // unplugged according to the hardware, GameController not told yetlet live = Set(snapshots.map(\.id))overrides = overrides.filter { live.contains($0.key) }snapshots = snapshots.map { snap in@@ -459,11 +536,19 @@ struct ConsolePadSnapshot: Equatable {var s = snap; s.playerIndex = chosen == 0 ? nil : chosenreturn s}- let assigned = Self.autoAssigned(snapshots)- for (before, after) in zip(snapshots, assigned) where before.playerIndex != after.playerIndex {- devices[after.id]?.playerIndex = GCControllerPlayerIndex(rawValue: (after.playerIndex ?? 1) - 1) ?? .indexUnset+ let assigned = Self.autoAssigned(snapshots, remembered: remembered)+ for (old, new) in zip(snapshots, assigned) where old.playerIndex != new.playerIndex {+ 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)) }+ 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)")+ state.controllers = list}- state.controllers = assigned.map(\.controller)}// MARK: Navigationdiff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex cdcb9802..094480a5 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -169,6 +169,8 @@ enum L10n {"console.assignedTo": ("%@ \u{662f}\u{73a9}\u{5bb6} %d", "%@ is player %d"),"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/Sources/NSPortBuilder/MockConsoleDriver.swift b/frontend/Sources/NSPortBuilder/MockConsoleDriver.swiftindex 9a9514fe..7d14b235 100644--- a/frontend/Sources/NSPortBuilder/MockConsoleDriver.swift+++ b/frontend/Sources/NSPortBuilder/MockConsoleDriver.swift@@ -43,7 +43,7 @@ import SwiftUIsnapshot.isPreview = trueif scenario == .controllers {snapshot.controllers += [.init(id: "pad.2", name: t("console.demoController2"), player: 2),- .init(id: "pad.3", name: t("console.demoController3"), player: nil)]+ .init(id: "pad.3", name: t("console.demoController3"), player: nil, wired: true)]snapshot.openControllers(); snapshot.assigningPlayer = 3}if scenario == .controllersMixed {diff --git a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swiftindex 18ab576c..1410a687 100644--- a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift+++ b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift@@ -260,7 +260,7 @@ import SwiftUIvar 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)+ repo: { "" }, lang: { .en }, labels: { $0 }, pads: { current }, artwork: { _, _ in nil }, observeSystem: true, watchHardware: false)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))@@ -356,4 +356,110 @@ import SwiftUIXCTAssertEqual(driver.state.toast?.message, "No button was pressed. Choose a player to try again.")XCTAssertEqual(driver.state.controllers.map(\.player), [1, 2])}++ func testNoBatteryObjectMeansWired() {+ var pad = ConsolePadSnapshot(id: "w", name: "Wired pad", category: "Generic", playerIndex: 1, battery: nil, hasBattery: false)+ XCTAssertTrue(pad.controller.wired, "no battery object: powered by its cable")+ XCTAssertNil(pad.controller.battery)+ pad.hasBattery = true+ XCTAssertFalse(pad.controller.wired, "a battery object with an unknown state is the neutral outline, not a cable")+ var keyboard = ConsolePadSnapshot(id: "k", name: "Keyboard", category: nil, playerIndex: 1, hasBattery: false)+ keyboard.category = "keyboard"+ XCTAssertNotNil(L10n.table["console.wired"])+ }++ // MARK: Hardware placeholders and reconnects++ private func liveDriver(pads: @escaping () -> [ConsolePadSnapshot]) -> LiveConsoleDriver {+ LiveConsoleDriver(library: GameLibrary(file: temporary.appendingPathComponent("library.json")),+ controls: ControlLayout(defaults: UserDefaults(suiteName: "ConsoleLiveTests-" + UUID().uuidString)!),+ 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).+ func testReconnectShowsTheControllerAgainWithItsPlayerAndFreshBattery() {+ var list = [ConsolePadSnapshot(id: "first", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil, battery: 0.65),+ ConsolePadSnapshot(id: "other", name: "Xbox Wireless Controller", category: "Xbox One", playerIndex: nil, battery: 0.5)]+ let driver = liveDriver { list }+ driver.refreshControllers(announce: false)+ XCTAssertEqual(driver.state.controllers.map(\.player), [1, 2])+ XCTAssertEqual(driver.state.controllers.first?.batteryPercent, 65)+ list.removeFirst() // unplugged+ driver.controllerListChanged(connectedName: nil, disconnectedName: "DUALSHOCK 4 Wireless Controller")+ XCTAssertEqual(driver.state.controllers.map(\.name), ["Xbox Wireless Controller"])+ // plugged in again: a new instance, a new id, nothing known about its battery yet+ list = [ConsolePadSnapshot(id: "second", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil, battery: nil)]+ + [ConsolePadSnapshot(id: "other", name: "Xbox Wireless Controller", category: "Xbox One", playerIndex: nil, battery: 0.5)]+ driver.controllerListChanged(connectedName: "DUALSHOCK 4 Wireless Controller", disconnectedName: nil)+ XCTAssertEqual(driver.state.controllers.count, 2, "it appears again")+ let back = driver.state.controllers.first { $0.id == "second" }+ XCTAssertEqual(back?.player, 1, "its old player comes back")+ XCTAssertNil(back?.battery, "unknown at first: the outline")+ list[0].battery = 0.64+ driver.refreshControllers(announce: false)+ 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")+ }}diff --git a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swiftindex ed3473a0..3a7943ab 100644--- a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift+++ b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift@@ -95,7 +95,7 @@ final class ConsolePadTests: XCTestCase {let repo = BuildModel.findRepo()for (sizeName, width, height) in [("1920", CGFloat(1920), CGFloat(1080)), ("compact", 390, 844)] {for (name, scenario, family) in [("home", MockConsoleDriver.Scenario.full, ConsoleGlyphs.Family.xbox), ("home-dualsense", .full, .playStation), ("home-keyboard", .full, .keyboard),- ("controllers", .controllersMixed, .xbox), ("home-4pads", .controllersMixed, .xbox), ("options", .full, .xbox), ("empty", .empty, .xbox), ("starting", .starting, .xbox)] {+ ("controllers", .controllersMixed, .xbox), ("home-4pads", .controllersMixed, .xbox), ("controllers-wired", .controllers, .xbox), ("options", .full, .xbox), ("empty", .empty, .xbox), ("starting", .starting, .xbox)] {let driver = MockConsoleDriver(scenario: scenario, lang: .en, animated: false, artworkRepo: repo.isEmpty ? nil : repo)if name == "options" { driver.openOptions("demo.0") }if name == "home-4pads" { driver.back() }