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: Select opens it, every controller counts, player assignment by press, battery rules

v0lumehi598354c35f2f
diff --git a/frontend/Console.md b/frontend/Console.md
index 52e13c97..6e5d10a0 100644
--- a/frontend/Console.md
+++ b/frontend/Console.md
@@ -82,5 +82,5 @@ Validation on 2026-10-28: release build passed. The complete frontend suite pass
`LiveConsoleDriver` is the real driver. It builds the games from `GameLibrary` (status, version, platforms, covers through `GameLibrary.artwork`), reads and writes launch options through `SavedChoices` and the library as LaunchOptionsView does, starts a game with `GameStart.environment` (the function the desktop Play button uses, so saved choices and `DM_PAD_MERGE` match), lists controllers from GameController and ends Starting when the game window takes the front or the game quits. A game that quits brings the console back (PR #110 brings the launcher back to the front for the desktop and does not conflict, since both only observe the termination).
-Enter it with the Console mode button in the desktop top bar, from the controller prompt (once per launch, off in Settings), or with View, Console Mode (Option-Command-K, because Control-Command-F is the system's full screen). The window goes full screen for the mode and returns to its earlier state on leaving. `ConsoleCoordinator` owns that, and RootView swaps the content. The desktop's controller hints use the same `ConsoleGlyphs`.
+Enter it with the controller's Select-type button on the desktop (DualShock Share, DualSense Create, Xbox View, Nintendo Minus, GameController's `buttonOptions`, which the system does not claim), from the controller prompt (once per launch, off in Settings), or with View, Console Mode (Option-Command-K, because Control-Command-F is the system's full screen). The desktop's bottom hint row shows the Select glyph of the controller in use with "Console mode", and nothing about controllers appears elsewhere on the desktop. Settings, Controls has a Controllers row (identify, assign players) next to the player-mode switch. In console mode Select does nothing special. The Home button is not touched. The window goes full screen for the mode and returns to its earlier state on leaving. `ConsoleCoordinator` owns that, and RootView swaps the content. Every controller GameController lists drives the launcher, wired or wireless, and each new one takes the next free player at once.
diff --git a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
index 4d4cafe6..62a09fcb 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
@@ -26,6 +26,7 @@ import Combine
func back() { base.back() }
func exitToDesktop() { base.exitToDesktop() }
func returnFromGame() { base.returnFromGame() }
+ func consumePress(controllerID: String, isBack: Bool) -> Bool { base.consumePress(controllerID: controllerID, isBack: isBack) }
}
/// The battery drawn as the iOS status bar does: an outline with a nub and a fill exactly as wide as the level, red at 20 percent
@@ -43,27 +44,45 @@ struct BatteryIcon: View {
}
static func isLow(_ level: Double?) -> Bool { level.map { fillFraction($0) <= 0.2 } ?? false }
+ /// Every rectangle of the icon, in points, snapped to the half point (whole pixels at 2x). The outline is stroked inside its
+ /// frame, the fill area is that frame inset by the stroke and a 1 point gap, and the fill is that area times the level, so the
+ /// fill can never leave the body.
+ struct Geometry: Equatable {
+ var outer: CGRect, inner: CGRect, fill: CGRect, nub: CGRect
+ var outerRadius: CGFloat, innerRadius: CGFloat
+ var size: CGSize
+ }
+ static func geometry(height: CGFloat, level: Double?) -> Geometry {
+ func snap(_ v: CGFloat) -> CGFloat { (v * 2).rounded() / 2 }
+ let h = snap(height), w = snap(height * 2), stroke: CGFloat = 1, gap: CGFloat = 1, nubWidth: CGFloat = 1.5
+ let outer = CGRect(x: 0, y: 0, width: w, height: h)
+ let inset = stroke + gap
+ let inner = outer.insetBy(dx: inset, dy: inset)
+ let fill = CGRect(x: inner.minX, y: inner.minY, width: snap(inner.width * fillFraction(level)), height: inner.height)
+ let nubHeight = snap(h * 0.36)
+ let nub = CGRect(x: w + 1, y: snap((h - nubHeight) / 2), width: nubWidth, height: nubHeight)
+ let radius = snap(h * 0.3)
+ return Geometry(outer: outer, inner: inner, fill: fill, nub: nub, outerRadius: radius, innerRadius: max(0, radius - inset),
+ size: CGSize(width: nub.maxX, height: h))
+ }
+
var body: some View {
- let width = height * 2.0, line: CGFloat = 1, inset: CGFloat = 1.5
- HStack(spacing: 1) {
- ZStack(alignment: .leading) {
- RoundedRectangle(cornerRadius: height * 0.3).strokeBorder(.white.opacity(level == nil ? 0.3 : 0.55), lineWidth: line)
- if level != nil {
- GeometryReader { g in
- RoundedRectangle(cornerRadius: height * 0.18)
- .fill(Self.isLow(level) && !charging ? Color.red : (charging ? LauncherPalette.ready : Color.white.opacity(0.9)))
- .frame(width: max(0, (g.size.width - 2 * inset) * Self.fillFraction(level)), height: g.size.height - 2 * inset)
- .offset(x: inset, y: inset)
- }
- }
- if charging {
- Image(systemName: "bolt.fill").font(.system(size: height * 0.62, weight: .bold)).foregroundStyle(.black.opacity(0.75))
- .frame(maxWidth: .infinity)
- }
+ let g = Self.geometry(height: height, level: level)
+ let line = Color.white.opacity(level == nil ? 0.3 : 0.55)
+ ZStack(alignment: .topLeading) {
+ RoundedRectangle(cornerRadius: g.outerRadius).strokeBorder(line, lineWidth: 1).frame(width: g.outer.width, height: g.outer.height)
+ if level != nil {
+ 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)
}
- .frame(width: width, height: height)
- Capsule().fill(.white.opacity(level == nil ? 0.3 : 0.55)).frame(width: 1.5, height: height * 0.36)
+ if charging {
+ Image(systemName: "bolt.fill").font(.system(size: height * 0.62, weight: .bold)).foregroundStyle(.black.opacity(0.75))
+ .frame(width: g.outer.width, height: g.outer.height)
+ }
+ Capsule().fill(line).frame(width: g.nub.width, height: g.nub.height).offset(x: g.nub.minX, y: g.nub.minY)
}
+ .frame(width: g.size.width, height: g.size.height, alignment: .topLeading)
.accessibilityHidden(true)
}
}
@@ -103,34 +122,42 @@ struct ConsoleControllerChips: View {
@EnvironmentObject private var pad: PadFocus
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private func t(_ key: String) -> String { L10n.string(key, lang) }
- var body: some View {
- ScrollViewReader { proxy in
- ScrollView(.horizontal, showsIndicators: false) {
- HStack(spacing: 8) {
- if controllers.isEmpty {
- chip(id: "empty", label: t("console.noControllers")) {
- Label(t("console.controllers"), systemImage: "gamecontroller")
- }
+ private var row: some View {
+ HStack(spacing: 8) {
+ if controllers.isEmpty {
+ chip(id: "empty", label: t("console.noControllers")) {
+ Label(t("console.controllers"), systemImage: "gamecontroller")
}
- ForEach(controllers) { controller in
- 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)
- }
+ }
+ ForEach(controllers) { controller in
+ 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)
}
}
}
- .padding(5)
}
- .frame(height: compact ? 40 : 52)
- .onChange(of: pad.focused) { id in
- if let id, id.hasPrefix(scope + ".chip.") {
- withAnimation(.easeOut(duration: reduceMotion ? 0 : 0.18)) { proxy.scrollTo(id, anchor: .center) }
+ .padding(5)
+ }
+
+ /// The chips take their own width (nothing is cut off) and sit at the trailing edge. Only when there are more than the row has
+ /// room for does it scroll sideways.
+ var body: some View {
+ ViewThatFits(in: .horizontal) {
+ row.fixedSize().frame(maxWidth: .infinity, alignment: .trailing)
+ ScrollViewReader { proxy in
+ ScrollView(.horizontal, showsIndicators: false) { row }
+ .mask(HStack(spacing: 0) { Rectangle(); LinearGradient(colors: [.black, .clear], startPoint: .leading, endPoint: .trailing).frame(width: 18) }) // an overflowing row fades out instead of ending in a cut
+ .onChange(of: pad.focused) { id in
+ if let id, id.hasPrefix(scope + ".chip.") {
+ withAnimation(.easeOut(duration: reduceMotion ? 0 : 0.18)) { proxy.scrollTo(id, anchor: .center) }
+ }
+ }
}
}
- }
+ .frame(height: compact ? 40 : 52)
}
private func chip<C: View>(id: String, label: String, @ViewBuilder content: () -> C) -> some View {
Button(action: openControllers) {
@@ -178,7 +205,7 @@ struct ConsoleToastView: View {
ScrollViewReader { proxy in
ScrollView {
VStack(alignment: .leading, spacing: 22) {
- action(id: "merge", label: t("console.playerMode"), value: t(state.padMerge ? "console.mergeAll" : "console.mergeEach"), symbol: "person.2", adjust: { _ in driver.setPadMerge(!state.padMerge) }) { driver.setPadMerge(!state.padMerge) }
+ mergeToggle
Text(t("console.controllerNote")).font(.manrope(compact ? 17 : 22)).foregroundStyle(.secondary)
HStack(spacing: 12) {
ForEach(1...4, id: \.self) { player in
@@ -206,6 +233,26 @@ struct ConsoleToastView: View {
}
}
}
+ /// "All controllers are player 1" as a switch with its state spelled out.
+ private var mergeToggle: some View {
+ let flip = { driver.setPadMerge(!state.padMerge) }
+ return Button(action: flip) {
+ HStack(spacing: 14) {
+ VStack(alignment: .leading, spacing: 6) {
+ Label(t("console.mergeAll"), systemImage: "person.2").font(.manrope(compact ? 16 : 18, .semibold))
+ Text(t(state.padMerge ? "console.on" : "console.off")).font(.manrope(compact ? 16 : 20)).foregroundStyle(state.padMerge ? LauncherPalette.cream : .secondary)
+ }
+ Spacer(minLength: 8)
+ Toggle("", isOn: Binding(get: { state.padMerge }, set: { _ in flip() })).labelsHidden().toggleStyle(LauncherSwitchStyle()).allowsHitTesting(false)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading).padding(14)
+ .background(.white.opacity(0.045), in: RoundedRectangle(cornerRadius: 10)).contentShape(RoundedRectangle(cornerRadius: 10))
+ }
+ .buttonStyle(.plain)
+ .padTarget("console.controller.merge", scope: scope, radius: 10, activate: flip, adjust: { _ in flip() })
+ .accessibilityLabel(t("console.mergeAll")).accessibilityValue(t(state.padMerge ? "console.on" : "console.off"))
+ }
+
private func row(_ controller: ConsoleController) -> some View {
VStack(alignment: .leading, spacing: 18) {
HStack(spacing: 16) {
diff --git a/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
index 4e846687..d4e6868d 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
@@ -45,11 +45,11 @@ 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
+ do { // how to switch from the desktop any time
HStack(spacing: 6) {
- Text(t("console.promptHomeBefore"))
- ConsoleGlyphView(glyph: glyphs.glyph(for: .home), size: 16)
- Text(t("console.promptHomeAfter"))
+ Text(t("console.promptSelectBefore"))
+ ConsoleGlyphView(glyph: glyphs.glyph(for: .select), size: 16)
+ Text(t("console.promptSelectAfter"))
}.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
diff --git a/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift b/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift
index 55e4360e..bf1d8041 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift
@@ -22,19 +22,19 @@ struct ConsoleGlyphs: Equatable {
}
}
/// A button as GameController names it.
- enum Element: Hashable { case a, b, x, y, menu, home }
+ enum Element: Hashable { case a, b, x, y, menu, select }
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
+ /// The Select-type button (Share, Create, View, Minus): opens console mode from the desktop.
+ case select
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 .select: return .select
case .controllers, .manage: return Self.element(of: .y)
case .launchOptions: return Self.element(of: .x)
}
@@ -49,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"; case .home: return "\u{2325}\u{2318}K" }
+ switch self { case .activate: return "return"; case .back: return "escape"; case .options, .launchOptions: return "O"; case .controllers, .manage: return "Y"; case .select: 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"; case .home: return "H" }
+ switch self { case .activate: return "A"; case .back: return "B"; case .options: return "+"; case .launchOptions: return "X"; case .controllers, .manage: return "Y"; case .select: return "\u{2212}" }
}
}
enum Glyph: Equatable { case symbol(String), key(String), keySymbol(String), letter(String) }
@@ -77,11 +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", .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 .xbox: return [.a: "a.circle", .b: "b.circle", .x: "x.circle", .y: "y.circle", .menu: "line.3.horizontal.circle", .select: "minus.circle"]
+ case .playStation: return [.a: "xmark.circle", .b: "circle.circle", .x: "square.circle", .y: "triangle.circle", .menu: "line.3.horizontal.circle", .select: "minus.circle"]
+ case .nintendo: return [.a: "a.circle", .b: "b.circle", .x: "x.circle", .y: "y.circle", .menu: "plus.circle", .select: "minus.circle"]
case .keyboard: return [:]
- case .neutral: return [.home: "house.circle"]
+ case .neutral: return [.select: "minus.circle"]
}
}
@@ -92,8 +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 }
+ // The system's own symbol for the Select-type button, whatever the controller calls it
+ if let name = pad.buttonOptions?.sfSymbolsName { reported[.select] = name }
}
}
@@ -110,7 +110,9 @@ struct ConsoleGlyphView: View {
var size: CGFloat = 22
var body: some View {
switch glyph {
- case .symbol(let name):
+ case .symbol(let requested):
+ // a symbol this macOS does not have draws nothing: a plain circle stands in
+ let name = NSImage(systemSymbolName: requested, accessibilityDescription: nil) == nil ? "circle" : requested
Image(systemName: name).font(.system(size: size, weight: .medium)).accessibilityHidden(true)
case .key(let cap):
keyCap { Text(cap).font(.manrope(size * 0.62, .bold)) }
diff --git a/frontend/Sources/NSPortBuilder/ConsoleState.swift b/frontend/Sources/NSPortBuilder/ConsoleState.swift
index 5f24b984..f4242953 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleState.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleState.swift
@@ -186,8 +186,12 @@ struct ConsoleState {
func back()
func exitToDesktop()
func returnFromGame()
+ /// A press from a controller: true when the driver used it (player assignment), so it does not also navigate.
+ func consumePress(controllerID: String, isBack: Bool) -> Bool
}
+extension ConsoleDriver { func consumePress(controllerID: String, isBack: Bool) -> Bool { false } }
+
/// Shared choice/range/toggle stepping for mouse, d-pad and keyboard. No settings store is touched.
enum ConsoleOption {
static func stepped(_ setting: LaunchSetting, value: String, by step: Int) -> String? {
diff --git a/frontend/Sources/NSPortBuilder/ConsoleView.swift b/frontend/Sources/NSPortBuilder/ConsoleView.swift
index 3b69241a..8ace0d07 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, .home: return nil
+ case .l, .r, .select: return nil // Select does nothing in console mode (B goes back)
}
}
}
@@ -90,8 +90,9 @@ enum ConsoleInput {
.onReceive(inputs, perform: handle)
.onChange(of: scope) { _ in resetFocus() }
.onChange(of: state.exited) { exited in if exited, let onExit { onExit() } else { resetFocus() } }
- .onAppear { gamepad.perform = { [self] action in if let input = ConsoleInput(action) { glyphs = .current(); handle(input) } }; resetFocus() }
- .onDisappear { gamepad.perform = { _ in } }
+ .onAppear { gamepad.capture = { [driver] id, action in driver.consumePress(controllerID: id, isBack: action == .b) }
+ gamepad.perform = { [self] action in if let input = ConsoleInput(action) { glyphs = .current(); handle(input) } }; resetFocus() }
+ .onDisappear { gamepad.perform = { _ in }; gamepad.capture = nil }
.onChange(of: pad.focused) { id in
if let id, id.hasPrefix("console.game.") { driver.focus(String(id.dropFirst("console.game.".count))) }
}
@@ -161,7 +162,7 @@ enum ConsoleInput {
.padding(.bottom, 24)
}
}
- if !state.games.isEmpty { hintBar(compact: compact).padding(.horizontal, inset).padding(.bottom, compact ? 20 : 32) }
+ if !state.games.isEmpty { hintBar(compact: compact, width: size.width).padding(.horizontal, inset).padding(.bottom, compact ? 20 : 32) }
}
.padScope("console", pad)
}
@@ -170,9 +171,7 @@ enum ConsoleInput {
/// Its height never changes, so a controller arriving or leaving moves nothing below it.
private func topBar(compact: Bool) -> some View {
HStack(spacing: compact ? 12 : 20) {
- Spacer(minLength: 0)
ConsoleControllerChips(controllers: state.controllers, merged: state.padMerge, lang: lang, compact: compact) { driver.openControllers() }
- .frame(maxWidth: CGFloat(max(1, state.controllers.count)) * (compact ? 120 : 150))
Text(state.time, style: .time).font(.manrope(compact ? 17 : 22, .medium)).monospacedDigit()
.foregroundStyle(.white.opacity(0.65)).fixedSize()
}
@@ -227,7 +226,7 @@ enum ConsoleInput {
}
}
- private func hintBar(compact: Bool) -> some View {
+ private func hintBar(compact: Bool, width: CGFloat) -> some View {
let items = {
Group {
hint(.activate, "console.play", "console.play", primary: true, compact: compact) { if let id = state.focusedGame?.id { driver.play(id) } }
@@ -243,7 +242,7 @@ enum ConsoleInput {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12), count: 2), spacing: 12) { items() }
} else {
// inline glyph and label, the group centered as a whole with even spacing, the active one a cream pill
- HStack(spacing: 44) { items() }.frame(maxWidth: .infinity)
+ HStack(spacing: min(width * 0.12, 220)) { items() }.frame(maxWidth: .infinity) // wide gaps, the group centered as a unit
}
}
}
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index f6ecaad8..014af195 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -2418,7 +2418,6 @@ struct BuilderView: View {
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)
@@ -2867,11 +2866,6 @@ 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() }
diff --git a/frontend/Sources/NSPortBuilder/Gamepad.swift b/frontend/Sources/NSPortBuilder/Gamepad.swift
index bc3ee00c..8bb02bd3 100644
--- a/frontend/Sources/NSPortBuilder/Gamepad.swift
+++ b/frontend/Sources/NSPortBuilder/Gamepad.swift
@@ -1,5 +1,6 @@
import AppKit
import GameController
+import os
/// A game controller drives the launcher, so a Mac on a TV needs no keyboard (PadFocus moves the focus). The buttons are
/// named by what is printed on them, which is how GameController reports them (see `face`): the A button activates, B goes
@@ -10,16 +11,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, home }
+ enum Action: Equatable { case left, right, up, down, a, b, x, y, l, r, plus, select }
@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 }
+ /// `select` is the Select-type button (DualShock Share, DualSense Create, Xbox View, Nintendo Minus): GameController's
+ /// `buttonOptions`. The system does not claim it, so it always reaches the app. The desktop launcher opens console mode with it.
var perform: (Action) -> Void = { _ in }
+ /// Sees every press with the controller it came from before it navigates. Returning true consumes it (the Controllers sheet uses
+ /// this to give the next press to the player being assigned).
+ var capture: ((String, Action) -> Bool)?
/// 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
/// controller and the cross on a DualSense, and a Nintendo-layout controller reports the button printed A (on the right) as
@@ -34,59 +34,73 @@ final class LauncherGamepad: ObservableObject {
default: return nil
}
}
- private var held: Set<String> = [] // edges, not levels: one press, one action
+ /// 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> = []
+ /// 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] = []
+ for (key, down, action) in state {
+ let id = controller + "/" + key
+ if down, !held.contains(id) { held.insert(id); pressed.append(action) }
+ else if !down, held.contains(id) { held.remove(id); released.append(action) }
+ }
+ return (pressed, released)
+ }
+ }
+ private var edges = Edges()
private var observers: [NSObjectProtocol] = []
private var repeatTimer: Timer?
private var repeating: Action?
+ private static let log = Logger(subsystem: "NX2Apple", category: "console.controllers")
init() {
let center = NotificationCenter.default
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() }
+ center.addObserver(forName: $0, object: nil, queue: .main) { [weak self] note in
+ if let pad = note.object as? GCController {
+ 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()
+ }
}
attach()
}
deinit { observers.forEach(NotificationCenter.default.removeObserver); repeatTimer?.invalidate() }
+ /// Every controller GameController lists, wired or wireless, whatever its vendor, drives the launcher: each gets a handler on its
+ /// physical input profile (an extended gamepad is one, so are the simpler ones).
private func attach() {
- let pads = GCController.controllers().compactMap(\.extendedGamepad)
+ let pads = GCController.controllers()
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
+ for pad in pads {
+ let id = String(UInt(bitPattern: ObjectIdentifier(pad).hashValue), radix: 16)
+ pad.physicalInputProfile.valueDidChangeHandler = { [weak self] profile, _ in self?.read(profile, controller: id) }
}
}
- private func read(_ pad: GCExtendedGamepad) {
- let x = pad.dpad.xAxis.value != 0 ? pad.dpad.xAxis.value : pad.leftThumbstick.xAxis.value
- let y = pad.dpad.yAxis.value != 0 ? pad.dpad.yAxis.value : pad.leftThumbstick.yAxis.value
+ private func read(_ pad: GCPhysicalInputProfile, controller: String) {
+ func button(_ name: String) -> Bool { pad.buttons[name]?.isPressed ?? false }
+ let dpad = pad.dpads[GCInputDirectionPad], stick = pad.dpads[GCInputLeftThumbstick]
+ let x = (dpad?.xAxis.value ?? 0) != 0 ? dpad!.xAxis.value : (stick?.xAxis.value ?? 0)
+ let y = (dpad?.yAxis.value ?? 0) != 0 ? dpad!.yAxis.value : (stick?.yAxis.value ?? 0)
let state: [(String, Bool, Action)] = [
("left", x < -0.5, .left), ("right", x > 0.5, .right), ("up", y > 0.5, .up), ("down", y < -0.5, .down),
- ("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), ("home", pad.buttonHome?.isPressed ?? false, .home), // the console mode's options; the desktop ignores it
+ ("a", button(GCInputButtonA), .a), ("b", button(GCInputButtonB), .b), // by label, see `face`
+ ("x", button(GCInputButtonX), .x), ("y", button(GCInputButtonY), .y),
+ ("l", button(GCInputLeftShoulder), .l), ("r", button(GCInputRightShoulder), .r),
+ ("plus", button(GCInputButtonMenu), .plus), ("select", button(GCInputButtonOptions), .select),
]
- for (key, down, action) in state {
- if down, !held.contains(key) {
- held.insert(key)
- DispatchQueue.main.async { self.fire(action) }
- if [.left, .right, .up, .down].contains(action) { DispatchQueue.main.async { self.startRepeat(action) } }
- } else if !down, held.contains(key) {
- held.remove(key)
- DispatchQueue.main.async { if self.repeating == action { self.stopRepeat() } }
+ let (pressed, released) = edges.changes(controller: controller, state: state)
+ for action in pressed {
+ DispatchQueue.main.async {
+ if NSApp.isActive, let capture = self.capture, capture(controller, action) { return }
+ self.fire(action)
+ if [.left, .right, .up, .down].contains(action) { self.startRepeat(action) }
}
}
+ for action in released { DispatchQueue.main.async { if self.repeating == action { self.stopRepeat() } } }
}
private func fire(_ action: Action) { if NSApp.isActive { perform(action) } }
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 9c65c117..c9d1281a 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -151,6 +151,7 @@ struct ContentView: View {
.frame(minWidth: 900, idealWidth: 1280, minHeight: 680, idealHeight: 900)
.onAppear {
gamepad.perform = padAction
+ gamepad.capture = { [consoleDriver] id, action in consoleDriver.consumePress(controllerID: id, isBack: action == .b) }
if performStartupChecks { library.migrateLaunchOptions() }
if qaManage.open {
if qaManage.ring { padFocus.show(default: nil) }
@@ -610,9 +611,7 @@ 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) }
+ if enterConsole != nil { padHint(.select, m.t("console.entry")) }
}
}
}
@@ -661,8 +660,8 @@ 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() }
+ if action == .select { // the controller's Select-type button opens console mode
+ if let enterConsole { consolePrompt = false; enterConsole() }
return
}
if consolePrompt {
@@ -715,7 +714,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, .home: // Y is the Manage menu: ManagePad.route opened it above
+ case .y, .plus, .select: // 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 92d64772..4163e38b 100644
--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
@@ -27,12 +27,13 @@ struct ConsolePadSnapshot: Equatable {
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.
+ /// DualShock 4 over Bluetooth and before the first report, and some pads over USB report no battery or an unknown one: those are
+ /// never guessed (no number, outline only). Charging and full are real states, shown with the bolt.
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 .charging: return (level.isFinite ? min(max(level, 0), 1) : nil, true) // the real level, with the bolt
+ case .full: return (1, true) // plugged in and full: the full battery with the bolt
case .discharging: return (level.isFinite ? min(max(level, 0), 1) : nil, false)
}
}
@@ -277,21 +278,75 @@ struct ConsolePadSnapshot: Equatable {
// MARK: Controllers
func openControllers() { state.openControllers() }
+
+ private var overrides: [String: Int] = [:] // player chosen by hand per controller id, 0 for none
+ private var assignTimeout: Task<Void, Never>?
+
+ /// Picking a player turns "all controllers are player 1" off: a per-player choice means nothing while it is on.
+ private func leaveMergeForAssignment() {
+ guard state.padMerge else { return }
+ controls.padMerge = false
+ state.padMerge = false
+ showToast(t("console.mergeOff"))
+ }
+
+ /// The next press from any controller is taken as the answer, for 8 seconds.
+ private func startCapture() {
+ assignTimeout?.cancel()
+ assignTimeout = Task { [weak self] in
+ try? await Task.sleep(nanoseconds: UInt64((self?.captureSeconds ?? 8) * 1_000_000_000))
+ guard !Task.isCancelled, let self, self.state.assigningPlayer != nil else { return }
+ self.cancelCapture()
+ self.showToast(self.t("console.assignTimeout"))
+ }
+ }
+ var captureSeconds: TimeInterval = 8
+
+ private func cancelCapture() {
+ assignTimeout?.cancel()
+ state.assigningPlayer = nil
+ state.assigningControllerID = nil
+ }
+
func requestPlayer(_ player: Int) {
guard state.presentedSheet == .controllers, (1...4).contains(player) else { return }
+ leaveMergeForAssignment()
state.assigningPlayer = player
+ startCapture()
}
func requestAssignment(controllerID: String) {
guard state.presentedSheet == .controllers, let c = state.controllers.first(where: { $0.id == controllerID }) else { return }
+ leaveMergeForAssignment()
state.assigningControllerID = controllerID
state.assigningPlayer = state.assigningPlayer ?? c.player ?? 1
+ startCapture()
}
+
+ /// While a player is being assigned, the next button press is the answer: it goes to the controller it came from and is not
+ /// used to navigate. B on the controller that is assigning cancels. Presses from the other controller while one is chosen by
+ /// hand are taken and ignored.
+ func consumePress(controllerID: String, isBack: Bool) -> Bool {
+ guard let player = state.assigningPlayer, state.presentedSheet == .controllers else { return false }
+ if let target = state.assigningControllerID, target != controllerID { return true }
+ if isBack { cancelCapture(); showToast(t("console.assignCancelled")); return true }
+ assignPlayer(controllerID: controllerID, player: player)
+ return true
+ }
+
+ /// The controller takes the player. Whoever held that player gets the number this controller had (or the next free one), and the
+ /// controller's own player lights follow.
func assignPlayer(controllerID: String, player: Int) {
- state.assignPlayer(controller: controllerID, player: player)
- guard let pad = devices[controllerID] else { return }
- for other in devices.values where other !== pad && other.playerIndex.rawValue == player - 1 { other.playerIndex = .indexUnset }
- pad.playerIndex = GCControllerPlayerIndex(rawValue: player - 1) ?? .indexUnset
+ guard (1...4).contains(player), let pad = state.controllers.first(where: { $0.id == controllerID }) else { return }
+ let old = pad.player
+ if let holder = state.controllers.first(where: { $0.player == player && $0.id != controllerID }) { overrides[holder.id] = old ?? 0 }
+ overrides[controllerID] = player
+ state.assigningPlayer = nil; state.assigningControllerID = nil
+ assignTimeout?.cancel()
+ for (id, value) in overrides {
+ devices[id]?.playerIndex = value == 0 ? .indexUnset : (GCControllerPlayerIndex(rawValue: value - 1) ?? .indexUnset)
+ }
refreshControllers(announce: false)
+ showToast(String(format: t("console.assignedTo"), pad.name, player))
}
func setPadMerge(_ enabled: Bool) { controls.padMerge = enabled }
@@ -360,9 +415,16 @@ struct ConsolePadSnapshot: Equatable {
}
}
+ /// A controller connected or disconnected: the list is rebuilt and published at once (not at the next battery tick), 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.
func padsChanged(connected: Bool, note: Notification) {
- refreshControllers(announce: false)
- guard let pad = note.object as? GCController else { return }
+ let pad = note.object as? GCController
+ if let pad {
+ Self.log.debug("\(connected ? "connect" : "disconnect"): vendor \(pad.vendorName ?? "?", privacy: .public), category \(pad.productCategory, privacy: .public), extendedGamepad \(pad.extendedGamepad != nil)")
+ }
+ refreshControllers(announce: false, including: connected ? pad : nil, excluding: connected ? nil : pad)
+ guard let pad else { return }
let name = pad.vendorName ?? pad.productCategory
guard connected else { showToast(String(format: t("console.disconnected"), name)); return }
let id = String(UInt(bitPattern: ObjectIdentifier(pad).hashValue), radix: 16)
@@ -371,12 +433,13 @@ struct ConsolePadSnapshot: Equatable {
} else { showToast(t("console.noFreePlayer"), glyph: ConsoleGlyphs.current().glyph(for: .controllers)) }
}
- func refreshControllers(announce: Bool) {
+ func refreshControllers(announce: Bool, including: GCController? = nil, excluding: GCController? = nil) {
var snapshots = pads()
if devicePads {
devices = [:]
- snapshots = GCController.controllers().compactMap { c in
- guard c.extendedGamepad != nil else { return nil }
+ 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
let id = String(UInt(bitPattern: ObjectIdentifier(c).hashValue), radix: 16)
devices[id] = c
let reading = c.battery.map { b -> (level: Double?, charging: Bool) in
@@ -389,6 +452,13 @@ struct ConsolePadSnapshot: Equatable {
charging: reading?.charging ?? false, canIdentify: !Self.identifyActions(c).isEmpty)
}
}
+ let live = Set(snapshots.map(\.id))
+ overrides = overrides.filter { live.contains($0.key) }
+ snapshots = snapshots.map { snap in
+ guard let chosen = overrides[snap.id] else { return snap }
+ var s = snap; s.playerIndex = chosen == 0 ? nil : chosen
+ return 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
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 2cc440f4..cdcb9802 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -161,12 +161,14 @@ 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.promptSelectBefore": ("\u{968f}\u{65f6}\u{6309}", "Press"),
+ "console.promptSelectAfter": ("\u{952e}\u{5373}\u{53ef}\u{5207}\u{6362}\u{3002}", "anytime to switch."),
+ "console.mergeOff": ("\u{73b0}\u{5728}\u{6bcf}\u{4e2a}\u{624b}\u{67c4}\u{5404}\u{662f}\u{4e00}\u{4f4d}\u{73a9}\u{5bb6}\u{3002}", "Each controller is now its own player."),
+ "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.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 3aa4c72b..8ce1f4b4 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, .home: return .swallow
+ case .x, .y, .l, .r, .plus, .select: 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 81618ea0..18ab576c 100644
--- a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
@@ -220,8 +220,14 @@ import SwiftUI
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)
+ XCTAssertEqual(ConsolePadSnapshot.batteryReading(level: 0, state: .charging).level, 0, "charging reports its real level, even a low one")
+ let full = ConsolePadSnapshot.batteryReading(level: 0, state: .full)
+ XCTAssertEqual(full.level, 1, "full: the full battery")
+ XCTAssertTrue(full.charging, "with the bolt")
+ let topped = ConsolePadSnapshot.batteryReading(level: 1.0, state: .charging)
+ XCTAssertEqual(topped.level, 1)
+ XCTAssertTrue(topped.charging)
+ XCTAssertNil(ConsolePadSnapshot.batteryReading(level: 1, state: .unknown).level, "no guess of full for a pad that reports no state")
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%")
@@ -238,13 +244,116 @@ import SwiftUI
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"))
+ func testSelectButtonGlyphAndInput() {
+ XCTAssertNil(ConsoleInput(.select), "in console mode Select does nothing special")
+ XCTAssertEqual(ConsoleGlyphs.Role.select.element, .select)
+ XCTAssertEqual(ConsoleGlyphs(family: .playStation, reported: [.select: "square.and.arrow.up"]).glyph(for: .select), .symbol("square.and.arrow.up"), "the controller's own symbol")
+ for family in [ConsoleGlyphs.Family.xbox, .playStation, .nintendo, .neutral] {
+ XCTAssertEqual(ConsoleGlyphs(family: family).glyph(for: .select), .symbol("minus.circle"), "\(family) reporting nothing")
+ }
+ XCTAssertEqual(ConsoleGlyphs.keyboard.glyph(for: .select), .key("\u{2325}\u{2318}K"))
+ }
+
+ /// Two fake controllers connecting one after the other: each is published as soon as the connect notification arrives and takes
+ /// the next free player, in connection order.
+ func testConnectNotificationPublishesTheNewControllerAtOnce() async throws {
+ var current = [ConsolePadSnapshot(id: "first", name: "First", category: "DualShock 4", playerIndex: nil)]
+ let library = GameLibrary(file: temporary.appendingPathComponent("library.json"))
+ let driver = LiveConsoleDriver(library: library, controls: ControlLayout(defaults: UserDefaults(suiteName: "ConsoleLiveTests-" + UUID().uuidString)!),
+ repo: { "" }, lang: { .en }, labels: { $0 }, pads: { current }, artwork: { _, _ in nil }, observeSystem: true)
+ 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))
+ NotificationCenter.default.post(name: .GCControllerDidConnect, object: nil)
+ for _ in 0..<50 where driver.state.controllers.count < 2 { try await Task.sleep(nanoseconds: 20_000_000) }
+ XCTAssertEqual(driver.state.controllers.map(\.id), ["first", "second"], "published at once, not at the next tick")
+ XCTAssertEqual(driver.state.controllers.map(\.player), [1, 2])
+ current.removeFirst()
+ NotificationCenter.default.post(name: .GCControllerDidDisconnect, object: nil)
+ for _ in 0..<50 where driver.state.controllers.count > 1 { try await Task.sleep(nanoseconds: 20_000_000) }
+ XCTAssertEqual(driver.state.controllers.map(\.id), ["second"])
+ }
+
+ func testInputFromASecondControllerIsNotHiddenByTheFirst() {
+ var edges = LauncherGamepad.Edges()
+ XCTAssertEqual(edges.changes(controller: "one", state: [("a", true, .a)]).pressed, [.a])
+ XCTAssertEqual(edges.changes(controller: "one", state: [("a", true, .a)]).pressed, [], "held on the same controller: no repeat")
+ XCTAssertEqual(edges.changes(controller: "two", state: [("a", true, .a)]).pressed, [.a], "the same button on another controller still counts")
+ XCTAssertEqual(edges.changes(controller: "one", state: [("a", false, .a)]).released, [.a])
+ XCTAssertEqual(edges.changes(controller: "two", state: [("select", true, .select)]).pressed, [.select])
+ }
+
+ func testBatteryFillStaysInsideTheOutline() {
+ for height: CGFloat in [10, 12, 13, 16] {
+ for level in [0, 0.12, 0.65, 1.0] as [Double] {
+ let g = BatteryIcon.geometry(height: height, level: level)
+ XCTAssertTrue(g.inner.contains(g.fill) || g.fill.width == 0, "height \(height) level \(level): \(g.fill) in \(g.inner)")
+ XCTAssertTrue(g.outer.contains(g.inner))
+ XCTAssertEqual(g.inner.minX - g.outer.minX, 2, "the stroke and a 1 point gap on every side")
+ XCTAssertEqual(g.outer.maxY - g.inner.maxY, 2)
+ XCTAssertEqual(g.fill.minX, g.inner.minX, "leading-aligned")
+ XCTAssertLessThanOrEqual(g.fill.width, g.inner.width)
+ XCTAssertGreaterThanOrEqual(g.nub.minX, g.outer.maxX, "the nub sits outside the body, to the right")
+ XCTAssertEqual(g.innerRadius, max(0, g.outerRadius - 2))
+ XCTAssertEqual(g.fill.width * 2, (g.fill.width * 2).rounded(), "snapped to whole pixels at 2x")
+ }
+ }
+ let half = BatteryIcon.geometry(height: 12, level: 0.5)
+ XCTAssertEqual(half.fill.width, (half.inner.width * 0.5 * 2).rounded() / 2)
+ XCTAssertEqual(BatteryIcon.geometry(height: 12, level: nil).fill.width, 0)
+ }
+
+ // MARK: Player assignment
+
+ private func twoPadDriver(merge: Bool) -> (LiveConsoleDriver, ControlLayout) {
+ let layout = ControlLayout(defaults: UserDefaults(suiteName: "ConsoleLiveTests-" + UUID().uuidString)!)
+ layout.padMerge = merge
+ let pads = [ConsolePadSnapshot(id: "xbox", name: "Xbox Wireless Controller", category: "Xbox One", playerIndex: nil),
+ ConsolePadSnapshot(id: "ds4", name: "DUALSHOCK 4", category: "DualShock 4", playerIndex: nil)]
+ let driver = LiveConsoleDriver(library: GameLibrary(file: temporary.appendingPathComponent("library.json")), controls: layout, repo: { "" }, lang: { .en },
+ labels: { $0 }, pads: { pads }, artwork: { _, _ in nil }, observeSystem: false)
+ driver.captureSeconds = 0.2
+ driver.openControllers()
+ return (driver, layout)
+ }
+
+ func testPickingAPlayerTurnsMergeOffAndTheNextPressAssignsIt() {
+ let (driver, layout) = twoPadDriver(merge: true)
+ XCTAssertEqual(driver.state.controllers.map(\.player), [1, 2], "assigned on connect whatever the merge")
+ driver.requestPlayer(2)
+ XCTAssertFalse(layout.padMerge, "merge is switched off by choosing a player")
+ XCTAssertFalse(driver.state.padMerge)
+ XCTAssertEqual(driver.state.toast?.message, "Each controller is now its own player.")
+ XCTAssertEqual(driver.state.assigningPlayer, 2)
+ // a press from the first controller: taken as the answer, never used to navigate
+ XCTAssertTrue(driver.consumePress(controllerID: "xbox", isBack: false))
+ XCTAssertEqual(driver.state.controllers.map(\.player), [2, 1], "the pressed one is P2, the holder of P2 got the freed P1")
+ XCTAssertNil(driver.state.assigningPlayer, "capture ended")
+ XCTAssertEqual(driver.state.toast?.message, "Xbox Wireless Controller is player 2")
+ XCTAssertFalse(driver.consumePress(controllerID: "ds4", isBack: false), "no capture any more: the press navigates")
+ }
+
+ func testBackCancelsAssignmentAndPressesFromTheOtherControllerAreIgnoredForARow() {
+ let (driver, _) = twoPadDriver(merge: false)
+ driver.requestPlayer(3)
+ XCTAssertTrue(driver.consumePress(controllerID: "ds4", isBack: true))
+ XCTAssertNil(driver.state.assigningPlayer)
+ XCTAssertEqual(driver.state.controllers.map(\.player), [1, 2], "nothing changed")
+ driver.requestAssignment(controllerID: "ds4")
+ XCTAssertTrue(driver.consumePress(controllerID: "xbox", isBack: false), "taken but ignored: the row chose the other controller")
+ XCTAssertEqual(driver.state.controllers.map(\.player), [1, 2])
+ XCTAssertNotNil(driver.state.assigningPlayer)
+ XCTAssertTrue(driver.consumePress(controllerID: "ds4", isBack: false))
+ XCTAssertEqual(driver.state.controllers.first { $0.id == "ds4" }?.player, 2, "the row's own player")
+ }
+
+ func testAssignmentTimesOut() async throws {
+ let (driver, _) = twoPadDriver(merge: false)
+ driver.requestPlayer(4)
+ XCTAssertNotNil(driver.state.assigningPlayer)
+ for _ in 0..<50 where driver.state.assigningPlayer != nil { try await Task.sleep(nanoseconds: 20_000_000) }
+ XCTAssertNil(driver.state.assigningPlayer)
+ XCTAssertEqual(driver.state.toast?.message, "No button was pressed. Choose a player to try again.")
+ XCTAssertEqual(driver.state.controllers.map(\.player), [1, 2])
}
}
diff --git a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
index b05008bc..ed3473a0 100644
--- a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
@@ -95,9 +95,10 @@ 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), ("options", .full, .xbox), ("empty", .empty, .xbox), ("starting", .starting, .xbox)] {
+ ("controllers", .controllersMixed, .xbox), ("home-4pads", .controllersMixed, .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() }
let host = NSHostingView(rootView: ConsoleView(driver: driver, lang: .en, glyphs: .init(family: family)).transaction { $0.disablesAnimations = true }.frame(width: width, height: height))
let window = NSWindow(contentRect: NSRect(x: -10000, y: 0, width: width, height: height), styleMask: [.borderless], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false