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: no battery shown unless it is known, battery observed with KVO

v0lumehi6d4fbcdfa25a
diff --git a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
index f5c07db9..4e582463 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
@@ -88,6 +88,8 @@ struct BatteryIcon: View {
}
}
+/// The battery as far as it is known: a level with its percentage, a bolt while charging. When the controller reports nothing usable
+/// (no battery object yet, or 0 with an unknown state) nothing is drawn at all.
struct ConsoleBattery: View {
let controller: ConsoleController
let lang: Lang
@@ -105,12 +107,6 @@ 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.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 percentage
- BatteryIcon(level: nil, height: compact ? 10 : 13)
- .accessibilityElement(children: .ignore).accessibilityLabel(L10n.string("console.batteryUnknown", lang))
}
}
}
@@ -264,9 +260,7 @@ struct ConsoleToastView: View {
VStack(alignment: .leading, spacing: 6) {
Text(controller.name).font(.manrope(compact ? 18 : 23, .semibold))
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) }
+ ConsoleBattery(controller: controller, lang: lang)
if controller.charging { Text(t("console.charging")).font(.manrope(13)).foregroundStyle(.secondary) }
}
Spacer(minLength: 0)
diff --git a/frontend/Sources/NSPortBuilder/ConsoleState.swift b/frontend/Sources/NSPortBuilder/ConsoleState.swift
index e7004004..f4242953 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleState.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleState.swift
@@ -70,8 +70,6 @@ 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
var batteryPercent: Int? { battery.map { Int((min(max($0.isFinite ? $0 : 0, 0), 1) * 100).rounded()) } }
}
diff --git a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
index 1986b9a3..70d9e0c9 100644
--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
@@ -25,8 +25,6 @@ struct ConsolePadSnapshot: Equatable {
var battery: Double?
var charging = false
var 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
@@ -48,7 +46,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, wired: !hasBattery && kind != .keyboard)
+ return ConsoleController(id: id, name: name, player: playerIndex, kind: kind, battery: battery, charging: charging, canIdentify: canIdentify)
}
}
@@ -68,11 +66,6 @@ struct ConsolePadSnapshot: Equatable {
private let launch: (LibraryGame, [String: String], @escaping (Int32?, Error?) -> Void) -> Void
private let artwork: (LibraryGame, String) -> NSImage?
private let startingTimeout: TimeInterval
- private let now: () -> Date
- /// 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 = 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,8 +80,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, now: @escaping () -> Date = Date.init) {
- self.now = now
+ artwork: ((LibraryGame, String) -> NSImage?)? = nil, startingTimeout: TimeInterval = 20, observeSystem: Bool = true) {
self.library = library; self.controls = controls; self.repo = repo; self.lang = lang; self.labels = labels
self.startingTimeout = startingTimeout
self.pads = pads ?? { [] }
@@ -430,6 +422,16 @@ struct ConsolePadSnapshot: Equatable {
private static let hidLog = Logger(subsystem: "NX2Apple", category: "console.controllers")
private var remembered: [String: Int] = [:]
+ 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.
+ func watchBattery(id: String, object: NSObject) {
+ if batteryWatchers[id]?.object == ObjectIdentifier(object) { return }
+ let watcher = KeyValueWatcher(object: object, keys: ["batteryLevel", "batteryState"]) { [weak self] in
+ DispatchQueue.main.async { MainActor.assumeIsolated { self?.refreshControllers(announce: false) } }
+ }
+ batteryWatchers[id] = (ObjectIdentifier(object), watcher)
+ }
private func stamp() -> String { String(format: "%.3f", Date().timeIntervalSince1970) }
@@ -466,6 +468,7 @@ struct ConsolePadSnapshot: Equatable {
if state.identifyingControllerID == id { identifyTask?.cancel(); state.identifyingControllerID = nil }
devices[id] = nil
overrides[id] = nil
+ batteryWatchers[id] = nil
Self.hidLog.debug("torn down \(id, privacy: .public)")
}
@@ -488,6 +491,7 @@ struct ConsolePadSnapshot: Equatable {
snapshots = all.compactMap { c in // every controller, whatever its vendor or profile, read fresh from its own instance
let id = String(UInt(bitPattern: ObjectIdentifier(c).hashValue), radix: 16)
devices[id] = c
+ if let battery = c.battery { watchBattery(id: id, object: battery) }
let reading = c.battery.map { b -> (level: Double?, charging: Bool) in
let state: PadBatteryState = b.batteryState == .charging ? .charging : b.batteryState == .full ? .full : b.batteryState == .discharging ? .discharging : .unknown
return ConsolePadSnapshot.batteryReading(level: Double(b.batteryLevel), state: state)
@@ -496,18 +500,11 @@ struct ConsolePadSnapshot: Equatable {
Self.hidLog.debug("battery read \(id, privacy: .public) \(c.vendorName ?? c.productCategory, privacy: .public): object \(c.battery != nil), level \(c.battery.map { Double($0.batteryLevel) } ?? -1), state \(c.battery.map { "\($0.batteryState.rawValue)" } ?? "none", privacy: .public)")
return 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, hasBattery: c.battery != nil)
+ charging: reading?.charging ?? false, canIdentify: !Self.identifyActions(c).isEmpty)
}
}
- for i in snapshots.indices {
- let id = snapshots[i].id
- if snapshots[i].hasBattery { noBatterySince[id] = nil; continue }
- let since = noBatterySince[id] ?? now()
- noBatterySince[id] = since
- 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 } }
let live = Set(snapshots.map(\.id))
+ batteryWatchers = batteryWatchers.filter { live.contains($0.key) || !devicePads }
overrides = overrides.filter { live.contains($0.key) }
snapshots = snapshots.map { snap in
guard let chosen = overrides[snap.id] else { return snap }
@@ -544,3 +541,17 @@ struct ConsolePadSnapshot: Equatable {
}
}
}
+
+/// Calls `handler` whenever one of the object's key-value observable properties changes.
+final class KeyValueWatcher: NSObject {
+ private let object: NSObject // held, so it cannot go away while observed
+ private let keys: [String]
+ private let handler: () -> Void
+ init(object: NSObject, keys: [String], handler: @escaping () -> Void) {
+ self.object = object; self.keys = keys; self.handler = handler
+ super.init()
+ for key in keys { object.addObserver(self, forKeyPath: key, options: [], context: nil) }
+ }
+ override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { handler() }
+ deinit { for key in keys { object.removeObserver(self, forKeyPath: key) } }
+}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 9b7911e3..cdcb9802 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -169,7 +169,6 @@ 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.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.swift
index 7d14b235..9a9514fe 100644
--- a/frontend/Sources/NSPortBuilder/MockConsoleDriver.swift
+++ b/frontend/Sources/NSPortBuilder/MockConsoleDriver.swift
@@ -43,7 +43,7 @@ import SwiftUI
snapshot.isPreview = true
if scenario == .controllers {
snapshot.controllers += [.init(id: "pad.2", name: t("console.demoController2"), player: 2),
- .init(id: "pad.3", name: t("console.demoController3"), player: nil, wired: true)]
+ .init(id: "pad.3", name: t("console.demoController3"), player: nil)]
snapshot.openControllers(); snapshot.assigningPlayer = 3
}
if scenario == .controllersMixed {
diff --git a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
index 37e7e1ac..c53a0efe 100644
--- a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
@@ -357,16 +357,6 @@ import SwiftUI
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
@@ -406,51 +396,20 @@ import SwiftUI
- /// GameController can give a controller its battery object a moment after the connect: not wired at first, then 65 percent.
- func testBatteryObjectArrivingLateIsNotWired() {
- var clock = Date()
- var list = [ConsolePadSnapshot(id: "ds4", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil, battery: nil, hasBattery: false)]
- 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.first?.wired, false, "no battery object at the first read is not enough to call it wired")
- XCTAssertNil(driver.state.controllers.first?.battery)
- clock = clock.addingTimeInterval(2)
- list[0].hasBattery = true; list[0].battery = 0.65 // the object is there on the 2 second read
- driver.refreshControllers(announce: false)
- XCTAssertEqual(driver.state.controllers.first?.batteryPercent, 65)
- XCTAssertEqual(driver.state.controllers.first?.wired, false)
- }
- func testStillNoBatteryObjectAfterSeveralSecondsMeansWired() {
- var clock = Date()
- let list = [ConsolePadSnapshot(id: "usb", name: "GamePad-1", category: nil, playerIndex: nil, battery: nil, hasBattery: false)]
- 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.first?.wired, false)
- clock = clock.addingTimeInterval(3)
- driver.refreshControllers(announce: false)
- XCTAssertEqual(driver.state.controllers.first?.wired, false)
- clock = clock.addingTimeInterval(4)
- 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),
+ var list = [ConsolePadSnapshot(id: "ds4", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil, battery: nil),
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 })
+ repo: { "" }, lang: { .en }, labels: { $0 }, pads: { list }, artwork: { _, _ in nil }, observeSystem: false)
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
+ XCTAssertEqual(driver.state.controllers.map(\.batteryPercent), [nil, 80], "nothing usable for the first one yet")
+ 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
@@ -484,4 +443,37 @@ import SwiftUI
XCTAssertTrue(driver.state.controllers.isEmpty)
XCTAssertFalse(FileManager.default.fileExists(atPath: sources.appendingPathComponent("HIDControllerWatcher.swift").path))
}
+
+ func testNothingIsShownWithoutAUsableBatteryReading() {
+ // unknown or 0 with an unknown state, and no battery object: no level, no percentage
+ for reading in [ConsolePadSnapshot.batteryReading(level: 0, state: .unknown), ConsolePadSnapshot.batteryReading(level: 0.4, state: .unknown)] {
+ XCTAssertNil(reading.level)
+ XCTAssertFalse(reading.charging)
+ }
+ let none = ConsolePadSnapshot(id: "a", name: "Pad", category: nil, playerIndex: 1, battery: nil).controller
+ XCTAssertNil(none.batteryPercent, "ConsoleBattery draws nothing for this")
+ XCTAssertFalse(none.charging)
+ let known = ConsolePadSnapshot(id: "b", name: "Pad", category: nil, playerIndex: 1, battery: 0.65).controller
+ XCTAssertEqual(known.batteryPercent, 65)
+ }
+
+ /// A fake battery object whose key-value observable properties change: the list follows without waiting for a read.
+ @objc final class FakeBattery: NSObject {
+ @objc dynamic var batteryLevel: Float = 0
+ @objc dynamic var batteryState: Int = 0
+ }
+
+ func testBatteryChangesArriveThroughKeyValueObserving() async throws {
+ let fake = FakeBattery()
+ let driver = liveDriver { [ConsolePadSnapshot(id: "ds4", name: "DUALSHOCK 4 Wireless Controller", category: "DualShock 4", playerIndex: nil,
+ battery: fake.batteryState == 1 ? Double(fake.batteryLevel) : nil)] }
+ driver.watchBattery(id: "ds4", object: fake)
+ XCTAssertNil(driver.state.controllers.first?.battery)
+ fake.batteryState = 1; fake.batteryLevel = 0.64
+ for _ in 0..<50 where driver.state.controllers.first?.batteryPercent != 64 { try await Task.sleep(nanoseconds: 20_000_000) }
+ XCTAssertEqual(driver.state.controllers.first?.batteryPercent, 64, "published from the KVO change, not a timer")
+ fake.batteryLevel = 0.62
+ 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)
+ }
}