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
Launcher: a Controls page for keys and controller buttons, and one width for the settings' buttons and controls
v0lumehi6267bb7889cb
diff --git a/frontend/README.md b/frontend/README.mdindex 4b748f21..5d0dc116 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -58,6 +58,18 @@ environment. Only a choice that differs from the game's tested default is kept,library manifest; **Reset to tested defaults** forgets them. An app without the listshows none. Starting the app from Finder uses its defaults.+## Controls++**Settings → Controls → Customize…** sets the keys and controller buttons for every game.+For a key, click its field and press the new key (Esc keeps the old one, × leaves the+function on no key). One key holds one function, so the function that had the key before+is left on none, as in the host. For a controller button, choose the button it sends+(A and B swapped, for example). The right stick has no keys by default and can get some+here. **Play** passes only the changes, as `DM_KEYMAP` and `DM_PAD_MAP`+(`dm/host/input_map.h`; the engine change is+[seedds/nxnative#386](https://github.com/seedds/nxnative/pull/386), so a sync from+upstream brings it). A build without it ignores them and uses the default keys.+## ArtworkThe launcher shows, in this order: a custom image chosen under **Manage > Changediff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 0c16fd94..fb96ad89 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -1479,6 +1479,8 @@ struct BuilderView: View {var onViewGame: () -> Void = {}var onOpenSettings: () -> Void = {}var onChooseLibraryFolder: () -> Void = {}+ var onOpenControls: () -> Void = {}+ var controlChanges = 0@State private var extrasOpen = false@State private var logOpen = false@@ -1815,8 +1817,15 @@ struct BuilderView: View {// ---- Settings ----+ /// Every button of the Settings cards is this wide, so they stand in one column.+ static let settingsButtonWidth: CGFloat = 150+@ViewBuilder private var settingsPage: some View {pageHeading(m.t("settings.heading"), note: m.t("settings.note"))+ settingsCards.buttonStyle(LauncherSecondaryButtonStyle(minWidth: Self.settingsButtonWidth))+ }++ @ViewBuilder private var settingsCards: some View {group(m.t("section.library"), footnote: m.t("library.folderHint")) {row(m.t("library.folderTitle"), detail: library.folder.isEmpty ? m.t("library.folderUnset") : m.shortPath(library.folder),dot: library.folder.isEmpty ? LauncherPalette.unbuilt : LauncherPalette.ready, help: library.folder) {@@ -1827,6 +1836,11 @@ struct BuilderView: View {Button(m.t("library.chooseFolder"), action: 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)+ }+ }toolsgroup(m.t("section.app"), footnote: m.appStatus) {// The interface language: the device default unless someone picks one here. Stored asdiff --git a/frontend/Sources/NSPortBuilder/Controls.swift b/frontend/Sources/NSPortBuilder/Controls.swiftnew file mode 100644index 00000000..6e7cac33--- /dev/null+++ b/frontend/Sources/NSPortBuilder/Controls.swift@@ -0,0 +1,231 @@+import AppKit+import SwiftUI++/// The player's keyboard and controller layout for every game, passed at Play as the host's DM_KEYMAP and DM_PAD_MAP+/// (dm/host/input_map.h). Only what differs from the host's defaults is kept and passed, so a build whose host does not+/// read the two variables plays as before, and an unchanged layout passes nothing.+final class ControlLayout: ObservableObject {+ /// A function the keyboard can hold, named as the host names it (DM_KEYS's names).+ struct Function: Identifiable {+ let id: String+ let defaultKey: Int? // macOS virtual key code; the right stick has none+ /// The sheet's two keyboard cards: the sticks and the D-pad, then the buttons and Shake.+ var isDirection: Bool { ControlLayout.directions.contains(id) }+ }++ /// The host's default keys (input_map.h key_map_default), in the order the Controls sheet lists them.+ static let functions: [Function] = [+ .init(id: "LUp", defaultKey: 13), .init(id: "LDown", defaultKey: 1), .init(id: "LLeft", defaultKey: 0), .init(id: "LRight", defaultKey: 2),+ .init(id: "RUp", defaultKey: nil), .init(id: "RDown", defaultKey: nil), .init(id: "RLeft", defaultKey: nil), .init(id: "RRight", defaultKey: nil),+ .init(id: "Up", defaultKey: 126), .init(id: "Down", defaultKey: 125), .init(id: "Left", defaultKey: 123), .init(id: "Right", defaultKey: 124),+ .init(id: "A", defaultKey: 38), .init(id: "B", defaultKey: 40), .init(id: "X", defaultKey: 32), .init(id: "Y", defaultKey: 34),+ .init(id: "L", defaultKey: 12), .init(id: "R", defaultKey: 14), .init(id: "ZL", defaultKey: 6), .init(id: "ZR", defaultKey: 8),+ .init(id: "Plus", defaultKey: 36), .init(id: "Minus", defaultKey: 48), .init(id: "LS", defaultKey: 3), .init(id: "RS", defaultKey: 5),+ .init(id: "Shake", defaultKey: 49),+ ]+ static let directions: Set = ["LUp", "LDown", "LLeft", "LRight", "RUp", "RDown", "RLeft", "RRight", "Up", "Down", "Left", "Right"]+ /// The 16 buttons a controller's buttons can send (DM_PAD_MAP), in the sheet's order.+ static let buttons = ["A", "B", "X", "Y", "L", "R", "ZL", "ZR", "Plus", "Minus", "LS", "RS", "Up", "Down", "Left", "Right"]++ /// 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.+ @Published private(set) var pad: [String: String] = [:]+ private let defaults: UserDefaults+ private struct Saved: Codable { var keys: [String: Int]; var pad: [String: String] } // a key code, -1 for no key++ init(defaults: UserDefaults = .standard) {+ self.defaults = defaults+ if 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)) }+ }+ }++ var isDefault: Bool { keys.isEmpty && pad.isEmpty }+ var changeCount: Int { keys.count + pad.count }++ /// The key a function is on now.+ func key(_ f: Function) -> Int? { keys[f.id] ?? f.defaultKey }++ /// Puts a function on a key, or on none. One key holds one function, as in the host: the function the key held+ /// before is left on no key.+ func assign(_ f: Function, key: Int?) {+ var next = keys+ if let key { for g in Self.functions where g.id != f.id && self.key(g) == key { next[g.id] = .some(nil) } }+ next[f.id] = key == f.defaultKey ? nil : .some(key)+ for g in Self.functions where next[g.id] != nil && next[g.id]! == g.defaultKey { next[g.id] = nil }+ keys = next+ save()+ }++ func sends(_ button: String) -> String { pad[button] ?? button }++ func setSends(_ button: String, _ to: String) {+ pad[button] = to == button ? nil : to+ save()+ }++ func resetKeyboard() { keys = [:]; save() }+ func resetController() { pad = [:]; 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)" } }+ 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") }+ }++ /// A key's name on a US keyboard, by virtual key code (the host reads codes, so the name is only for the label).+ static func keyName(_ code: Int?) -> String? {+ guard let code else { return nil }+ let names: [Int: String] = [+ 0: "A", 1: "S", 2: "D", 3: "F", 4: "H", 5: "G", 6: "Z", 7: "X", 8: "C", 9: "V", 11: "B", 12: "Q", 13: "W", 14: "E", 15: "R",+ 16: "Y", 17: "T", 18: "1", 19: "2", 20: "3", 21: "4", 22: "6", 23: "5", 24: "=", 25: "9", 26: "7", 27: "-", 28: "8", 29: "0",+ 30: "]", 31: "O", 32: "U", 33: "[", 34: "I", 35: "P", 36: "Return", 37: "L", 38: "J", 39: "'", 40: "K", 41: ";", 42: "\\",+ 43: ",", 44: "/", 45: "N", 46: "M", 47: ".", 48: "Tab", 49: "Space", 50: "`", 51: "Delete", 65: "Keypad .", 67: "Keypad *",+ 69: "Keypad +", 71: "Clear", 75: "Keypad /", 76: "Enter", 78: "Keypad -", 81: "Keypad =", 82: "Keypad 0", 83: "Keypad 1",+ 84: "Keypad 2", 85: "Keypad 3", 86: "Keypad 4", 87: "Keypad 5", 88: "Keypad 6", 89: "Keypad 7", 91: "Keypad 8", 92: "Keypad 9",+ 96: "F5", 97: "F6", 98: "F7", 99: "F3", 100: "F8", 101: "F9", 103: "F11", 105: "F13", 107: "F14", 109: "F10", 111: "F12",+ 113: "F15", 115: "Home", 116: "Page Up", 117: "Forward Delete", 118: "F4", 119: "End", 120: "F2", 121: "Page Down", 122: "F1",+ 123: "←", 124: "→", 125: "↓", 126: "↑",+ ]+ return names[code] ?? "Key \(code)"+ }+}++/// The Controls sheet: the keyboard's key for each function (click, then press a key) and what each controller button sends.+struct ControlsView: View {+ @ObservedObject var m: BuildModel+ @ObservedObject var layout: ControlLayout+ @Environment(\.dismiss) private var dismiss+ @State private var listening: String?+ @State private var monitor: Any?++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ VStack(alignment: .leading, spacing: 4) {+ Text(m.t("controls.title")).font(.manrope(26, .heavy)).tracking(-0.6)+ Text(m.t("controls.note")).font(.manrope(14)).foregroundStyle(.secondary)+ }+ .padding(.horizontal, 30).padding(.top, 28).padding(.bottom, 20)+ ScrollView {+ 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) }+ section(m.t("controls.pad"), ControlLayout.buttons, note: m.t("controls.padNote")) { padRow($0) }+ }+ .padding(.horizontal, 30).padding(.bottom, 24)+ }+ Divider().opacity(0.3)+ HStack(spacing: 14) {+ Text(m.t("controls.applied")).font(.manrope(12)).foregroundStyle(.secondary).lineLimit(2)+ Spacer(minLength: 8)+ if !layout.isDefault {+ Button(m.t("controls.reset")) { stopListening(); layout.resetKeyboard(); layout.resetController() }+ .buttonStyle(LauncherSecondaryButtonStyle())+ }+ Button { stopListening(); dismiss() } label: {+ Text(m.t("launch.done")).font(.manrope(13.5, .bold)).foregroundStyle(.black)+ .padding(.horizontal, 22).padding(.vertical, 9)+ .background(LauncherPalette.cream, in: Capsule())+ }+ .buttonStyle(.plain).keyboardShortcut(listening == nil ? .defaultAction : nil)+ }+ .padding(.horizontal, 30).padding(.vertical, 16)+ }+ .frame(width: 600, height: 700)+ .background(LauncherPalette.background)+ .font(.manrope(13))+ .preferredColorScheme(.dark)+ .tint(LauncherPalette.cream)+ .onDisappear { stopListening() }+ }++ private func section<Item, Row: View>(_ title: String, _ items: [Item], note: String = "", @ViewBuilder row: @escaping (Item) -> Row) -> some View {+ VStack(alignment: .leading, spacing: 10) {+ Text(title).font(.manrope(15, .semibold)).foregroundStyle(.secondary).padding(.leading, 2)+ VStack(spacing: 0) {+ ForEach(items.indices, id: \.self) { i in+ row(items[i])+ if i < items.count - 1 { Divider().opacity(0.25).padding(.leading, 18) }+ }+ }+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))+ if !note.isEmpty {+ Text(note).font(.manrope(12)).foregroundStyle(.secondary).padding(.leading, 2).fixedSize(horizontal: false, vertical: true)+ }+ }+ }++ private func line<Trailing: View>(_ title: String, @ViewBuilder trailing: () -> Trailing) -> some View {+ HStack(spacing: 16) {+ Text(title).font(.manrope(14, .medium))+ Spacer(minLength: 12)+ trailing().frame(width: LaunchControl.width, alignment: .trailing)+ }+ .padding(.horizontal, 18).padding(.vertical, 9)+ .frame(minHeight: 46)+ }++ private func keyRow(_ f: ControlLayout.Function) -> some View {+ let on = listening == f.id+ let key = layout.key(f)+ return line(m.t("controls.fn." + f.id)) {+ HStack(spacing: 6) {+ if key != nil && !on {+ Button { layout.assign(f, key: nil) } label: {+ Image(systemName: "xmark").font(.system(size: 9, weight: .bold)).foregroundStyle(.secondary)+ .frame(width: 22, height: 22).contentShape(Circle())+ }+ .buttonStyle(.plain).help(m.t("controls.clear"))+ }+ Button { on ? stopListening() : listen(f) } label: {+ Text(on ? m.t("controls.press") : ControlLayout.keyName(key) ?? m.t("controls.none"))+ .font(.manrope(12.5, on ? .bold : .semibold))+ .foregroundStyle(on ? Color.black : key == nil ? Color.white.opacity(0.45) : Color.white.opacity(0.92))+ .frame(maxWidth: .infinity).padding(.vertical, 6)+ .background(on ? LauncherPalette.cream : Color.white.opacity(0.06), in: Capsule())+ .overlay(Capsule().strokeBorder(Color.white.opacity(on ? 0 : 0.10)))+ .contentShape(Capsule())+ }+ .buttonStyle(.plain)+ .frame(width: 140)+ }+ }+ }++ private func padRow(_ button: String) -> some View {+ line(m.t("controls.fn." + button)) {+ 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: 140)+ }+ }++ /// The next key pressed goes to the function; Esc leaves it as it was. Keys with ⌘ stay with the menu, as in the game.+ private func listen(_ f: ControlLayout.Function) {+ stopListening()+ listening = f.id+ monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { e in+ if e.modifierFlags.contains(.command) { return e }+ if e.keyCode != 53 { layout.assign(f, key: Int(e.keyCode)) }+ stopListening()+ return nil+ }+ }++ private func stopListening() {+ if let monitor { NSEvent.removeMonitor(monitor) }+ monitor = nil+ listening = nil+ }+}diff --git a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swiftindex 8d876e49..2d9f3e44 100644--- a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift+++ b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift@@ -87,29 +87,36 @@ struct LaunchOptionsView: View {}}Spacer(minLength: 12)+ control(s, value).frame(width: LaunchControl.width, alignment: .trailing)+ }+ .padding(.horizontal, 18).padding(.vertical, 13)+ .frame(minHeight: 52)+ }++ /// The setting's control, filling the column every row shares (a toggle keeps its size at the column's right edge).+ @ViewBuilder private func control(_ s: LaunchSetting, _ value: String) -> some View {+ HStack(spacing: 10) {switch s.kind {case "choice":let options = (s.options ?? []).map { (value: $0[0], label: $0.count > 1 ? $0[1] : $0[0]) }if options.count <= 3 {LauncherSegmented(options: options, selection: value) { set(s, $0) }} else {- LauncherMenuPicker(options: options, selection: value) { set(s, $0) }+ LauncherMenuPicker(options: options, selection: value, fill: true) { set(s, $0) }}case "range":let lo = s.min ?? 0, hi = s.max ?? 1LauncherSlider(value: Double(value) ?? Double(s.def) ?? lo, range: lo...hi, step: s.step ?? 0.05) {set(s, String(format: "%.2f", $0))}- .frame(width: 170)Text("\(Int(((Double(value) ?? 0) * 100).rounded()))%").font(.manrope(13, .semibold)).monospacedDigit().foregroundStyle(.secondary).frame(width: 44, alignment: .trailing)default:+ Spacer(minLength: 0)Toggle("", isOn: Binding(get: { value == s.onValue }, set: { set(s, $0 ? s.onValue : s.offValue) })).labelsHidden().toggleStyle(LauncherSwitchStyle())}}- .padding(.horizontal, 18).padding(.vertical, 13)- .frame(minHeight: 52)}}diff --git a/frontend/Sources/NSPortBuilder/LauncherStyles.swift b/frontend/Sources/NSPortBuilder/LauncherStyles.swiftindex 92b51fbd..f152a093 100644--- a/frontend/Sources/NSPortBuilder/LauncherStyles.swift+++ b/frontend/Sources/NSPortBuilder/LauncherStyles.swift@@ -19,11 +19,15 @@ struct LauncherWindowChrome: NSViewRepresentable {struct LauncherSecondaryButtonStyle: ButtonStyle {/// Text and border in this colour (the build bar's Stop); plain white otherwise.var accent: Color? = nil+ /// At least this wide, the label centred: the buttons of a card line up in one column (Settings).+ var minWidth: CGFloat? = nil@Environment(\.isEnabled) private var enabledfunc makeBody(configuration: Configuration) -> some View {configuration.label.font(.manrope(13, .semibold))+ .lineLimit(1).padding(.horizontal, 15).padding(.vertical, 9)+ .frame(minWidth: minWidth).background(Color.white.opacity(configuration.isPressed ? 0.13 : 0.055), in: RoundedRectangle(cornerRadius: 9)).overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(accent?.opacity(0.75) ?? Color.white.opacity(0.10))).foregroundStyle(enabled ? (accent ?? Color.white.opacity(0.92)) : .gray)@@ -52,7 +56,14 @@ struct LauncherSwitchStyle: ToggleStyle {}}-/// Two or three choices side by side; the chosen one is a cream pill.+/// The width of a launch option's control (choices, list, slider with its value), so the controls of a card line up+/// in one column whatever their labels.+enum LaunchControl {+ static let width: CGFloat = 220+}++/// Two or three choices side by side; the chosen one is a cream pill. Each choice takes an equal share of the width+/// it is given.struct LauncherSegmented: View {let options: [(value: String, label: String)]let selection: String@@ -64,7 +75,9 @@ struct LauncherSegmented: View {Button { withAnimation(.easeOut(duration: 0.15)) { choose(o.value) } } label: {Text(o.label).font(.manrope(12.5, on ? .bold : .medium)).foregroundStyle(on ? Color.black : Color.white.opacity(0.75))+ .lineLimit(1).minimumScaleFactor(0.85).padding(.horizontal, 12).padding(.vertical, 6)+ .frame(maxWidth: .infinity).background(on ? LauncherPalette.cream : .clear, in: Capsule()).contentShape(Capsule())}@@ -78,19 +91,23 @@ struct LauncherSegmented: View {}}-/// A longer list of choices: a pill with the current one that opens the list.+/// A longer list of choices: a pill with the current one that opens the list. With `fill` it takes the width it is+/// given, the chevron at its right end.struct LauncherMenuPicker: View {let options: [(value: String, label: String)]let selection: String+ var fill = falselet choose: (String) -> Void@State private var open = falsevar body: some View {Button { open.toggle() } label: {HStack(spacing: 8) {- Text(options.first { $0.value == selection }?.label ?? selection).font(.manrope(12.5, .semibold))+ Text(options.first { $0.value == selection }?.label ?? selection).font(.manrope(12.5, .semibold)).lineLimit(1)+ if fill { Spacer(minLength: 0) }Image(systemName: "chevron.down").font(.system(size: 9, weight: .bold)).foregroundStyle(.secondary)}.padding(.horizontal, 14).padding(.vertical, 7)+ .frame(maxWidth: fill ? .infinity : nil).background(Color.white.opacity(0.06), in: Capsule()).overlay(Capsule().strokeBorder(Color.white.opacity(0.10))).contentShape(Capsule())diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 17ee83b5..7af84ea2 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -34,6 +34,8 @@ struct ContentView: View {@State private var launchError: String?@State private var removing: LibraryGame?@State private var optionsFor: UUID?+ @State private var controlsOpen = false+ @StateObject private var controls = ControlLayout()@StateObject private var row = RowScroller()private var performStartupChecks: Bool@Environment(\.scenePhase) private var scenePhase@@ -60,7 +62,8 @@ struct ContentView: View {libraryPage} else {BuilderView(m: m, library: library, settings: page == .settings, onViewGame: { page = .library },- onOpenSettings: { page = .settings }, onChooseLibraryFolder: chooseLibraryFolder)+ onOpenSettings: { page = .settings }, onChooseLibraryFolder: chooseLibraryFolder,+ onOpenControls: { controlsOpen = true }, controlChanges: controls.changeCount).frame(maxWidth: .infinity, maxHeight: .infinity)}if m.running || page == .library { activityBar }@@ -118,6 +121,7 @@ struct ContentView: View {.sheet(isPresented: Binding(get: { optionsFor != nil }, set: { if !$0 { optionsFor = nil } })) {if let id = optionsFor { LaunchOptionsView(m: m, library: library, gameID: id) }}+ .sheet(isPresented: $controlsOpen) { ControlsView(m: m, layout: controls) }}private var topBar: some View {@@ -469,7 +473,10 @@ struct ContentView: View {launching = truelet configuration = NSWorkspace.OpenConfiguration()// The launch options; the app's launcher (dm/mac/launcher.c) keeps a variable that is already set.- if let settings = LaunchSetting.read(app: game.appPath) { configuration.environment = game.launchEnvironment(settings) }+ // The keyboard and controller layout (Settings → Controls) goes to every game; a build whose host does not read it plays with the default keys.+ var environment = controls.environment+ if let settings = LaunchSetting.read(app: game.appPath) { environment.merge(game.launchEnvironment(settings)) { _, own in own } }+ if !environment.isEmpty { configuration.environment = environment }NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: game.appPath), configuration: configuration) { _, error inDispatchQueue.main.async {launching = falsediff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex fd28f470..45d826e3 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -396,6 +396,48 @@ enum L10n {"prog.archiveDone": ("游戏数据就绪:%@/romfs.img", "game data ready: %@/romfs.img"),"prog.archiveReused": ("复用上次的镜像(%d 个文件未变)", "reused the previous image (%d files unchanged)"),"msg.archiveReused": ("归档未变,复用 %@", "archive unchanged, reusing %@"),+ "section.controls": ("操作", "Controls"),+ "controls.settingsHint": ("适用于所有在 Mac 上运行的游戏。", "Used by every game you play on this Mac."),+ "controls.row": ("键盘与手柄", "Keyboard and controller"),+ "controls.defaultLayout": ("默认布局", "Default layout"),+ "controls.changes": ("已更改 %d 项", "%d changes"),+ "controls.customize": ("自定义…", "Customize…"),+ "controls.title": ("操作", "Controls"),+ "controls.note": ("每个游戏都使用这里的按键和手柄按钮。", "The keys and controller buttons every game uses."),+ "controls.sticks": ("键盘:摇杆和方向键", "Keyboard: sticks and D-pad"),+ "controls.keyButtons": ("键盘:按钮", "Keyboard: buttons"),+ "controls.pad": ("手柄:每个按钮发送的按键", "Controller: what each button sends"),+ "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"),+ "controls.clear": ("不使用按键", "No key"),+ "controls.press": ("请按一个键…", "Press a key…"),+ "controls.none": ("无", "None"),+ "controls.fn.LUp": ("左摇杆 上", "Left stick up"),+ "controls.fn.LDown": ("左摇杆 下", "Left stick down"),+ "controls.fn.LLeft": ("左摇杆 左", "Left stick left"),+ "controls.fn.LRight": ("左摇杆 右", "Left stick right"),+ "controls.fn.RUp": ("右摇杆 上", "Right stick up"),+ "controls.fn.RDown": ("右摇杆 下", "Right stick down"),+ "controls.fn.RLeft": ("右摇杆 左", "Right stick left"),+ "controls.fn.RRight": ("右摇杆 右", "Right stick right"),+ "controls.fn.Up": ("方向键 上", "D-pad up"),+ "controls.fn.Down": ("方向键 下", "D-pad down"),+ "controls.fn.Left": ("方向键 左", "D-pad left"),+ "controls.fn.Right": ("方向键 右", "D-pad right"),+ "controls.fn.A": ("A", "A"),+ "controls.fn.B": ("B", "B"),+ "controls.fn.X": ("X", "X"),+ "controls.fn.Y": ("Y", "Y"),+ "controls.fn.L": ("L", "L"),+ "controls.fn.R": ("R", "R"),+ "controls.fn.ZL": ("ZL", "ZL"),+ "controls.fn.ZR": ("ZR", "ZR"),+ "controls.fn.Plus": ("+", "+"),+ "controls.fn.Minus": ("−", "−"),+ "controls.fn.LS": ("按下左摇杆", "Left stick press"),+ "controls.fn.RS": ("按下右摇杆", "Right stick press"),+ "controls.fn.Shake": ("摇动手柄", "Shake"),"msg.archiveLog": ("归档:%@ → %@", "Archive: %@ → %@"),]diff --git a/frontend/Tests/NSPortBuilderTests/ControlsTests.swift b/frontend/Tests/NSPortBuilderTests/ControlsTests.swiftnew file mode 100644index 00000000..48b3fe92--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/ControlsTests.swift@@ -0,0 +1,65 @@+import XCTest+@testable import NSPortBuilder++/// The Controls page's layout and the DM_KEYMAP / DM_PAD_MAP it passes (read by dm/host/input_map.h).+final class ControlsTests: XCTestCase {+ private var defaults: UserDefaults!+ private let suite = "nxnative-controls-tests"++ override func setUp() {+ defaults = UserDefaults(suiteName: suite)+ defaults.removePersistentDomain(forName: suite)+ }++ override func tearDown() { defaults.removePersistentDomain(forName: suite) }++ private func fn(_ id: String) -> ControlLayout.Function { ControlLayout.functions.first { $0.id == id }! }++ func testDefaultsPassNothing() {+ let layout = ControlLayout(defaults: defaults)+ XCTAssertTrue(layout.isDefault)+ XCTAssertEqual(layout.environment, [:])+ XCTAssertEqual(layout.key(fn("A")), 38)+ XCTAssertNil(layout.key(fn("RUp")))+ }++ func testAssigningAnotherFunctionsKeyLeavesThatFunctionOnNone() {+ let layout = ControlLayout(defaults: defaults)+ layout.assign(fn("A"), key: 40) // K, B's key+ XCTAssertEqual(layout.key(fn("A")), 40)+ XCTAssertNil(layout.key(fn("B")))+ XCTAssertEqual(layout.environment, ["DM_KEYMAP": "A=40,B=none"])+ layout.assign(fn("B"), key: 38) // and B to J: a swap+ XCTAssertEqual(layout.environment, ["DM_KEYMAP": "A=40,B=38"])+ }++ func testMovingBackToTheDefaultKeyDropsTheEntry() {+ let layout = ControlLayout(defaults: defaults)+ layout.assign(fn("RUp"), key: 126) // ↑, the D-pad's+ XCTAssertEqual(layout.environment, ["DM_KEYMAP": "RUp=126,Up=none"])+ layout.assign(fn("Up"), key: 126)+ XCTAssertTrue(layout.isDefault, "RUp lost ↑ and is back on no key, its default")+ }++ func testControllerButtonsAndPersistence() {+ let layout = ControlLayout(defaults: defaults)+ layout.setSends("A", "B"); layout.setSends("B", "A"); layout.setSends("Minus", "none")+ layout.assign(fn("Shake"), key: nil)+ XCTAssertEqual(layout.environment, ["DM_KEYMAP": "Shake=none", "DM_PAD_MAP": "A=B,B=A,Minus=none"])+ XCTAssertEqual(layout.changeCount, 4)+ let reloaded = ControlLayout(defaults: defaults)+ XCTAssertEqual(reloaded.environment, layout.environment)+ reloaded.setSends("A", "A")+ XCTAssertEqual(reloaded.environment["DM_PAD_MAP"], "B=A,Minus=none")+ reloaded.resetKeyboard(); reloaded.resetController()+ XCTAssertTrue(ControlLayout(defaults: defaults).isDefault)+ }++ func testEveryFunctionHasALabelAndTheDefaultKeysAreDistinct() {+ let keys = ControlLayout.functions.compactMap(\.defaultKey)+ XCTAssertEqual(Set(keys).count, keys.count)+ for f in ControlLayout.functions { XCTAssertNotNil(L10n.table["controls.fn." + f.id], f.id) }+ XCTAssertEqual(ControlLayout.keyName(49), "Space")+ XCTAssertEqual(ControlLayout.keyName(126), "↑")+ }+}diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swiftindex 5bb2e507..bc7bfddc 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -549,6 +549,24 @@ final class LibraryTests: XCTestCase {try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("launch-options.png"))window.orderOut(nil)}+ do { // the Controls sheet with a few changes, kept in a suite of its own+ let suite = "nxnative-visual-qa-controls"+ let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))+ defaults.removePersistentDomain(forName: suite)+ defer { defaults.removePersistentDomain(forName: suite) }+ 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 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.5))+ 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("controls.png"))+ window.orderOut(nil)+ }let crowded = GameLibrary(file: temporary.appendingPathComponent("crowded.json")) // more games than the row shows: its pager chevronsfor (index, name) in ["Hades", "Metroid Dread", "Bayonetta 3", "Pikmin 4", "Splatoon 3", "Kirby and the Forgotten Land", "Xenoblade Chronicles 3", "Fire Emblem Engage"].enumerated() {model.slots[0].paths = ["/preview/\(name) [01000000000\(String(format: "%02X", index))000].nsp"]