Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
The launcher can preview console mode and shared controller controls
v0lumehiaa251df825df
diff --git a/frontend/Console.md b/frontend/Console.mdnew file mode 100644index 00000000..8c5f4ff8--- /dev/null+++ b/frontend/Console.md@@ -0,0 +1,74 @@+# Console mode UI++This is a native SwiftUI presentation preview for macOS 13+, built off `main`. It never launches a game, reads the real library, discovers controllers or writes settings. The existing desktop launcher remains the default. The onboarding pattern was read from `onboarding-ui`; that branch is not a dependency.++## Run the demos++```sh+cd frontend+NSPB_CONSOLE_DEMO=full swift run+NSPB_CONSOLE_DEMO=few swift run+NSPB_CONSOLE_DEMO=empty swift run+NSPB_CONSOLE_DEMO=controllers swift run+NSPB_CONSOLE_DEMO=controllersMixed swift run+NSPB_CONSOLE_DEMO=starting swift run+```++`full` contains 12 games with ready, needs-build, missing-data and broken states. `few` contains two games. `controllers` opens three controllers with player 3 awaiting assignment. `controllersMixed` adds a Pro-style pad, an Xbox-style pad with 12% battery, a keyboard and charging paired controllers. `starting` animates simulated shader compilation, then waits at Opening game window until the driver reports a return. No real shader compilation runs, and the mock never fabricates a completed game launch. Unknown or absent demo values open the desktop launcher as before.++Arrow keys navigate. Return or Space activates the focused item. O or + opens game options; Y opens Controllers. Escape acts as B: close the top sheet, then exit from Home. Home's Play action explains incomplete setup instead of launching. In options, left/right changes the selected row; Return advances its value. Choose a player, use Assign player on a controller, then Simulate a button press to exercise assignment. Identify and Disconnect update the mock only. The exit preview offers Return to console. The mode fills its window and works in macOS full screen; the view does not change system window state.++## Driver API++`ConsoleView<Driver: ConsoleDriver>` observes one published `ConsoleState` snapshot on the main actor. Implement:++```swift+focus(_ gameID: String)+play(_ gameID: String)+openOptions(_ gameID: String)+setOption(gameID: String, setting: String, value: String)+openControllers()+requestPlayer(_ player: Int)+requestAssignment(controllerID: String)+identify(controllerID: String)+disconnect(controllerID: String)+setPadMerge(_ enabled: Bool)+dismissToast()+assignPlayer(controllerID: String, player: Int)+back()+exitToDesktop()+returnFromGame()+```++The state includes games, decoded SwiftUI artwork images, versions, platforms, ready/build/data/broken status, focused game ID, controllers with kind, player, optional battery fraction (0–1) and charging state, an assignment target, player merge mode, a toast, a sheet stack, Starting, exit status and a clock value. Broken messages and `LaunchSetting` labels/choices/notes are localized by the driver. Option values are in-memory overrides keyed by the existing setting's environment variable; the console uses `LaunchSetting.accepts`, defaults and `needs` dependencies. It renders every supported choice, range and toggle supplied to it, including advanced options, without loading a launcher JSON or a settings store. `ConsoleOption` implements controller stepping. The real driver decides how to persist and apply those values. `setPadMerge` is a presentation intent for the future `DM_PAD_MERGE` bridge. Merged display assigns every controller to player 1 while preserving its separate-player mapping for switching back.++`ConsoleState` provides pure guarded navigation/mutation methods used by the mock and available to the eventual real driver. Sheet nesting preserves the preceding options sheet; player reassignment releases that player's former controller. Focus does not wrap at the collection ends. Starting ignores further Play/Back actions until the driver completes the transition. Call `returnFromGame` for the future controller Home-button route; it preserves the selected game and clears Starting and sheets.++Pass a publisher of `ConsoleInput` to the view for future controller events: left/right/up/down, activate, back, options and controllers. This adapter is intentionally absent. Every interactive element registers with `padTarget` in `console`, `console.options`, `console.controllers`, `console.explanation` or `console.entry`. The future controller adapter must intercept an assigning controller's button and call `assignPlayer(controllerID:player:)`, rather than treating it as generic activation. The real driver supplies controller connect/disconnect snapshots, short localized toasts and clock ticks. The mock exposes `connect` and `disconnect` events with a three-second toast lifetime. It never flashes, rumbles or disconnects real hardware.++The desktop's `ContentView(enterConsole:controllerDriver:)` button and controller-connect prompt report the injected entry intent only. The default closure is inert until the coordinator is wired. The prompt uses the launcher's existing connection observation, without adding hardware APIs. `ConsoleConnectionPrompt` is also independently renderable. Exiting the mock renders an explicit desktop preview, never constructs the real build launcher. Production navigation and actual window transitions belong to the coordinator. Inject `AnyConsoleDriver(realDriver)` to show the same controller snapshot in the desktop chips and `ConsoleControllersSheet`. With no injection, the desktop controller snapshot is empty. It never guesses controller identity from the existing boolean connection flag. The desktop sheet uses `ConsoleControllerList`, the very same view as console mode. A fixed-height controller strip occupies the second row of the top bar so four chips fit even at 900 points. Narrow windows use accessible icon actions in the first row, preserving the logo and avoiding wrapped navigation labels.++## Design++The visual target is the existing launcher code: `LauncherPalette`, embedded Manrope, cream capsule actions and its 1.8:1 artwork crop. Console mode places the selected game's name and platform badges above large landscape cards, with a soft artwork backdrop and a fixed text-and-glyph hint strip. It has no round system-action row, system avatars, Nintendo fonts, Nintendo sounds or copied home-menu arrangement. The typography and generous spacing carry the console feel. Standard SF Symbols identify controls.++The reusable `ConsoleArtwork` and `ConsoleGameTile` accept presentation values. At compact widths the cards become a touch-friendly horizontal collection, hints form two columns, and the side sheet fills the width. Vertically short windows scroll the library and sheet contents; the primary option action stays visible. Focus/background transitions last 0.18–0.22 seconds, without springs. Reduced Motion removes focus scaling and scroll animation, retaining only fades. No UI sounds are included. Controller kinds use neutral SF Symbols, including a split rectangle for paired controllers, with no Nintendo artwork. Chips have fixed strip height, horizontal overflow, player numbers, battery percentage when reported and charging status. Connect/disconnect toasts overlay the screen without moving it. All controller copy is localized and contains no semicolons.++The mock bundles reduced previews copied from the repository's existing game gallery, matched to each title. These are demonstration screenshots, not a new title-art lookup or game assets. All interface copy and mock controller labels live in the shared English/Chinese localization table.++Starting takes a `ConsoleStarting` snapshot: preparing, compiling shaders (completed/total), or opening. Shader progress uses the existing cream launcher progress bar, animating for 0.3 seconds per update, and Reduced Motion removes interpolation. A preview label explicitly identifies simulated shader progress. The live driver must publish actual shader stages and counts, then end Starting when the game window appears.++## Checks++```sh+cd frontend+swift build -c release+swift test+NX_CONSOLE_CAPTURE_DIR=/Volumes/NX/console-captures swift test --filter ConsoleTests+```++The optional offscreen capture test hosts every screen, setup explanation, exit preview and entry prompt in English and Chinese at 1920×1080, 1280×800 and 390×844. Ordinary tests skip captures. State tests cover focus bounds, each status's Play behavior, sheet nesting, B/exit/return, launch-setting validation/dependencies and unique controller assignment. Localization tests check both languages for the console keys.++Files added: `ConsoleState.swift`, `MockConsoleDriver.swift`, `ConsoleView.swift`, `ConsoleKeyboardInput.swift`, `ConsoleEntryView.swift`, `ConsoleControllersView.swift`, `Resources/ConsoleCover0.jpg` through `ConsoleCover11.jpg`, `ConsoleTests.swift`, and this note. Files changed: `Package.swift` (resources), `NSPortBuilderApp.swift` (isolated demo hook), `LauncherView.swift` (entry intent and connection prompt), and `Localization.swift` (English/Chinese).++Validation on 2026-10-28: release build passed. The complete frontend suite passed with 188 tests, zero failures and six unrelated opt-in capture tests skipped. The console's two capture tests ran and produced 94 images, including desktop integration at 900 and 1280 points. Native UI checks exercised keyboard focus, option changes after mouse clicks, setup explanations, Identify feedback, assignment, merged player display, Disconnect, chip updates, Escape and return from the exit preview. Visual review corrected missing bundled artwork, duplicate tile focus borders, the Starting crop, minimum-height card clipping, and crowded desktop navigation. This is a new console composition derived from the existing design system, not a pixel-matching recreation of a supplied console mockup.diff --git a/frontend/Package.swift b/frontend/Package.swiftindex 2eed0a5b..d5c9fd97 100644--- a/frontend/Package.swift+++ b/frontend/Package.swift@@ -5,7 +5,7 @@ let package = Package(name: "NSPortBuilder",platforms: [.macOS(.v13)],targets: [- .executableTarget(name: "NSPortBuilder", path: "Sources/NSPortBuilder"),+ .executableTarget(name: "NSPortBuilder", path: "Sources/NSPortBuilder", resources: [.process("Resources")]),.testTarget(name: "NSPortBuilderTests", dependencies: ["NSPortBuilder"])])diff --git a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swiftnew file mode 100644index 00000000..875b9dee--- /dev/null+++ b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift@@ -0,0 +1,233 @@+import SwiftUI+import Combine++/// One presentation model and one set of intents in desktop and console mode.+@MainActor final class AnyConsoleDriver: ConsoleDriver {+ private let base: any ConsoleDriver+ private var subscription: AnyCancellable?+ @Published private var revision = 0+ var state: ConsoleState { base.state }+ init<D: ConsoleDriver>(_ driver: D) {+ base = driver+ subscription = driver.objectWillChange.sink { [weak self] _ in self?.revision += 1 }+ }+ func focus(_ id: String) { base.focus(id) }+ func play(_ id: String) { base.play(id) }+ func openOptions(_ id: String) { base.openOptions(id) }+ func setOption(gameID: String, setting: String, value: String) { base.setOption(gameID: gameID, setting: setting, value: value) }+ func openControllers() { base.openControllers() }+ func requestPlayer(_ player: Int) { base.requestPlayer(player) }+ func assignPlayer(controllerID: String, player: Int) { base.assignPlayer(controllerID: controllerID, player: player) }+ func requestAssignment(controllerID: String) { base.requestAssignment(controllerID: controllerID) }+ func identify(controllerID: String) { base.identify(controllerID: controllerID) }+ func disconnect(controllerID: String) { base.disconnect(controllerID: controllerID) }+ func setPadMerge(_ enabled: Bool) { base.setPadMerge(enabled) }+ func dismissToast() { base.dismissToast() }+ func back() { base.back() }+ func exitToDesktop() { base.exitToDesktop() }+ func returnFromGame() { base.returnFromGame() }+}++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))+ } else if controller.charging {+ Image(systemName: "bolt.fill").accessibilityLabel(L10n.string("console.charging", lang))+ }+ }+}++/// Fixed-height strip: controller arrivals only change its horizontal content, never the library's position.+struct ConsoleControllerChips: View {+ let controllers: [ConsoleController]+ let merged: Bool+ let lang: Lang+ var compact = false+ var scope = "console"+ let openControllers: () -> Void+ @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")+ }+ }+ 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) } ?? t("console.unassigned"))+ 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) }+ }+ }+ }+ }+ private func chip<C: View>(id: String, label: String, @ViewBuilder content: () -> C) -> some View {+ Button(action: openControllers) {+ content().font(.manrope(compact ? 12 : 17, .semibold))+ .padding(.horizontal, compact ? 10 : 14).frame(height: compact ? 30 : 40)+ .background(.white.opacity(0.075), in: Capsule()).contentShape(Capsule())+ }+ .buttonStyle(.plain)+ .accessibilityLabel(label)+ .accessibilityHint(t("console.controllers"))+ .padTarget(scope + ".chip." + id, scope: scope, radius: 24, activate: openControllers)+ }+}++struct ConsoleToastView: View {+ let toast: ConsoleToast+ var body: some View {+ Label(toast.message, systemImage: "gamecontroller")+ .font(.manrope(17, .semibold)).padding(.horizontal, 22).padding(.vertical, 15)+ .background(LauncherPalette.surface, in: Capsule())+ .overlay(Capsule().strokeBorder(.white.opacity(0.15)))+ .foregroundStyle(LauncherPalette.cream)+ .accessibilityElement(children: .combine)+ .allowsHitTesting(false)+ .padding(20)+ }+}++@MainActor struct ConsoleControllerList<Driver: ConsoleDriver>: View {+ @ObservedObject var driver: Driver+ let lang: Lang+ let compact: Bool+ var scope = "console.controllers"+ @EnvironmentObject private var pad: PadFocus+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ private var state: ConsoleState { driver.state }+ private func t(_ key: String) -> String { L10n.string(key, lang) }+ private func playerLabel(_ controller: ConsoleController) -> String {+ (state.padMerge ? 1 : controller.player).map { String(format: t("console.player"), $0) } ?? t("console.unassigned")+ }+ var body: some 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) }+ Text(t("console.controllerNote")).font(.manrope(compact ? 17 : 22)).foregroundStyle(.secondary)+ HStack(spacing: 12) {+ ForEach(1...4, id: \.self) { player in+ Button { driver.requestPlayer(player) } label: {+ Text(String(format: t("console.playerShort"), player)).font(.manrope(compact ? 18 : 22, .bold))+ .frame(maxWidth: .infinity, minHeight: 56)+ .background(state.assigningPlayer == player ? LauncherPalette.cream : LauncherPalette.surface, in: RoundedRectangle(cornerRadius: 12))+ .foregroundStyle(state.assigningPlayer == player ? LauncherPalette.background : .white)+ }+ .buttonStyle(.plain).accessibilityLabel(String(format: t("console.player"), player))+ .accessibilityAddTraits(state.assigningPlayer == player ? .isSelected : [])+ .padTarget("console.player.\(player)", scope: scope, activate: { driver.requestPlayer(player) })+ }+ }+ if let player = state.assigningPlayer {+ Text(String(format: t("console.pressToAssign"), player)).font(.manrope(compact ? 19 : 26, .semibold)).foregroundStyle(LauncherPalette.cream)+ }+ if state.controllers.isEmpty { Text(t("console.noControllers")) }+ ForEach(state.controllers) { controller in row(controller) }+ }+ .padding(.horizontal, compact ? 24 : 40).padding(.vertical, 12)+ }+ .onChange(of: pad.focused) { id in+ if let id { withAnimation(.easeOut(duration: reduceMotion ? 0 : 0.18)) { proxy.scrollTo(id, anchor: .center) } }+ }+ }+ }+ private func row(_ controller: ConsoleController) -> some View {+ VStack(alignment: .leading, spacing: 18) {+ HStack(spacing: 16) {+ Image(systemName: controller.kind.symbol).font(.system(size: compact ? 26 : 34)).frame(width: 42).accessibilityHidden(true)+ VStack(alignment: .leading, spacing: 6) {+ Text(controller.name).font(.manrope(compact ? 18 : 23, .semibold))+ Text(t(controller.kind.labelKey) + " · " + playerLabel(controller)).font(.manrope(compact ? 14 : 17)).foregroundStyle(.secondary)+ if controller.battery == nil { Text(t("console.batteryUnknown")).font(.manrope(13)).foregroundStyle(.secondary) }+ else { ConsoleBattery(controller: controller, lang: lang) }+ if controller.charging { Text(t("console.charging")).font(.manrope(13)).foregroundStyle(.secondary) }+ }+ Spacer(minLength: 0)+ }+ let layout = compact ? AnyLayout(VStackLayout(alignment: .leading, spacing: 10)) : AnyLayout(HStackLayout(spacing: 10))+ layout {+ action(id: controller.id + ".identify", label: t(state.identifyingControllerID == controller.id ? "console.identifying" : "console.identify"), symbol: "wave.3.right") { driver.identify(controllerID: controller.id) }+ action(id: controller.id + ".assign", label: t("console.assign"), symbol: "person.crop.circle.badge.plus") { driver.requestAssignment(controllerID: controller.id) }+ action(id: controller.id + ".disconnect", label: t("console.disconnect"), symbol: "xmark.circle") { driver.disconnect(controllerID: controller.id) }+ }+ if state.isPreview, state.assigningPlayer != nil, state.assigningControllerID == nil || state.assigningControllerID == controller.id {+ action(id: controller.id + ".press", label: t("console.mockPress"), symbol: "a.circle") {+ driver.assignPlayer(controllerID: controller.id, player: state.assigningPlayer ?? 1)+ }+ }+ }+ .padding(20).background(LauncherPalette.surface, in: RoundedRectangle(cornerRadius: 16))+ }+ private func action(id: String, label: String, value: String? = nil, symbol: String, adjust: ((Int) -> Void)? = nil, perform: @escaping () -> Void) -> some View {+ Button(action: perform) {+ VStack(alignment: .leading, spacing: 8) {+ Label(label, systemImage: symbol).font(.manrope(compact ? 16 : 18, .semibold))+ if let value { Text(value).font(.manrope(compact ? 16 : 20)).foregroundStyle(LauncherPalette.cream) }+ }+ .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." + id, scope: scope, radius: 10, activate: perform, adjust: adjust)+ .accessibilityLabel(label).accessibilityValue(value ?? "")+ }+}++@MainActor struct ConsoleControllersSheet<Driver: ConsoleDriver>: View {+ @ObservedObject var driver: Driver+ let lang: Lang+ let close: () -> Void+ @EnvironmentObject private var pad: PadFocus+ var body: some View {+ VStack(spacing: 0) {+ HStack {+ Text(L10n.string("console.controllers", lang)).font(.manrope(28, .bold)).accessibilityAddTraits(.isHeader)+ Spacer()+ Button(action: close) { Image(systemName: "xmark").frame(width: 48, height: 48) }+ .buttonStyle(.plain).accessibilityLabel(L10n.string("console.close", lang))+ .padTarget("console.sheet.close", scope: "console.controllers", activate: close)+ }.padding(24)+ ConsoleControllerList(driver: driver, lang: lang, compact: true)+ }+ .frame(minWidth: 360, idealWidth: 580, maxWidth: 580, minHeight: 600, idealHeight: 720, maxHeight: 720).background(LauncherPalette.background).preferredColorScheme(.dark)+ .foregroundStyle(.white).padScope("console.controllers", pad)+ .onAppear { pad.scope = "console.controllers"; pad.focused = "console.controller.merge" }+ .overlay(alignment: .bottom) { if let toast = driver.state.toast { ConsoleToastView(toast: toast) } }+ .background(ConsoleKeyboardInput { input in+ pad.show(default: "console.controller.merge")+ switch input {+ case .back: close()+ case .left: pad.horizontal(-1)+ case .right: pad.horizontal(1)+ case .up: pad.move(dx: 0, dy: -1)+ case .down: pad.move(dx: 0, dy: 1)+ case .activate: pad.activate()+ default: break+ }+ })+ }+}diff --git a/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swiftnew file mode 100644index 00000000..07ee492d--- /dev/null+++ b/frontend/Sources/NSPortBuilder/ConsoleEntryView.swift@@ -0,0 +1,73 @@+import SwiftUI++/// The desktop integration only reports an intent. The application coordinator will supply it later.+struct ConsoleEntryButton: View {+ let lang: Lang+ var compact = false+ let enterConsole: () -> Void+ var body: some View {+ Button(action: enterConsole) {+ Group {+ if compact { Image(systemName: "tv") }+ else { Label(L10n.string("console.entry", lang), systemImage: "tv") }+ }+ .font(.manrope(13, .semibold)).padding(.horizontal, 12).padding(.vertical, 8)+ .background(.white.opacity(0.07), in: Capsule()).contentShape(Capsule())+ }+ .buttonStyle(.plain).accessibilityLabel(L10n.string("console.entry", lang)).help(L10n.string("console.entry", lang))+ .padTarget("top.console", scope: "main", radius: 24, activate: enterConsole)+ }+}++struct ConsoleConnectionPrompt: View {+ let lang: Lang+ let enterConsole: () -> Void+ let dismissPrompt: () -> Void+ @EnvironmentObject private var pad: PadFocus+ private func t(_ key: String) -> String { L10n.string(key, lang) }+ var body: some View {+ ZStack {+ Color.black.opacity(0.65)+ VStack(alignment: .leading, spacing: 20) {+ Label(t("console.connectionTitle"), systemImage: "gamecontroller").font(.manrope(26, .bold))+ Text(t("console.connectionNote")).font(.manrope(18)).foregroundStyle(.secondary)+ VStack(alignment: .leading, spacing: 16) {+ Button(t("console.later"), action: dismissPrompt).buttonStyle(LauncherSecondaryButtonStyle())+ .keyboardShortcut(.cancelAction)+ .padTarget("console.entry.later", scope: "console.entry", activate: dismissPrompt)+ Button(action: enterConsole) {+ Text(t("console.entry")).font(.manrope(17, .bold)).foregroundStyle(LauncherPalette.background)+ .padding(.horizontal, 24).padding(.vertical, 14).background(LauncherPalette.cream, in: Capsule())+ }+ .buttonStyle(.plain).keyboardShortcut(.defaultAction)+ .padTarget("console.entry.enter", scope: "console.entry", radius: 30, activate: enterConsole)+ }+ }+ .padding(36).frame(maxWidth: 530).background(LauncherPalette.surface, in: RoundedRectangle(cornerRadius: 22))+ .overlay(RoundedRectangle(cornerRadius: 22).strokeBorder(.white.opacity(0.10)))+ .padding(24)+ }+ .padScope("console.entry", pad)+ .background(ConsoleKeyboardInput { input in+ pad.show(default: "console.entry.enter")+ switch input {+ case .back: dismissPrompt()+ case .activate: pad.activate()+ case .left: pad.horizontal(-1)+ case .right: pad.horizontal(1)+ case .up: pad.move(dx: 0, dy: -1)+ case .down: pad.move(dx: 0, dy: 1)+ default: break+ }+ })+ .onAppear { pad.scope = "console.entry"; pad.focused = "console.entry.enter" }+ .accessibilityAddTraits(.isModal)+ }+}++/// The demo is isolated from ContentView: no BuildModel, library discovery, controller adapter or process is made.+@MainActor struct ConsoleDemoView: View {+ @StateObject private var driver: MockConsoleDriver+ init(scenario: MockConsoleDriver.Scenario) { _driver = StateObject(wrappedValue: MockConsoleDriver(scenario: scenario)) }+ var body: some View { ConsoleView(driver: driver).frame(minWidth: 360, minHeight: 600) }+}diff --git a/frontend/Sources/NSPortBuilder/ConsoleKeyboardInput.swift b/frontend/Sources/NSPortBuilder/ConsoleKeyboardInput.swiftnew file mode 100644index 00000000..6896b831--- /dev/null+++ b/frontend/Sources/NSPortBuilder/ConsoleKeyboardInput.swift@@ -0,0 +1,43 @@+import AppKit+import SwiftUI++/// A window-local keyboard adapter. A local monitor keeps navigation working after a click gives a+/// native button first-responder status; it never consumes another window's keys or global shortcuts.+struct ConsoleKeyboardInput: NSViewRepresentable {+ var perform: (ConsoleInput) -> Void+ final class KeyView: NSView {+ var perform: (ConsoleInput) -> Void = { _ in }+ private var monitor: Any?+ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ if let monitor { NSEvent.removeMonitor(monitor); self.monitor = nil }+ guard window != nil else { return }+ monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in+ guard let self, let window = self.window, event.window === window, window.isKeyWindow,+ NSApp.isActive, event.modifierFlags.intersection([.command, .control, .option]).isEmpty,+ let input = Self.input(event) else { return event }+ self.perform(input)+ return nil+ }+ }+ deinit { if let monitor { NSEvent.removeMonitor(monitor) } }+ private static func input(_ event: NSEvent) -> ConsoleInput? {+ switch event.keyCode {+ case 123: return .left+ case 124: return .right+ case 125: return .down+ case 126: return .up+ case 36, 76, 49: return .activate+ case 53: return .back+ default:+ switch event.charactersIgnoringModifiers?.lowercased() {+ case "o", "+", "=": return .options+ case "y": return .controllers+ default: return nil+ }+ }+ }+ }+ func makeNSView(context: Context) -> KeyView { let view = KeyView(); view.perform = perform; return view }+ func updateNSView(_ view: KeyView, context: Context) { view.perform = perform }+}diff --git a/frontend/Sources/NSPortBuilder/ConsoleState.swift b/frontend/Sources/NSPortBuilder/ConsoleState.swiftnew file mode 100644index 00000000..8a86ec2b--- /dev/null+++ b/frontend/Sources/NSPortBuilder/ConsoleState.swift@@ -0,0 +1,210 @@+import SwiftUI+import Combine++/// Presentation snapshots only. The eventual driver supplies decoded artwork, localized launch settings,+/// controller names and a clock value; none of these types inspects a library or a controller device.+struct ConsoleGame: Identifiable {+ enum Status: Equatable {+ case ready, needsBuild, needsData, broken(String)+ var labelKey: String {+ switch self {+ case .ready: return "console.ready"+ case .needsBuild, .needsData: return "console.setup"+ case .broken: return "console.unavailable"+ }+ }+ var explanationKey: String? {+ switch self {+ case .ready: return nil+ case .needsBuild: return "console.needsBuild"+ case .needsData: return "console.needsData"+ case .broken: return "console.broken"+ }+ }+ }+ enum Platform: String, CaseIterable { case mac, iphone+ var labelKey: String { "console.platform." + rawValue }+ }+ var id: String+ var title: String+ var version: String+ var platforms: [Platform]+ var artwork: Image?+ var status: Status+ /// The exact launcher's model, already decoded and localized by the driver.+ var settings: [LaunchSetting] = []+ var values: [String: String] = [:]++ func value(_ setting: LaunchSetting) -> String { values[setting.env] ?? setting.def }+ var visibleSettings: [LaunchSetting] {+ settings.filter { setting in+ guard let needs = setting.needs else { return true }+ let parts = needs.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false).map(String.init)+ guard parts.count == 2, let parent = settings.first(where: { $0.env == parts[0] }) else { return false }+ return value(parent) == parts[1]+ }+ }+}++struct ConsoleController: Identifiable, Equatable {+ var id: String+ var name: String+ var player: Int?+ enum Kind: String, CaseIterable { case gamepad, pro, joyCon, xbox, keyboard+ var labelKey: String { "console.kind." + rawValue }+ var symbol: String {+ switch self {+ case .gamepad: return "gamecontroller"+ case .pro: return "gamecontroller.fill"+ case .joyCon: return "rectangle.split.2x1"+ case .xbox: return "circle.grid.cross"+ case .keyboard: return "keyboard"+ }+ }+ }+ var kind: Kind = .gamepad+ var battery: Double? = nil+ var charging = false+ var batteryPercent: Int? { battery.map { Int((min(max($0.isFinite ? $0 : 0, 0), 1) * 100).rounded()) } }+}++struct ConsoleToast: Equatable, Identifiable {+ var id = UUID()+ /// Already localized by the driver, using console connection/identification keys.+ var message: String+}++enum ConsoleStarting: Equatable {+ case preparing, compilingShaders(completed: Int, total: Int), opening+ var progress: Double? {+ if case let .compilingShaders(completed, total) = self, total > 0 { return min(max(Double(completed) / Double(total), 0), 1) }+ return nil+ }+}++enum ConsoleSheet: Equatable {+ case options(String), controllers, explanation(String)+ var scope: String {+ switch self {+ case .options: return "console.options"+ case .controllers: return "console.controllers"+ case .explanation: return "console.explanation"+ }+ }+}++struct ConsoleState {+ var games: [ConsoleGame] = []+ var focusedGameID: String?+ /// A stack allows an explanation or Controllers to return to the options underneath it.+ var sheets: [ConsoleSheet] = []+ var controllers: [ConsoleController] = []+ var isPreview = false+ var padMerge = false+ var toast: ConsoleToast?+ var identifyingControllerID: String?+ var assigningControllerID: String?+ var starting: ConsoleStarting = .preparing+ var assigningPlayer: Int?+ var startingGameID: String?+ var exited = false+ var time: Date = Date()+ var presentedSheet: ConsoleSheet? { sheets.last }+ var focusedGame: ConsoleGame? { games.first { $0.id == focusedGameID } ?? games.first }+ var startingGame: ConsoleGame? { games.first { $0.id == startingGameID } }++ mutating func focus(_ id: String) {+ guard startingGameID == nil, sheets.isEmpty, !exited, games.contains(where: { $0.id == id }) else { return }+ focusedGameID = id+ }+ mutating func moveFocus(_ step: Int) {+ guard !games.isEmpty else { return }+ let index = games.firstIndex { $0.id == focusedGame?.id } ?? 0+ focus(games[min(max(index + step, 0), games.count - 1)].id)+ }+ mutating func play(_ id: String) {+ guard !exited, startingGameID == nil, let game = games.first(where: { $0.id == id }) else { return }+ if game.status == .ready { startingGameID = id; starting = .preparing; sheets = [] }+ else if presentedSheet != .explanation(id) { sheets.append(.explanation(id)) }+ }+ mutating func openOptions(_ id: String) {+ guard !exited, startingGameID == nil, games.contains(where: { $0.id == id }), presentedSheet != .options(id) else { return }+ sheets.append(.options(id))+ }+ mutating func openControllers() {+ guard !exited, startingGameID == nil, presentedSheet != .controllers else { return }+ sheets.append(.controllers)+ }+ mutating func back() {+ guard !exited else { return }+ if startingGameID != nil { return } // the driver ends Starting when the game window appears+ if !sheets.isEmpty { sheets.removeLast(); assigningPlayer = nil; assigningControllerID = nil }+ else { exitToDesktop() }+ }+ mutating func exitToDesktop() { exited = true; sheets = []; startingGameID = nil; assigningPlayer = nil; assigningControllerID = nil }+ mutating func returnFromGame() { exited = false; startingGameID = nil; sheets = []; assigningPlayer = nil; assigningControllerID = nil }+ mutating func setOption(game id: String, setting env: String, value: String) {+ guard !exited, startingGameID == nil, let i = games.firstIndex(where: { $0.id == id }),+ let setting = games[i].visibleSettings.first(where: { $0.env == env }), setting.accepts(value) else { return }+ games[i].values[env] = value+ }+ mutating func assignPlayer(controller id: String, player: Int) {+ guard presentedSheet == .controllers, assigningControllerID == nil || assigningControllerID == id, (1...4).contains(player), controllers.contains(where: { $0.id == id }) else { return }+ // A player belongs to one controller; reassignment releases its former controller.+ for i in controllers.indices {+ if controllers[i].id == id { controllers[i].player = player }+ else if controllers[i].player == player { controllers[i].player = nil }+ }+ assigningPlayer = nil+ assigningControllerID = nil+ }+}++/// Main-actor intents form the entire I/O seam. A real driver owns launching, persistence, hardware+/// and returning to the desktop. B/Escape is `back`; the future Home-button adapter calls `returnFromGame`.+@MainActor protocol ConsoleDriver: ObservableObject {+ var state: ConsoleState { get }+ func focus(_ gameID: String)+ func play(_ gameID: String)+ func openOptions(_ gameID: String)+ func setOption(gameID: String, setting: String, value: String)+ func openControllers()+ func identify(controllerID: String)+ func disconnect(controllerID: String)+ func requestAssignment(controllerID: String)+ func setPadMerge(_ enabled: Bool)+ func dismissToast()+ func requestPlayer(_ player: Int)+ func assignPlayer(controllerID: String, player: Int)+ func back()+ func exitToDesktop()+ func returnFromGame()+}++/// 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? {+ switch setting.kind {+ case "choice":+ let values = (setting.options ?? []).compactMap(\.first)+ guard !values.isEmpty else { return nil }+ let index = values.firstIndex(of: value) ?? 0+ return values[((index + step) % values.count + values.count) % values.count]+ case "range":+ guard let lo = setting.min, let hi = setting.max, lo <= hi else { return nil }+ let delta = setting.step ?? 0.05+ guard delta > 0, delta.isFinite else { return nil }+ let current = Double(value) ?? Double(setting.def) ?? lo+ return String(format: "%.6g", min(max(lo + ((current - lo) / delta).rounded() * delta + Double(step) * delta, lo), hi))+ case "toggle": return value == setting.onValue ? setting.offValue : setting.onValue+ default: return nil+ }+ }+ static func label(_ setting: LaunchSetting, value: String, lang: Lang) -> String {+ if setting.kind == "toggle" { return L10n.string(value == setting.onValue ? "console.on" : "console.off", lang) }+ if setting.kind == "choice" {+ return setting.options?.first { $0.first == value }.flatMap { $0.count > 1 ? $0[1] : $0.first } ?? value+ }+ return value+ }+}diff --git a/frontend/Sources/NSPortBuilder/ConsoleView.swift b/frontend/Sources/NSPortBuilder/ConsoleView.swiftnew file mode 100644index 00000000..f8eaaa32--- /dev/null+++ b/frontend/Sources/NSPortBuilder/ConsoleView.swift@@ -0,0 +1,405 @@+import SwiftUI+import Combine++/// Semantic inputs from a future controller adapter; the view does not discover hardware.+enum ConsoleInput { case left, right, up, down, activate, back, options, controllers }++@MainActor struct ConsoleView<Driver: ConsoleDriver>: View {+ @ObservedObject var driver: Driver+ var lang: Lang = .initial()+ var inputs: AnyPublisher<ConsoleInput, Never> = Empty().eraseToAnyPublisher()+ @StateObject private var pad = PadFocus()+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ private var state: ConsoleState { driver.state }+ private var scope: String { state.presentedSheet?.scope ?? "console" }+ private func t(_ key: String) -> String { L10n.string(key, lang) }++ var body: some View {+ GeometryReader { geometry in+ let compact = geometry.size.width < 650+ ZStack(alignment: .trailing) {+ backdrop(size: geometry.size)+ if state.exited {+ exitPreview(compact: compact)+ } else if let game = state.startingGame {+ starting(game, compact: compact)+ } else {+ home(size: geometry.size, compact: compact)+ .allowsHitTesting(state.presentedSheet == nil)+ .accessibilityHidden(state.presentedSheet != nil)+ if let sheet = state.presentedSheet {+ Color.black.opacity(0.5).ignoresSafeArea().accessibilityHidden(true)+ sheetContent(sheet, compact: compact)+ .frame(width: compact ? geometry.size.width : min(700, max(520, geometry.size.width * 0.46)))+ .frame(maxHeight: .infinity)+ .background(LauncherPalette.background)+ .overlay(alignment: .leading) { Rectangle().fill(.white.opacity(0.10)).frame(width: 1) }+ .transition(.opacity)+ }+ }+ }+ .overlay(alignment: .top) {+ if let toast = state.toast { ConsoleToastView(toast: toast).id(toast.id).transition(.opacity) }+ }+ .frame(width: geometry.size.width, height: geometry.size.height)+ .clipped()+ }+ .background(LauncherPalette.background)+ .foregroundStyle(.white)+ .font(.manrope(22))+ .tint(LauncherPalette.cream)+ .preferredColorScheme(.dark)+ .environmentObject(pad)+ .background(ConsoleKeyboardInput(perform: handle).frame(width: 0, height: 0))+ .onReceive(inputs, perform: handle)+ .onChange(of: scope) { _ in resetFocus() }+ .onChange(of: state.exited) { _ in resetFocus() }+ .onAppear { resetFocus() }+ .onChange(of: pad.focused) { id in+ if let id, id.hasPrefix("console.game.") { driver.focus(String(id.dropFirst("console.game.".count))) }+ }+ .animation(.easeOut(duration: 0.22), value: state.focusedGame?.id)+ .animation(.easeOut(duration: 0.18), value: state.presentedSheet)+ .animation(.easeOut(duration: 0.18), value: state.toast?.id)+ .animation(.easeOut(duration: 0.22), value: state.startingGameID)+ }++ private func backdrop(size: CGSize) -> some View {+ ZStack {+ LauncherPalette.background+ if let game = state.startingGame ?? state.focusedGame, let image = game.artwork {+ image.resizable().scaledToFill().frame(width: size.width, height: size.height)+ .blur(radius: 70).drawingGroup().opacity(0.30).id(game.id).transition(.opacity)+ }+ LinearGradient(colors: [.black.opacity(0.10), LauncherPalette.background.opacity(0.95)], startPoint: .top, endPoint: .bottom)+ }+ .clipped().ignoresSafeArea().accessibilityHidden(true)+ }++ private func home(size: CGSize, compact: Bool) -> some View {+ let inset: CGFloat = compact ? 24 : 64+ return VStack(alignment: .leading, spacing: 0) {+ topBar(compact: compact).padding(.horizontal, inset).padding(.top, compact ? 24 : 40)+ if state.games.isEmpty {+ empty(compact: compact).frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ ScrollView(.vertical, showsIndicators: false) {+ VStack(alignment: .leading, spacing: compact || size.height < 900 ? 24 : 32) {+ if let game = state.focusedGame {+ VStack(alignment: .leading, spacing: compact ? 14 : 20) {+ Text(t("console.library")).font(.manrope(compact ? 14 : 18, .semibold))+ .tracking(2).foregroundStyle(LauncherPalette.cream.opacity(0.75))+ Text(game.title).font(.manrope(compact ? 36 : min(64, size.width / 24), .bold))+ .tracking(-1.6).lineLimit(2).fixedSize(horizontal: false, vertical: true)+ .accessibilityAddTraits(.isHeader)+ HStack(spacing: 12) {+ Text(String(format: t("console.version"), game.version)).foregroundStyle(.white.opacity(0.6))+ ForEach(game.platforms, id: \.self) { platform in+ Text(t(platform.labelKey)).font(.manrope(compact ? 13 : 17, .semibold))+ .padding(.horizontal, 12).padding(.vertical, 5)+ .background(.white.opacity(0.08), in: Capsule())+ }+ }+ .font(.manrope(compact ? 14 : 18))+ }+ .padding(.horizontal, inset)+ .frame(minHeight: compact ? 165 : size.height < 900 ? 140 : 195, alignment: .bottomLeading)+ }+ gameRow(size: size, compact: compact, inset: inset)+ }+ .padding(.top, compact ? 44 : size.height < 900 ? 24 : max(36, size.height * 0.065))+ .padding(.bottom, 24)+ }+ }+ if !state.games.isEmpty { hintBar(compact: compact).padding(.horizontal, inset).padding(.bottom, compact ? 20 : 32) }+ }+ .padScope("console", pad)+ }++ private func topBar(compact: Bool) -> some View {+ VStack(alignment: .leading, spacing: 20) {+ HStack(alignment: .firstTextBaseline) {+ Text(t("console.brand")).font(.manrope(compact ? 24 : 30, .bold)).tracking(-1)+ .foregroundStyle(LauncherPalette.cream)+ Spacer()+ Text(state.time, style: .time).font(.manrope(compact ? 17 : 22, .medium)).monospacedDigit()+ .foregroundStyle(.white.opacity(0.65))+ }+ ConsoleControllerChips(controllers: state.controllers, merged: state.padMerge, lang: lang, compact: compact) { driver.openControllers() }++ }+ }++ private func gameRow(size: CGSize, compact: Bool, inset: CGFloat) -> some View {+ let width: CGFloat = compact ? size.width - 70 : min(470, size.width * 0.32)+ return ScrollViewReader { proxy in+ ScrollView(.horizontal, showsIndicators: false) {+ HStack(alignment: .top, spacing: compact ? 22 : 28) {+ 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)+ .frame(width: width)+ .scaleEffect(selected && !reduceMotion ? 1.025 : 1)+ .contentShape(RoundedRectangle(cornerRadius: 18))+ }+ .buttonStyle(.plain)+ .padTarget("console.game." + game.id, scope: "console", radius: 18, activate: { driver.play(game.id) })+ .accessibilityLabel(game.title + ", " + t(game.status.labelKey))+ .accessibilityHint(t("console.playHint"))+ .accessibilityAddTraits(selected ? .isSelected : [])+ }+ }+ .padding(.horizontal, inset).padding(.vertical, 12)+ }+ .onChange(of: state.focusedGame?.id) { id in+ if let id { withAnimation(.easeOut(duration: reduceMotion ? 0 : 0.22)) { proxy.scrollTo("console.game." + id, anchor: .center) } }+ }+ .onAppear { if let id = state.focusedGame?.id { proxy.scrollTo("console.game." + id, anchor: .center) } }+ }+ }++ private func hintBar(compact: Bool) -> some View {+ let columns = compact ? [GridItem(.flexible()), GridItem(.flexible())] : Array(repeating: GridItem(.flexible(), alignment: .leading), count: 4)+ return VStack(spacing: 20) {+ Rectangle().fill(.white.opacity(0.10)).frame(height: 1)+ LazyVGrid(columns: columns, alignment: .leading, spacing: 16) {+ hint("a.circle", "console.play", "console.play", primary: true, compact: compact) { if let id = state.focusedGame?.id { driver.play(id) } }+ hint("plus.circle", "console.options", "console.options", compact: compact) { if let id = state.focusedGame?.id { driver.openOptions(id) } }+ hint("y.circle", "console.controllers", "console.controllers", compact: compact) { driver.openControllers() }+ hint("b.circle", "console.desktop", "console.desktop", compact: compact) { driver.exitToDesktop() }+ }+ }+ }++ private func hint(_ symbol: String, _ key: String, _ id: String, primary: Bool = false, compact: Bool, action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Label(t(key), systemImage: symbol).font(.manrope(compact ? 15 : 20, .semibold))+ .padding(.horizontal, primary ? 20 : 4).frame(minHeight: 48)+ .foregroundStyle(primary ? LauncherPalette.background : .white.opacity(0.8))+ .background(primary ? LauncherPalette.cream : .clear, in: Capsule())+ .contentShape(Capsule())+ }+ .buttonStyle(.plain).padTarget(id, scope: "console", radius: 28, activate: action)+ }++ @ViewBuilder private func sheetContent(_ sheet: ConsoleSheet, compact: Bool) -> some View {+ VStack(alignment: .leading, spacing: 0) {+ HStack {+ Text(t(sheetTitle(sheet)))+ .font(.manrope(compact ? 28 : 36, .bold)).accessibilityAddTraits(.isHeader)+ Spacer()+ Button { driver.back() } label: { Image(systemName: "xmark").font(.system(size: 20)).frame(width: 48, height: 48).contentShape(Circle()) }+ .buttonStyle(.plain).accessibilityLabel(t("console.close"))+ .padTarget("console.sheet.close", scope: sheet.scope, radius: 24, activate: { driver.back() })+ }+ .padding(.horizontal, compact ? 24 : 40).padding(.top, 30).padding(.bottom, 20)+ switch sheet {+ case let .options(id):+ if let game = state.games.first(where: { $0.id == id }) { options(game, compact: compact) }+ case .controllers: controllers(compact: compact)+ case let .explanation(id):+ if let game = state.games.first(where: { $0.id == id }) { explanation(game, compact: compact) }+ }+ }+ .padScope(sheet.scope, pad)+ }++ private func options(_ game: ConsoleGame, compact: Bool) -> some View {+ VStack(alignment: .leading, spacing: 0) {+ Text(game.title).font(.manrope(compact ? 19 : 24, .semibold)).foregroundStyle(LauncherPalette.cream)+ .padding(.horizontal, compact ? 24 : 40).padding(.bottom, 24)+ ScrollViewReader { proxy in+ ScrollView {+ VStack(spacing: 12) {+ if game.visibleSettings.isEmpty { Text(t("console.noOptions")).foregroundStyle(.secondary) }+ ForEach(game.visibleSettings) { setting in+ optionRow(setting, game: game, compact: compact)+ }+ }+ .padding(.horizontal, compact ? 24 : 40).padding(.vertical, 8)+ }+ .onChange(of: pad.focused) { id in if let id { withAnimation(.easeOut(duration: reduceMotion ? 0 : 0.18)) { proxy.scrollTo(id, anchor: .center) } } }+ }+ VStack(alignment: .leading, spacing: 18) {+ Text(t("console.adjustHint")).font(.manrope(compact ? 14 : 17)).foregroundStyle(.secondary)+ primaryButton(t("console.play"), id: "console.options.play", scope: "console.options") { driver.play(game.id) }+ }+ .padding(compact ? 24 : 40)+ }+ }++ private func optionRow(_ setting: LaunchSetting, game: ConsoleGame, compact: Bool) -> some View {+ let value = game.value(setting)+ let label = setting.env == "DM_RENDER_SCALE" ? "\(Int((Double(value) ?? 1) * 100))%" : ConsoleOption.label(setting, value: value, lang: lang)+ let adjust: (Int) -> Void = { step in+ if let next = ConsoleOption.stepped(setting, value: value, by: step) {+ driver.setOption(gameID: game.id, setting: setting.env, value: next)+ }+ }+ return Button { adjust(1) } label: {+ VStack(alignment: .leading, spacing: 10) {+ Text(setting.label).font(.manrope(compact ? 18 : 22, .semibold))+ HStack {+ Image(systemName: "chevron.left").font(.system(size: 12, weight: .bold))+ Text(label).font(.manrope(compact ? 18 : 23, .medium)).frame(maxWidth: .infinity)+ Image(systemName: "chevron.right").font(.system(size: 12, weight: .bold))+ }+ .foregroundStyle(LauncherPalette.cream)+ if !setting.note.isEmpty { Text(setting.note).font(.manrope(compact ? 14 : 17)).foregroundStyle(.secondary) }+ }+ .padding(20).frame(maxWidth: .infinity, minHeight: compact ? 100 : 112, alignment: .leading)+ .background(LauncherPalette.surface, in: RoundedRectangle(cornerRadius: 14))+ .contentShape(RoundedRectangle(cornerRadius: 14))+ }+ .buttonStyle(.plain)+ .padTarget("console.option." + setting.env, scope: "console.options", radius: 14, activate: { adjust(1) }, adjust: adjust)+ .accessibilityLabel(setting.label).accessibilityValue(label)+ .accessibilityHint(t("console.adjustHint"))+ .accessibilityAdjustableAction { direction in adjust(direction == .increment ? 1 : -1) }+ }++ private func controllers(compact: Bool) -> some View {+ ConsoleControllerList(driver: driver, lang: lang, compact: compact)+ }++ private func explanation(_ game: ConsoleGame, compact: Bool) -> some View {+ VStack(alignment: .leading, spacing: 24) {+ Text(game.title).font(.manrope(compact ? 27 : 38, .bold))+ Text(t(game.status.explanationKey ?? "console.ready")).font(.manrope(compact ? 20 : 26)).foregroundStyle(.secondary)+ if case let .broken(message) = game.status { Text(message).font(.manrope(compact ? 17 : 21)).foregroundStyle(.secondary) }+ Spacer(minLength: 24)+ primaryButton(t("console.desktop"), id: "console.explanation.desktop", scope: "console.explanation") { driver.exitToDesktop() }+ }+ .padding(compact ? 24 : 40)+ }++ private func empty(compact: Bool) -> some View {+ VStack(spacing: 24) {+ Image(systemName: "rectangle.stack").font(.system(size: compact ? 44 : 64, weight: .light)).foregroundStyle(LauncherPalette.cream.opacity(0.65)).accessibilityHidden(true)+ Text(t("console.empty")).font(.manrope(compact ? 34 : 54, .bold)).accessibilityAddTraits(.isHeader)+ Text(t("console.emptyNote")).font(.manrope(compact ? 20 : 26)).foregroundStyle(.secondary)+ primaryButton(t("console.desktop"), id: "console.empty.desktop", scope: "console") { driver.exitToDesktop() }.frame(maxWidth: 340)+ }+ .multilineTextAlignment(.center).padding(24)+ }++ private func starting(_ game: ConsoleGame, compact: Bool) -> some View {+ VStack(spacing: 30) {+ ConsoleArtwork(image: game.artwork).aspectRatio(1.8, contentMode: .fit).frame(maxWidth: compact ? 320 : 680)+ .clipShape(RoundedRectangle(cornerRadius: 22)).accessibilityHidden(true)+ Text(String(format: t("console.starting"), game.title)).font(.manrope(compact ? 30 : 48, .bold))+ .multilineTextAlignment(.center).accessibilityAddTraits(.isHeader)+ VStack(spacing: 16) {+ Text(startingLabel).font(.manrope(compact ? 17 : 22, .medium)).foregroundStyle(LauncherPalette.cream)+ if let progress = state.starting.progress {+ LauncherProgressBar(value: progress, height: 8, tint: LauncherPalette.cream)+ .transaction { if reduceMotion { $0.disablesAnimations = true } }+ .accessibilityLabel(t("console.shaders"))+ .accessibilityValue(String(format: t("console.batteryPercent"), Int(progress * 100)))+ }+ if state.isPreview { Text(t("console.simulatedShaders")).font(.manrope(compact ? 13 : 16)).foregroundStyle(.secondary) }+ }.frame(maxWidth: compact ? 320 : 540)+ }+ .padding(32).frame(maxWidth: .infinity, maxHeight: .infinity)+ }++ private var startingLabel: String {+ switch state.starting {+ case .preparing: return t("console.startingNote")+ case let .compilingShaders(completed, total): return String(format: t("console.shadersProgress"), completed, total)+ case .opening: return t("console.openingGame")+ }+ }++ private func exitPreview(compact: Bool) -> some View {+ VStack(spacing: 24) {+ Text(t("console.desktopPreview")).font(.manrope(compact ? 30 : 48, .bold))+ Text(t("console.desktopPreviewNote")).font(.manrope(compact ? 18 : 24)).foregroundStyle(.secondary)+ primaryButton(t("console.return"), id: "console.return", scope: "console") { driver.returnFromGame() }.frame(maxWidth: 360)+ }+ .multilineTextAlignment(.center).padding(24).frame(maxWidth: .infinity, maxHeight: .infinity)+ .padScope("console", pad)+ }++ private func primaryButton(_ label: String, id: String, scope: String, action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Text(label).font(.manrope(21, .bold)).foregroundStyle(LauncherPalette.background)+ .frame(maxWidth: .infinity, minHeight: 60).background(LauncherPalette.cream, in: Capsule()).contentShape(Capsule())+ }+ .buttonStyle(.plain).padTarget(id, scope: scope, radius: 32, activate: action)+ }+ private func sheetTitle(_ sheet: ConsoleSheet) -> String {+ switch sheet {+ case .controllers: return "console.controllers"+ case .options: return "console.options"+ case .explanation: return "console.setup"+ }+ }+ private func resetFocus() {+ pad.scope = scope+ pad.show(default: nil)+ switch state.presentedSheet {+ case let .options(id): pad.focused = state.games.first { $0.id == id }?.visibleSettings.first.map { "console.option." + $0.env } ?? "console.options.play"+ case .controllers: pad.focused = "console.player.\(state.assigningPlayer ?? 1)"+ case .explanation: pad.focused = "console.explanation.desktop"+ case nil: pad.focused = state.exited ? "console.return" : state.focusedGame.map { "console.game." + $0.id } ?? "console.empty.desktop"+ }+ }+ private func handle(_ input: ConsoleInput) {+ if input == .back { driver.back(); return }+ if state.exited { if input == .activate { driver.returnFromGame() }; return }+ guard state.startingGameID == nil else { return }+ pad.show(default: pad.focused)+ switch input {+ case .left, .right:+ let step = input == .left ? -1 : 1+ if state.presentedSheet == nil, pad.focused?.hasPrefix("console.game.") == true {+ var snapshot = state; snapshot.moveFocus(step)+ if let id = snapshot.focusedGame?.id { driver.focus(id); pad.focused = "console.game." + id }+ } else { pad.horizontal(step) }+ case .up: pad.move(dx: 0, dy: -1)+ case .down: pad.move(dx: 0, dy: 1)+ case .activate: pad.activate()+ case .options: if state.presentedSheet == nil, let id = state.focusedGame?.id { driver.openOptions(id) }+ case .controllers: driver.openControllers()+ case .back: break+ }+ }+}++/// Reusable 1.8:1 presentation; nil artwork uses the same quiet surface as the desktop library.+struct ConsoleArtwork: View {+ let image: Image?+ var body: some View {+ GeometryReader { geometry in+ if let image { image.resizable().scaledToFill().frame(width: geometry.size.width, height: geometry.size.height).clipped() }+ else { LauncherPalette.surface.overlay { Image(systemName: "gamecontroller").font(.system(size: 50)).foregroundStyle(.secondary) } }+ }+ }+}++struct ConsoleGameTile: View {+ let game: ConsoleGame+ let selected: Bool+ let compact: Bool+ let lang: Lang+ var body: some View {+ VStack(alignment: .leading, spacing: 16) {+ ConsoleArtwork(image: game.artwork).aspectRatio(1.8, contentMode: .fit)+ .overlay(alignment: .bottomLeading) {+ if game.status != .ready {+ Text(L10n.string(game.status.labelKey, lang)).font(.manrope(compact ? 14 : 18, .semibold))+ .padding(.horizontal, 14).padding(.vertical, 10)+ .background(LauncherPalette.background.opacity(0.93), in: Capsule()).padding(14)+ }+ }+ .clipShape(RoundedRectangle(cornerRadius: 16))+ .overlay(RoundedRectangle(cornerRadius: 16).strokeBorder(.white.opacity(0.12), lineWidth: 1))+ Text(game.title).font(.manrope(compact ? 18 : 23, .semibold)).lineLimit(2)+ .foregroundStyle(selected ? .white : .white.opacity(0.6)).padding(.horizontal, 16).padding(.bottom, 16)+ }+ .background(LauncherPalette.surface.opacity(0.65), in: RoundedRectangle(cornerRadius: 18))+ }+}diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 6e844631..aa413fb4 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -27,6 +27,10 @@ struct ContentView: View {@State private var page: LauncherPage = .library@State private var search = ""@State private var searching = false+ @State private var consolePrompt = false+ private let enterConsole: () -> Void+ @StateObject private var consoleDriver: AnyConsoleDriver+ @State private var controllerSheet = false@FocusState private var searchFocused: Bool@State private var artwork: [UUID: NSImage] = [:]@State private var activeBuildID: UUID?@@ -51,8 +55,11 @@ 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) {+ manageOpen: Bool = false, padRing: Bool = false, onRunSetup: (() -> Void)? = nil,+ enterConsole: @escaping () -> Void = {}, controllerDriver: AnyConsoleDriver? = nil) {self.onRunSetup = onRunSetup+ _consoleDriver = StateObject(wrappedValue: controllerDriver ?? AnyConsoleDriver(MockConsoleDriver(state: ConsoleState())))+ self.enterConsole = enterConsoleqaManage = (manageOpen, padRing)if let search { _search = State(initialValue: search); _searching = State(initialValue: true) } // visual QA: the bar with its field open_toolsAge = StateObject(wrappedValue: ToolsAge(older: olderTools)) // visual QA: games marked without a checkout to compare@@ -68,6 +75,33 @@ struct ContentView: View {}var body: some View {+ launcherBody+ .overlay(alignment: .top) {+ if !controllerSheet, let toast = consoleDriver.state.toast { ConsoleToastView(toast: toast) }+ }+ .sheet(isPresented: $controllerSheet) {+ ConsoleControllersSheet(driver: consoleDriver, lang: m.lang, close: { controllerSheet = false; consoleDriver.back() })+ .environmentObject(padFocus)+ }+ .onChange(of: controllerSheet) { open in+ padFocus.scope = open ? "console.controllers" : currentPadScope+ if open { consoleDriver.openControllers(); padFocus.focused = "console.controller.merge" }+ else if consoleDriver.state.presentedSheet == .controllers { consoleDriver.back() }+ }+ .overlay {+ if consolePrompt {+ ConsoleConnectionPrompt(lang: m.lang, enterConsole: { consolePrompt = false; enterConsole() }, dismissPrompt: { consolePrompt = false })+ }+ }+ .onChange(of: gamepad.connected) { connected in if connected { consolePrompt = true } }+ .onChange(of: consolePrompt) { open in+ padFocus.scope = open ? "console.entry" : currentPadScope+ if open { padFocus.focused = "console.entry.enter" }+ }+ .environmentObject(padFocus)+ }++ private var launcherBody: some View {VStack(spacing: 0) {topBarDivider().opacity(0.3)@@ -186,46 +220,68 @@ struct ContentView: View {}private var topBar: some View {- HStack(spacing: 6) {- // The project is NX2Apple (the user's call: what this fork produces is NX2Apple);- // "by nxnative" credits the engine it stands on, which the sketch kept.- VStack(alignment: .leading, spacing: -2) {- Text("NX2Apple").font(.manrope(27, .bold)).tracking(-0.8)- Text("— by nxnative").font(.manrope(10.5, .medium))- .foregroundStyle(LauncherPalette.unbuilt).tracking(0.2)- }- .padding(.trailing, 34)- ForEach(LauncherPage.allCases, id: \.self) { destination in- Button { page = destination } label: {- Label(m.t("nav." + destination.rawValue), systemImage: destination.symbol)- .font(.manrope(15, page == destination ? .bold : .medium))- .padding(.horizontal, 18).padding(.vertical, 10)- .background(page == destination ? Color.white.opacity(0.10) : .clear,- in: RoundedRectangle(cornerRadius: 9))- .contentShape(RoundedRectangle(cornerRadius: 9)) // the whole pill takes the click, not only its text+ GeometryReader { geometry in+ let compact = geometry.size.width < 1100 || (searching && geometry.size.width < 1400)+ VStack(spacing: 0) {+ HStack(spacing: 6) {+ // The project is NX2Apple (the user's call: what this fork produces is NX2Apple);+ // "by nxnative" credits the engine it stands on, which the sketch kept.+ VStack(alignment: .leading, spacing: -2) {+ Text("NX2Apple").font(.manrope(27, .bold)).tracking(-0.8)+ Text("— by nxnative").font(.manrope(10.5, .medium))+ .foregroundStyle(LauncherPalette.unbuilt).tracking(0.2)+ }+ .fixedSize(horizontal: true, vertical: false)+ .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) }+ }+ .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))+ .contentShape(RoundedRectangle(cornerRadius: 9)) // the whole pill takes the click, not only its text+ }+ .buttonStyle(.plain).help(m.t("nav." + destination.rawValue))+ .accessibilityAddTraits(page == destination ? .isSelected : [])+ .padTarget("tab." + destination.rawValue, scope: "main") { page = destination }+ }+ Spacer(minLength: 8)+ ConsoleEntryButton(lang: m.lang, compact: compact, enterConsole: enterConsole)+ searchField+ Button { newBuild() } label: {+ Group {+ if compact { Image(systemName: "plus").accessibilityLabel(m.t("library.newBuild")) }+ else { Label(m.t("library.newBuild"), systemImage: "plus") }+ }+ .padding(.horizontal, 12).padding(.vertical, 8)+ .background(Color.white.opacity(0.07), in: RoundedRectangle(cornerRadius: 8))+ .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Color.white.opacity(0.1)))+ .contentShape(RoundedRectangle(cornerRadius: 8))+ }+ .buttonStyle(.plain).disabled(m.running).help(m.t("library.newBuild")).accessibilityLabel(m.t("library.newBuild"))+ .padTarget("top.build", scope: "main", radius: 8) { if !m.running { newBuild() } }+ .padding(.leading, 12)}- .buttonStyle(.plain)- .accessibilityAddTraits(page == destination ? .isSelected : [])- .padTarget("tab." + destination.rawValue, scope: "main") { page = destination }- }- Spacer(minLength: 8)- searchField- Button { newBuild() } label: {- Label(m.t("library.newBuild"), systemImage: "plus")- .padding(.horizontal, 12).padding(.vertical, 8)- .background(Color.white.opacity(0.07), in: RoundedRectangle(cornerRadius: 8))- .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Color.white.opacity(0.1)))- .contentShape(RoundedRectangle(cornerRadius: 8))+ .padding(.leading, 90).padding(.trailing, 24)+ .frame(height: 64)+ .background(TitlebarDoubleClick()) // an empty part of the bar acts as the title bar does+ HStack {+ Spacer(minLength: 0)+ ConsoleControllerChips(controllers: consoleDriver.state.controllers, merged: consoleDriver.state.padMerge, lang: m.lang,+ compact: true, scope: "main") { controllerSheet = true }+ .frame(width: min(geometry.size.width - 114, max(120, CGFloat(consoleDriver.state.controllers.count) * 116)))+ }+ .padding(.leading, 90).padding(.trailing, 24)}- .buttonStyle(.plain).disabled(m.running)- .padTarget("top.build", scope: "main", radius: 8) { if !m.running { newBuild() } }- .padding(.leading, 12)}- .padding(.leading, 90).padding(.trailing, 24)- .frame(height: 64)- .background(TitlebarDoubleClick()) // an empty part of the bar acts as the title bar does+ .frame(height: 104)}+/// The magnifier opens into a search field in the bar itself; Esc, or leaving it empty, closes it again.private var searchField: some View {HStack(spacing: 8) {@@ -588,7 +644,19 @@ 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) {- let sheetOpen = optionsFor != nil || controlsOpen || savesFor != nil || freeSpaceFor != nil+ if consolePrompt {+ switch action {+ case .b: consolePrompt = false+ case .a: padFocus.activate()+ case .left: padFocus.horizontal(-1)+ case .right: padFocus.horizontal(1)+ case .up: padFocus.move(dx: 0, dy: -1)+ case .down: padFocus.move(dx: 0, dy: 1)+ default: break+ }+ return+ }+ let sheetOpen = controllerSheet || optionsFor != nil || controlsOpen || savesFor != nil || freeSpaceFor != nilswitch ManagePad.route(action, menuOpen: manageOpenFor != nil, sheetOpen: sheetOpen, hasGame: library.selected != nil && page == .library) {case .close: manageOpenFor = nil; returncase .swallow: return@@ -599,6 +667,7 @@ struct ContentView: View {returncase .pass: break}+ if action == .b, controllerSheet { controllerSheet = false; return }if action == .b, savesFor != nil { savesFor = nil; return }// The Free space sheet: B closes it, the D-pad and A work in it, X, L and R do nothing behind itif freeSpaceFor != nil && [.b, .x, .l, .r].contains(action) { if action == .b { freeSpaceFor = nil }; return }@@ -647,7 +716,7 @@ struct ContentView: View {/// The scope a controller acts in when no menu is open: the innermost sheet, else the window.private var currentPadScope: String {- savesFor != nil ? "saves" : freeSpaceFor != nil ? "free" : optionsFor != nil ? "launch" : controlsOpen ? "controls" : "main"+ controllerSheet ? "console.controllers" : savesFor != nil ? "saves" : freeSpaceFor != nil ? "free" : optionsFor != nil ? "launch" : controlsOpen ? "controls" : "main"}/// The space the collection row keeps around its cards for the focus ring (PadFocus draws it 4 pt outside a target).diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex c7fe38f4..27dff608 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -131,6 +131,89 @@ enum L10n {"onboarding.demo.library": ("\u{6e38}\u{620f}\u{5e93}\u{5c06}\u{5728}\u{6b64}\u{6253}\u{5f00}\u{3002}", "Your library would open here."),"onboarding.demo.note": ("\u{8fd9}\u{662f}\u{9884}\u{89c8}\u{3002}\u{672a}\u{8bfb}\u{53d6}\u{4efb}\u{4f55}\u{6587}\u{4ef6}\u{ff0c}\u{4e5f}\u{672a}\u{5b89}\u{88c5}\u{4efb}\u{4f55}\u{5de5}\u{5177}\u{3002}", "This is a preview. No files were read and no tools were installed."),"onboarding.demo.resume": ("\u{7ee7}\u{7eed}\u{8bbe}\u{7f6e}", "Resume setup"),+ "console.kind.gamepad": ("\u{6e38}\u{620f}\u{624b}\u{67c4}", "Gamepad"),+ "console.kind.pro": ("\u{4e13}\u{4e1a}\u{578b}\u{624b}\u{67c4}", "Pro-style pad"),+ "console.kind.joyCon": ("\u{53cc}\u{4f53}\u{624b}\u{67c4}", "Paired controllers"),+ "console.kind.xbox": ("Xbox \u{578b}\u{624b}\u{67c4}", "Xbox-style pad"),+ "console.kind.keyboard": ("\u{952e}\u{76d8}", "Keyboard"),+ "console.batteryPercent": ("%d%%", "%d%%"),+ "console.batteryLevel": ("\u{7535}\u{91cf}\u{767e}\u{5206}\u{4e4b} %d", "Battery %d percent"),+ "console.batteryCharging": ("\u{7535}\u{91cf}\u{767e}\u{5206}\u{4e4b} %d\u{ff0c}\u{6b63}\u{5728}\u{5145}\u{7535}", "Battery %d percent, charging"),+ "console.charging": ("\u{6b63}\u{5728}\u{5145}\u{7535}", "Charging"),+ "console.batteryUnknown": ("\u{672a}\u{62a5}\u{544a}\u{7535}\u{91cf}", "Battery not reported"),+ "console.identify": ("\u{8bc6}\u{522b}", "Identify"),+ "console.identifying": ("\u{6b63}\u{5728}\u{8bc6}\u{522b}\u{2026}", "Identifying\u{2026}"),+ "console.identifyingName": ("\u{6b63}\u{5728}\u{8bc6}\u{522b} %@\u{2026}", "Identifying %@\u{2026}"),+ "console.assign": ("\u{5206}\u{914d}\u{73a9}\u{5bb6}", "Assign player"),+ "console.disconnect": ("\u{65ad}\u{5f00}\u{8fde}\u{63a5}", "Disconnect"),+ "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.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"),+ "console.connected": ("%@ \u{5df2}\u{8fde}\u{63a5}\u{ff0c}\u{73a9}\u{5bb6} %d", "%@ connected, player %d"),+ "console.disconnected": ("%@ \u{5df2}\u{65ad}\u{5f00}\u{8fde}\u{63a5}", "%@ disconnected"),+ "console.demoXbox": ("Xbox \u{624b}\u{67c4}", "Xbox controller"),+ "console.demoKeyboard": ("\u{952e}\u{76d8}", "Keyboard"),+ "console.demoPaired": ("\u{53cc}\u{4f53}\u{624b}\u{67c4}", "Paired controllers"),+ "console.shaders": ("\u{6b63}\u{5728}\u{7f16}\u{8bd1}\u{7740}\u{8272}\u{5668}", "Compiling shaders"),+ "console.shadersProgress": ("\u{6b63}\u{5728}\u{7f16}\u{8bd1}\u{7740}\u{8272}\u{5668} \u{b7} %d / %d", "Compiling shaders \u{b7} %d of %d"),+ "console.openingGame": ("\u{6b63}\u{5728}\u{6253}\u{5f00}\u{6e38}\u{620f}\u{7a97}\u{53e3}\u{2026}", "Opening game window\u{2026}"),+ "console.simulatedShaders": ("\u{6b64}\u{9884}\u{89c8}\u{4e2d}\u{7684}\u{8fdb}\u{5ea6}\u{4e3a}\u{6a21}\u{62df}\u{8fdb}\u{5ea6}", "Simulated progress in this preview"),+ // Console presentation and its in-memory previews.+ "console.brand": ("NX2Apple", "NX2Apple"),+ "console.entry": ("\u{4e3b}\u{673a}\u{6a21}\u{5f0f}", "Console mode"),+ "console.connectionTitle": ("\u{5207}\u{6362}\u{5230}\u{4e3b}\u{673a}\u{6a21}\u{5f0f}\u{ff1f}", "Switch to console mode?"),+ "console.connectionNote": ("\u{624b}\u{67c4}\u{5df2}\u{8fde}\u{63a5}\u{3002}\u{5728}\u{5927}\u{5c4f}\u{5e55}\u{4e0a}\u{9009}\u{62e9}\u{5e76}\u{7545}\u{73a9}\u{6e38}\u{620f}\u{3002}", "A controller is connected. Your games, ready for the big screen."),+ "console.later": ("\u{7559}\u{5728}\u{684c}\u{9762}\u{6a21}\u{5f0f}", "Stay on desktop"),+ "console.library": ("\u{4f60}\u{7684}\u{6e38}\u{620f}", "YOUR GAMES"),+ "console.ready": ("\u{53ef}\u{4ee5}\u{5f00}\u{59cb}\u{6e38}\u{620f}", "Ready to play"),+ "console.setup": ("\u{5728} Mac \u{4e0a}\u{5b8c}\u{6210}\u{8bbe}\u{7f6e}", "Set up on your Mac"),+ "console.unavailable": ("\u{9700}\u{8981}\u{5904}\u{7406}", "Needs attention"),+ "console.needsBuild": ("\u{5148}\u{5728} Mac \u{4e0a}\u{6784}\u{5efa}\u{6b64}\u{6e38}\u{620f}\u{ff0c}\u{7136}\u{540e}\u{56de}\u{6765}\u{5f00}\u{59cb}\u{6e38}\u{620f}\u{3002}", "Build this game on your Mac, then come back to play."),+ "console.needsData": ("\u{5148}\u{5728}\u{684c}\u{9762}\u{6a21}\u{5f0f}\u{4e2d}\u{9009}\u{62e9}\u{6e38}\u{620f}\u{6570}\u{636e}\u{ff0c}\u{7136}\u{540e}\u{56de}\u{6765}\u{5f00}\u{59cb}\u{6e38}\u{620f}\u{3002}", "Choose this game\u{2019}s data in desktop mode, then come back to play."),+ "console.broken": ("\u{6b64}\u{6e38}\u{620f}\u{9700}\u{8981}\u{5728}\u{684c}\u{9762}\u{6a21}\u{5f0f}\u{4e2d}\u{5904}\u{7406}\u{3002}", "This game needs attention in desktop mode."),+ "console.platform.mac": ("Mac", "Mac"),+ "console.platform.iphone": ("iPhone", "iPhone"),+ "console.version": ("\u{7248}\u{672c} %@", "Version %@"),+ "console.play": ("\u{5f00}\u{59cb}\u{6e38}\u{620f}", "Play"),+ "console.playHint": ("\u{5f00}\u{59cb}\u{6e38}\u{620f}\u{ff0c}\u{6216}\u{4e86}\u{89e3}\u{5982}\u{4f55}\u{5b8c}\u{6210}\u{8bbe}\u{7f6e}\u{3002}", "Play, or learn how to finish setup."),+ "console.options": ("\u{6e38}\u{620f}\u{9009}\u{9879}", "Game options"),+ "console.controllers": ("\u{624b}\u{67c4}", "Controllers"),+ "console.desktop": ("\u{8fd4}\u{56de}\u{684c}\u{9762}", "Back to desktop"),+ "console.close": ("\u{8fd4}\u{56de}", "Back"),+ "console.empty": ("\u{8fd8}\u{6ca1}\u{6709}\u{6e38}\u{620f}", "No games yet"),+ "console.emptyNote": ("\u{5728} Mac \u{4e0a}\u{6784}\u{5efa}\u{4e00}\u{4e2a}\u{6e38}\u{620f}\u{3002}", "Build one on your Mac."),+ "console.starting": ("\u{6b63}\u{5728}\u{542f}\u{52a8} %@\u{2026}", "Starting %@\u{2026}"),+ "console.startingNote": ("\u{6b63}\u{5728}\u{51c6}\u{5907}\u{6e38}\u{620f}", "Getting your game ready"),+ "console.noOptions": ("\u{6b64}\u{6e38}\u{620f}\u{6ca1}\u{6709}\u{542f}\u{52a8}\u{9009}\u{9879}\u{3002}", "This game has no launch options."),+ "console.adjustHint": ("\u{4f7f}\u{7528}\u{5de6}\u{53f3}\u{65b9}\u{5411}\u{952e}\u{8c03}\u{6574}\u{3002}", "Use left or right to adjust."),+ "console.on": ("\u{5f00}\u{542f}", "On"),+ "console.off": ("\u{5173}\u{95ed}", "Off"),+ "console.noControllers": ("\u{672a}\u{8fde}\u{63a5}\u{624b}\u{67c4}", "No controllers connected"),+ "console.player": ("\u{73a9}\u{5bb6} %d", "Player %d"),+ "console.playerShort": ("P%d", "P%d"),+ "console.unassigned": ("\u{672a}\u{5206}\u{914d}", "Unassigned"),+ "console.pressToAssign": ("\u{6309}\u{4e0b}\u{4e00}\u{4e2a}\u{6309}\u{94ae}\u{4ee5}\u{5206}\u{914d}\u{73a9}\u{5bb6} %d\u{3002}", "Press a button to assign player %d."),+ "console.controllerNote": ("\u{9009}\u{62e9}\u{73a9}\u{5bb6}\u{ff0c}\u{7136}\u{540e}\u{6309}\u{4e0b}\u{8be5}\u{73a9}\u{5bb6}\u{624b}\u{67c4}\u{4e0a}\u{7684}\u{6309}\u{94ae}\u{3002}", "Choose a player, then press a button on their controller."),+ "console.desktopPreview": ("\u{5df2}\u{8fd4}\u{56de}\u{684c}\u{9762}\u{6a21}\u{5f0f}", "Back on desktop"),+ "console.desktopPreviewNote": ("\u{9884}\u{89c8}\u{5df2}\u{7ed3}\u{675f}\u{3002}\u{6e38}\u{620f}\u{5e93}\u{4fdd}\u{6301}\u{4e0d}\u{53d8}\u{3002}", "Preview complete. Your library stays as it is."),+ "console.return": ("\u{8fd4}\u{56de}\u{4e3b}\u{673a}\u{6a21}\u{5f0f}", "Return to console"),+ "console.resolution": ("\u{5206}\u{8fa8}\u{7387}\u{7f29}\u{653e}", "Resolution scale"),+ "console.frameRate": ("\u{5e27}\u{7387}", "Frame rate"),+ "console.fps30": ("30 \u{5e27}/\u{79d2}", "30 fps"),+ "console.fps60": ("60 \u{5e27}/\u{79d2}", "60 fps"),+ "console.language": ("\u{6e38}\u{620f}\u{8bed}\u{8a00}", "Game language"),+ "console.english": ("\u{82f1}\u{8bed}", "English"),+ "console.chinese": ("\u{4e2d}\u{6587}", "Chinese"),+ "console.japanese": ("\u{65e5}\u{8bed}", "Japanese"),+ "console.fullscreen": ("\u{5168}\u{5c4f}", "Full screen"),+ "console.rumble": ("\u{624b}\u{67c4}\u{632f}\u{52a8}", "Controller vibration"),+ "console.demoBroken": ("\u{4e0a}\u{6b21}\u{6784}\u{5efa}\u{672a}\u{5b8c}\u{6210}\u{3002}\u{8bf7}\u{5728} Mac \u{4e0a}\u{91cd}\u{65b0}\u{6784}\u{5efa}\u{3002}", "The last build did not finish. Rebuild it on your Mac."),+ "console.demoController": ("\u{65e0}\u{7ebf}\u{624b}\u{67c4}", "Wireless controller"),+ "console.demoController2": ("\u{4e13}\u{4e1a}\u{624b}\u{67c4}", "Pro controller"),+ "console.demoController3": ("USB \u{624b}\u{67c4}", "USB controller"),+"library.readyIOS": ("\u{53ef}\u{7528}\u{4e8e} iPhone", "Ready for iPhone"),"library.stopping": ("\u{6b63}\u{5728}\u{505c}\u{6b62}…", "Stopping…"),"build.setup": ("\u{5b8c}\u{6210}\u{8bbe}\u{7f6e}", "Finish setup"),diff --git a/frontend/Sources/NSPortBuilder/MockConsoleDriver.swift b/frontend/Sources/NSPortBuilder/MockConsoleDriver.swiftnew file mode 100644index 00000000..3dfd6151--- /dev/null+++ b/frontend/Sources/NSPortBuilder/MockConsoleDriver.swift@@ -0,0 +1,128 @@+import SwiftUI++@MainActor final class MockConsoleDriver: ConsoleDriver {+ enum Scenario: String, CaseIterable { case full, few, empty, controllers, controllersMixed, starting }+ @Published var state: ConsoleState+ private var toastTask: Task<Void, Never>?+ private var startingTask: Task<Void, Never>?+ private var lang: Lang = .initial()+ private var animated = true++ init(state: ConsoleState, lang: Lang = .initial(), animated: Bool = true) { self.state = state; self.lang = lang; self.animated = animated }+ convenience init(scenario: Scenario = .full, lang: Lang = .initial(), animated: Bool = true) {+ func t(_ key: String) -> String { L10n.string(key, lang) }+ let settings = [+ LaunchSetting(env: "DM_RENDER_SCALE", kind: "range", label: t("console.resolution"), note: "", def: "1", section: nil,+ options: nil, min: 0.5, max: 2, step: 0.25, on: nil, off: nil),+ LaunchSetting(env: "DM_FPS_TARGET", kind: "choice", label: t("console.frameRate"), note: "", def: "60", section: nil,+ options: [["30", t("console.fps30")], ["60", t("console.fps60")]], min: nil, max: nil, step: nil, on: nil, off: nil),+ LaunchSetting(env: "DM_LANG", kind: "choice", label: t("console.language"), note: "", def: "en", section: nil,+ options: [["en", t("console.english")], ["zh", t("console.chinese")], ["ja", t("console.japanese")]], min: nil, max: nil, step: nil, on: nil, off: nil),+ LaunchSetting(env: "DM_FULLSCREEN", kind: "toggle", label: t("console.fullscreen"), note: "", def: "1", section: nil,+ options: nil, min: nil, max: nil, step: nil, on: nil, off: nil),+ LaunchSetting(env: "DM_RUMBLE", kind: "toggle", label: t("console.rumble"), note: "", def: "1", section: nil,+ options: nil, min: nil, max: nil, step: nil, on: nil, off: nil)+ ]+ // Packaged preview artwork; no title database, library, file path or network access.+ let titles = ["Hollow Knight: Silksong", "Celeste", "Hades", "Sea of Stars", "Portal", "Balatro", "Animal Well", "Cuphead", "Stardew Valley", "Return of the Obra Dinn", "Blasphemous", "Hades II"]+ let games = titles.enumerated().map { index, title in+ ConsoleGame(id: "demo.\(index)", title: title, version: "1.0.\(index % 3)", platforms: index % 3 == 1 ? [.mac] : [.mac, .iphone],+ artwork: Bundle.module.image(forResource: "ConsoleCover\(index).jpg").map { Image(nsImage: $0) },+ status: index == 3 ? .needsBuild : index == 5 ? .needsData : index == 7 ? .broken(t("console.demoBroken")) : .ready,+ settings: settings)+ }+ var snapshot = ConsoleState(games: scenario == .empty ? [] : scenario == .few ? Array(games.prefix(2)) : games,+ focusedGameID: scenario == .empty ? nil : "demo.0",+ controllers: [.init(id: "pad.1", name: t("console.demoController"), player: 1)],+ time: Date(timeIntervalSince1970: 1_793_210_400))+ snapshot.isPreview = true+ if scenario == .controllers {+ snapshot.controllers += [.init(id: "pad.2", name: t("console.demoController2"), player: 2),+ .init(id: "pad.3", name: t("console.demoController3"), player: nil)]+ snapshot.openControllers(); snapshot.assigningPlayer = 3+ }+ if scenario == .controllersMixed {+ snapshot.controllers = [+ .init(id: "pad.1", name: t("console.demoController2"), player: 1, kind: .pro, battery: 0.76),+ .init(id: "pad.2", name: t("console.demoXbox"), player: 2, kind: .xbox, battery: 0.12),+ .init(id: "keyboard", name: t("console.demoKeyboard"), player: 3, kind: .keyboard),+ .init(id: "pad.4", name: t("console.demoPaired"), player: 4, kind: .joyCon, battery: 0.48, charging: true)+ ]+ snapshot.openControllers()+ }+ if scenario == .starting { snapshot.play("demo.0"); snapshot.starting = .compilingShaders(completed: 18, total: 48) }+ self.init(state: snapshot, lang: lang, animated: animated)+ if scenario == .starting, animated { animateStarting("demo.0") }+ }+ func focus(_ gameID: String) { state.focus(gameID) }+ func play(_ gameID: String) {+ let wasStarting = state.startingGameID != nil+ state.play(gameID)+ if !wasStarting, state.startingGameID != nil, animated { animateStarting(gameID) }+ }+ private func animateStarting(_ gameID: String) {+ startingTask?.cancel()+ startingTask = Task { [weak self] in+ for count in stride(from: 0, through: 48, by: 4) {+ try? await Task.sleep(nanoseconds: 180_000_000)+ guard !Task.isCancelled, let self, self.state.startingGameID == gameID else { return }+ self.state.starting = .compilingShaders(completed: count, total: 48)+ }+ self?.state.starting = .opening+ }+ }++ func openOptions(_ gameID: String) { state.openOptions(gameID) }+ func setOption(gameID: String, setting: String, value: String) { state.setOption(game: gameID, setting: setting, value: value) }+ func openControllers() { state.openControllers() }+ deinit { toastTask?.cancel(); startingTask?.cancel() }+ func requestPlayer(_ player: Int) {+ guard state.presentedSheet == .controllers, (1...4).contains(player) else { return }+ state.assigningPlayer = player+ }+ func assignPlayer(controllerID: String, player: Int) { state.assignPlayer(controller: controllerID, player: player) }+ func back() { state.back() }+ func exitToDesktop() { startingTask?.cancel(); state.exitToDesktop() }+ func returnFromGame() { startingTask?.cancel(); state.returnFromGame() }+ func identify(controllerID: String) {+ guard let controller = state.controllers.first(where: { $0.id == controllerID }) else { return }+ state.identifyingControllerID = controllerID+ showToast(String(format: L10n.string("console.identifyingName", lang), controller.name))+ }+ func disconnect(controllerID: String) {+ guard let controller = state.controllers.first(where: { $0.id == controllerID }) else { return }+ state.controllers.removeAll { $0.id == controllerID }+ if state.assigningControllerID == controllerID { state.assigningControllerID = nil; state.assigningPlayer = nil }+ showToast(String(format: L10n.string("console.disconnected", lang), controller.name))+ }+ func requestAssignment(controllerID: String) {+ guard state.presentedSheet == .controllers, let controller = state.controllers.first(where: { $0.id == controllerID }) else { return }+ state.assigningControllerID = controllerID+ state.assigningPlayer = state.assigningPlayer ?? controller.player ?? 1+ }+ func setPadMerge(_ enabled: Bool) { state.padMerge = enabled }+ func dismissToast() { toastTask?.cancel(); state.toast = nil; state.identifyingControllerID = nil }+ /// A transport event simulated by tests or a preview coordinator, without hardware discovery.+ func connect(_ controller: ConsoleController) {+ state.controllers.removeAll { $0.id == controller.id }+ var connected = controller+ if let player = connected.player, state.controllers.contains(where: { $0.player == player }) {+ connected.player = (1...4).first { player in !state.controllers.contains(where: { $0.player == player }) }+ }+ state.controllers.append(connected)+ if let player = state.padMerge ? 1 : connected.player {+ showToast(String(format: L10n.string("console.connected", lang), connected.name, player))+ } else { showToast(String(format: L10n.string("console.connectedUnassigned", lang), connected.name)) }+ }+ private func showToast(_ message: String) {+ toastTask?.cancel()+ state.toast = ConsoleToast(message: message)+ guard animated else { return }+ 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/NSPortBuilderApp.swift b/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swiftindex e05f4d18..27db125d 100644--- a/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift+++ b/frontend/Sources/NSPortBuilder/NSPortBuilderApp.swift@@ -9,6 +9,8 @@ struct NSPortBuilderApp: App {if let name = ProcessInfo.processInfo.environment["NSPB_ONBOARDING_DEMO"],let scenario = MockOnboardingDriver.Scenario(rawValue: name) {OnboardingDemoHost(scenario: scenario)+ } else if let scenario = ProcessInfo.processInfo.environment["NSPB_CONSOLE_DEMO"].flatMap(MockConsoleDriver.Scenario.init(rawValue:)) {+ ConsoleDemoView(scenario: scenario)} else { RootView() }}.windowStyle(.hiddenTitleBar)diff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover0.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover0.jpgnew file mode 100644index 00000000..4acb9a33Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover0.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover1.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover1.jpgnew file mode 100644index 00000000..cabb6531Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover1.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover10.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover10.jpgnew file mode 100644index 00000000..28ac4f26Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover10.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover11.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover11.jpgnew file mode 100644index 00000000..397c9c3dBinary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover11.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover2.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover2.jpgnew file mode 100644index 00000000..4f90f5c8Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover2.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover3.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover3.jpgnew file mode 100644index 00000000..e4ec0463Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover3.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover4.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover4.jpgnew file mode 100644index 00000000..1d0ee393Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover4.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover5.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover5.jpgnew file mode 100644index 00000000..58b49bb8Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover5.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover6.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover6.jpgnew file mode 100644index 00000000..27125b95Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover6.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover7.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover7.jpgnew file mode 100644index 00000000..82f0fa67Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover7.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover8.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover8.jpgnew file mode 100644index 00000000..da9154f1Binary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover8.jpg differdiff --git a/frontend/Sources/NSPortBuilder/Resources/ConsoleCover9.jpg b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover9.jpgnew file mode 100644index 00000000..600e969dBinary files /dev/null and b/frontend/Sources/NSPortBuilder/Resources/ConsoleCover9.jpg differdiff --git a/frontend/Tests/NSPortBuilderTests/ConsoleTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleTests.swiftnew file mode 100644index 00000000..5e88c774--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/ConsoleTests.swift@@ -0,0 +1,268 @@+import XCTest+import SwiftUI+import Combine+@testable import NSPortBuilder++final class ConsoleTests: XCTestCase {+ @MainActor func testScenariosAndBoundedFocus() {+ let driver = MockConsoleDriver(animated: false)+ XCTAssertEqual(driver.state.games.count, 12)+ XCTAssertTrue(driver.state.games.allSatisfy { $0.artwork != nil }, "Every preview game must have bundled artwork")+ driver.focus("demo.2")+ XCTAssertEqual(driver.state.focusedGameID, "demo.2")+ driver.focus("missing")+ XCTAssertEqual(driver.state.focusedGameID, "demo.2")+ var state = driver.state+ state.moveFocus(-100)+ XCTAssertEqual(state.focusedGame?.id, "demo.0")+ state.moveFocus(100)+ XCTAssertEqual(state.focusedGame?.id, "demo.11")+ XCTAssertEqual(MockConsoleDriver(scenario: .few, animated: false).state.games.count, 2)+ var empty = MockConsoleDriver(scenario: .empty, animated: false).state+ empty.moveFocus(1)+ XCTAssertNil(empty.focusedGame)+ XCTAssertNil(MockConsoleDriver.Scenario(rawValue: "unknown"))+ XCTAssertNotNil(MockConsoleDriver(scenario: .starting, animated: false).state.startingGame)+ }++ @MainActor func testPlayExplainsEachUnavailableStatus() {+ for (id, key) in [("demo.3", "console.needsBuild"), ("demo.5", "console.needsData"), ("demo.7", "console.broken")] {+ let driver = MockConsoleDriver(animated: false)+ driver.focus(id)+ driver.play(id)+ XCTAssertNil(driver.state.startingGameID)+ XCTAssertEqual(driver.state.presentedSheet, .explanation(id))+ XCTAssertEqual(driver.state.focusedGame?.status.explanationKey, key)+ driver.play(id) // repeated input must not stack duplicate explanations+ XCTAssertEqual(driver.state.sheets.count, 1)+ }+ let driver = MockConsoleDriver(animated: false)+ driver.play("unknown")+ XCTAssertNil(driver.state.startingGameID)+ driver.play("demo.0")+ XCTAssertEqual(driver.state.startingGameID, "demo.0")+ driver.back() // Starting ends only through the driver, not a second launch or a timeout+ driver.play("demo.1")+ XCTAssertEqual(driver.state.startingGameID, "demo.0")+ driver.returnFromGame()+ XCTAssertNil(driver.state.startingGameID)+ XCTAssertEqual(driver.state.focusedGameID, "demo.0")+ }++ @MainActor func testSheetStackAndBackExitRestoration() {+ let driver = MockConsoleDriver(animated: false)+ driver.focus("demo.5")+ driver.openOptions("demo.5")+ driver.openOptions("demo.5")+ XCTAssertEqual(driver.state.sheets.count, 1)+ driver.openControllers()+ driver.focus("demo.0")+ XCTAssertEqual(driver.state.focusedGameID, "demo.5")+ driver.back()+ XCTAssertEqual(driver.state.presentedSheet, .options("demo.5"))+ driver.play("demo.5")+ XCTAssertEqual(driver.state.presentedSheet, .explanation("demo.5"))+ driver.back()+ XCTAssertEqual(driver.state.presentedSheet, .options("demo.5"))+ driver.back()+ XCTAssertNil(driver.state.presentedSheet)+ XCTAssertFalse(driver.state.exited)+ driver.back()+ XCTAssertTrue(driver.state.exited)+ driver.openOptions("demo.0"); driver.openControllers(); driver.play("demo.0")+ XCTAssertNil(driver.state.presentedSheet)+ XCTAssertNil(driver.state.startingGameID)+ driver.returnFromGame()+ XCTAssertFalse(driver.state.exited)+ XCTAssertEqual(driver.state.focusedGameID, "demo.5")+ driver.openControllers()+ driver.exitToDesktop()+ XCTAssertTrue(driver.state.sheets.isEmpty)+ }++ @MainActor func testOptionsUseLaunchSettingValidationAndDependencies() throws {+ let driver = MockConsoleDriver(animated: false)+ driver.setOption(gameID: "demo.0", setting: "DM_FPS_TARGET", value: "120")+ XCTAssertNil(driver.state.games[0].values["DM_FPS_TARGET"])+ driver.setOption(gameID: "demo.0", setting: "DM_FPS_TARGET", value: "30")+ XCTAssertEqual(driver.state.games[0].values["DM_FPS_TARGET"], "30")+ let scale = try XCTUnwrap(driver.state.games[0].settings.first { $0.kind == "range" })+ XCTAssertEqual(ConsoleOption.stepped(scale, value: "2", by: 1), "2")+ XCTAssertEqual(ConsoleOption.stepped(scale, value: "0.5", by: -1), "0.5")+ XCTAssertEqual(ConsoleOption.stepped(scale, value: "1", by: 1), "1.25")+ let choice = try XCTUnwrap(driver.state.games[0].settings.first { $0.kind == "choice" })+ XCTAssertEqual(ConsoleOption.stepped(choice, value: "60", by: 1), "30")+ XCTAssertEqual(ConsoleOption.stepped(choice, value: "30", by: -1), "60")+ let toggle = try XCTUnwrap(driver.state.games[0].settings.first { $0.kind == "toggle" })+ XCTAssertEqual(ConsoleOption.stepped(toggle, value: "1", by: 1), "0")+ var child = toggle+ child.needs = "DM_FPS_TARGET=60"+ var game = driver.state.games[0]+ game.settings = [choice, child]+ game.values = ["DM_FPS_TARGET": "30"]+ XCTAssertEqual(game.visibleSettings.count, 1)+ game.values["DM_FPS_TARGET"] = "60"+ XCTAssertEqual(game.visibleSettings.count, 2)+ driver.setOption(gameID: "demo.0", setting: "DM_RENDER_SCALE", value: "nan")+ XCTAssertNil(driver.state.games[0].values["DM_RENDER_SCALE"])+ driver.setOption(gameID: "missing", setting: "DM_LANG", value: "en")+ }++ @MainActor func testControllerAssignmentIsUniqueAndScoped() {+ let driver = MockConsoleDriver(scenario: .controllers, animated: false)+ XCTAssertEqual(driver.state.controllers.count, 3)+ XCTAssertEqual(driver.state.assigningPlayer, 3)+ driver.assignPlayer(controllerID: "pad.3", player: 1)+ XCTAssertNil(driver.state.controllers[0].player)+ XCTAssertEqual(driver.state.controllers[2].player, 1)+ XCTAssertNil(driver.state.assigningPlayer)+ driver.requestPlayer(4)+ XCTAssertEqual(driver.state.assigningPlayer, 4)+ driver.assignPlayer(controllerID: "missing", player: 4)+ XCTAssertEqual(driver.state.assigningPlayer, 4)+ driver.assignPlayer(controllerID: "pad.2", player: 5)+ XCTAssertEqual(driver.state.controllers[1].player, 2)+ driver.back()+ XCTAssertNil(driver.state.assigningPlayer)+ driver.assignPlayer(controllerID: "pad.3", player: 2)+ XCTAssertEqual(driver.state.controllers[2].player, 1)+ }++ @MainActor func testMixedControllersActionsMergeAndToasts() {+ let driver = MockConsoleDriver(scenario: .controllersMixed, lang: .en, animated: false)+ XCTAssertFalse(driver.state.padMerge)+ XCTAssertEqual(driver.state.controllers.map(\.kind), [.pro, .xbox, .keyboard, .joyCon])+ XCTAssertEqual(driver.state.controllers[1].batteryPercent, 12)+ XCTAssertNil(driver.state.controllers[2].batteryPercent)+ XCTAssertTrue(driver.state.controllers[3].charging)+ driver.setPadMerge(true)+ XCTAssertTrue(driver.state.padMerge)+ XCTAssertEqual(driver.state.controllers[1].player, 2, "Merging preserves the separate-player mapping for switching back")+ driver.identify(controllerID: "pad.2")+ XCTAssertEqual(driver.state.identifyingControllerID, "pad.2")+ XCTAssertTrue(driver.state.toast?.message.contains("Identifying") == true)+ driver.requestPlayer(3)+ driver.requestAssignment(controllerID: "pad.2")+ driver.assignPlayer(controllerID: "pad.1", player: 3)+ XCTAssertEqual(driver.state.assigningControllerID, "pad.2")+ driver.assignPlayer(controllerID: "pad.2", player: 3)+ XCTAssertEqual(driver.state.controllers[1].player, 3)+ driver.disconnect(controllerID: "pad.2")+ XCTAssertEqual(driver.state.controllers.count, 3)+ XCTAssertTrue(driver.state.toast?.message.contains("disconnected") == true)+ driver.connect(.init(id: "pad.5", name: "Controller 5", player: 4))+ XCTAssertTrue(driver.state.toast?.message.contains("player 1") == true)+ driver.dismissToast()+ XCTAssertNil(driver.state.toast)+ driver.setPadMerge(false)+ XCTAssertFalse(driver.state.padMerge)+ let bridge = AnyConsoleDriver(driver)+ bridge.setPadMerge(true)+ XCTAssertTrue(bridge.state.padMerge)+ }++ func testStartingProgressAndControllerCopy() {+ XCTAssertNil(ConsoleStarting.preparing.progress)+ XCTAssertEqual(ConsoleStarting.compilingShaders(completed: 18, total: 48).progress, 0.375)+ XCTAssertNil(ConsoleStarting.compilingShaders(completed: 0, total: 0).progress)+ XCTAssertEqual(ConsoleStarting.compilingShaders(completed: 60, total: 48).progress, 1)+ for kind in ConsoleController.Kind.allCases { XCTAssertNotNil(L10n.table[kind.labelKey]) }+ for (key, pair) in L10n.table where key.hasPrefix("console.") {+ XCTAssertFalse(pair.en.contains(";"), key)+ XCTAssertFalse(pair.zh.contains(";") || pair.zh.contains("\u{ff1b}"), key)+ }+ }++ func testEveryConsoleStringHasBothLanguages() {+ let keys = L10n.table.keys.filter { $0.hasPrefix("console.") }+ XCTAssertGreaterThan(keys.count, 45)+ for key in keys {+ for lang in [Lang.en, .zh] {+ XCTAssertFalse(L10n.string(key, lang).isEmpty, key)+ XCTAssertNotEqual(L10n.string(key, lang), key)+ }+ }+ for status in [ConsoleGame.Status.ready, .needsBuild, .needsData, .broken("")] {+ XCTAssertNotNil(L10n.table[status.labelKey])+ if let key = status.explanationKey { XCTAssertNotNil(L10n.table[key]) }+ }+ XCTAssertTrue(L10n.selfCheck().isEmpty)+ }++ @MainActor func testRenderDesktopControllerIntegration() throws {+ guard let directory = ProcessInfo.processInfo.environment["NX_CONSOLE_CAPTURE_DIR"] else { throw XCTSkip("Set NX_CONSOLE_CAPTURE_DIR for desktop captures") }+ let output = URL(fileURLWithPath: directory)+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ for lang in [Lang.en, .zh] {+ for width: CGFloat in [900, 1280] {+ let model = BuildModel()+ model.lang = lang+ let library = GameLibrary(file: output.appendingPathComponent("unused-library.json"))+ let driver = MockConsoleDriver(scenario: .controllersMixed, lang: lang, animated: false)+ driver.back()+ let view = ContentView(model: model, library: library, performStartupChecks: false, controllerDriver: AnyConsoleDriver(driver))+ let host = NSHostingView(rootView: view)+ let window = NSWindow(contentRect: NSRect(x: -10000, y: 0, width: width, height: 800), styleMask: [.borderless], backing: .buffered, defer: false)+ window.isReleasedWhenClosed = false+ window.contentView = host+ window.orderBack(nil)+ RunLoop.main.run(until: Date().addingTimeInterval(0.2))+ 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("desktop-\(Int(width))-\(lang.rawValue).png"))+ window.orderOut(nil)+ window.contentView = nil+ window.close()+ }+ }+ }++ /// Offscreen, deterministic SwiftUI snapshots; opt-in to avoid opening windows during normal tests.+ @MainActor func testRenderConsoleForVisualQA() throws {+ guard let directory = ProcessInfo.processInfo.environment["NX_CONSOLE_CAPTURE_DIR"] else {+ throw XCTSkip("Set NX_CONSOLE_CAPTURE_DIR to capture console screens")+ }+ let output = URL(fileURLWithPath: directory)+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ NSApplication.shared.setActivationPolicy(.accessory)+ let sizes: [(String, CGFloat, CGFloat)] = [("tv", 1920, 1080), ("mac", 1280, 800), ("compact", 390, 844)]+ for lang in [Lang.en, .zh] {+ for (name, width, height) in sizes {+ for screen in ["full", "few", "empty", "controllers", "controllersMixed", "mixedHome", "controllerDesktop", "connectedToast", "starting", "options", "needsBuild", "needsData", "broken", "desktop", "prompt"] {+ let driver = MockConsoleDriver(scenario: MockConsoleDriver.Scenario(rawValue: screen) ?? (screen == "mixedHome" || screen == "controllerDesktop" || screen == "connectedToast" ? .controllersMixed : .full), lang: lang, animated: false)+ switch screen {+ case "mixedHome": driver.back()+ case "connectedToast": driver.back(); driver.disconnect(controllerID: "pad.2"); driver.connect(.init(id: "pad.2", name: L10n.string("console.demoController", lang), player: 2))+ case "options": driver.openOptions("demo.0")+ case "needsBuild": driver.focus("demo.3"); driver.play("demo.3")+ case "needsData": driver.focus("demo.5"); driver.play("demo.5")+ case "broken": driver.focus("demo.7"); driver.play("demo.7")+ case "desktop": driver.exitToDesktop()+ default: break+ }+ let view: AnyView+ if screen == "controllerDesktop" {+ view = AnyView(ConsoleControllersSheet(driver: driver, lang: lang, close: {}).environmentObject(PadFocus()))+ } else if screen == "prompt" {+ view = AnyView(ConsoleConnectionPrompt(lang: lang, enterConsole: {}, dismissPrompt: {}).environmentObject(PadFocus()).preferredColorScheme(.dark))+ } else { view = AnyView(ConsoleView(driver: driver, lang: lang).transaction { $0.disablesAnimations = true }) }+ let host = NSHostingView(rootView: view.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+ window.contentView = host+ window.orderBack(nil)+ RunLoop.main.run(until: Date().addingTimeInterval(0.12))+ 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("\(screen)-\(name)-\(lang.rawValue).png"))+ window.orderOut(nil)+ window.contentView = nil+ window.close()+ }+ }+ }+ }+}