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
Controller navigation across the launcher (#38)
v0lumehi3594e8009213
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 31241a6c..8e69392c 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -1489,8 +1489,10 @@ struct BuilderView: View {var controlChanges = 0@State private var extrasOpen = false@State private var logOpen = false+ @EnvironmentObject private var padFocus: PadFocusvar body: some View {+ ScrollViewReader { proxy inScrollView(.vertical) {VStack(alignment: .leading, spacing: 34) {if settings { settingsPage } else { buildPage }@@ -1499,6 +1501,10 @@ struct BuilderView: View {.frame(maxWidth: 900).frame(maxWidth: .infinity)}+ .onChange(of: padFocus.focused) { id in // a controller's focus on this page scrolls into view+ if let id, id.hasPrefix("set.") { withAnimation(.easeInOut(duration: 0.2)) { proxy.scrollTo(id, anchor: .center) } }+ }+ }.buttonStyle(LauncherSecondaryButtonStyle())}@@ -1838,13 +1844,16 @@ struct BuilderView: View {if library.scanning { ProgressView().controlSize(.small) }if !library.folder.isEmpty {Button(m.t("library.rescan")) { library.discover() }.disabled(library.scanning)+ .padTarget("set.rescan", scope: "main") { if !library.scanning { library.discover() } }}Button(m.t("library.chooseFolder"), action: onChooseLibraryFolder)+ .padTarget("set.folder", scope: "main") { onChooseLibraryFolder() }}}group(m.t("section.controls"), footnote: m.t("controls.settingsHint")) {row(m.t("controls.row"), detail: controlChanges == 0 ? m.t("controls.defaultLayout") : String(format: m.t("controls.changes"), controlChanges)) {Button(m.t("controls.customize"), action: onOpenControls)+ .padTarget("set.controls", scope: "main") { onOpenControls() }}}tools@@ -1863,18 +1872,30 @@ struct BuilderView: View {m.lang = Lang.initial()}.frame(width: Self.settingsButtonWidth)+ .padTarget("set.language", scope: "main", activate: { cycleLanguage(1) }, adjust: { cycleLanguage($0) })}dividerrow("NX2Apple", detail: String(format: m.t("app.version"), BuildModel.appVersion)) {if let u = m.appUpdate {Button(String(format: m.t("app.updateBtn"), u.tag)) { m.performAppUpdate() }.disabled(m.appBusy)+ .padTarget("set.appUpdate", scope: "main") { if !m.appBusy { m.performAppUpdate() } }} else {Button(m.t("repo.check")) { m.checkAppUpdate() }.disabled(m.appBusy)+ .padTarget("set.appCheck", scope: "main") { if !m.appBusy { m.checkAppUpdate() } }}}}}+ /// The interface language one step on (a controller's left / right on the language list).+ private func cycleLanguage(_ by: Int) {+ let values = ["", "zh", "en"]+ let at = values.firstIndex(of: Lang.saved.map { $0.rawValue } ?? "") ?? 0+ let v = values[(at + by + values.count) % values.count]+ Lang.saved = v.isEmpty ? nil : Lang(rawValue: v)+ m.lang = Lang.initial()+ }+private var tools: some View {group(m.t("section.tools"), footnote: m.repoStatus.isEmpty ? (m.repoOK ? "" : m.t("repo.firstHint")) : m.repoStatus) {row(m.t("repo.title"),@@ -1886,10 +1907,13 @@ struct BuilderView: View {if m.repoIsGit {if let n = m.repoBehind, n > 0 {Button(m.t("repo.pull")) { m.pullRepo() }.disabled(m.repoBusy || m.running)+ .padTarget("set.repoPull", scope: "main") { if !(m.repoBusy || m.running) { m.pullRepo() } }}Button(m.t("repo.check")) { m.checkRepoUpdates() }.disabled(m.repoBusy || m.running)+ .padTarget("set.repoCheck", scope: "main") { if !(m.repoBusy || m.running) { m.checkRepoUpdates() } }} else {Button(m.t("repo.adopt")) { m.adoptRepoAsGit() }.disabled(m.repoBusy || m.running)+ .padTarget("set.repoAdopt", scope: "main") { if !(m.repoBusy || m.running) { m.adoptRepoAsGit() } }}} else {Button(m.t("repo.choose")) { pickRepo() }@@ -1919,6 +1943,7 @@ struct BuilderView: View {open: m.depsOpen) {if !m.depsChecked { ProgressView().controlSize(.small) }Button(m.t("dep.recheck")) { m.checkDeps() }+ .padTarget("set.deps", scope: "main") { m.checkDeps() }}.contentShape(Rectangle())}diff --git a/frontend/Sources/NSPortBuilder/Controls.swift b/frontend/Sources/NSPortBuilder/Controls.swiftindex e0c89acf..d33bdf56 100644--- a/frontend/Sources/NSPortBuilder/Controls.swift+++ b/frontend/Sources/NSPortBuilder/Controls.swift@@ -108,6 +108,7 @@ struct ControlsView: View {@Environment(\.dismiss) private var dismiss@State private var listening: String?@State private var monitor: Any?+ @EnvironmentObject private var focus: PadFocusvar body: some View {VStack(alignment: .leading, spacing: 0) {@@ -116,6 +117,7 @@ struct ControlsView: View {Text(m.t("controls.note")).font(.manrope(14)).foregroundStyle(.secondary)}.padding(.horizontal, 30).padding(.top, 28).padding(.bottom, 20)+ ScrollViewReader { proxy inScrollView {VStack(alignment: .leading, spacing: 24) {section(m.t("controls.sticks"), ControlLayout.functions.filter(\.isDirection)) { keyRow($0) }@@ -124,6 +126,8 @@ struct ControlsView: View {}.padding(.horizontal, 30).padding(.bottom, 24)}+ .onChange(of: focus.focused) { id in if let id { withAnimation(.easeInOut(duration: 0.2)) { proxy.scrollTo(id, anchor: .center) } } }+ }Divider().opacity(0.3)HStack(spacing: 14) {Text(m.t("controls.applied")).font(.manrope(12)).foregroundStyle(.secondary).lineLimit(2)@@ -131,6 +135,7 @@ struct ControlsView: View {if !layout.isDefault {Button(m.t("controls.reset")) { stopListening(); layout.resetKeyboard(); layout.resetController() }.buttonStyle(LauncherSecondaryButtonStyle())+ .padTarget("controls.reset", scope: "controls") { stopListening(); layout.resetKeyboard(); layout.resetController() }}Button { stopListening(); dismiss() } label: {Text(m.t("launch.done")).font(.manrope(13.5, .bold)).foregroundStyle(.black)@@ -138,9 +143,11 @@ struct ControlsView: View {.background(LauncherPalette.cream, in: Capsule())}.buttonStyle(.plain).keyboardShortcut(listening == nil ? .defaultAction : nil)+ .padTarget("controls.done", scope: "controls", radius: 20) { stopListening(); dismiss() }}.padding(.horizontal, 30).padding(.vertical, 16)}+ .padScope("controls", focus).frame(width: 600, height: 700).background(LauncherPalette.background).font(.manrope(13))@@ -166,7 +173,8 @@ struct ControlsView: View {}}- private func line<Trailing: View>(_ title: String, @ViewBuilder trailing: () -> Trailing) -> some View {+ private func line<Trailing: View>(_ title: String, target: String, activate: (() -> Void)? = nil, adjust: ((Int) -> Void)? = nil,+ @ViewBuilder trailing: () -> Trailing) -> some View {HStack(spacing: 16) {Text(title).font(.manrope(14, .medium))Spacer(minLength: 12)@@ -174,12 +182,13 @@ struct ControlsView: View {}.padding(.horizontal, 18).padding(.vertical, 9).frame(minHeight: 46)+ .padTarget(target, scope: "controls", radius: 10, activate: activate, adjust: adjust)}private func keyRow(_ f: ControlLayout.Function) -> some View {let on = listening == f.idlet key = layout.key(f)- return line(m.t("controls.fn." + f.id)) {+ return line(m.t("controls.fn." + f.id), target: "key." + f.id, activate: { on ? stopListening() : listen(f) }) {HStack(spacing: 6) {if key != nil && !on {Button { layout.assign(f, key: nil) } label: {@@ -204,7 +213,12 @@ struct ControlsView: View {}private func padRow(_ button: String) -> some View {- line(m.t("controls.fn." + button)) {+ let choices = ControlLayout.buttons + ["none"]+ return line(m.t("controls.fn." + button), target: "pad." + button,+ adjust: { by in+ let at = choices.firstIndex(of: layout.sends(button)) ?? 0+ layout.setSends(button, choices[(at + by + choices.count) % choices.count])+ }) {LauncherMenuPicker(options: ControlLayout.buttons.map { (value: $0, label: m.t("controls.fn." + $0)) } + [(value: "none", label: m.t("controls.none"))],selection: layout.sends(button), fill: true) { layout.setSends(button, $0) }.frame(width: 168) // the keyboard rows' width (× and key field), and "Right stick press" fitsdiff --git a/frontend/Sources/NSPortBuilder/Gamepad.swift b/frontend/Sources/NSPortBuilder/Gamepad.swiftnew file mode 100644index 00000000..66839266--- /dev/null+++ b/frontend/Sources/NSPortBuilder/Gamepad.swift@@ -0,0 +1,70 @@+import AppKit+import GameController++/// A game controller drives the launcher, so a Mac on a TV needs no keyboard (PadFocus moves the focus). The buttons are+/// named as the game names them, by position (dm/host/front_mac.m pad_read): A on the right, B at the bottom, X at the+/// top, Y on the left. The D-pad or left stick moves (held, it repeats), A activates, B goes back, X opens the selected+/// game's launch options, L and R switch the pages. Input counts only while the launcher is the active app: a game it+/// started is in front then, and GameController gives a controller's input to the app in front, so the launcher never+/// acts behind a running game.+final class LauncherGamepad: ObservableObject {+ enum Action: Equatable { case left, right, up, down, a, b, x, y, l, r }++ @Published private(set) var connected = false+ var perform: (Action) -> Void = { _ in }+ private var held: Set<String> = [] // edges, not levels: one press, one action+ private var observers: [NSObjectProtocol] = []+ private var repeatTimer: Timer?+ private var repeating: Action?++ init() {+ let center = NotificationCenter.default+ observers = [NSNotification.Name.GCControllerDidConnect, .GCControllerDidDisconnect].map {+ center.addObserver(forName: $0, object: nil, queue: .main) { [weak self] _ in self?.attach() }+ }+ attach()+ }++ deinit { observers.forEach(NotificationCenter.default.removeObserver); repeatTimer?.invalidate() }++ private func attach() {+ let pads = GCController.controllers().compactMap(\.extendedGamepad)+ connected = !pads.isEmpty+ for pad in pads { pad.valueChangedHandler = { [weak self] pad, _ in self?.read(pad) } }+ }++ private func read(_ pad: GCExtendedGamepad) {+ let x = pad.dpad.xAxis.value != 0 ? pad.dpad.xAxis.value : pad.leftThumbstick.xAxis.value+ let y = pad.dpad.yAxis.value != 0 ? pad.dpad.yAxis.value : pad.leftThumbstick.yAxis.value+ let state: [(String, Bool, Action)] = [+ ("left", x < -0.5, .left), ("right", x > 0.5, .right), ("up", y > 0.5, .up), ("down", y < -0.5, .down),+ ("a", pad.buttonB.isPressed, .a), ("b", pad.buttonA.isPressed, .b), // by position: right A, bottom B, top X, left Y+ ("x", pad.buttonY.isPressed, .x), ("y", pad.buttonX.isPressed, .y),+ ("l", pad.leftShoulder.isPressed, .l), ("r", pad.rightShoulder.isPressed, .r),+ ]+ for (key, down, action) in state {+ if down, !held.contains(key) {+ held.insert(key)+ DispatchQueue.main.async { self.fire(action) }+ if [.left, .right, .up, .down].contains(action) { DispatchQueue.main.async { self.startRepeat(action) } }+ } else if !down, held.contains(key) {+ held.remove(key)+ DispatchQueue.main.async { if self.repeating == action { self.stopRepeat() } }+ }+ }+ }++ private func fire(_ action: Action) { if NSApp.isActive { perform(action) } }++ /// A held direction repeats after 0.4 s, every 0.12 s.+ private func startRepeat(_ action: Action) {+ stopRepeat()+ repeating = action+ repeatTimer = Timer.scheduledTimer(withTimeInterval: 0.4, repeats: false) { [weak self] _ in+ guard let self, self.repeating == action else { return }+ self.repeatTimer = Timer.scheduledTimer(withTimeInterval: 0.12, repeats: true) { [weak self] _ in self?.fire(action) }+ }+ }++ private func stopRepeat() { repeatTimer?.invalidate(); repeatTimer = nil; repeating = nil }+}diff --git a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swiftindex 2cac9d1d..fabf04e9 100644--- a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift+++ b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift@@ -10,6 +10,7 @@ struct LaunchOptionsView: View {let gameID: UUID@Environment(\.dismiss) private var dismiss@State private var advancedOpen = false+ @EnvironmentObject private var focus: PadFocusprivate var game: LibraryGame? { library.games.first { $0.id == gameID } }private var settings: [LaunchSetting]? {@@ -27,6 +28,7 @@ struct LaunchOptionsView: View {}.padding(.horizontal, 30).padding(.top, 28).padding(.bottom, 20)if let settings, !settings.isEmpty, let game {+ ScrollViewReader { proxy inScrollView {VStack(alignment: .leading, spacing: 24) {groups(settings.filter(\.isBasic), game, all: settings)@@ -44,12 +46,15 @@ struct LaunchOptionsView: View {.padding(.horizontal, 18).frame(minHeight: 52).contentShape(Rectangle())}.buttonStyle(.plain)+ .padTarget("opt.advanced", scope: "launch", radius: 14) { withAnimation(.easeInOut(duration: 0.18)) { advancedOpen.toggle() } }}if advancedOpen { groups(advanced, game, all: settings) }}}.padding(.horizontal, 30).padding(.bottom, 24)}+ .onChange(of: focus.focused) { id in if let id { withAnimation(.easeInOut(duration: 0.2)) { proxy.scrollTo(id, anchor: .center) } } }+ }} else {Text(m.t("launch.none")).font(.manrope(14)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)@@ -62,6 +67,7 @@ struct LaunchOptionsView: View {if let game, !game.launchOptions.isEmpty {Button(m.t("launch.reset")) { library.resetLaunchOptions(for: gameID) }.buttonStyle(LauncherSecondaryButtonStyle())+ .padTarget("opt.reset", scope: "launch") { library.resetLaunchOptions(for: gameID) }}Button { dismiss() } label: {Text(m.t("launch.done")).font(.manrope(13.5, .bold)).foregroundStyle(.black)@@ -69,9 +75,11 @@ struct LaunchOptionsView: View {.background(LauncherPalette.cream, in: Capsule())}.buttonStyle(.plain).keyboardShortcut(.defaultAction)+ .padTarget("opt.done", scope: "launch", radius: 20) { dismiss() }}.padding(.horizontal, 30).padding(.vertical, 16)}+ .padScope("launch", focus).frame(width: 600, height: 700).background(LauncherPalette.background).font(.manrope(13))@@ -139,6 +147,24 @@ struct LaunchOptionsView: View {}.padding(.horizontal, 18).padding(.vertical, 13).frame(minHeight: 52)+ .padTarget("opt." + s.env, scope: "launch", radius: 10, activate: { step(s, value, 1) }, adjust: { step(s, value, $0) })+ }++ /// A controller's step through a setting: the next or previous choice (wrapping), the slider by its step, the switch flipped.+ private func step(_ s: LaunchSetting, _ value: String, _ by: Int) {+ switch s.kind {+ case "choice":+ let values = (s.options ?? []).map { $0[0] }+ guard !values.isEmpty else { return }+ let at = values.firstIndex(of: value) ?? 0+ set(s, values[(at + by + values.count) % values.count])+ case "range":+ let lo = s.min ?? 0, hi = s.max ?? 1, st = s.step ?? 0.05+ let next = min(max(((Double(value) ?? lo) / st).rounded() * st + Double(by) * st, lo), hi)+ set(s, String(format: "%.2f", next))+ default:+ set(s, value == s.onValue ? s.offValue : s.onValue)+ }}/// The setting's control, filling the column every row shares (a toggle keeps its size at the column's right edge).diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex cdfff77d..b2c7aeb8 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -36,6 +36,8 @@ struct ContentView: View {@State private var optionsFor: UUID?@State private var controlsOpen = false@StateObject private var controls = ControlLayout()+ @StateObject private var gamepad = LauncherGamepad()+ @StateObject private var padFocus = PadFocus()@StateObject private var row = RowScroller()private var performStartupChecks: Bool@Environment(\.scenePhase) private var scenePhase@@ -68,6 +70,8 @@ struct ContentView: View {}if m.running || page == .library { activityBar }}+ .padScope("main", padFocus)+ .environmentObject(padFocus).background(LauncherPalette.background).background(LauncherWindowChrome()).ignoresSafeArea(.container, edges: .top)@@ -76,6 +80,7 @@ struct ContentView: View {.font(.manrope(13)) // the default for text without a font of its own.frame(minWidth: 900, idealWidth: 1280, minHeight: 680, idealHeight: 900).onAppear {+ gamepad.perform = padActionrefreshArtwork()if performStartupChecks { library.discover(); fetchArtwork() }if performStartupChecks {@@ -119,9 +124,15 @@ struct ContentView: View {}} message: { Text(m.t("library.removeNote")) }.sheet(isPresented: Binding(get: { optionsFor != nil }, set: { if !$0 { optionsFor = nil } })) {- if let id = optionsFor { LaunchOptionsView(m: m, library: library, gameID: id) }+ if let id = optionsFor { LaunchOptionsView(m: m, library: library, gameID: id).environmentObject(padFocus) }+ }+ .sheet(isPresented: $controlsOpen) { ControlsView(m: m, layout: controls).environmentObject(padFocus) }+ .onChange(of: optionsFor) { id in padFocus.scope = id != nil ? "launch" : (controlsOpen ? "controls" : "main") }+ .onChange(of: controlsOpen) { open in padFocus.scope = open ? "controls" : (optionsFor != nil ? "launch" : "main") }+ .onChange(of: page) { _ in padFocus.focused = nil }+ .onChange(of: padFocus.focused) { id in // a controller moving onto a game's card selects it, as a click does+ if let id, id.hasPrefix("card."), let uuid = UUID(uuidString: String(id.dropFirst(5))) { library.selectedID = uuid }}- .sheet(isPresented: $controlsOpen) { ControlsView(m: m, layout: controls) }}private var topBar: some View {@@ -145,6 +156,7 @@ struct ContentView: View {}.buttonStyle(.plain).accessibilityAddTraits(page == destination ? .isSelected : [])+ .padTarget("tab." + destination.rawValue, scope: "main") { page = destination }}Spacer(minLength: 8)searchField@@ -155,8 +167,9 @@ struct ContentView: View {.overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Color.white.opacity(0.1))).contentShape(RoundedRectangle(cornerRadius: 8))}- .padding(.leading, 12).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)@@ -276,6 +289,7 @@ struct ContentView: View {}.buttonStyle(.plain).disabled(launching || (m.running && !game.isReady)).keyboardShortcut(.return, modifiers: [])+ .padTarget("hero.play", scope: "main", radius: 30) { if !launching { primaryAction(game) } }if game.isReady {Button { optionsFor = game.id } label: {Image(systemName: "slider.horizontal.3").font(.system(size: 17))@@ -284,6 +298,7 @@ struct ContentView: View {.overlay(Circle().strokeBorder(Color.white.opacity(0.14)))}.buttonStyle(.plain).help(m.t("launch.title")).accessibilityLabel(m.t("launch.title"))+ .padTarget("hero.options", scope: "main", radius: 24) { optionsFor = game.id }}Menu {Button(m.t("library.buildAgain")) { configureBuild(game) }.disabled(m.running || game.inputs["base", default: []].isEmpty)@@ -326,6 +341,7 @@ struct ContentView: View {if filteredGames.isEmpty {Text(m.t("library.noResults")).foregroundStyle(.secondary).padding(.vertical, 28)} else {+ ScrollViewReader { proxy inScrollView(.horizontal, showsIndicators: false) {HStack(alignment: .top, spacing: 14) {ForEach(filteredGames) { game in@@ -352,11 +368,20 @@ struct ContentView: View {}.buttonStyle(.plain).accessibilityAddTraits(game.id == library.selectedID ? .isSelected : [])+ .padTarget("card." + game.id.uuidString, scope: "main", radius: 7) { if !launching { primaryAction(game) } }}}- .padding(.bottom, 5)+ // Room for the controller's focus ring, which sits 4 pt outside a card: the row clips at its edges, so it+ // gets the room inside and gives it back outside (the cards stay where they were)+ .padding(.horizontal, Self.ringRoom).padding(.top, Self.ringRoom).padding(.bottom, 5 + Self.ringRoom).background(EnclosingScrollView(row: row))}+ .padding(.horizontal, -Self.ringRoom).padding(.vertical, -Self.ringRoom)+ .onChange(of: padFocus.focused) { id in // the focused card scrolls into the row's view+ guard let id, id.hasPrefix("card.") else { return }+ withAnimation(.easeInOut(duration: 0.25)) { proxy.scrollTo(id, anchor: .center) }+ }+ }.overlay(alignment: .topLeading) {if row.canBack {pager("chevron.left", height: cardWidth / 1.8) { row.page(-1, step: step) }.offset(x: -22)@@ -429,12 +454,27 @@ struct ContentView: View {Image(systemName: "desktopcomputer").foregroundStyle(.secondary)Text(m.t("library.localNote")).font(.manrope(13)).foregroundStyle(.secondary)Spacer()+ if gamepad.connected {+ // The buttons a controller has here, named as the game names them (A on the right)+ HStack(spacing: 18) {+ padHint("A", m.t("pad.play")); padHint("X", m.t("pad.options")); padHint("B", m.t("pad.back"))+ Image(systemName: "gamecontroller").foregroundStyle(.secondary)+ }+ }}}.padding(.horizontal, 30).frame(height: 84)}}+ private func padHint(_ button: String, _ label: String) -> some View {+ HStack(spacing: 7) {+ Text(button).font(.manrope(11, .bold)).foregroundStyle(.black)+ .frame(width: 20, height: 20).background(LauncherPalette.cream.opacity(0.9), in: Circle())+ Text(label).font(.manrope(13)).foregroundStyle(.secondary)+ }+ }+private var buildProgress: Double? {// The script reports a percentage for the current step, not for all remaining work.guard let percent = m.stages.last(where: { $0.state == .running })?.percent else { return nil }@@ -462,6 +502,41 @@ struct ContentView: View {page = .builds}+ /// A controller's button (LauncherGamepad): the first press shows the focus (on the selected game's card in the library),+ /// 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+ if action == .b {+ if optionsFor != nil { optionsFor = nil } else if controlsOpen { controlsOpen = false }+ else if searching { searching = false; search = "" } else if page != .library { page = .library }+ return+ }+ if removing != nil { return } // the remove dialog is AppKit's; it takes the mouse or the keyboard+ if !padFocus.visible {+ padFocus.show(default: !sheetOpen && page == .library ? library.selectedID.map { "card." + $0.uuidString } : nil)+ if [.up, .down, .left, .right].contains(action) { return } // the first press only shows where the focus is+ }+ switch action {+ case .up: padFocus.move(dx: 0, dy: -1)+ case .down: padFocus.move(dx: 0, dy: 1)+ case .left: padFocus.horizontal(-1)+ case .right: padFocus.horizontal(1)+ case .a: padFocus.activate()+ case .x:+ if !sheetOpen, let game = library.selected, game.isReady { optionsFor = game.id }+ case .l, .r:+ guard !sheetOpen, let at = LauncherPage.allCases.firstIndex(of: page) else { return }+ let pages = LauncherPage.allCases+ page = pages[(at + (action == .l ? pages.count - 1 : 1)) % pages.count]+ case .b, .y:+ return+ }+ }++ /// The space the collection row keeps around its cards for the focus ring (PadFocus draws it 4 pt outside a target).+ static let ringRoom: CGFloat = 6+private func primaryAction(_ game: LibraryGame) {if !game.isReady && game.hasIOSBuild {NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: game.ipaPath)])diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 7dd4dc01..6abc5d6c 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -445,6 +445,9 @@ enum L10n {"launch.advancedCount": ("%ld 项", "%ld settings"),"launch.scaleOfDocked": ("底座模式 %2$@ 的 %1$ld%%", "%ld%% of %@ docked"),"launch.scaleOfHandheld": ("掌机模式 %2$@ 的 %1$ld%%", "%ld%% of %@ handheld"),+ "pad.play": ("开始游戏", "Play"),+ "pad.options": ("启动选项", "Options"),+ "pad.back": ("返回", "Back"),"msg.archiveLog": ("归档:%@ → %@", "Archive: %@ → %@"),]diff --git a/frontend/Sources/NSPortBuilder/PadFocus.swift b/frontend/Sources/NSPortBuilder/PadFocus.swiftnew file mode 100644index 00000000..27ed677b--- /dev/null+++ b/frontend/Sources/NSPortBuilder/PadFocus.swift@@ -0,0 +1,98 @@+import SwiftUI++/// Controller focus across the launcher. macOS gives SwiftUI controls keyboard focus only with Full Keyboard Access+/// turned on, so the launcher keeps a focus of its own: every control a controller can reach is a target (`padTarget`)+/// that reports its frame in its scope (the main window, or one sheet). The D-pad or left stick moves to the nearest+/// target in that direction, A activates it, and on a target that holds a value (a choice, a slider, a switch) left and+/// right change the value instead. The ring shows only after a controller was used, so mouse users never see it.+final class PadFocus: ObservableObject {+ struct Target: Equatable { let id: String; let frame: CGRect }+ struct Handlers { var activate: (() -> Void)?; var adjust: ((Int) -> Void)? }++ @Published var focused: String?+ @Published private(set) var visible = false+ /// The scope the controller acts in: "main", or the open sheet's.+ var scope = "main" { didSet { if scope != oldValue { focused = nil } } }+ private var frames: [String: [Target]] = [:]+ private var handlers: [String: Handlers] = [:] // refreshed on every render of the target, so the closures see current state++ func setFrames(_ targets: [Target], scope: String) { frames[scope] = targets }+ func register(_ id: String, _ h: Handlers) { handlers[id] = h }++ /// Focus a target (a default when nothing is focused yet) and show the ring.+ func show(default id: String?) {+ visible = true+ if focused == nil || !(frames[scope] ?? []).contains(where: { $0.id == focused }) {+ focused = id.flatMap { want in (frames[scope] ?? []).first { $0.id == want }?.id } ?? topLeft()+ }+ }++ func hide() { visible = false }++ /// Left / right: the target's own value when it holds one, else a move.+ func horizontal(_ step: Int) {+ if let id = focused, let adjust = handlers[id]?.adjust { adjust(step) } else { move(dx: CGFloat(step), dy: 0) }+ }++ func activate() { if let id = focused { handlers[id]?.activate?() } }++ /// The nearest target in the direction, scored by distance along it plus twice the distance across it. Left and right+ /// stay in the row (the target must overlap it vertically), so the last card does not jump to a button across the+ /// screen; up and down prefer a target in the same column and take the nearest otherwise (a card row up to the tabs).+ func move(dx: CGFloat, dy: CGFloat) {+ let all = frames[scope] ?? []+ guard let current = all.first(where: { $0.id == focused })?.frame else { focused = topLeft(); return }+ let from = CGPoint(x: current.midX, y: current.midY)+ let ahead = all.filter { $0.id != focused }.compactMap { t -> (target: Target, score: CGFloat)? in+ let to = CGPoint(x: t.frame.midX, y: t.frame.midY)+ let along = dx != 0 ? (to.x - from.x) * dx : (to.y - from.y) * dy+ let across = dx != 0 ? abs(to.y - from.y) : abs(to.x - from.x)+ return along > 4 ? (t, along + 2 * across) : nil+ }+ let overlapping = ahead.filter { c in+ dx != 0 ? c.target.frame.minY < current.maxY && c.target.frame.maxY > current.minY+ : c.target.frame.minX < current.maxX && c.target.frame.maxX > current.minX+ }+ let pool = dx != 0 || !overlapping.isEmpty ? overlapping : ahead+ if let best = pool.min(by: { $0.score < $1.score }) { focused = best.target.id }+ }++ private func topLeft() -> String? {+ (frames[scope] ?? []).min { ($0.frame.minY, $0.frame.minX) < ($1.frame.minY, $1.frame.minX) }?.id+ }+}++private struct PadTargetKey: PreferenceKey {+ static var defaultValue: [PadFocus.Target] = []+ static func reduce(value: inout [PadFocus.Target], nextValue: () -> [PadFocus.Target]) { value += nextValue() }+}++extension View {+ /// A control the controller can focus: A runs `activate`, left / right run `adjust` when given. `shape` draws the ring.+ func padTarget(_ id: String, scope: String, radius: CGFloat = 9, activate: (() -> Void)? = nil, adjust: ((Int) -> Void)? = nil) -> some View {+ modifier(PadTargetModifier(id: id, scope: scope, radius: radius, handlers: .init(activate: activate, adjust: adjust)))+ }++ /// The root of a scope: collects its targets' frames for the focus.+ func padScope(_ scope: String, _ focus: PadFocus) -> some View {+ coordinateSpace(name: "pad." + scope)+ .onPreferenceChange(PadTargetKey.self) { focus.setFrames($0, scope: scope) }+ }+}++private struct PadTargetModifier: ViewModifier {+ let id: String, scope: String, radius: CGFloat+ let handlers: PadFocus.Handlers+ @EnvironmentObject private var focus: PadFocus++ func body(content: Content) -> some View {+ focus.register(id, handlers)+ let on = focus.visible && focus.focused == id+ return content+ .overlay(RoundedRectangle(cornerRadius: radius).strokeBorder(LauncherPalette.cream, lineWidth: on ? 2 : 0).padding(-4).allowsHitTesting(false))+ .background(GeometryReader { g in+ Color.clear.preference(key: PadTargetKey.self, value: [.init(id: id, frame: g.frame(in: .named("pad." + scope)))])+ })+ .id(id)+ }+}diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swiftindex bc7bfddc..6dfc5f9e 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -539,7 +539,7 @@ final class LibraryTests: XCTestCase {try FileManager.default.createDirectory(at: dm, withIntermediateDirectories: true)try FileManager.default.copyItem(at: URL(fileURLWithPath: json), to: dm.appendingPathComponent("launcher.json"))if let fps = LaunchSetting.read(app: first.appPath)?.first(where: { $0.env == "DM_FPS_TARGET" }) { library.setLaunchOption(fps, "60", for: first.id) }- let host = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: first.id))+ let host = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: first.id).environmentObject(PadFocus()))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 700), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)@@ -548,6 +548,19 @@ final class LibraryTests: XCTestCase {host.cacheDisplay(in: host.bounds, to: rep)try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("launch-options.png"))window.orderOut(nil)+ // The same sheet with a controller's focus on the console mode row+ let focus = PadFocus()+ let focused = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: first.id).environmentObject(focus))+ window.contentView = focused+ window.orderFront(nil)+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))+ focus.scope = "launch"+ focus.show(default: "opt.DM_OPMODE")+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))+ let focusRep = try XCTUnwrap(focused.bitmapImageRepForCachingDisplay(in: focused.bounds))+ focused.cacheDisplay(in: focused.bounds, to: focusRep)+ try XCTUnwrap(focusRep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("launch-options-focus.png"))+ window.orderOut(nil)}do { // the Controls sheet with a few changes, kept in a suite of its ownlet suite = "nxnative-visual-qa-controls"@@ -557,7 +570,7 @@ final class LibraryTests: XCTestCase {let layout = ControlLayout(defaults: defaults)if let up = ControlLayout.functions.first(where: { $0.id == "RUp" }) { layout.assign(up, key: 34) }layout.setSends("A", "B"); layout.setSends("B", "A")- let host = NSHostingView(rootView: ControlsView(m: model, layout: layout))+ let host = NSHostingView(rootView: ControlsView(m: model, layout: layout).environmentObject(PadFocus()))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 700), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)diff --git a/frontend/Tests/NSPortBuilderTests/PadFocusTests.swift b/frontend/Tests/NSPortBuilderTests/PadFocusTests.swiftnew file mode 100644index 00000000..8bb9d517--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/PadFocusTests.swift@@ -0,0 +1,51 @@+import XCTest+@testable import NSPortBuilder++/// The controller focus: moves go to the nearest target in the direction and stay in their row when they can, left / right+/// change a value where the target holds one, and the first press only shows the focus.+final class PadFocusTests: XCTestCase {+ private func grid() -> PadFocus {+ let f = PadFocus()+ // a row of three cards under a tab bar of two, and one button far right on the tab bar's line+ f.setFrames([.init(id: "tab.a", frame: CGRect(x: 0, y: 0, width: 80, height: 30)),+ .init(id: "tab.b", frame: CGRect(x: 100, y: 0, width: 80, height: 30)),+ .init(id: "build", frame: CGRect(x: 900, y: 0, width: 80, height: 30)),+ .init(id: "card.1", frame: CGRect(x: 0, y: 300, width: 200, height: 120)),+ .init(id: "card.2", frame: CGRect(x: 220, y: 300, width: 200, height: 120)),+ .init(id: "card.3", frame: CGRect(x: 440, y: 300, width: 200, height: 120))], scope: "main")+ return f+ }++ func testFirstShowFocusesTheDefaultOrTheTopLeft() {+ let f = grid()+ f.show(default: "card.2")+ XCTAssertEqual(f.focused, "card.2")+ XCTAssertTrue(f.visible)+ let g = grid()+ g.show(default: "missing")+ XCTAssertEqual(g.focused, "tab.a")+ }++ func testMovesStayInTheRowAndFindTheNearestAboveOrBelow() {+ let f = grid()+ f.show(default: "card.1")+ f.move(dx: 1, dy: 0); XCTAssertEqual(f.focused, "card.2")+ f.move(dx: 1, dy: 0); XCTAssertEqual(f.focused, "card.3")+ f.move(dx: 1, dy: 0); XCTAssertEqual(f.focused, "card.3", "nothing further right in reach of the row")+ f.move(dx: 0, dy: -1); XCTAssertEqual(f.focused, "tab.b", "up from the third card: the tab nearest above, not the far button")+ f.move(dx: 0, dy: 1); XCTAssertEqual(f.focused, "card.1")+ }++ func testLeftAndRightChangeAValueWhereTheTargetHoldsOne() {+ let f = grid()+ var value = 0, activated = 0+ f.register("card.2", .init(activate: { activated += 1 }, adjust: { value += $0 }))+ f.show(default: "card.2")+ f.horizontal(1); f.horizontal(1); f.horizontal(-1)+ XCTAssertEqual(value, 1)+ XCTAssertEqual(f.focused, "card.2", "a value target keeps the focus")+ f.activate(); XCTAssertEqual(activated, 1)+ f.scope = "launch"+ XCTAssertNil(f.focused, "another scope starts without a focus")+ }+}