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 is usable: live driver, entry points, desktop glyphs, battery icon, layout fixes

v0lumehib0ae5f1e6491
diff --git a/frontend/Console.md b/frontend/Console.md
index 943b7865..52e13c97 100644
--- a/frontend/Console.md
+++ b/frontend/Console.md
@@ -77,4 +77,10 @@ Validation on 2026-10-28: release build passed. The complete frontend suite pass
`ConsoleView` takes the launcher's `LauncherGamepad` (Gamepad.swift), like the onboarding, and maps its actions with `ConsoleInput(_:)`: the D-pad and left stick move, A activates, B backs out, + and X open game options, Y opens Controllers. L and R are unused. `ConsoleGlyphs` resolves each action to the physical button Gamepad.swift reads and shows what the controller last used prints there (Apple's `sfSymbolsName`, a per-family table as fallback, key caps after the keyboard, a neutral letter otherwise). The Controls page layout (By label) only changes what a game receives, so it does not move these glyphs.
-"All controllers are player 1" is a launcher setting (off by default, `ControlLayout.padMerge` in UserDefaults). Play passes `DM_PAD_MERGE=1` with the Controls environment. It is in Settings and in the Controllers sheet. The console entry button and the controller strip stay hidden until the coordinator supplies `enterConsole` and a real driver.
+"All controllers are player 1" is a launcher setting (off by default, `ControlLayout.padMerge` in UserDefaults). Play passes `DM_PAD_MERGE=1` with the Controls environment. It is in Settings and in the Controllers sheet.
+## Using it
+
+`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`.
+
diff --git a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
index 86b5e478..20b6df0d 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift
@@ -28,18 +28,63 @@ import Combine
func returnFromGame() { base.returnFromGame() }
}
+/// 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
+/// or less, a bolt over it while charging, the outline alone when the level is unknown.
+struct BatteryIcon: View {
+ /// 0...1, nil when the controller reports none.
+ let level: Double?
+ var charging = false
+ var height: CGFloat = 12
+
+ /// The fill's share of the inner width: the level, clamped to 0...1 (a non-finite level counts as empty).
+ static func fillFraction(_ level: Double?) -> Double {
+ guard let level, level.isFinite else { return 0 }
+ return min(max(level, 0), 1)
+ }
+ static func isLow(_ level: Double?) -> Bool { level.map { fillFraction($0) <= 0.2 } ?? false }
+
+ 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)
+ }
+ }
+ .frame(width: width, height: height)
+ Capsule().fill(.white.opacity(level == nil ? 0.3 : 0.55)).frame(width: 1.5, height: height * 0.36)
+ }
+ .accessibilityHidden(true)
+ }
+}
+
struct ConsoleBattery: View {
let controller: ConsoleController
let lang: Lang
var compact = false
var body: some View {
if let percent = controller.batteryPercent {
- Label(String(format: L10n.string("console.batteryPercent", lang), percent), systemImage: controller.charging ? "battery.100percent.bolt" : percent <= 20 ? "battery.25percent" : percent <= 50 ? "battery.50percent" : "battery.100percent")
- .font(.manrope(compact ? 11 : 16, .medium))
- .foregroundStyle(percent <= 20 && !controller.charging ? LauncherPalette.building : .white.opacity(0.7))
- .accessibilityLabel(String(format: L10n.string(controller.charging ? "console.batteryCharging" : "console.batteryLevel", lang), percent))
+ HStack(spacing: 5) {
+ BatteryIcon(level: controller.battery, charging: controller.charging, height: compact ? 10 : 13)
+ Text(String(format: L10n.string("console.batteryPercent", lang), percent))
+ }
+ .font(.manrope(compact ? 11 : 16, .medium))
+ .foregroundStyle(BatteryIcon.isLow(controller.battery) && !controller.charging ? Color.red : .white.opacity(0.7))
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(String(format: L10n.string(controller.charging ? "console.batteryCharging" : "console.batteryLevel", lang), percent))
} else if controller.charging {
- Image(systemName: "bolt.fill").accessibilityLabel(L10n.string("console.charging", lang))
+ HStack(spacing: 5) { BatteryIcon(level: nil, charging: true, height: compact ? 10 : 13) }
+ .accessibilityElement(children: .ignore).accessibilityLabel(L10n.string("console.charging", lang))
}
}
}
diff --git a/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift b/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift
new file mode 100644
index 00000000..d11e180d
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/ConsoleCoordinator.swift
@@ -0,0 +1,44 @@
+import SwiftUI
+import AppKit
+
+/// Enters and leaves the console mode: the window content switches (RootView) and the window goes full screen for the mode, then
+/// back to what it was. A window that was already full screen is left that way.
+@MainActor final class ConsoleCoordinator: ObservableObject {
+ @Published private(set) var active = false
+ /// The launcher is showing (not the guided setup), so the mode can be entered.
+ @Published var available = false
+ private var enteredFullScreen = false
+ private let window: () -> NSWindow?
+ private let setFullScreen: (NSWindow, Bool) -> Void
+
+ init(window: @escaping () -> NSWindow? = { NSApp.keyWindow ?? NSApp.windows.first { $0.canBecomeMain } },
+ setFullScreen: @escaping (NSWindow, Bool) -> Void = { w, _ in w.toggleFullScreen(nil) }) {
+ self.window = window
+ self.setFullScreen = setFullScreen
+ }
+
+ func enter() {
+ guard available, !active else { return }
+ active = true
+ if let w = window(), !w.styleMask.contains(.fullScreen) { enteredFullScreen = true; setFullScreen(w, true) }
+ }
+
+ func exit() {
+ guard active else { return }
+ active = false
+ if enteredFullScreen, let w = window(), w.styleMask.contains(.fullScreen) { setFullScreen(w, false) }
+ enteredFullScreen = false
+ }
+
+ func toggle() { active ? exit() : enter() }
+}
+
+/// The controller-connect prompt: once per session, and never when the player turned it off in Settings.
+enum ConsolePrompt {
+ static let defaultsKey = "consolePrompt"
+ private(set) static var shownThisSession = false
+ static var enabled: Bool { UserDefaults.standard.object(forKey: defaultsKey) as? Bool ?? true }
+ static func shouldShow(enabled: Bool, shown: Bool) -> Bool { enabled && !shown }
+ static func didShow() { shownThisSession = true }
+ static func resetSessionForTests() { shownThisSession = false }
+}
diff --git a/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
index 05ea23f2..c8956733 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift
@@ -8,8 +8,8 @@ struct ConsoleEntryButton: View {
var body: some View {
Button(action: enterConsole) {
Group {
- if compact { Image(systemName: "tv") }
- else { Label(L10n.string("console.entry", lang), systemImage: "tv") }
+ if compact { Image(systemName: "gamecontroller") }
+ else { Label(L10n.string("console.entry", lang), systemImage: "gamecontroller") }
}
.font(.manrope(13, .semibold)).padding(.horizontal, 12).padding(.vertical, 8)
.background(.white.opacity(0.07), in: Capsule()).contentShape(Capsule())
diff --git a/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift b/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift
index aeef1b89..7d938604 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleGlyphs.swift
@@ -25,12 +25,15 @@ struct ConsoleGlyphs: Equatable {
enum Element: Hashable { case a, b, x, y, menu }
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
var element: Element {
switch self {
case .activate: return Self.element(of: .a)
case .back: return Self.element(of: .b)
case .options: return .menu
- case .controllers: return Self.element(of: .y)
+ case .controllers, .manage: return Self.element(of: .y)
+ case .launchOptions: return Self.element(of: .x)
}
}
/// The element that performs a launcher action, taken from the one mapping Gamepad.swift reads, so glyph and button cannot differ.
@@ -43,14 +46,14 @@ struct ConsoleGlyphs: Equatable {
}
}
var keyCap: String {
- switch self { case .activate: return "return"; case .back: return "escape"; case .options: return "O"; case .controllers: return "Y" }
+ switch self { case .activate: return "return"; case .back: return "escape"; case .options, .launchOptions: return "O"; case .controllers, .manage: return "Y" }
}
/// 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; case .options, .controllers: return false }
+ 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 .controllers: return "Y" }
+ switch self { case .activate: return "A"; case .back: return "B"; case .options: return "+"; case .launchOptions: return "X"; case .controllers, .manage: return "Y" }
}
}
enum Glyph: Equatable { case symbol(String), key(String), keySymbol(String), letter(String) }
diff --git a/frontend/Sources/NSPortBuilder/ConsoleView.swift b/frontend/Sources/NSPortBuilder/ConsoleView.swift
index 0a2d1bd0..df681f48 100644
--- a/frontend/Sources/NSPortBuilder/ConsoleView.swift
+++ b/frontend/Sources/NSPortBuilder/ConsoleView.swift
@@ -26,13 +26,17 @@ enum ConsoleInput {
@ObservedObject var driver: Driver
var lang: Lang = .initial()
var inputs: AnyPublisher<ConsoleInput, Never> = Empty().eraseToAnyPublisher()
+ /// Set by the real launcher: leaving the mode calls it instead of showing the preview's "Back on desktop" screen.
+ var onExit: (() -> Void)?
@StateObject private var pad = PadFocus()
@StateObject private var gamepad: LauncherGamepad
+ @State private var tileFrames: [String: CGRect] = [:]
/// The glyph set follows the input used last: a controller's own buttons, or key caps after the keyboard.
@State private var glyphs: ConsoleGlyphs
/// `gamepad` is the one the root view owns (the controller has a single handler, so two would fight); without one the view makes its own.
- init(driver: Driver, lang: Lang = .initial(), inputs: AnyPublisher<ConsoleInput, Never> = Empty().eraseToAnyPublisher(), gamepad: LauncherGamepad? = nil, glyphs: ConsoleGlyphs? = nil) {
+ init(driver: Driver, lang: Lang = .initial(), inputs: AnyPublisher<ConsoleInput, Never> = Empty().eraseToAnyPublisher(), gamepad: LauncherGamepad? = nil, glyphs: ConsoleGlyphs? = nil, onExit: (() -> Void)? = nil) {
+ self.onExit = onExit
_glyphs = State(initialValue: glyphs ?? .current())
self.driver = driver
self.lang = lang
@@ -85,7 +89,7 @@ enum ConsoleInput {
.background(ConsoleKeyboardInput(perform: { input in glyphs = .keyboard; handle(input) }).frame(width: 0, height: 0))
.onReceive(inputs, perform: handle)
.onChange(of: scope) { _ in resetFocus() }
- .onChange(of: state.exited) { _ 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 } }
.onChange(of: pad.focused) { id in
@@ -175,6 +179,12 @@ enum ConsoleInput {
.frame(height: compact ? 40 : 52)
}
+ /// A caption shows only while its tile is fully inside the row, so a clipped tile never leaves a fragment of text at the margin.
+ private func tileVisible(_ id: String, rowWidth: CGFloat) -> Bool {
+ guard let frame = tileFrames[id] else { return true }
+ return frame.minX >= -1 && frame.maxX <= rowWidth + 1
+ }
+
private func gameRow(size: CGSize, compact: Bool, inset: CGFloat) -> some View {
let width: CGFloat = compact ? size.width - inset * 2 - 16 : min(470, size.width * 0.32)
return ScrollViewReader { proxy in
@@ -183,14 +193,16 @@ enum ConsoleInput {
ForEach(state.games) { game in
let selected = state.focusedGame?.id == game.id
Button { driver.focus(game.id); driver.play(game.id) } label: {
- ConsoleGameTile(game: game, selected: selected, compact: compact, lang: lang)
+ ConsoleGameTile(game: game, selected: selected, compact: compact, lang: lang, captionVisible: tileVisible(game.id, rowWidth: size.width - 2 * (inset - 8)))
.frame(width: width)
- .scaleEffect(selected && !reduceMotion ? 1.025 : 1)
- .animation(.easeOut(duration: 0.15), value: selected)
- .contentShape(RoundedRectangle(cornerRadius: 18))
+ .contentShape(RoundedRectangle(cornerRadius: 16))
}
.buttonStyle(.plain)
.padTarget("console.game." + game.id, scope: "console", radius: 16, activate: { driver.play(game.id) })
+ // the focus scale is applied to the button with its ring, so the ring frames the image flush at any scale
+ .scaleEffect(selected && !reduceMotion ? 1.025 : 1)
+ .animation(.easeOut(duration: 0.15), value: selected)
+ .background(GeometryReader { g in Color.clear.preference(key: ConsoleTileFramesKey.self, value: [game.id: g.frame(in: .named("console.row"))]) })
.accessibilityLabel(game.title + ", " + t(game.status.labelKey))
.accessibilityHint(t("console.playHint"))
.accessibilityAddTraits(selected ? .isSelected : [])
@@ -198,6 +210,8 @@ enum ConsoleInput {
}
.padding(.horizontal, 8).padding(.vertical, 12) // room for the focused tile's small scale inside the clip
}
+ .coordinateSpace(name: "console.row")
+ .onPreferenceChange(ConsoleTileFramesKey.self) { tileFrames = $0 }
.padding(.horizontal, inset - 8) // the scroll area is the page margin, so tiles clip there and the title lines up with the first tile
.onChange(of: state.focusedGame?.id) { id in
// a new focus replaces the running scroll, it does not queue
@@ -208,10 +222,11 @@ enum ConsoleInput {
}
private func hintBar(compact: Bool) -> some View {
- let columns = compact ? [GridItem(.flexible()), GridItem(.flexible())] : Array(repeating: GridItem(.flexible(), alignment: .leading), count: 4)
+ // Equal-width slots between the page margins, every item the same pill and centered in its slot (two by two when compact).
+ let columns = Array(repeating: GridItem(.flexible(), spacing: compact ? 12 : 20), count: compact ? 2 : 4)
return VStack(spacing: 20) {
Rectangle().fill(.white.opacity(0.10)).frame(height: 1)
- LazyVGrid(columns: columns, alignment: .leading, spacing: 16) {
+ LazyVGrid(columns: columns, spacing: compact ? 12 : 16) {
hint(.activate, "console.play", "console.play", primary: true, compact: compact) { if let id = state.focusedGame?.id { driver.play(id) } }
hint(.options, "console.options", "console.options", compact: compact) { if let id = state.focusedGame?.id { driver.openOptions(id) } }
hint(.controllers, "console.controllers", "console.controllers", compact: compact) { driver.openControllers() }
@@ -222,11 +237,11 @@ enum ConsoleInput {
private func hint(_ role: ConsoleGlyphs.Role, _ key: String, _ id: String, primary: Bool = false, compact: Bool, action: @escaping () -> Void) -> some View {
Button(action: action) {
- HStack(spacing: 10) { ConsoleGlyphView(glyph: glyphs.glyph(for: role), size: compact ? 20 : 24); Text(t(key)) }
+ HStack(alignment: .center, spacing: 10) { ConsoleGlyphView(glyph: glyphs.glyph(for: role), size: compact ? 20 : 24); Text(t(key)).lineLimit(1).minimumScaleFactor(0.8) }
.font(.manrope(compact ? 15 : 20, .semibold))
- .padding(.horizontal, primary ? 20 : 4).frame(minHeight: 48)
+ .padding(.horizontal, 12).frame(maxWidth: .infinity, minHeight: 48)
.foregroundStyle(primary ? LauncherPalette.background : .white.opacity(0.8))
- .background(primary ? LauncherPalette.cream : .clear, in: Capsule())
+ .background(primary ? LauncherPalette.cream : .white.opacity(0.07), in: Capsule())
.contentShape(Capsule())
}
.buttonStyle(.plain).padTarget(id, scope: "console", radius: 28, activate: action)
@@ -335,8 +350,7 @@ enum ConsoleInput {
private func starting(_ game: ConsoleGame, compact: Bool) -> some View {
VStack(spacing: 30) {
- ConsoleArtwork(image: game.artwork, title: game.title).aspectRatio(1.8, contentMode: .fit).frame(maxWidth: compact ? 320 : 680)
- .clipShape(RoundedRectangle(cornerRadius: 22)).accessibilityHidden(true)
+ // The only image is the blurred cover behind (backdrop). The text and the bar sit in the middle of the screen.
Text(String(format: t("console.starting"), game.title)).font(.manrope(compact ? 30 : 48, .bold))
.multilineTextAlignment(.center).accessibilityAddTraits(.isHeader)
VStack(spacing: 16) {
@@ -449,11 +463,17 @@ struct ConsoleArtwork: View {
}
}
+private struct ConsoleTileFramesKey: PreferenceKey {
+ static var defaultValue: [String: CGRect] = [:]
+ static func reduce(value: inout [String: CGRect], nextValue: () -> [String: CGRect]) { value.merge(nextValue()) { _, new in new } }
+}
+
struct ConsoleGameTile: View {
let game: ConsoleGame
let selected: Bool
let compact: Bool
let lang: Lang
+ var captionVisible = true
var body: some View {
VStack(alignment: .leading, spacing: 12) {
ConsoleArtwork(image: game.artwork, title: game.title).aspectRatio(1.8, contentMode: .fit)
@@ -469,7 +489,7 @@ struct ConsoleGameTile: View {
// The focused game's name is the big title above, so its tile shows the image alone (the row is top-aligned, so
// nothing else moves). The others keep a small, muted caption.
if !selected {
- Text(game.title).font(.manrope(compact ? 14 : 17, .medium)).lineLimit(1)
+ Text(game.title).opacity(captionVisible ? 1 : 0).font(.manrope(compact ? 14 : 17, .medium)).lineLimit(1)
.foregroundStyle(.white.opacity(0.5)).padding(.horizontal, 4).accessibilityHidden(true)
}
}
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index c0356a35..0c02a3f2 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -2420,6 +2420,7 @@ struct BuilderView: View {
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)
+ @AppStorage(ConsolePrompt.defaultsKey) private var consolePromptOn = true // ConsoleCoordinator.swift
@AppStorage(BuildNotice.defaultsKey) private var notifyBuilds = true // BuildNotifications.swift
@State private var extrasOpen = false
@State private var logOpen = false
@@ -2863,6 +2864,11 @@ struct BuilderView: View {
Toggle("", isOn: padMerge).labelsHidden().toggleStyle(LauncherSwitchStyle())
.padTarget("set.padMerge", scope: "main") { padMerge.wrappedValue.toggle() }
}
+ divider
+ row(m.t("console.promptSetting"), detail: m.t("console.promptSettingNote")) {
+ Toggle("", isOn: $consolePromptOn).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ .padTarget("set.consolePrompt", scope: "main") { consolePromptOn.toggle() }
+ }
}
tools
group(m.t("section.app"), footnote: m.appStatus) {
diff --git a/frontend/Sources/NSPortBuilder/GameStart.swift b/frontend/Sources/NSPortBuilder/GameStart.swift
new file mode 100644
index 00000000..94424596
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/GameStart.swift
@@ -0,0 +1,16 @@
+import Foundation
+
+/// What Play starts a Mac game with, in one place: the desktop launcher's Play button and the console mode both use it, so a
+/// game gets the same environment from either (the saved choices for an app that does not read them itself, the mods, the Controls
+/// page's layout, DM_PAD_MERGE, and DM_LAUNCHER=0).
+enum GameStart {
+ @MainActor static func environment(for game: LibraryGame, library: GameLibrary, controls: ControlLayout, repo: String,
+ labels: (String) -> String) -> [String: String] {
+ library.migrateLaunchOptions()
+ let settings = LaunchSetting.forMac(app: game.appPath, titleID: game.titleID, repo: repo, labels: labels) ?? []
+ let mods = GameMod.list(in: GameMod.folder(for: game, library: library.folder), titleID: game.titleID)
+ return game.startEnvironment(controls: controls.environment, settings: settings, mods: mods,
+ store: SavedChoices(app: game.appPath, titleID: game.titleID),
+ appReadsStore: SavedChoices.appReadsStore(app: game.appPath))
+ }
+}
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 34c2e702..031e3724 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -57,9 +57,9 @@ struct ContentView: View {
init(model: BuildModel? = nil, library: GameLibrary? = nil, initialPage: LauncherPage = .library,
activeBuildID: UUID? = nil, performStartupChecks: Bool = true, search: String? = nil, olderTools: Set<UUID> = [],
manageOpen: Bool = false, padRing: Bool = false, onRunSetup: (() -> Void)? = nil,
- enterConsole: (() -> Void)? = nil, controllerDriver: AnyConsoleDriver? = nil) {
+ enterConsole: (() -> Void)? = nil, controllerDriver: AnyConsoleDriver? = nil, controls sharedControls: ControlLayout? = nil) {
self.onRunSetup = onRunSetup
- let layout = ControlLayout()
+ let layout = sharedControls ?? ControlLayout()
_controls = StateObject(wrappedValue: layout)
_consoleDriver = StateObject(wrappedValue: controllerDriver ?? AnyConsoleDriver(LauncherControllerDriver(layout: layout)))
injectedDriver = controllerDriver != nil
@@ -103,7 +103,12 @@ struct ContentView: View {
ConsoleConnectionPrompt(lang: m.lang, enterConsole: { consolePrompt = false; enterConsole() }, dismissPrompt: { consolePrompt = false })
}
}
- .onChange(of: gamepad.connected) { connected in if connected, enterConsole != nil { consolePrompt = true } }
+ .onChange(of: gamepad.connected) { connected in
+ if connected, enterConsole != nil, ConsolePrompt.shouldShow(enabled: ConsolePrompt.enabled, shown: ConsolePrompt.shownThisSession) {
+ ConsolePrompt.didShow()
+ consolePrompt = true
+ }
+ }
.onChange(of: consoleDriver.state.padMerge) { merged in if injectedDriver { controls.padMerge = merged } }
.onChange(of: consolePrompt) { open in
padFocus.scope = open ? "console.entry" : currentPadScope
@@ -234,6 +239,11 @@ 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) }
+ }
+
private var topBar: some View {
GeometryReader { geometry in
let compact = (enterConsole != nil || showsControllers) && (geometry.size.width < 1100 || (searching && geometry.size.width < 1400))
@@ -250,11 +260,11 @@ struct ContentView: View {
.padding(.trailing, compact ? 16 : 34)
ForEach(LauncherPage.allCases, id: \.self) { destination in
Button { page = destination } label: {
- Group {
- if compact { Image(systemName: destination.symbol).accessibilityLabel(m.t("nav." + destination.rawValue)) }
- else { Label(m.t("nav." + destination.rawValue), systemImage: destination.symbol) }
+ // The selected tab is bold. The bold text also sizes the (hidden) slot, so a tab never changes width as the selection moves.
+ ZStack {
+ navLabel(destination, compact: compact).font(.manrope(15, .bold)).hidden()
+ navLabel(destination, compact: compact).font(.manrope(15, page == destination ? .bold : .medium))
}
- .font(.manrope(15, page == destination ? .bold : .medium))
.padding(.horizontal, compact ? 14 : 18).padding(.vertical, 10)
.background(page == destination ? Color.white.opacity(0.10) : .clear,
in: RoundedRectangle(cornerRadius: 9))
@@ -609,8 +619,8 @@ struct ContentView: View {
if gamepad.connected {
// The buttons a controller has here, named as the game names them (A on the right)
HStack(spacing: 18) {
- padHint("A", m.t("pad.play")); padHint("X", m.t("pad.options")); padHint("B", m.t("pad.back"))
- padHint("Y", m.t("pad.manage"))
+ padHint(.activate, m.t("pad.play")); padHint(.launchOptions, m.t("pad.options")); padHint(.back, m.t("pad.back"))
+ padHint(.manage, m.t("pad.manage"))
Image(systemName: "gamecontroller").foregroundStyle(.secondary)
}
}
@@ -620,10 +630,11 @@ struct ContentView: View {
}
}
- private func padHint(_ button: String, _ label: String) -> some View {
+ /// A pad hint shows the glyph of the controller connected (the same ConsoleGlyphs the console mode uses), so it names the button
+ /// that really performs the action on a DualSense, an Xbox or a Nintendo-layout controller.
+ private func padHint(_ role: ConsoleGlyphs.Role, _ label: String) -> some View {
HStack(spacing: 7) {
- Text(button).font(.manrope(11, .bold)).foregroundStyle(.black)
- .frame(width: 20, height: 20).background(LauncherPalette.cream.opacity(0.9), in: Circle())
+ ConsoleGlyphView(glyph: ConsoleGlyphs.current().glyph(for: role), size: 18).foregroundStyle(LauncherPalette.cream)
Text(label).font(.manrope(13)).foregroundStyle(.secondary)
}
}
@@ -754,12 +765,7 @@ struct ContentView: View {
// The launch options; the app's launcher (dm/mac/launcher.c) keeps a variable that is already set.
// The keyboard and controller layout (Settings → Controls) goes to every game; a build whose host does not read it plays with the default keys.
// They stay launch overrides (the environment) for now: DM_KEYMAP and DM_PAD_MAP become saved choices only when seedds/nxnative#386 merges.
- library.migrateLaunchOptions()
- let settings = LaunchSetting.forMac(app: game.appPath, titleID: game.titleID, repo: m.repoPath, labels: m.t) ?? []
- let mods = GameMod.list(in: GameMod.folder(for: game, library: library.folder), titleID: game.titleID)
- let environment = game.startEnvironment(controls: controls.environment, settings: settings, mods: mods,
- store: SavedChoices(app: game.appPath, titleID: game.titleID),
- appReadsStore: SavedChoices.appReadsStore(app: game.appPath))
+ let environment = GameStart.environment(for: game, library: library, controls: controls, repo: m.repoPath, labels: m.t) // GameStart.swift: the console mode starts games with the same
if !environment.isEmpty { configuration.environment = environment }
NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: game.appPath), configuration: configuration) { _, error in
DispatchQueue.main.async {
diff --git a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
new file mode 100644
index 00000000..471adcb2
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
@@ -0,0 +1,305 @@
+import SwiftUI
+import Combine
+import AppKit
+import GameController
+import CoreHaptics
+
+/// A controller as GameController reports it, reduced to what the console mode shows. Tests build these instead of hardware.
+struct ConsolePadSnapshot: Equatable {
+ var id: String
+ var name: String
+ var category: String?
+ var playerIndex: Int? // 1...4, nil when unset
+ var battery: Double?
+ var charging = false
+
+ var controller: ConsoleController {
+ let family = ConsoleGlyphs.Family(category: category)
+ let c = (category ?? "").lowercased().replacingOccurrences(of: "-", with: "")
+ let kind: ConsoleController.Kind
+ if c.contains("joycon") { kind = .paired }
+ 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)
+ }
+}
+
+/// The console mode over the launcher's real data. It reuses what the desktop launcher uses and keeps no second copy of anything:
+/// the games and their status come from `GameLibrary`, covers from `GameLibrary.artwork`, launch options from `SavedChoices` and the
+/// library (as LaunchOptionsView reads and writes them), Play from `GameStart.environment`, the player-mode setting from
+/// `ControlLayout`, and the controllers from GameController.
+@MainActor final class LiveConsoleDriver: ConsoleDriver {
+ @Published var state = ConsoleState()
+
+ private let library: GameLibrary
+ private let controls: ControlLayout
+ private let repo: () -> String
+ private let lang: () -> Lang
+ private let labels: (String) -> String
+ private let pads: () -> [ConsolePadSnapshot]
+ private let launch: (LibraryGame, [String: String], @escaping (Int32?, Error?) -> Void) -> Void
+ private let artwork: (LibraryGame, String) -> NSImage?
+ private let startingTimeout: TimeInterval
+ private var cancellables = Set<AnyCancellable>()
+ private var observers: [NSObjectProtocol] = []
+ private var refreshQueued = false
+ private var covers: [UUID: (path: String, image: Image?)] = [:]
+ private var launchedPID: Int32?
+ private var timeoutTask: Task<Void, Never>?
+ private var toastTask: Task<Void, Never>?
+ private var clock: Timer?
+ /// Real controllers by id, for Identify and player assignment.
+ private var devices: [String: GCController] = [:]
+
+ 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) {
+ self.library = library; self.controls = controls; self.repo = repo; self.lang = lang; self.labels = labels
+ self.startingTimeout = startingTimeout
+ self.pads = pads ?? { [] }
+ self.launch = launch ?? Self.openApplication
+ self.artwork = artwork ?? { game, repo in GameLibrary.artwork(for: game, repo: repo) }
+ if pads == nil { self.devicePads = true }
+ state.padMerge = controls.padMerge
+ library.objectWillChange.sink { [weak self] _ in self?.queueRefresh() }.store(in: &cancellables)
+ controls.$padMerge.sink { [weak self] merged in self?.state.padMerge = merged }.store(in: &cancellables)
+ refresh()
+ refreshControllers(announce: false)
+ guard observeSystem else { return }
+ let center = NotificationCenter.default
+ observers = [
+ center.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { [weak self] note in
+ MainActor.assumeIsolated { self?.padsChanged(connected: true, note: note) }
+ },
+ center.addObserver(forName: .GCControllerDidDisconnect, object: nil, queue: .main) { [weak self] note in
+ MainActor.assumeIsolated { self?.padsChanged(connected: false, note: note) }
+ },
+ ]
+ let workspace = NSWorkspace.shared.notificationCenter
+ observers.append(workspace.addObserver(forName: NSWorkspace.didTerminateApplicationNotification, object: nil, queue: .main) { [weak self] note in
+ let pid = (note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication)?.processIdentifier
+ MainActor.assumeIsolated { if let pid { self?.gameDidTerminate(pid: pid) } }
+ })
+ 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() } }
+ }
+ private var devicePads = false
+
+ deinit {
+ observers.forEach { NotificationCenter.default.removeObserver($0); NSWorkspace.shared.notificationCenter.removeObserver($0) }
+ clock?.invalidate()
+ }
+
+ // MARK: Games
+
+ private func t(_ key: String) -> String { L10n.string(key, lang()) }
+
+ private func queueRefresh() {
+ guard !refreshQueued else { return }
+ refreshQueued = true
+ DispatchQueue.main.async { [weak self] in self?.refreshQueued = false; self?.refresh() }
+ }
+
+ /// The library as console games, in the library's order, keeping the focus and each game's shown values.
+ func refresh() {
+ let focus = state.focusedGameID
+ let games = library.games.map { consoleGame($0) }
+ state.games = games
+ state.focusedGameID = games.contains { $0.id == focus } ? focus : (library.selected.map { $0.id.uuidString }.flatMap { id in games.contains { $0.id == id } ? id : nil } ?? games.first?.id)
+ state.time = Date()
+ }
+
+ static func status(of game: LibraryGame, brokenMessage: String) -> ConsoleGame.Status {
+ if game.isReady { return .ready }
+ if !game.appPath.isEmpty { return .broken(brokenMessage) } // an app is recorded but is not a complete game app
+ return game.inputs.values.contains { !$0.isEmpty } ? .needsBuild : .needsData
+ }
+
+ static func platforms(of game: LibraryGame) -> [ConsoleGame.Platform] {
+ var result: [ConsoleGame.Platform] = []
+ if game.isReady { result.append(.mac) }
+ if game.hasIOSBuild || game.onDevice { result.append(.iphone) }
+ return result.isEmpty ? [.mac] : result
+ }
+
+ private func consoleGame(_ game: LibraryGame) -> ConsoleGame {
+ let settings = game.isReady ? (LaunchSetting.forMac(app: game.appPath, titleID: game.titleID, repo: repo(), labels: labels) ?? []) : []
+ let store = SavedChoices(app: game.appPath, titleID: game.titleID)
+ var values: [String: String] = [:]
+ for s in settings { values[s.env] = s.storeBacked ? store.current(s) : game.launchValue(s) }
+ return ConsoleGame(id: game.id.uuidString, title: game.name, version: version(of: game),
+ platforms: Self.platforms(of: game), artwork: cover(game),
+ status: Self.status(of: game, brokenMessage: t("console.broken")), settings: settings, values: values)
+ }
+
+ /// The app's version as its Info.plist states it; empty for a game that has no app yet.
+ private func version(of game: LibraryGame) -> String {
+ let plist = URL(fileURLWithPath: game.appPath).appendingPathComponent("Contents/Info.plist")
+ guard let data = try? Data(contentsOf: plist),
+ let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { return "" }
+ return info["CFBundleShortVersionString"] as? String ?? ""
+ }
+
+ /// Covers through the launcher's own lookup, decoded once per image path.
+ private func cover(_ game: LibraryGame) -> Image? {
+ let key = game.artworkPath + "|" + game.titleID + "|" + game.name
+ if let cached = covers[game.id], cached.path == key { return cached.image }
+ let image = artwork(game, repo()).map { Image(nsImage: $0) }
+ covers[game.id] = (key, image)
+ return image
+ }
+
+ /// Covers downloaded after the first draw (ArtworkStore) show up when the console asks again.
+ func reloadCovers() { covers = [:]; refresh() }
+
+ func focus(_ gameID: String) { state.focus(gameID) }
+
+ func play(_ gameID: String) {
+ state.play(gameID)
+ guard state.startingGameID == gameID, let game = library.games.first(where: { $0.id.uuidString == gameID }) else { return }
+ let environment = GameStart.environment(for: game, library: library, controls: controls, repo: repo(), labels: labels)
+ state.starting = .preparing
+ launch(game, environment) { [weak self] pid, error in
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated {
+ guard let self, self.state.startingGameID == gameID else { return }
+ if let error { self.state.returnFromGame(); self.showToast(error.localizedDescription); return }
+ self.launchedPID = pid
+ self.state.starting = .opening
+ self.timeoutTask?.cancel()
+ self.timeoutTask = Task { [weak self] in
+ try? await Task.sleep(nanoseconds: UInt64((self?.startingTimeout ?? 20) * 1_000_000_000))
+ guard !Task.isCancelled else { return }
+ self?.gameWindowAppeared()
+ }
+ }
+ }
+ }
+ }
+
+ private static func openApplication(_ game: LibraryGame, _ environment: [String: String], _ done: @escaping (Int32?, Error?) -> Void) {
+ let configuration = NSWorkspace.OpenConfiguration()
+ if !environment.isEmpty { configuration.environment = environment }
+ NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: game.appPath), configuration: configuration) { app, error in
+ done(app?.processIdentifier, error)
+ }
+ }
+
+ /// The game's window took the front (or the wait ran out): Starting ends, the console stays selected on the game.
+ func gameWindowAppeared() {
+ guard state.startingGameID != nil, launchedPID != nil || !devicePads else { return }
+ timeoutTask?.cancel()
+ state.returnFromGame()
+ }
+
+ /// The game this console started quit: the console comes back to the front (PR #110's launcher-wide return does the same for the desktop).
+ func gameDidTerminate(pid: Int32) {
+ guard pid == launchedPID else { return }
+ launchedPID = nil
+ timeoutTask?.cancel()
+ state.returnFromGame()
+ NSApp.unhide(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ }
+
+ // MARK: Options
+
+ func openOptions(_ gameID: String) { state.openOptions(gameID) }
+
+ func setOption(gameID: String, setting env: String, value: String) {
+ state.setOption(game: gameID, setting: env, value: value)
+ guard let game = library.games.first(where: { $0.id.uuidString == gameID }),
+ let shown = state.games.first(where: { $0.id == gameID }), let s = shown.settings.first(where: { $0.env == env }),
+ let stored = shown.values[env] else { return }
+ if s.storeBacked { SavedChoices(app: game.appPath, titleID: game.titleID).set(s, stored) } else { library.setLaunchOption(s, stored, for: game.id) }
+ }
+
+ // MARK: Controllers
+
+ func openControllers() { state.openControllers() }
+ func requestPlayer(_ player: Int) {
+ guard state.presentedSheet == .controllers, (1...4).contains(player) else { return }
+ state.assigningPlayer = player
+ }
+ func requestAssignment(controllerID: String) {
+ guard state.presentedSheet == .controllers, let c = state.controllers.first(where: { $0.id == controllerID }) else { return }
+ state.assigningControllerID = controllerID
+ state.assigningPlayer = state.assigningPlayer ?? c.player ?? 1
+ }
+ 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
+ refreshControllers(announce: false)
+ }
+ func setPadMerge(_ enabled: Bool) { controls.padMerge = enabled }
+
+ /// A short rumble when the controller has haptics, nothing otherwise (and never an error).
+ 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 }
+ 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 */ }
+ }
+
+ /// macOS offers apps no way to drop a Bluetooth controller, so this says where to do it instead.
+ func disconnect(controllerID: String) { showToast(t("console.disconnectHint")) }
+
+ func padsChanged(connected: Bool, note: Notification) {
+ refreshControllers(announce: false)
+ guard let pad = note.object as? GCController else { return }
+ let name = pad.vendorName ?? pad.productCategory
+ let player = state.padMerge ? 1 : state.controllers.first { $0.name == name }?.player
+ if connected {
+ showToast(player.map { String(format: t("console.connected"), name, $0) } ?? String(format: t("console.connectedUnassigned"), name))
+ } else { showToast(String(format: t("console.disconnected"), name)) }
+ }
+
+ func refreshControllers(announce: Bool) {
+ var snapshots = pads()
+ if devicePads {
+ devices = [:]
+ snapshots = GCController.controllers().compactMap { c in
+ 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 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)
+ }
+ }
+ state.controllers = snapshots.map(\.controller)
+ }
+
+ // MARK: Navigation
+
+ func dismissToast() { toastTask?.cancel(); state.toast = nil; state.identifyingControllerID = nil }
+ func back() { state.back() }
+ func exitToDesktop() { state.exitToDesktop() }
+ func returnFromGame() { state.returnFromGame() }
+
+ private func showToast(_ message: String) {
+ toastTask?.cancel()
+ state.toast = ConsoleToast(message: message)
+ toastTask = Task { [weak self] in
+ try? await Task.sleep(nanoseconds: 3_000_000_000)
+ guard !Task.isCancelled else { return }
+ self?.state.toast = nil
+ self?.state.identifyingControllerID = nil
+ }
+ }
+}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 1ba698f4..28b8800e 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -149,6 +149,10 @@ enum L10n {
"console.playerMode": ("\u{73a9}\u{5bb6}\u{6a21}\u{5f0f}", "Player mode"),
"console.mergeAll": ("\u{6240}\u{6709}\u{624b}\u{67c4}\u{5747}\u{4e3a}\u{73a9}\u{5bb6} 1", "All controllers are player 1"),
"console.mergeNote": ("\u{6253}\u{5f00}\u{540e}\u{ff0c}\u{6bcf}\u{4e2a}\u{624b}\u{67c4}\u{90fd}\u{6309}\u{73a9}\u{5bb6} 1 \u{8f93}\u{5165}\u{3002}\u{5173}\u{95ed}\u{65f6}\u{ff0c}\u{6bcf}\u{4e2a}\u{624b}\u{67c4}\u{5404}\u{6709}\u{81ea}\u{5df1}\u{7684}\u{73a9}\u{5bb6}\u{3002}\u{4ec5}\u{5bf9}\u{5728} Mac \u{4e0a}\u{8fd0}\u{884c}\u{7684}\u{6e38}\u{620f}\u{751f}\u{6548}\u{3002}", "Every controller sends player 1\u{2019}s input. When off, each controller is its own player. Applies to games running on this Mac."),
+ "console.disconnectHint": ("\u{5728} macOS \u{7684}\u{84dd}\u{7259}\u{8bbe}\u{7f6e}\u{4e2d}\u{65ad}\u{5f00}\u{8fd9}\u{4e2a}\u{624b}\u{67c4}\u{3002}", "Disconnect it in the macOS Bluetooth settings."),
+ "console.promptSetting": ("\u{63d2}\u{5165}\u{624b}\u{67c4}\u{65f6}\u{63d0}\u{793a}\u{8fdb}\u{5165}\u{4e3b}\u{673a}\u{6a21}\u{5f0f}", "Offer console mode when a controller connects"),
+ "console.promptSettingNote": ("\u{6bcf}\u{6b21}\u{542f}\u{52a8}\u{6700}\u{591a}\u{63d0}\u{793a}\u{4e00}\u{6b21}\u{3002}", "At most once each time the launcher starts."),
+ "console.menuLeave": ("\u{9000}\u{51fa}\u{4e3b}\u{673a}\u{6a21}\u{5f0f}", "Leave Console Mode"),
"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/NSPortBuilderApp.swift b/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift
index 27db125d..09422970 100644
--- a/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift
+++ b/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift
@@ -3,6 +3,7 @@ import SwiftUI
@main
struct NSPortBuilderApp: App {
@NSApplicationDelegateAdaptor private var delegate: AppDelegate
+ @StateObject private var console = ConsoleCoordinator()
var body: some Scene {
WindowGroup("NX2Apple") {
@@ -11,11 +12,18 @@ struct NSPortBuilderApp: App {
OnboardingDemoHost(scenario: scenario)
} else if let scenario = ProcessInfo.processInfo.environment["NSPB_CONSOLE_DEMO"].flatMap(MockConsoleDriver.Scenario.init(rawValue:)) {
ConsoleDemoView(scenario: scenario)
- } else { RootView() }
+ } else { RootView(console: console) }
}
.windowStyle(.hiddenTitleBar)
.defaultSize(width: 1280, height: 900)
.windowResizability(.automatic)
+ .commands {
+ // View → Console Mode. Command-Option-K: Control-Command-F is the system's full screen, and the others are taken by Find and Show Colors.
+ CommandGroup(after: .toolbar) {
+ Button(L10n.string(console.active ? "console.menuLeave" : "console.entry", Lang.initial())) { console.toggle() }
+ .keyboardShortcut("k", modifiers: [.command, .option]).disabled(!console.available && !console.active)
+ }
+ }
}
}
diff --git a/frontend/Sources/NSPortBuilder/OnboardingRoot.swift b/frontend/Sources/NSPortBuilder/OnboardingRoot.swift
index a3b7e107..e04644a7 100644
--- a/frontend/Sources/NSPortBuilder/OnboardingRoot.swift
+++ b/frontend/Sources/NSPortBuilder/OnboardingRoot.swift
@@ -5,13 +5,19 @@ import SwiftUI
struct RootView: View {
private enum Mode { case checking, onboarding, launcher }
/// Holds the two objects without publishing, so this view does not redraw with every line of a build log.
- private final class Shared: ObservableObject { let model = BuildModel(); let library = GameLibrary() }
+ @MainActor private final class Shared: ObservableObject {
+ let model = BuildModel(); let library = GameLibrary(); let controls = ControlLayout()
+ /// The console mode's driver over this window's model, library and controls.
+ lazy var console = LiveConsoleDriver(library: library, controls: controls, repo: { [model] in model.repoPath }, lang: { [model] in model.lang },
+ labels: { [model] in model.t($0) })
+ }
@StateObject private var shared = Shared()
private var model: BuildModel { shared.model }
private var library: GameLibrary { shared.library }
@State private var mode: Mode = .checking
@State private var driver: LiveOnboardingDriver?
@StateObject private var gamepad = LauncherGamepad()
+ @ObservedObject var console: ConsoleCoordinator
var body: some View {
Group {
@@ -21,13 +27,20 @@ struct RootView: View {
case .onboarding:
if let driver { OnboardingView(driver: driver, lang: model.lang, gamepad: gamepad) }
case .launcher:
- ContentView(model: model, library: library, onRunSetup: runSetupAgain)
+ if console.active {
+ ConsoleView(driver: shared.console, lang: model.lang, onExit: { console.exit(); shared.console.returnFromGame() })
+ .onAppear { shared.console.reloadCovers() }
+ } else {
+ ContentView(model: model, library: library, onRunSetup: runSetupAgain, enterConsole: { console.enter() },
+ controllerDriver: AnyConsoleDriver(shared.console), controls: shared.controls)
+ }
}
}
.background(LauncherPalette.background)
.preferredColorScheme(.dark)
.frame(minWidth: 900, idealWidth: 1280, minHeight: 680, idealHeight: 900)
.task { await decide() }
+ .onChange(of: mode) { console.available = $0 == .launcher }
}
/// On launch: a setup marked done, or one that is complete already, goes straight to the launcher (and is marked done);
diff --git a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
new file mode 100644
index 00000000..b8f128ee
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift
@@ -0,0 +1,176 @@
+import XCTest
+import SwiftUI
+@testable import NSPortBuilder
+
+/// The live console driver over a real GameLibrary in a temporary folder, with fake controllers and a fake launch call.
+@MainActor final class ConsoleLiveTests: XCTestCase {
+ private var temporary: URL!
+ private let titleID = "01001A9012345000"
+ private let bundleID = "org.nxnative.consolelivetests"
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("ConsoleLiveTests-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+ override func tearDown() {
+ try? FileManager.default.removeItem(at: temporary)
+ for key in ["launcher.DM_FPS_TARGET"] { CFPreferencesSetAppValue(key as CFString, nil, bundleID as CFString) }
+ CFPreferencesAppSynchronize(bundleID as CFString)
+ }
+
+ private func makeApp(name: String = "Hades") throws -> URL {
+ let app = temporary.appendingPathComponent(name + ".app")
+ let macos = app.appendingPathComponent("Contents/MacOS"), dm = app.appendingPathComponent("Contents/Resources/dm")
+ try FileManager.default.createDirectory(at: macos, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: dm, withIntermediateDirectories: true)
+ for exe in ["nxnative", "dmhost"] { try FileManager.default.createSymbolicLink(at: macos.appendingPathComponent(exe), withDestinationURL: URL(fileURLWithPath: "/usr/bin/true")) }
+ let info: [String: Any] = ["DMTitleID": titleID, "CFBundleDisplayName": name, "CFBundleExecutable": "nxnative", "CFBundleIdentifier": bundleID,
+ "CFBundleShortVersionString": "1.2.3"]
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))
+ let list = #"{"schema":1,"settings":[{"env":"DM_FPS_TARGET","kind":"choice","label":"Frame rate","note":"","default":"60","section":"Game","options":[["30","30 fps"],["60","60 fps"]]}]}"#
+ try Data(list.utf8).write(to: dm.appendingPathComponent("launcher.json"))
+ return app
+ }
+
+ private struct Launch { var game: LibraryGame; var environment: [String: String] }
+
+ private func makeDriver(controls: ControlLayout? = nil, pads: [ConsolePadSnapshot] = [], launched: @escaping (Launch) -> Void = { _ in }) throws
+ -> (LiveConsoleDriver, GameLibrary, ControlLayout) {
+ let library = GameLibrary(file: temporary.appendingPathComponent("library.json"))
+ _ = try library.addApp(try makeApp())
+ let layout = controls ?? ControlLayout(defaults: UserDefaults(suiteName: "ConsoleLiveTests-" + UUID().uuidString)!)
+ let driver = LiveConsoleDriver(library: library, controls: layout, repo: { "" }, lang: { .en }, labels: { L10n.string($0, .en) },
+ pads: { pads }, launch: { game, env, done in launched(Launch(game: game, environment: env)); done(4242, nil) },
+ artwork: { _, _ in nil }, startingTimeout: 0.2, observeSystem: false)
+ return (driver, library, layout)
+ }
+
+ func testLibraryEntriesBecomeConsoleGames() throws {
+ let (driver, library, _) = try makeDriver()
+ let game = try XCTUnwrap(driver.state.games.first)
+ XCTAssertEqual(library.games.count, 1)
+ XCTAssertEqual(game.title, "Hades")
+ XCTAssertEqual(game.version, "1.2.3")
+ XCTAssertEqual(game.status, .ready)
+ XCTAssertEqual(game.platforms, [.mac])
+ XCTAssertTrue(game.settings.map(\.env).contains("DM_FPS_TARGET"))
+ XCTAssertEqual(game.values["DM_FPS_TARGET"], "60")
+ XCTAssertEqual(driver.state.focusedGameID, game.id)
+ }
+
+ func testStatusAndPlatformsPerLibraryEntry() {
+ let broken = LibraryGame(titleID: titleID, name: "A", appPath: "/gone/A.app")
+ XCTAssertEqual(LiveConsoleDriver.status(of: broken, brokenMessage: "x"), .broken("x"))
+ XCTAssertEqual(LiveConsoleDriver.status(of: LibraryGame(titleID: titleID, name: "B"), brokenMessage: "x"), .needsData)
+ var chosen = LibraryGame(titleID: titleID, name: "C")
+ chosen.inputs = ["keys": ["/k"]]
+ XCTAssertEqual(LiveConsoleDriver.status(of: chosen, brokenMessage: "x"), .needsBuild)
+ XCTAssertEqual(LiveConsoleDriver.platforms(of: broken), [.mac])
+ }
+
+ func testPlayRoutesToTheLaunchWithTheDesktopEnvironment() throws {
+ var launches: [Launch] = []
+ let (driver, _, layout) = try makeDriver { launches.append($0) }
+ layout.padMerge = true
+ let id = try XCTUnwrap(driver.state.games.first?.id)
+ driver.play(id)
+ XCTAssertEqual(launches.count, 1)
+ XCTAssertEqual(launches.first?.environment["DM_PAD_MERGE"], "1")
+ XCTAssertEqual(launches.first?.environment["DM_LAUNCHER"], "0")
+ XCTAssertEqual(launches.first?.game.titleID, titleID)
+ let expected = launches.first.map { GameStart.environment(for: $0.game, library: GameLibrary(file: temporary.appendingPathComponent("other.json")), controls: layout, repo: "", labels: { $0 }) }
+ XCTAssertEqual(launches.first?.environment, expected, "the same function the desktop Play uses")
+ }
+
+ func testStartingEndsWhenTheGameQuits() async throws {
+ let (driver, _, _) = try makeDriver()
+ let id = try XCTUnwrap(driver.state.games.first?.id)
+ driver.play(id)
+ for _ in 0..<50 where driver.state.starting != .opening { try await Task.sleep(nanoseconds: 20_000_000) }
+ XCTAssertEqual(driver.state.startingGameID, id)
+ XCTAssertEqual(driver.state.starting, .opening)
+ driver.gameDidTerminate(pid: 1)
+ XCTAssertEqual(driver.state.startingGameID, id, "another process changes nothing")
+ driver.gameDidTerminate(pid: 4242)
+ XCTAssertNil(driver.state.startingGameID)
+ XCTAssertFalse(driver.state.exited)
+ XCTAssertEqual(driver.state.focusedGameID, id, "the selected game is kept")
+ }
+
+ func testOptionsRoundTripThroughSavedChoices() throws {
+ let (driver, library, _) = try makeDriver()
+ let game = try XCTUnwrap(library.games.first)
+ let id = game.id.uuidString
+ driver.setOption(gameID: id, setting: "DM_FPS_TARGET", value: "30")
+ XCTAssertEqual(driver.state.games.first?.values["DM_FPS_TARGET"], "30")
+ let setting = try XCTUnwrap(driver.state.games.first?.settings.first { $0.env == "DM_FPS_TARGET" })
+ XCTAssertEqual(SavedChoices(app: game.appPath, titleID: game.titleID).current(setting), "30", "the same store LaunchOptionsView reads")
+ driver.refresh()
+ XCTAssertEqual(driver.state.games.first?.values["DM_FPS_TARGET"], "30")
+ driver.setOption(gameID: id, setting: "DM_FPS_TARGET", value: "60")
+ XCTAssertNil(SavedChoices(app: game.appPath, titleID: game.titleID).value(setting), "the default removes the saved choice")
+ driver.setOption(gameID: id, setting: "DM_FPS_TARGET", value: "999")
+ XCTAssertEqual(driver.state.games.first?.values["DM_FPS_TARGET"], "60", "a value the build does not offer is refused")
+ }
+
+ func testControllerSnapshotMapping() {
+ let xbox = ConsolePadSnapshot(id: "a", name: "Wireless Controller", category: "Xbox One", playerIndex: 2, battery: 0.76, charging: false).controller
+ XCTAssertEqual(xbox.kind, .xbox)
+ XCTAssertEqual(xbox.player, 2)
+ XCTAssertEqual(xbox.batteryPercent, 76)
+ XCTAssertEqual(ConsolePadSnapshot(id: "b", name: "p", category: "Switch Pro Controller", playerIndex: nil).controller.kind, .fullSize)
+ XCTAssertEqual(ConsolePadSnapshot(id: "c", name: "j", category: "Nintendo Switch JoyCon (L/R)", playerIndex: 1).controller.kind, .paired)
+ let ps = ConsolePadSnapshot(id: "d", name: "DualSense", category: "DualSense", playerIndex: 4, battery: 0.1, charging: true).controller
+ XCTAssertEqual(ps.kind, .gamepad)
+ XCTAssertTrue(ps.charging)
+ XCTAssertNil(ConsolePadSnapshot(id: "e", name: "x", category: nil, playerIndex: nil).controller.battery)
+ }
+
+ func testDriverShowsFakeControllersAndTheSharedPlayerMode() throws {
+ let pads = [ConsolePadSnapshot(id: "a", name: "Pad", category: "Xbox One", playerIndex: 1, battery: 0.5)]
+ let (driver, _, layout) = try makeDriver(pads: pads)
+ XCTAssertEqual(driver.state.controllers.map(\.id), ["a"])
+ driver.setPadMerge(true)
+ XCTAssertTrue(layout.padMerge)
+ XCTAssertTrue(driver.state.padMerge)
+ driver.disconnect(controllerID: "a")
+ XCTAssertNotNil(driver.state.toast, "a Bluetooth controller cannot be dropped by an app: the toast says where")
+ }
+
+ func testEnteringAndLeavingConsoleModeRestoresTheWindow() {
+ var calls: [Bool] = []
+ let window = NSWindow(contentRect: .zero, styleMask: [.titled], backing: .buffered, defer: true)
+ let coordinator = ConsoleCoordinator(window: { window }, setFullScreen: { _, on in calls.append(on) })
+ coordinator.enter()
+ XCTAssertFalse(coordinator.active, "not while the guided setup shows")
+ coordinator.available = true
+ coordinator.enter()
+ XCTAssertTrue(coordinator.active)
+ XCTAssertEqual(calls, [true])
+ coordinator.enter()
+ XCTAssertEqual(calls, [true], "entering twice does nothing")
+ coordinator.exit()
+ XCTAssertFalse(coordinator.active)
+ coordinator.toggle()
+ XCTAssertTrue(coordinator.active)
+ }
+
+ func testControllerPromptOncePerSessionAndSetting() {
+ XCTAssertTrue(ConsolePrompt.shouldShow(enabled: true, shown: false))
+ XCTAssertFalse(ConsolePrompt.shouldShow(enabled: true, shown: true))
+ XCTAssertFalse(ConsolePrompt.shouldShow(enabled: false, shown: false))
+ }
+
+ func testBatteryFillFraction() {
+ XCTAssertEqual(BatteryIcon.fillFraction(0.76), 0.76)
+ XCTAssertEqual(BatteryIcon.fillFraction(0), 0)
+ XCTAssertEqual(BatteryIcon.fillFraction(1.4), 1)
+ XCTAssertEqual(BatteryIcon.fillFraction(-1), 0)
+ XCTAssertEqual(BatteryIcon.fillFraction(.nan), 0)
+ XCTAssertEqual(BatteryIcon.fillFraction(nil), 0)
+ XCTAssertTrue(BatteryIcon.isLow(0.2))
+ XCTAssertTrue(BatteryIcon.isLow(0.12))
+ XCTAssertFalse(BatteryIcon.isLow(0.21))
+ XCTAssertFalse(BatteryIcon.isLow(nil))
+ }
+}
diff --git a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
index ee9a5894..9dd552e1 100644
--- a/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ConsolePadTests.swift
@@ -174,4 +174,34 @@ final class ConsolePadTests: XCTestCase {
XCTAssertEqual(ConsoleGlyphs(family: .nintendo).glyph(for: .activate), .symbol("a.circle"))
XCTAssertEqual(ConsoleGlyphs(family: .nintendo).glyph(for: .back), .symbol("b.circle"))
}
+
+ /// Opt-in: the desktop top bar with the entry button and the controller strip, and the connect prompt.
+ @MainActor func testCaptureDesktopEntry() throws {
+ guard let directory = ProcessInfo.processInfo.environment["NX_CONSOLE_SHOTS_DIR"] else { throw XCTSkip("Set NX_CONSOLE_SHOTS_DIR") }
+ let output = URL(fileURLWithPath: directory)
+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
+ NSApplication.shared.setActivationPolicy(.accessory)
+ func shot(_ view: AnyView, _ name: String, _ width: CGFloat, _ height: CGFloat) throws {
+ // a titled window, as the launcher's own screenshots use: the launcher draws under its transparent title bar
+ let host = NSHostingView(rootView: view)
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: height), styleMask: [.titled], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = host
+ window.orderFront(nil)
+ RunLoop.main.run(until: Date().addingTimeInterval(1.0))
+ host.layoutSubtreeIfNeeded()
+ let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
+ host.cacheDisplay(in: host.bounds, to: rep)
+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent(name + ".png"))
+ window.orderOut(nil); window.contentView = nil; window.close()
+ }
+ let driver = MockConsoleDriver(scenario: .controllersMixed, lang: .en, animated: false)
+ driver.back()
+ let library = GameLibrary(file: output.appendingPathComponent("unused-library.json"))
+ for width: CGFloat in [1280, 900] {
+ try shot(AnyView(ContentView(model: BuildModel(), library: library, performStartupChecks: false, enterConsole: {}, controllerDriver: AnyConsoleDriver(driver))),
+ "desktop-entry-\(Int(width))", width, 560)
+ }
+ try shot(AnyView(ConsoleConnectionPrompt(lang: .en, enterConsole: {}, dismissPrompt: {}).environmentObject(PadFocus()).preferredColorScheme(.dark)), "prompt-1280", 1280, 720)
+ }
}