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
Controls: one-click controller layouts, and Auto picks one for the controller (#70)
v0lumehi82537942a3d1
diff --git a/frontend/README.md b/frontend/README.mdindex 5a1cfcb9..ab684d59 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -96,6 +96,22 @@ reads through `dm/host/input_map.h` — upstream'swhile it is open, and listed in `docs/env_switches.tsv`. A host built before the carrierhas no `input_map.h` and ignores both, so its games play with the default keys.+The controller has four layouts, each only a `DM_PAD_MAP` value. **Standard layout**+(the default) passes nothing: the host reads the face buttons by position, in the+Nintendo layout (right A, bottom B, top X, left Y), for PlayStation and other+controllers. **By label** passes `A=B,B=A,X=Y,Y=X`, so A, B, X and Y are the letters+printed on a Nintendo or Xbox controller: GameController reports both families'+buttons by their letters (an Xbox controller's letters are Apple's button diamond, and+a Pro Controller's A, on the right, arrives as `buttonA`, as+[seedds/nxnative#382](https://github.com/seedds/nxnative/pull/382) found), which the+host's positional reading turns into the other letter, so one swap serves both.+**Custom** is the per-button choice; changing a button switches to it. **Auto** picks+By label or Standard from `GCController.productCategory` of the controller connected+when **Play** is pressed (Nintendo, Switch Pro, Joy-Con or Xbox in its name: By label).+One map goes to every controller, so two different kinds at once cannot both be right;+a per-controller choice belongs in the host (#382 does it for Nintendo controllers).+The page shows the connected controller and what Auto picks for it.+## ArtworkThe launcher shows, in this order: a custom image chosen under **Manage > Changediff --git a/frontend/Sources/NSPortBuilder/ControlPresets.swift b/frontend/Sources/NSPortBuilder/ControlPresets.swiftnew file mode 100644index 00000000..0e8359c8--- /dev/null+++ b/frontend/Sources/NSPortBuilder/ControlPresets.swift@@ -0,0 +1,96 @@+import GameController+import SwiftUI++/// The controller layouts of the Controls page (#70). Each produces only a DM_PAD_MAP value (dm/host/input_map.h), so the+/// host is unchanged: Standard passes nothing, By label one swap, Custom the buttons set by hand, and Auto picks Standard or+/// By label from the controller connected when Play is pressed.+enum PadMode: String, CaseIterable {+ case auto, standard, byLabel, custom+}++extension ControlLayout {+ /// By label, as one swap of the host's mapping. The host reads GameController's face buttons by position, in the+ /// Nintendo layout (front_mac.m pad_read: buttonB, on the right of Apple's diamond, is the Switch's A; buttonA, at the+ /// bottom, its B; buttonY, at the top, X; buttonX, on the left, Y). An Xbox controller's printed letters are Apple's+ /// diamond, so its A arrives as buttonA and reaches the game as B. A Nintendo controller arrives by its letters too: a+ /// real Pro Controller's A, on the right, arrives as buttonA (seedds/nxnative#382), so it also reaches the game as B. In+ /// both families the button printed A arrives as buttonA, B as buttonB, X as buttonX, Y as buttonY, and the same swap+ /// gives each its letter. For a Nintendo controller that is also its position, since its letters are the Switch's.+ static let byLabelPad = ["A": "B", "B": "A", "X": "Y", "Y": "X"]++ /// What each button sends in a layout (only the buttons that send another); Auto resolves to Standard or By label.+ func padMap(for mode: PadMode, category: String?) -> [String: String] {+ switch mode {+ case .standard: return [:]+ case .byLabel: return Self.byLabelPad+ case .custom: return pad+ case .auto: return padMap(for: Self.autoMode(category: category), category: nil)+ }+ }++ /// Auto's choice: By label for a Nintendo or an Xbox controller (GCController.productCategory: "Switch Pro Controller",+ /// "Nintendo Switch JoyCon (L/R)", "Xbox One", …), Standard for every other one and when none is connected. Matched by+ /// parts of the name, as the categories differ between controllers and macOS versions (JoyCon, Joy-Con).+ static func autoMode(category: String?) -> PadMode {+ guard let c = category?.lowercased().replacingOccurrences(of: "-", with: "") else { return .standard }+ return ["nintendo", "switch pro", "joycon", "xbox"].contains(where: c.contains) ? .byLabel : .standard+ }++ /// The controller a game started now would get: the one used last, else the first one connected.+ static func connectedCategory() -> String? {+ let pads = GCController.controllers().filter { $0.extendedGamepad != nil }+ let current = GCController.current.flatMap { c in pads.contains(c) ? c : nil }+ return (current ?? pads.first)?.productCategory+ }+}++/// The Controls page's layout choice: a picker, which controller is connected and what Auto picks for it, and a note+/// on the layout chosen.+struct PadModeSection: View {+ @ObservedObject var m: BuildModel+ @ObservedObject var layout: ControlLayout+ @State private var category: String?++ var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ Text(m.t("controls.mode")).font(.manrope(15, .semibold)).foregroundStyle(.secondary).padding(.leading, 2)+ HStack(spacing: 16) {+ VStack(alignment: .leading, spacing: 3) {+ Text(m.t("controls.modeRow")).font(.manrope(14, .medium))+ Text(connected).font(.manrope(12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }+ Spacer(minLength: 12)+ LauncherMenuPicker(options: PadMode.allCases.map { (value: $0.rawValue, label: label($0)) },+ selection: layout.padMode.rawValue, fill: true) { v in PadMode(rawValue: v).map(layout.setPadMode) }+ .frame(width: 168) // as wide as the button rows' choices below it+ .frame(width: LaunchControl.width, alignment: .trailing)+ }+ .padding(.horizontal, 18).padding(.vertical, 9)+ .frame(minHeight: 46)+ .padTarget("pad.mode", scope: "controls", radius: 10, activate: { step(1) }, adjust: step)+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))+ Text(m.t("controls.modeNote." + layout.padMode.rawValue)).font(.manrope(12)).foregroundStyle(.secondary)+ .padding(.leading, 2).fixedSize(horizontal: false, vertical: true)+ }+ .onAppear { category = layout.controllerCategory() }+ .onReceive(NotificationCenter.default.publisher(for: .GCControllerDidConnect).merge(with: NotificationCenter.default.publisher(for: .GCControllerDidDisconnect))) { _ in+ category = layout.controllerCategory()+ layout.objectWillChange.send() // Auto's buttons below follow the controller+ }+ }++ private func label(_ mode: PadMode) -> String { m.t("controls.mode." + mode.rawValue) }++ private var connected: String {+ let pick = label(ControlLayout.autoMode(category: category))+ return category.map { String(format: m.t("controls.connected"), $0, pick) } ?? String(format: m.t("controls.noController"), pick)+ }++ /// A controller's left / right through the layouts.+ private func step(_ by: Int) {+ let all = PadMode.allCases+ let at = all.firstIndex(of: layout.padMode) ?? 0+ layout.setPadMode(all[(at + by + all.count) % all.count])+ }+}diff --git a/frontend/Sources/NSPortBuilder/Controls.swift b/frontend/Sources/NSPortBuilder/Controls.swiftindex d33bdf56..4942ad40 100644--- a/frontend/Sources/NSPortBuilder/Controls.swift+++ b/frontend/Sources/NSPortBuilder/Controls.swift@@ -29,21 +29,35 @@ final class ControlLayout: ObservableObject {/// Function → key code, nil for no key; only functions moved from their default key.@Published private(set) var keys: [String: Int?] = [:]- /// Button → the button it sends, "none" for nothing; only buttons that send another.+ /// Button → the button it sends, "none" for nothing; only buttons that send another. The Custom layout's.@Published private(set) var pad: [String: String] = [:]+ /// The controller's layout (ControlPresets.swift): Standard, By label, Auto between the two, or Custom (`pad`).+ @Published private(set) var padMode: PadMode = .standard+ /// The connected controller's GCController.productCategory, which Auto goes by; tests stand in for it.+ var controllerCategory: () -> String? = ControlLayout.connectedCategoryprivate let defaults: UserDefaults- private struct Saved: Codable { var keys: [String: Int]; var pad: [String: String] } // a key code, -1 for no key+ /// A key code, -1 for no key. `mode` is nil in settings saved before the layouts, which had only the custom buttons.+ private struct Saved: Codable { var keys: [String: Int]; var pad: [String: String]; var mode: String? }init(defaults: UserDefaults = .standard) {self.defaults = defaultsif let data = defaults.data(forKey: "controlLayout"), let saved = try? JSONDecoder().decode(Saved.self, from: data) {keys = saved.keys.filter { k, code in Self.functions.contains { $0.id == k } && code < 128 }.mapValues { $0 < 0 ? nil : $0 }pad = saved.pad.filter { b, to in Self.buttons.contains(b) && (to == "none" || Self.buttons.contains(to)) }+ padMode = saved.mode.flatMap(PadMode.init(rawValue:)) ?? (pad.isEmpty ? .standard : .custom)}}- var isDefault: Bool { keys.isEmpty && pad.isEmpty }- var changeCount: Int { keys.count + pad.count }+ var isDefault: Bool { keys.isEmpty && padChanges == 0 }+ var changeCount: Int { keys.count + padChanges }+ /// A preset counts as one change; Custom as its buttons.+ private var padChanges: Int {+ switch padMode {+ case .standard: return 0+ case .custom: return pad.count+ case .byLabel, .auto: return 1+ }+ }/// The key a function is on now.func key(_ f: Function) -> Int? { keys[f.id] ?? f.defaultKey }@@ -59,28 +73,36 @@ final class ControlLayout: ObservableObject {save()}- func sends(_ button: String) -> String { pad[button] ?? button }+ /// What a button sends in the layout chosen (for Auto, the one it picks for the controller connected now).+ func sends(_ button: String) -> String { activePad[button] ?? button }+ /// A button changed by hand makes the layout Custom, starting from what the buttons sent until then.func setSends(_ button: String, _ to: String) {+ if padMode != .custom { pad = activePad; padMode = .custom }pad[button] = to == button ? nil : tosave()}+ func setPadMode(_ mode: PadMode) { padMode = mode; save() }++ private var activePad: [String: String] { padMap(for: padMode, category: padMode == .auto ? controllerCategory() : nil) }+func resetKeyboard() { keys = [:]; save() }- func resetController() { pad = [:]; save() }+ func resetController() { pad = [:]; padMode = .standard; save() }/// DM_KEYMAP and DM_PAD_MAP for the changes, in the sheet's order; empty when nothing changed.var environment: [String: String] {var env: [String: String] = [:]let k = Self.functions.compactMap { f in keys[f.id].map { "\(f.id)=\($0.map(String.init) ?? "none")" } }if !k.isEmpty { env["DM_KEYMAP"] = k.joined(separator: ",") }- let p = Self.buttons.compactMap { b in pad[b].map { "\(b)=\($0)" } }+ let active = activePad+ let p = Self.buttons.compactMap { b in active[b].map { "\(b)=\($0)" } }if !p.isEmpty { env["DM_PAD_MAP"] = p.joined(separator: ",") }return env}private func save() {- if let data = try? JSONEncoder().encode(Saved(keys: keys.mapValues { $0 ?? -1 }, pad: pad)) { defaults.set(data, forKey: "controlLayout") }+ if let data = try? JSONEncoder().encode(Saved(keys: keys.mapValues { $0 ?? -1 }, pad: pad, mode: padMode.rawValue)) { defaults.set(data, forKey: "controlLayout") }}/// A key's name on a US keyboard, by virtual key code (the host reads codes, so the name is only for the label).@@ -122,6 +144,7 @@ struct ControlsView: View {VStack(alignment: .leading, spacing: 24) {section(m.t("controls.sticks"), ControlLayout.functions.filter(\.isDirection)) { keyRow($0) }section(m.t("controls.keyButtons"), ControlLayout.functions.filter { !$0.isDirection }) { keyRow($0) }+ PadModeSection(m: m, layout: layout)section(m.t("controls.pad"), ControlLayout.buttons, note: m.t("controls.padNote")) { padRow($0) }}.padding(.horizontal, 30).padding(.bottom, 24)diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 163da946..5d64591a 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -445,6 +445,19 @@ enum L10n {"controls.padNote": ("按钮按位置命名:右侧为 A,下方为 B,上方为 X,左侧为 Y。", "Buttons are named by position: A on the right, B at the bottom, X at the top, Y on the left."),"controls.applied": ("下次在这里按下“开始游戏”时生效。较早的构建会忽略这些设置。", "Applied the next time you press Play here. Older builds ignore it."),"controls.reset": ("恢复默认", "Reset to defaults"),+ // ---- the controller's layouts (ControlPresets.swift) ----+ "controls.mode": ("手柄:布局", "Controller: layout"),+ "controls.modeRow": ("按钮布局", "Button layout"),+ "controls.mode.auto": ("自动", "Auto"),+ "controls.mode.standard": ("标准布局", "Standard layout"),+ "controls.mode.byLabel": ("按标签", "By label"),+ "controls.mode.custom": ("自定义", "Custom"),+ "controls.modeNote.standard": ("按位置,采用任天堂布局:右侧 A,下方 B,上方 X,左侧 Y。适用于 PlayStation 和其他手柄。", "By position, in the Nintendo layout: right A, bottom B, top X, left Y. For PlayStation and other controllers."),+ "controls.modeNote.byLabel": ("A、B、X、Y 与按钮上印的字母一致。适用于任天堂和 Xbox 手柄。", "A, B, X and Y as printed on the buttons. For Nintendo and Xbox controllers."),+ "controls.modeNote.custom": ("每个按钮发送下面选择的按键。更改任何按钮都会切换到自定义。", "Each button sends what is chosen below. Changing any button switches to Custom."),+ "controls.modeNote.auto": ("按开始游戏时连接的手柄选择:任天堂或 Xbox 手柄按标签,其他手柄用标准布局。所有手柄共用一种布局,因此同时连接两种不同的手柄时,无法两者都正确。", "Picked from the controller connected when you press Play: by label for a Nintendo or Xbox controller, the standard layout for any other. Every controller gets the same layout, so two different kinds at once can’t both be right."),+ "controls.connected": ("已连接:%1$@。自动选择“%2$@”。", "Connected: %@. Auto picks %@."),+ "controls.noController": ("没有连接手柄。自动选择“%@”。", "No controller connected. Auto picks %@."),"controls.clear": ("不使用按键", "No key"),"controls.press": ("请按一个键…", "Press a key…"),"controls.none": ("无", "None"),diff --git a/frontend/Tests/NSPortBuilderTests/ControlPresetsTests.swift b/frontend/Tests/NSPortBuilderTests/ControlPresetsTests.swiftnew file mode 100644index 00000000..36ae7b94--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/ControlPresetsTests.swift@@ -0,0 +1,106 @@+import XCTest+@testable import NSPortBuilder++/// Issue #70: the controller layouts and the DM_PAD_MAP each passes. Controllers are stand-in product categories; nothing+/// reads a real controller.+final class ControlPresetsTests: XCTestCase {+ private var defaults: UserDefaults!+ private let suite = "nxnative-control-presets-tests"++ override func setUp() {+ defaults = UserDefaults(suiteName: suite)+ defaults.removePersistentDomain(forName: suite)+ }++ override func tearDown() { defaults.removePersistentDomain(forName: suite) }++ private func layout(_ category: String? = nil) -> ControlLayout {+ let l = ControlLayout(defaults: defaults)+ l.controllerCategory = { category }+ return l+ }++ func testEachLayoutsPadMap() {+ let l = layout()+ XCTAssertEqual(l.padMode, .standard, "the default")+ XCTAssertNil(l.environment["DM_PAD_MAP"])+ l.setPadMode(.byLabel)+ XCTAssertEqual(l.environment, ["DM_PAD_MAP": "A=B,B=A,X=Y,Y=X"])+ XCTAssertEqual(l.sends("A"), "B")+ XCTAssertEqual(l.changeCount, 1)+ XCTAssertFalse(l.isDefault)+ l.setPadMode(.custom)+ XCTAssertNil(l.environment["DM_PAD_MAP"], "Custom with no button changed")+ XCTAssertTrue(l.isDefault)+ l.setSends("ZL", "ZR")+ XCTAssertEqual(l.environment, ["DM_PAD_MAP": "ZL=ZR"])+ l.setPadMode(.standard)+ XCTAssertNil(l.environment["DM_PAD_MAP"], "Standard ignores the custom buttons")+ l.setPadMode(.custom)+ XCTAssertEqual(l.environment, ["DM_PAD_MAP": "ZL=ZR"], "and Custom has them back")+ }++ func testAutoPicksByLabelForNintendoAndXboxControllers() {+ for category in ["Switch Pro Controller", "Nintendo Switch JoyCon (L/R)", "Nintendo Switch Joy-Con (L/R)", "Nintendo Switch Joy-Con (L)",+ "Xbox One", "Xbox Series X", "XBOX Wireless Controller"] {+ XCTAssertEqual(ControlLayout.autoMode(category: category), .byLabel, category)+ }+ for category in ["DualSense", "DualShock 4", "MFi", "HID", "Arcade Stick", ""] {+ XCTAssertEqual(ControlLayout.autoMode(category: category), .standard, category)+ }+ XCTAssertEqual(ControlLayout.autoMode(category: nil), .standard, "no controller")+ let xbox = layout("Xbox One")+ xbox.setPadMode(.auto)+ XCTAssertEqual(xbox.environment, ["DM_PAD_MAP": "A=B,B=A,X=Y,Y=X"])+ let dualSense = layout("DualSense")+ dualSense.setPadMode(.auto)+ XCTAssertEqual(dualSense.environment, [:])+ XCTAssertEqual(dualSense.changeCount, 1, "Auto is a choice, whatever it picks now")+ }++ func testEditingAButtonSwitchesToCustomFromWhatTheButtonsSent() {+ let l = layout("Switch Pro Controller")+ l.setPadMode(.auto)+ l.setSends("ZL", "none")+ XCTAssertEqual(l.padMode, .custom)+ XCTAssertEqual(l.environment, ["DM_PAD_MAP": "A=B,B=A,X=Y,Y=X,ZL=none"], "Auto's By label, plus the change")+ let reloaded = layout()+ XCTAssertEqual(reloaded.padMode, .custom)+ XCTAssertEqual(reloaded.environment, l.environment)+ reloaded.resetController()+ XCTAssertEqual(reloaded.padMode, .standard)+ XCTAssertTrue(layout().isDefault)+ }++ func testSettingsSavedBeforeTheLayoutsStillLoad() throws {+ defaults.set(Data(#"{"keys":{"A":40,"B":-1},"pad":{"A":"B","B":"A","Minus":"none"}}"#.utf8), forKey: "controlLayout")+ let old = layout()+ XCTAssertEqual(old.padMode, .custom, "buttons set by hand are the Custom layout")+ XCTAssertEqual(old.environment, ["DM_KEYMAP": "A=40,B=none", "DM_PAD_MAP": "A=B,B=A,Minus=none"])+ defaults.set(Data(#"{"keys":{"Shake":-1},"pad":{}}"#.utf8), forKey: "controlLayout")+ XCTAssertEqual(layout().padMode, .standard)+ defaults.set(Data(#"{"keys":{},"pad":{},"mode":"byLabel"}"#.utf8), forKey: "controlLayout")+ XCTAssertEqual(layout().padMode, .byLabel)+ defaults.set(Data(#"{"keys":{},"pad":{"X":"Y"},"mode":"a mode from a later version"}"#.utf8), forKey: "controlLayout")+ XCTAssertEqual(layout().padMode, .custom)+ }++ /// The reasoning behind one By label map for both families, played through: GameController's element for each printed+ /// letter, the host's positional reading of it (front_mac.m pad_read), then DM_PAD_MAP as input_map.h applies it.+ func testByLabelGivesEveryPrintedLetterOnNintendoAndXboxControllers() {+ let host = ["buttonA": "B", "buttonB": "A", "buttonX": "Y", "buttonY": "X"] // pad_read: by position, right A, bottom B, top X, left Y+ // Xbox: the letters are Apple's diamond. Nintendo: GameController reports the letters (seedds/nxnative#382: the Pro+ // Controller's A, on the right, arrives as buttonA). Either way the letter's element has the letter's name.+ let families = ["Xbox": ["A": "buttonA", "B": "buttonB", "X": "buttonX", "Y": "buttonY"],+ "Nintendo": ["A": "buttonA", "B": "buttonB", "X": "buttonX", "Y": "buttonY"]]+ let map = ControlLayout.byLabelPad+ for (family, element) in families {+ for letter in ["A", "B", "X", "Y"] {+ let positional = host[element[letter]!]!+ XCTAssertEqual(map[positional] ?? positional, letter, "\(family) \(letter)")+ }+ }+ // A PlayStation controller has no letters: Standard leaves the host's positions, the Switch's layout+ XCTAssertEqual(ControlLayout.autoMode(category: "DualSense"), .standard)+ }+}diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swiftindex 20b9fddf..cc336939 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -761,6 +761,33 @@ final class LibraryTests: XCTestCase {model.stages = [Stage(id: 1, name: "Extract game files", state: .running, percent: 40)]try capture("building", activeID: library.games[1].id)model.running = false++ // ---- Controller layouts (#70): the Controls sheet scrolled to the layout by the controller's focus, Auto with a+ // stand-in Xbox controller, then By label with none connected (a suite of its own; no real controller is read) ----+ do {+ let suite = "nxnative-visual-qa-control-presets"+ let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))+ defaults.removePersistentDomain(forName: suite)+ defer { defaults.removePersistentDomain(forName: suite) }+ for (name, mode, category) in [("controls-layout-auto", PadMode.auto, "Xbox One" as String?), ("controls-layout-bylabel", .byLabel, nil)] {+ let layout = ControlLayout(defaults: defaults)+ layout.controllerCategory = { category }+ layout.setPadMode(mode)+ let focus = PadFocus()+ let host = NSHostingView(rootView: ControlsView(m: model, layout: layout).environmentObject(focus))+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 700), styleMask: [.titled], backing: .buffered, defer: false)+ window.contentView = host+ window.orderFront(nil)+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))+ focus.scope = "controls"+ focus.show(default: "pad.mode")+ RunLoop.main.run(until: Date().addingTimeInterval(0.6))+ let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))+ host.cacheDisplay(in: host.bounds, to: rep)+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent(name + ".png"))+ window.orderOut(nil)+ }+ }}/// Issue #52: the failure note names the last real line, not just the exit code.