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: Home button, Identify, battery, bottom-bar entry, Settings row

v0lumehi7dbf05e0da72
diff --git a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
index 8bc789f7..4d4cafe6 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
@@ -85,6 +85,9 @@ 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
+ BatteryIcon(level: nil, height: compact ? 10 : 13)
+ .accessibilityElement(children: .ignore).accessibilityLabel(L10n.string("console.batteryUnknown", lang))
}
}
}
@@ -142,57 +145,6 @@ struct ConsoleControllerChips: View {
}
}
-/// The controller strip of the desktop top bar: one row, never clipped. When the bar is short of room it drops the battery and
-/// shows the first controllers followed by a "+N" chip. Everything opens the Controllers sheet.
-struct DesktopControllerChips: View {
- let controllers: [ConsoleController]
- let merged: Bool
- let lang: Lang
- let barWidth: CGFloat
- let compactBar: Bool
- let openControllers: () -> Void
- @EnvironmentObject private var pad: PadFocus
-
- /// How many chips fit in a top bar of this width, and whether each can show its battery. The rest of the bar (logo, tabs, entry
- /// button, search, build button) takes about 900 points with labelled tabs and 640 with icons.
- static func layout(count: Int, barWidth: CGFloat, compactBar: Bool) -> (visible: Int, showsBattery: Bool) {
- let available = barWidth - (compactBar ? 640 : 900)
- let perChip: CGFloat = compactBar ? 62 : 122
- let fit = max(1, Int(available / perChip))
- guard count > fit else { return (count, !compactBar) }
- return (max(1, fit - 1), false)
- }
-
- private func t(_ key: String) -> String { L10n.string(key, lang) }
- var body: some View {
- let layout = Self.layout(count: controllers.count, barWidth: barWidth, compactBar: compactBar)
- HStack(spacing: 6) {
- ForEach(controllers.prefix(layout.visible)) { controller in
- let player = merged ? 1 : controller.player
- chip(id: controller.id, label: controller.name + ", " + t(controller.kind.labelKey) + ", " + (player.map { String(format: t("console.player"), $0) } ?? t("console.unassigned"))) {
- HStack(spacing: 5) {
- Image(systemName: controller.kind.symbol).accessibilityHidden(true)
- Text(player.map { String(format: t("console.playerShort"), $0) } ?? "\u{2014}")
- if layout.showsBattery { ConsoleBattery(controller: controller, lang: lang, compact: true) }
- }
- }
- }
- if controllers.count > layout.visible {
- chip(id: "more", label: t("console.controllers")) { Text("+\(controllers.count - layout.visible)") }
- }
- }
- .fixedSize()
- }
- private func chip<C: View>(id: String, label: String, @ViewBuilder content: () -> C) -> some View {
- Button(action: openControllers) {
- content().font(.manrope(12, .semibold)).padding(.horizontal, 10).frame(height: 30)
- .background(.white.opacity(0.075), in: Capsule()).contentShape(Capsule())
- }
- .buttonStyle(.plain).accessibilityLabel(label).accessibilityHint(t("console.controllers"))
- .padTarget("main.chip." + id, scope: "main", radius: 24, activate: openControllers)
- }
-}
-
struct ConsoleToastView: View {
let toast: ConsoleToast
var body: some View {
@@ -269,7 +221,7 @@ struct ConsoleToastView: View {
}
// 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) {
- tile(id: controller.id + ".identify", label: t(state.identifyingControllerID == controller.id ? "console.identifying" : "console.identify"), symbol: "wave.3.right") { driver.identify(controllerID: controller.id) }
+ 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) }
}
diff --git a/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
index 0e4571a2..4e846687 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
@@ -45,6 +45,13 @@ struct ConsoleConnectionPrompt: View {
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)
+ if LauncherGamepad.homeOpensConsole { // how to come back to this any time
+ HStack(spacing: 6) {
+ Text(t("console.promptHomeBefore"))
+ ConsoleGlyphView(glyph: glyphs.glyph(for: .home), size: 16)
+ Text(t("console.promptHomeAfter"))
+ }.font(.manrope(14)).foregroundStyle(.secondary)
+ }
// one row, macOS order: the way out on the left of the main choice, both of the launcher's standard size
HStack(spacing: 10) {
Toggle(t("console.promptNever"), isOn: Binding(get: { !promptOn }, set: { promptOn = !$0 }))
diff --git a/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift b/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift
index 7d938604..55e4360e 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift
@@ -22,16 +22,19 @@ struct ConsoleGlyphs: Equatable {
}
}
/// A button as GameController names it.
- enum Element: Hashable { case a, b, x, y, menu }
+ enum Element: Hashable { case a, b, x, y, menu, home }
enum Role {
case activate, back, options, controllers
/// The desktop launcher's own: X opens a game's launch options and Y its Manage menu (LauncherView.padAction).
case launchOptions, manage
+ /// The controller's Home button (PlayStation, guide, Home): console mode.
+ case home
var element: Element {
switch self {
case .activate: return Self.element(of: .a)
case .back: return Self.element(of: .b)
case .options: return .menu
+ case .home: return .home
case .controllers, .manage: return Self.element(of: .y)
case .launchOptions: return Self.element(of: .x)
}
@@ -46,14 +49,14 @@ struct ConsoleGlyphs: Equatable {
}
}
var keyCap: String {
- switch self { case .activate: return "return"; case .back: return "escape"; case .options, .launchOptions: return "O"; case .controllers, .manage: return "Y" }
+ switch self { case .activate: return "return"; case .back: return "escape"; case .options, .launchOptions: return "O"; case .controllers, .manage: return "Y"; case .home: return "\u{2325}\u{2318}K" }
}
/// Keys drawn as an SF Symbol in their cap (Return, Escape) instead of a word.
var keySymbol: Bool {
switch self { case .activate, .back: return true; default: return false }
}
var letter: String {
- switch self { case .activate: return "A"; case .back: return "B"; case .options: return "+"; case .launchOptions: return "X"; case .controllers, .manage: return "Y" }
+ switch self { case .activate: return "A"; case .back: return "B"; case .options: return "+"; case .launchOptions: return "X"; case .controllers, .manage: return "Y"; case .home: return "H" }
}
}
enum Glyph: Equatable { case symbol(String), key(String), keySymbol(String), letter(String) }
@@ -74,10 +77,11 @@ struct ConsoleGlyphs: Equatable {
/// What a family's elements are printed with, for a controller that reports no symbol of its own.
static func table(_ family: Family) -> [Element: String] {
switch family {
- case .xbox: return [.a: "a.circle", .b: "b.circle", .x: "x.circle", .y: "y.circle", .menu: "line.3.horizontal.circle"]
- case .playStation: return [.a: "xmark.circle", .b: "circle.circle", .x: "square.circle", .y: "triangle.circle", .menu: "line.3.horizontal.circle"]
- case .nintendo: return [.a: "a.circle", .b: "b.circle", .x: "x.circle", .y: "y.circle", .menu: "plus.circle"]
- case .keyboard, .neutral: return [:]
+ case .xbox: return [.a: "a.circle", .b: "b.circle", .x: "x.circle", .y: "y.circle", .menu: "line.3.horizontal.circle", .home: "house.circle"]
+ case .playStation: return [.a: "xmark.circle", .b: "circle.circle", .x: "square.circle", .y: "triangle.circle", .menu: "line.3.horizontal.circle", .home: "house.circle"]
+ case .nintendo: return [.a: "a.circle", .b: "b.circle", .x: "x.circle", .y: "y.circle", .menu: "plus.circle", .home: "house.circle"]
+ case .keyboard: return [:]
+ case .neutral: return [.home: "house.circle"]
}
}
@@ -88,6 +92,8 @@ struct ConsoleGlyphs: Equatable {
if let pad = controller.extendedGamepad {
let elements: [(Element, GCControllerButtonInput)] = [(.a, pad.buttonA), (.b, pad.buttonB), (.x, pad.buttonX), (.y, pad.buttonY), (.menu, pad.buttonMenu)]
for (element, button) in elements { if let name = button.sfSymbolsName { reported[element] = name } }
+ // The Home button reports a brand logo on some controllers: ours is a neutral house
+ if let name = pad.buttonHome?.sfSymbolsName, !name.lowercased().contains("logo") { reported[.home] = name }
}
}
diff --git a/frontend/Sources/NSPortBuilder/ConsoleState.swift b/frontend/Sources/NSPortBuilder/ConsoleState.swift
index e430c320..5f24b984 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleState.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleState.swift
@@ -68,6 +68,8 @@ struct ConsoleController: Identifiable, Equatable {
var kind: Kind = .gamepad
var battery: Double? = nil
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
var batteryPercent: Int? { battery.map { Int((min(max($0.isFinite ? $0 : 0, 0), 1) * 100).rounded()) } }
}
diff --git a/frontend/Sources/NSPortBuilder/ConsoleView.swift b/frontend/Sources/NSPortBuilder/ConsoleView.swift
index 919ab4eb..3b69241a 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleView.swift
@@ -17,7 +17,7 @@ enum ConsoleInput {
case .b: self = .back
case .plus, .x: self = .options
case .y: self = .controllers
- case .l, .r: return nil
+ case .l, .r, .home: return nil
}
}
}
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 0c02a3f2..f6ecaad8 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -2417,6 +2417,8 @@ struct BuilderView: View {
var onOpenSettings: () -> Void = {}
var onChooseLibraryFolder: () -> Void = {}
var onOpenControls: () -> Void = {}
+ var onOpenControllers: () -> Void = {} // the Controllers sheet (the console mode's list, with the player-mode setting)
+ @AppStorage(LauncherGamepad.homeKey) private var homeOpensConsole = true
var onRunSetup: (() -> Void)? // the guided first-run setup, again (nil where there is none)
var controlChanges = 0
var padMerge: Binding<Bool> = .constant(false) // "All controllers are player 1" (ControlLayout.padMerge)
@@ -2865,6 +2867,16 @@ struct BuilderView: View {
.padTarget("set.padMerge", scope: "main") { padMerge.wrappedValue.toggle() }
}
divider
+ row(m.t("console.homeSetting"), detail: m.t("console.homeSettingNote")) {
+ Toggle("", isOn: $homeOpensConsole).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ .padTarget("set.homeConsole", scope: "main") { homeOpensConsole.toggle() }
+ }
+ divider
+ row(m.t("console.controllers"), detail: m.t("console.controllersRowNote")) {
+ Button(m.t("console.controllersOpen"), action: onOpenControllers)
+ .padTarget("set.controllers", scope: "main") { onOpenControllers() }
+ }
+ divider
row(m.t("console.promptSetting"), detail: m.t("console.promptSettingNote")) {
Toggle("", isOn: $consolePromptOn).labelsHidden().toggleStyle(LauncherSwitchStyle())
.padTarget("set.consolePrompt", scope: "main") { consolePromptOn.toggle() }
diff --git a/frontend/Sources/NSPortBuilder/Gamepad.swift b/frontend/Sources/NSPortBuilder/Gamepad.swift
index 30368cb7..bc3ee00c 100644
--- a/frontend/Sources/NSPortBuilder/Gamepad.swift
+++ b/frontend/Sources/NSPortBuilder/Gamepad.swift
@@ -10,9 +10,15 @@ import GameController
/// started is in front then, and GameController gives a controller's input to the app in front, so the launcher never
/// acts behind a running game.
final class LauncherGamepad: ObservableObject {
- enum Action: Equatable { case left, right, up, down, a, b, x, y, l, r, plus }
+ enum Action: Equatable { case left, right, up, down, a, b, x, y, l, r, plus, home }
@Published private(set) var connected = false
+ /// "Home button opens console mode" (Settings, Controls). On by default.
+ static let homeKey = "homeOpensConsole"
+ static var homeOpensConsole: Bool { UserDefaults.standard.object(forKey: homeKey) as? Bool ?? true }
+ /// Whether the controller's Home button (PlayStation, Xbox guide, Nintendo Home) goes to the launcher instead of the system.
+ /// Only while the launcher is the front app: a game it started is in front then and gets the button for itself.
+ static func capturesHome(enabled: Bool, appIsActive: Bool) -> Bool { enabled && appIsActive }
var perform: (Action) -> Void = { _ in }
/// The GameController button an action reads, in one place (the glyphs of the console mode follow it). GameController names
/// the face buttons by label: buttonA is the bottom of Apple's diamond (GCExtendedGamepad.h), which is A on an Xbox
@@ -38,6 +44,9 @@ final class LauncherGamepad: ObservableObject {
observers = [NSNotification.Name.GCControllerDidConnect, .GCControllerDidDisconnect].map {
center.addObserver(forName: $0, object: nil, queue: .main) { [weak self] _ in self?.attach() }
}
+ observers += [NSApplication.didBecomeActiveNotification, NSApplication.didResignActiveNotification].map {
+ center.addObserver(forName: $0, object: nil, queue: .main) { [weak self] _ in self?.applyHomeCapture() }
+ }
attach()
}
@@ -47,6 +56,15 @@ final class LauncherGamepad: ObservableObject {
let pads = GCController.controllers().compactMap(\.extendedGamepad)
connected = !pads.isEmpty
for pad in pads { pad.valueChangedHandler = { [weak self] pad, _ in self?.read(pad) } }
+ applyHomeCapture()
+ }
+
+ /// The Home button reaches the app (`.alwaysReceive`) while the launcher is in front and the setting is on, else the system keeps it.
+ func applyHomeCapture() {
+ let capture = Self.capturesHome(enabled: Self.homeOpensConsole, appIsActive: NSApp?.isActive ?? false)
+ for pad in GCController.controllers().compactMap(\.extendedGamepad) {
+ pad.buttonHome?.preferredSystemGestureState = capture ? .alwaysReceive : .enabled
+ }
}
private func read(_ pad: GCExtendedGamepad) {
@@ -57,7 +75,7 @@ final class LauncherGamepad: ObservableObject {
("a", pad.buttonA.isPressed, .a), ("b", pad.buttonB.isPressed, .b), // by label, see `face`
("x", pad.buttonX.isPressed, .x), ("y", pad.buttonY.isPressed, .y),
("l", pad.leftShoulder.isPressed, .l), ("r", pad.rightShoulder.isPressed, .r),
- ("plus", pad.buttonMenu.isPressed, .plus), // the console mode's options; the desktop ignores it
+ ("plus", pad.buttonMenu.isPressed, .plus), ("home", pad.buttonHome?.isPressed ?? false, .home), // the console mode's options; the desktop ignores it
]
for (key, down, action) in state {
if down, !held.contains(key) {
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 310bdacd..9c65c117 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -126,7 +126,7 @@ struct ContentView: View {
} else {
BuilderView(m: m, library: library, settings: page == .settings, onViewGame: { page = .library },
onOpenSettings: { page = .settings }, onChooseLibraryFolder: chooseLibraryFolder,
- onOpenControls: { controlsOpen = true }, onRunSetup: onRunSetup, controlChanges: controls.changeCount,
+ onOpenControls: { controlsOpen = true }, onOpenControllers: { controllerSheet = true }, onRunSetup: onRunSetup, controlChanges: controls.changeCount,
padMerge: Binding(get: { controls.padMerge }, set: { setPadMerge($0) }))
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
@@ -236,9 +236,6 @@ struct ContentView: View {
}
}
- /// The controller strip appears with the first controller the driver reports (none yet outside the preview).
- private var showsControllers: Bool { !consoleDriver.state.controllers.isEmpty }
-
@ViewBuilder private func navLabel(_ destination: LauncherPage, compact: Bool) -> some View {
if compact { Image(systemName: destination.symbol).accessibilityLabel(m.t("nav." + destination.rawValue)) }
else { Label(m.t("nav." + destination.rawValue), systemImage: destination.symbol) }
@@ -246,7 +243,7 @@ struct ContentView: View {
private var topBar: some View {
GeometryReader { geometry in
- let compact = (enterConsole != nil || showsControllers) && (geometry.size.width < 1100 || (searching && geometry.size.width < 1400))
+ let compact = false // the bar holds the tabs, search and Build game only, as before the console mode
VStack(spacing: 0) {
HStack(spacing: 6) {
// The project is NX2Apple (the user's call: what this fork produces is NX2Apple);
@@ -275,11 +272,6 @@ struct ContentView: View {
.padTarget("tab." + destination.rawValue, scope: "main") { page = destination }
}
Spacer(minLength: 8)
- if showsControllers {
- DesktopControllerChips(controllers: consoleDriver.state.controllers, merged: consoleDriver.state.padMerge, lang: m.lang,
- barWidth: geometry.size.width, compactBar: compact) { controllerSheet = true }
- }
- if let enterConsole { ConsoleEntryButton(lang: m.lang, compact: compact, enterConsole: enterConsole) }
searchField
Button { newBuild() } label: {
Group {
@@ -618,7 +610,9 @@ struct ContentView: View {
HStack(spacing: 18) {
padHint(.activate, m.t("pad.play")); padHint(.launchOptions, m.t("pad.options")); padHint(.back, m.t("pad.back"))
padHint(.manage, m.t("pad.manage"))
+ if enterConsole != nil, LauncherGamepad.homeOpensConsole { padHint(.home, m.t("console.entry")) }
Image(systemName: "gamecontroller").foregroundStyle(.secondary)
+ if let enterConsole { ConsoleEntryButton(lang: m.lang, compact: false, enterConsole: enterConsole) }
}
}
}
@@ -667,6 +661,10 @@ struct ContentView: View {
/// then the D-pad moves it (PadFocus), A activates, B closes a sheet or goes back to the library, X opens the selected
/// game's launch options, L and R switch the pages.
private func padAction(_ action: LauncherGamepad.Action) {
+ if action == .home { // the controller's Home button, while the launcher is in front: console mode, like a console's guide button
+ if let enterConsole, LauncherGamepad.homeOpensConsole { consolePrompt = false; enterConsole() }
+ return
+ }
if consolePrompt {
switch action {
case .b: consolePrompt = false
@@ -717,7 +715,7 @@ struct ContentView: View {
guard !sheetOpen, let at = LauncherPage.allCases.firstIndex(of: page) else { return }
let pages = LauncherPage.allCases
page = pages[(at + (action == .l ? pages.count - 1 : 1)) % pages.count]
- case .y, .plus: // Y is the Manage menu: ManagePad.route opened it above
+ case .y, .plus, .home: // Y is the Manage menu: ManagePad.route opened it above
return
case .b:
return
diff --git a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
index 3a36acd5..92d64772 100644
--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
@@ -3,8 +3,20 @@ import Combine
import AppKit
import GameController
import CoreHaptics
+import os
/// A controller as GameController reports it, reduced to what the console mode shows. Tests build these instead of hardware.
+/// What a controller reports about its battery.
+enum PadBatteryState: Equatable { case unknown, discharging, charging, full }
+
+/// What Identify can use on a controller, in the order it is tried: the player lights, the light bar, a rumble.
+struct IdentifyPlan: Equatable {
+ enum Action: Equatable { case playerLights, lightBar, rumble }
+ static func actions(playerLights: Bool, lightBar: Bool, rumble: Bool) -> [Action] {
+ (playerLights ? [.playerLights] : []) + (lightBar ? [.lightBar] : []) + (rumble ? [.rumble] : [])
+ }
+}
+
struct ConsolePadSnapshot: Equatable {
var id: String
var name: String
@@ -12,6 +24,18 @@ struct ConsolePadSnapshot: Equatable {
var playerIndex: Int? // 1...4, nil when unset
var battery: Double?
var charging = false
+ var canIdentify = 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, before the first report and while wired, so 0 counts only when the state says it is discharging.
+ static func batteryReading(level: Double, state: PadBatteryState) -> (level: Double?, charging: Bool) {
+ switch state {
+ case .unknown: return (nil, false)
+ case .charging: return (level.isFinite && level > 0 ? level : nil, true)
+ case .full: return (1, false)
+ case .discharging: return (level.isFinite ? min(max(level, 0), 1) : nil, false)
+ }
+ }
var controller: ConsoleController {
let family = ConsoleGlyphs.Family(category: category)
@@ -21,7 +45,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)
+ return ConsoleController(id: id, name: name, player: playerIndex, kind: kind, battery: battery, charging: charging, canIdentify: canIdentify)
}
}
@@ -85,7 +109,7 @@ struct ConsolePadSnapshot: Equatable {
observers.append(center.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.gameWindowAppeared() }
})
- clock = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.state.time = Date() } }
+ clock = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.state.time = Date(); self?.refreshControllers(announce: false) } } // the battery has no change callback: it is read again each tick
}
private var devicePads = false
@@ -271,19 +295,55 @@ struct ConsolePadSnapshot: Equatable {
}
func setPadMerge(_ enabled: Bool) { controls.padMerge = enabled }
- /// A short rumble when the controller has haptics, nothing otherwise (and never an error).
+ /// What this controller can do for Identify. The player lights have no capability flag in GameController, so any gamepad counts.
+ static func identifyActions(_ c: GCController) -> [IdentifyPlan.Action] {
+ IdentifyPlan.actions(playerLights: c.extendedGamepad != nil, lightBar: c.light != nil, rumble: c.haptics != nil)
+ }
+
+ private static let log = Logger(subsystem: "NX2Apple", category: "console.identify")
+ private var identifyEngines: [String: CHHapticEngine] = [:] // kept alive: an engine that is released stops its pattern
+ private var identifyTask: Task<Void, Never>?
+
+ /// Everything the controller has: its player lights step through 1 to 4, the light bar pulses, it rumbles. The assigned player
+ /// and the light's colour are restored after.
func identify(controllerID: String) {
guard let c = state.controllers.first(where: { $0.id == controllerID }) else { return }
state.identifyingControllerID = controllerID
showToast(String(format: t("console.identifyingName"), c.name))
- guard let engine = devices[controllerID]?.haptics?.createEngine(withLocality: .default) else { return }
+ guard let pad = devices[controllerID] else { return }
+ let actions = Self.identifyActions(pad)
+ Self.log.debug("identify \(c.name, privacy: .public): \(actions.map { "\($0)" }.joined(separator: ","), privacy: .public)")
+ identifyTask?.cancel()
+ identifyTask = Task { [weak self] in
+ let player = pad.playerIndex
+ let color = pad.light?.color
+ if actions.contains(.rumble) { self?.rumble(pad, id: controllerID) }
+ for step in 0..<8 {
+ guard !Task.isCancelled else { break }
+ if actions.contains(.playerLights) { pad.playerIndex = GCControllerPlayerIndex(rawValue: step % 4) ?? .indexUnset }
+ if actions.contains(.lightBar) { pad.light?.color = step % 2 == 0 ? GCColor(red: 1, green: 0.1, blue: 0.9) : GCColor(red: 0.1, green: 0.9, blue: 1) }
+ try? await Task.sleep(nanoseconds: 140_000_000)
+ }
+ pad.playerIndex = player
+ if let color { pad.light?.color = color }
+ }
+ }
+
+ private func rumble(_ pad: GCController, id: String) {
+ guard let haptics = pad.haptics else { Self.log.debug("identify: no haptics on this controller"); return }
+ let localities: [GCHapticsLocality] = [.default, .all, .handles, .leftHandle, .rightHandle]
+ guard let engine = localities.lazy.compactMap({ haptics.createEngine(withLocality: $0) }).first else {
+ Self.log.debug("identify: haptics exist but no engine could be created (supported localities: \(haptics.supportedLocalities.map(\.rawValue).joined(separator: ","), privacy: .public))")
+ return
+ }
+ identifyEngines[id] = engine
do {
try engine.start()
- let events = [CHHapticEvent(eventType: .hapticContinuous, parameters: [CHHapticEventParameter(parameterID: .hapticIntensity, value: 0.8),
- CHHapticEventParameter(parameterID: .hapticSharpness, value: 0.5)],
- relativeTime: 0, duration: 0.45)]
- try engine.makePlayer(with: CHHapticPattern(events: events, parameters: [])).start(atTime: 0)
- } catch { /* no rumble on this controller: the toast is the answer */ }
+ let events = [CHHapticEvent(eventType: .hapticContinuous, parameters: [CHHapticEventParameter(parameterID: .hapticIntensity, value: 1),
+ CHHapticEventParameter(parameterID: .hapticSharpness, value: 0.6)],
+ relativeTime: 0, duration: 0.9)]
+ try engine.makePlayer(with: CHHapticPattern(events: events, parameters: [])).start(atTime: CHHapticTimeImmediate)
+ } catch { Self.log.debug("identify: rumble failed: \(error.localizedDescription, privacy: .public)") }
}
/// macOS offers apps no way to drop a Bluetooth controller, so this says where to do it instead.
@@ -319,11 +379,14 @@ struct ConsolePadSnapshot: Equatable {
guard c.extendedGamepad != nil else { return nil }
let id = String(UInt(bitPattern: ObjectIdentifier(c).hashValue), radix: 16)
devices[id] = c
- let level = c.battery.map { Double($0.batteryLevel) }
+ 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)
+ }
let index = c.playerIndex.rawValue
return ConsolePadSnapshot(id: id, name: c.vendorName ?? c.productCategory, category: c.productCategory,
- playerIndex: (0...3).contains(index) ? index + 1 : nil, battery: level,
- charging: c.battery.map { $0.batteryState == .charging } ?? false)
+ playerIndex: (0...3).contains(index) ? index + 1 : nil, battery: reading?.level,
+ charging: reading?.charging ?? false, canIdentify: !Self.identifyActions(c).isEmpty)
}
}
let assigned = Self.autoAssigned(snapshots)
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 3384aa7a..2cc440f4 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -161,6 +161,12 @@ enum L10n {
"console.explanationTitle": ("\u{6682}\u{65f6}\u{65e0}\u{6cd5}\u{6e38}\u{73a9}", "Not ready to play"),
"console.connectedNextPlayer": ("%@ \u{5df2}\u{8fde}\u{63a5}\u{ff0c}\u{73a9}\u{5bb6} %d", "%@ connected, player %d"),
"console.noFreePlayer": ("\u{56db}\u{4f4d}\u{73a9}\u{5bb6}\u{90fd}\u{5df2}\u{5360}\u{7528}\u{3002}\u{8bf7}\u{6253}\u{5f00}\u{624b}\u{67c4}\u{9875}\u{9762}\u{8c03}\u{6574}\u{3002}", "All four players are taken. Open Controllers to change them."),
+ "console.homeSetting": ("\u{4e3b}\u{9875}\u{952e}\u{6253}\u{5f00}\u{4e3b}\u{673a}\u{6a21}\u{5f0f}", "Home button opens console mode"),
+ "console.homeSettingNote": ("\u{5728}\u{542f}\u{52a8}\u{5668}\u{4f4d}\u{4e8e}\u{524d}\u{53f0}\u{65f6}\u{ff0c}\u{6309}\u{624b}\u{67c4}\u{7684}\u{4e3b}\u{9875}\u{952e}\u{5373}\u{53ef}\u{5207}\u{6362}\u{3002}", "While the launcher is in front, the controller\u{2019}s Home button switches over."),
+ "console.controllersRowNote": ("\u{67e5}\u{770b}\u{5df2}\u{8fde}\u{63a5}\u{7684}\u{624b}\u{67c4}\u{ff0c}\u{8bc6}\u{522b}\u{3001}\u{5206}\u{914d}\u{73a9}\u{5bb6}\u{3002}", "See connected controllers, identify them and assign players."),
+ "console.controllersOpen": ("\u{6253}\u{5f00}\u{2026}", "Open\u{2026}"),
+ "console.promptHomeBefore": ("\u{968f}\u{65f6}\u{6309}", "Press"),
+ "console.promptHomeAfter": ("\u{952e}\u{5373}\u{53ef}\u{5207}\u{6362}\u{3002}", "anytime to switch."),
"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/ManageMenu.swift b/frontend/Sources/NSPortBuilder/ManageMenu.swift
index 724cb087..3aa4c72b 100644
--- a/frontend/Sources/NSPortBuilder/ManageMenu.swift
+++ b/frontend/Sources/NSPortBuilder/ManageMenu.swift
@@ -57,7 +57,7 @@ enum ManagePad {
if menuOpen {
switch action {
case .b: return .close
- case .x, .y, .l, .r, .plus: return .swallow
+ case .x, .y, .l, .r, .plus, .home: return .swallow
case .up, .down, .left, .right, .a: return .pass
}
}
diff --git a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
index 50771fd4..81618ea0 100644
--- a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
@@ -211,4 +211,40 @@ import SwiftUI
XCTAssertEqual(LiveConsoleDriver.version(at: ios.path), "2.0.1")
XCTAssertEqual(LiveConsoleDriver.version(at: temporary.appendingPathComponent("none.app").path), "")
}
+
+ func testBatteryReadingTreatsAnUnreportedLevelAsUnknown() {
+ XCTAssertNil(ConsolePadSnapshot.batteryReading(level: 0, state: .unknown).level, "a DualShock 4 over Bluetooth: 0 with an unknown state")
+ XCTAssertNil(ConsolePadSnapshot.batteryReading(level: 0.5, state: .unknown).level)
+ XCTAssertEqual(ConsolePadSnapshot.batteryReading(level: 0.12, state: .discharging).level, 0.12)
+ XCTAssertEqual(ConsolePadSnapshot.batteryReading(level: 0, state: .discharging).level, 0, "an explicit empty battery is real")
+ let charging = ConsolePadSnapshot.batteryReading(level: 0.4, state: .charging)
+ XCTAssertEqual(charging.level, 0.4)
+ XCTAssertTrue(charging.charging)
+ XCTAssertNil(ConsolePadSnapshot.batteryReading(level: 0, state: .charging).level)
+ XCTAssertEqual(ConsolePadSnapshot.batteryReading(level: 0, state: .full).level, 1)
+ let pad = ConsolePadSnapshot(id: "a", name: "DUALSHOCK 4", category: "DualShock 4", playerIndex: 1, battery: nil).controller
+ XCTAssertNil(pad.battery)
+ XCTAssertNil(pad.batteryPercent, "no percentage, so no red 0%")
+ }
+
+ func testIdentifyUsesWhatTheControllerHasInOrder() {
+ XCTAssertEqual(IdentifyPlan.actions(playerLights: true, lightBar: true, rumble: true), [.playerLights, .lightBar, .rumble])
+ XCTAssertEqual(IdentifyPlan.actions(playerLights: false, lightBar: true, rumble: true), [.lightBar, .rumble], "a DualShock 4: light bar and rumble")
+ XCTAssertEqual(IdentifyPlan.actions(playerLights: false, lightBar: false, rumble: true), [.rumble])
+ XCTAssertEqual(IdentifyPlan.actions(playerLights: false, lightBar: false, rumble: false), [], "nothing to do: the button is hidden")
+ var pad = ConsolePadSnapshot(id: "a", name: "x", category: nil, playerIndex: 1)
+ XCTAssertTrue(pad.controller.canIdentify)
+ pad.canIdentify = false
+ XCTAssertFalse(pad.controller.canIdentify)
+ }
+
+ func testHomeButtonIsCapturedOnlyWhileTheLauncherIsInFront() {
+ XCTAssertTrue(LauncherGamepad.capturesHome(enabled: true, appIsActive: true))
+ XCTAssertFalse(LauncherGamepad.capturesHome(enabled: true, appIsActive: false), "a game in front keeps its own Home button")
+ XCTAssertFalse(LauncherGamepad.capturesHome(enabled: false, appIsActive: true))
+ XCTAssertNil(ConsoleInput(.home), "in console mode Home does nothing special")
+ XCTAssertEqual(ConsoleGlyphs(family: .xbox).glyph(for: .home), .symbol("house.circle"), "no brand logo")
+ XCTAssertEqual(ConsoleGlyphs(family: .playStation, reported: [.home: "house.fill"]).glyph(for: .home), .symbol("house.fill"))
+ XCTAssertEqual(ConsoleGlyphs.neutral.glyph(for: .home), .symbol("house.circle"))
+ }
}
diff --git a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
index 23c11ca8..b05008bc 100644
--- a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
@@ -197,29 +197,13 @@ final class ConsolePadTests: XCTestCase {
}
ConsolePrompt.didShow() // the desktop shots must not show the prompt a connected controller would raise
let library = GameLibrary(file: output.appendingPathComponent("unused-library.json"))
- for (name, scenario) in [("1", MockConsoleDriver.Scenario.full), ("3", .controllersMixed)] {
- let driver = MockConsoleDriver(scenario: scenario, lang: .en, animated: false)
- driver.back()
- for width: CGFloat in [1280, 900] {
- try shot(AnyView(ContentView(model: BuildModel(), library: library, performStartupChecks: false, enterConsole: {}, controllerDriver: AnyConsoleDriver(driver))),
- "desktop-\(name)c-\(Int(width))", width, 720)
- }
+ // the bottom right shows the Home hint and the Console mode button while a controller is connected (this Mac's, when one is)
+ for width: CGFloat in [1280, 900] {
+ try shot(AnyView(ContentView(model: BuildModel(), library: library, performStartupChecks: false, enterConsole: {})), "desktop-bar-\(Int(width))", width, 720)
}
for lang in [Lang.en, .zh] {
try shot(AnyView(ConsoleConnectionPrompt(lang: lang, enterConsole: {}, dismissPrompt: {}).environmentObject(PadFocus()).preferredColorScheme(.dark)), "prompt-\(lang.rawValue)", 900, 500)
}
}
- func testChipStripFitsTheBar() {
- // plenty of room: every chip with its battery
- XCTAssertEqual(DesktopControllerChips.layout(count: 3, barWidth: 1400, compactBar: false).visible, 3)
- XCTAssertTrue(DesktopControllerChips.layout(count: 3, barWidth: 1400, compactBar: false).showsBattery)
- // a narrow bar: no battery, and the rest folds into one "+N" chip, at least one controller stays
- let narrow = DesktopControllerChips.layout(count: 4, barWidth: 800, compactBar: true)
- XCTAssertFalse(narrow.showsBattery)
- XCTAssertGreaterThanOrEqual(narrow.visible, 1)
- XCTAssertLessThan(narrow.visible, 4)
- XCTAssertEqual(DesktopControllerChips.layout(count: 1, barWidth: 700, compactBar: true).visible, 1)
- XCTAssertEqual(DesktopControllerChips.layout(count: 0, barWidth: 700, compactBar: true).visible, 0)
- }
}