Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

ios: add global and per-game controller button mappings

Haseenesss2341b358dc0b
diff --git a/frontend-ios/README.md b/frontend-ios/README.md
index 825683a4..27c17b6f 100644
--- a/frontend-ios/README.md
+++ b/frontend-ios/README.md
@@ -33,7 +33,7 @@ All boundary types are in `Sources/ShellUI/ShellInputs.swift` and `ShellArtwork.
- `ShellActions`: selection, Play, setting changes, game-data and cloud-folder requests, reset, log, app update and Back. The game ID is always passed.
- `ShellInput`: an optional semantic controller event with an increasing sequence and the device that sent it (`InputDevice`: a controller family or the keyboard), so the hints draw that device's glyphs.
-`ShellControllers` is a separate library target, not part of the views: `GamepadAdapter` reads every GameController controller (D-pad and left stick with a deadzone and the Mac's repeat on hold, A activates, B goes back, X and Menu open game settings, Y opens Controllers, by label so each family confirms with its own button) and reports `ShellInput` actions and the connected controllers with their battery. Its pure mapping (`PadMapper`, `RepeatTiming`) is unit tested. The demo uses it, the real shell can too.
+`ShellControllers` is a separate library target, not part of the views: `GamepadAdapter` reads every GameController controller (D-pad and left stick with a deadzone and the Mac's repeat on hold, A activates, B goes back, X and Menu open game settings, Y opens Controllers, by label so each family confirms with its own button) and reports `ShellInput` actions and the connected controllers with their battery. Its pure mapping (`PadMapper`, `RepeatTiming`) is unit tested. The Controllers page also edits global physical-controller button mappings, including Swap A and B. These affect games only. Shell menus keep A to confirm and B to go back. Each game's Controller settings can follow global, override individual buttons, disable a button, or explicitly turn the swap off. The demo uses it, the real shell can too.
```swift
LibraryView(
@@ -63,7 +63,7 @@ The caller returns changed values through `games`. The views keep no second copy
| `FolderPicker` | `DocumentFolderPicker` is a `UIDocumentPickerViewController` for a folder, opened in place. Tests use a fake. | `DocumentPicker` in `dm/ios/Sources/Launcher.swift` |
| Log | Show log reads the tail (256 KB) of `log.txt` in the game's data folder, else the app's folder, into a read-only sheet. | |
| Update | `ShellHostConfig.updateURL` is opened by Update app. | |
-| Controllers | `ShellHostModel.startControllers()` runs `GamepadAdapter` and fills `controllers` (`ControllerInfo`) and `input` (`ShellInput`). | |
+| Controllers | `ShellHostModel.startControllers()` runs `GamepadAdapter` and fills `controllers` (`ControllerInfo`) and `input` (`ShellInput`). Global mappings are stored in `ShellSettingsStore.padMap`, individual overrides in the game's suite under `GameDefaults.padMapKey`. At launch, each button resolves game > global > default and is passed to the engine as `DM_PAD_MAP`. A profile's own `DM_PAD_MAP` row takes precedence. Touch controls and shell navigation keep their original mapping. | |
```swift
let config = ShellHostConfig(gamesRoot: gamesURL, appDataRoot: ShellHostConfig.defaultAppDataRoot(),
diff --git a/frontend-ios/Sources/ShellDemo/HostDemo.swift b/frontend-ios/Sources/ShellDemo/HostDemo.swift
index e859bfd2..a99c9377 100644
--- a/frontend-ios/Sources/ShellDemo/HostDemo.swift
+++ b/frontend-ios/Sources/ShellDemo/HostDemo.swift
@@ -47,7 +47,9 @@ struct HostDemoScreen: View {
var body: some View {
ShellHostView(model: model, initialSelection: ProcessInfo.processInfo.arguments.firstIndex(of: "--select")
- .flatMap { ProcessInfo.processInfo.arguments.indices.contains($0 + 1) ? ProcessInfo.processInfo.arguments[$0 + 1] : nil })
+ .flatMap { ProcessInfo.processInfo.arguments.indices.contains($0 + 1) ? ProcessInfo.processInfo.arguments[$0 + 1] : nil },
+ initialDetailOpen: ProcessInfo.processInfo.arguments.firstIndex(of: "--screen")
+ .flatMap { ProcessInfo.processInfo.arguments.indices.contains($0 + 1) ? ProcessInfo.processInfo.arguments[$0 + 1] : nil } == "settings")
.background(ShellPalette.background)
}
}
diff --git a/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift b/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift
index 331d49d1..035e3e6b 100644
--- a/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift
+++ b/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift
@@ -20,6 +20,7 @@ import ShellControllers
/// The demo owns sample values. None of this state or callback simulation is part of ShellUI.
struct DemoScreen: View {
+ @State private var padMap = PadMap()
@State private var games = SampleData.games
@State private var notice: String?
@State private var input: ShellInput?
@@ -83,7 +84,7 @@ struct DemoScreen: View {
initialDetailOpen: scenario == "settings",
initialControllersOpen: scenario.hasPrefix("controllers"),
initialShellSettingsOpen: scenario == "shell-settings",
- initialFocusVisible: scenario == "focus")
+ initialFocusVisible: scenario == "focus", globalPadMap: padMap)
}
/// A stand-in for the foldable while no Simulator runtime for it is installed: the same running shell in a frame
@@ -164,7 +165,10 @@ struct DemoScreen: View {
games[i].cloudSaves = original.cloudSaves; games[i].cloudFromShell = true; games[i].cloudCanUseShell = false
}
}, onClearShellData: { ShellSettingsStore.current.clearDataFolderName() },
- onClearShellCloud: { ShellSettingsStore.current.clearCloudSavesFolderName() })
+ onClearShellCloud: { ShellSettingsStore.current.clearCloudSavesFolderName() },
+ onGlobalPadMapChange: { button, value in
+ if button == "swapAB" { padMap.setSwapAB(value == "1") } else { padMap.set(button, to: value) }
+ }, onGlobalPadMapReset: { padMap = PadMap() })
}
}
diff --git a/frontend-ios/Sources/ShellHost/GamePadMapStore.swift b/frontend-ios/Sources/ShellHost/GamePadMapStore.swift
new file mode 100644
index 00000000..f8b1126d
--- /dev/null
+++ b/frontend-ios/Sources/ShellHost/GamePadMapStore.swift
@@ -0,0 +1,55 @@
+import Foundation
+import ShellUI
+
+/// Sparse overrides in the game's own suite. An absent button follows global, an identity explicitly restores default.
+public struct GamePadMapStore {
+ public let defaults: UserDefaults
+ public init(defaults: UserDefaults) { self.defaults = defaults }
+ public var entries: [String: String] {
+ PadMap.validated(defaults.dictionary(forKey: GameDefaults.padMapKey) as? [String: String] ?? [:])
+ }
+ public var swapValue: String {
+ let map = entries
+ if map["A"] == nil && map["B"] == nil { return "follow" }
+ if map["A"] == "B" && map["B"] == "A" { return "on" }
+ if map["A"] == "A" && map["B"] == "B" { return "off" }
+ return "custom"
+ }
+ public func change(_ setting: String, value: String) {
+ var map = entries
+ if setting == "pad.swapAB" {
+ switch value {
+ case "follow": map["A"] = nil; map["B"] = nil
+ case "on": map["A"] = "B"; map["B"] = "A"
+ case "off": map["A"] = "A"; map["B"] = "B"
+ default: return
+ }
+ } else {
+ guard setting.hasPrefix("pad.") else { return }
+ let button = String(setting.dropFirst(4))
+ guard PadMap.buttons.contains(button) else { return }
+ if value == "follow" { map[button] = nil }
+ else if PadMap.validated([button: value])[button] != nil { map[button] = value }
+ else { return }
+ }
+ if map.isEmpty { reset() } else { defaults.set(map, forKey: GameDefaults.padMapKey) }
+ }
+ public func reset() { defaults.removeObject(forKey: GameDefaults.padMapKey) }
+
+ public func section(global: PadMap) -> SettingSection {
+ func follow(_ label: String) -> SettingOption { SettingOption("follow", hostText("Follow global (\(label))")) }
+ let on = hostText("On"), off = hostText("Off")
+ var swapOptions = [follow(global.swapAB ? on : off), SettingOption("on", on), SettingOption("off", off)]
+ // A single-button edit need not be a complete swap or an explicit off. Show that state truthfully.
+ if swapValue == "custom" { swapOptions.append(SettingOption("custom", hostText("Custom"))) }
+ var rows = [SettingRow(id: "pad.swapAB", label: hostText("Swap A and B"),
+ note: hostText("Only affects physical controllers in games. Shell menus keep A to confirm and B to go back."),
+ kind: .choice(swapOptions), value: swapValue, fromShell: swapValue == "follow")]
+ rows += PadMap.buttons.map { button in
+ SettingRow(id: "pad.\(button)", label: PadMap.label(button),
+ kind: .choice([follow(PadMap.label(global.output(for: button)))] + PadMap.options),
+ value: entries[button] ?? "follow", fromShell: entries[button] == nil)
+ }
+ return SettingSection(id: "pad", title: hostText("Controller"), rows: rows)
+ }
+}
diff --git a/frontend-ios/Sources/ShellHost/GameSettingsStore.swift b/frontend-ios/Sources/ShellHost/GameSettingsStore.swift
index 2f742b94..045106d3 100644
--- a/frontend-ios/Sources/ShellHost/GameSettingsStore.swift
+++ b/frontend-ios/Sources/ShellHost/GameSettingsStore.swift
@@ -5,6 +5,7 @@ import ShellUI
/// inside are the ones the per-game app uses in its standard defaults: `launcher.<VAR>`, `pickedDataBookmark`,
/// `cloudSavesBookmark`, so the engine can read the same names later.
public enum GameDefaults {
+ public static let padMapKey = "padMap"
public static let suitePrefix = "dev.nx2apple.shell.game."
/// True when the player turned cloud saves off for this game. It wins over the shell's cloud-saves folder, and
/// choosing a folder for the game clears it.
diff --git a/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings
index 964a99f4..0ce83010 100644
--- a/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings
+++ b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings
@@ -944,7 +944,119 @@
}
}
}
+ },
+ "Swap A and B": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Swap A and B"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "交换 A 和 B"
+ }
+ }
+ }
+ },
+ "Controller": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Controller"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "手柄"
+ }
+ }
+ }
+ },
+ "Follow global (%@)": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Follow global (%@)"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "跟随全局(%@)"
+ }
+ }
+ }
+ },
+ "On": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "On"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "开"
+ }
+ }
+ }
+ },
+ "Off": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Off"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "关"
+ }
+ }
+ }
+ },
+ "Custom": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Custom"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "自定义"
+ }
+ }
+ }
+ },
+ "Only affects physical controllers in games. Shell menus keep A to confirm and B to go back.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Only affects physical controllers in games. Shell menus keep A to confirm and B to go back."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "仅影响游戏内的实体手柄。shell 菜单始终使用 A 确认、B 返回。"
+ }
+ }
+ }
}
},
"version": "1.0"
-}
\ No newline at end of file
+}
diff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
index fc5d9204..91c52ce2 100644
--- a/frontend-ios/Sources/ShellHost/ShellHostModel.swift
+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
@@ -58,6 +58,8 @@ public struct ShellHostConfig: Sendable {
/// The log the host view shows in a read-only sheet.
public var log: LogPresentation?
+ public private(set) var globalPadMap = PadMap()
+
@ObservationIgnored private let config: ShellHostConfig
@ObservationIgnored private let launcher: any GameLauncher
@ObservationIgnored private let picker: any FolderPicker
@@ -85,6 +87,7 @@ public struct ShellHostConfig: Sendable {
shellData = BookmarkStore(defaults: shellSettings.defaults, key: ShellSettingsStore.dataFolderKey)
shellCloud = BookmarkStore(defaults: shellSettings.defaults, key: ShellSettingsStore.cloudSavesKey)
shellChoices = Self.choices(of: shellSettings)
+ globalPadMap = shellSettings.padMap
reload()
defaultsObserver = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.defaultsDidChange() }
@@ -93,13 +96,14 @@ public struct ShellHostConfig: Sendable {
deinit { defaultsObserver.map(NotificationCenter.default.removeObserver) }
- /// What the details show of the shell settings besides the folders: the overlay default.
+ /// Shell choices that change the displayed game defaults.
private static func choices(of settings: ShellSettingsStore) -> [String] {
- [settings.gameDefaults.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: ",")]
+ [settings.gameDefaults.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: ","), settings.padMap.envValue ?? ""]
}
- /// Builds the details again, in the same order. A change of a shell folder or of the performance overlay comes through here.
+ /// Rebuilds the details in place after a shell folder, overlay or controller mapping changes.
public func refreshAll() {
+ globalPadMap = shellSettings.padMap
shellChoices = Self.choices(of: shellSettings)
startShellScan()
details = entries.map(detail(for:))
@@ -234,10 +238,14 @@ public struct ShellHostConfig: Sendable {
var shellFolder = false
if case .url = shellCloud.resolve() { shellFolder = true }
let fromShell = Set(profile.settings.filter(store.isFromShell).map(\.env))
+ let pad = GamePadMapStore(defaults: config.defaults(entry.id))
+ let sections = SettingsPresenter.sections(profile: profile, values: store.values(), fromShell: fromShell)
+ // A profile-provided DM_PAD_MAP row owns the mapping, so do not offer conflicting shell overrides.
+ let padSections = profile.settings.contains { $0.env == "DM_PAD_MAP" } ? [] : [pad.section(global: shellSettings.padMap)]
return GameDetail(
- game: tile, sections: SettingsPresenter.sections(profile: profile, values: store.values(), fromShell: fromShell),
+ game: tile, sections: sections + padSections,
dataSource: dataSource(data), dataNote: dataNote(data, found: data.found),
- cloudSaves: cloud, cloudNote: cloudNote, dlc: dlc(data), hasModifiedSettings: store.hasModifiedSettings,
+ cloudSaves: cloud, cloudNote: cloudNote, dlc: dlc(data), hasModifiedSettings: store.hasModifiedSettings || !pad.entries.isEmpty,
dataFromShell: data.source == .shell, cloudFromShell: cloudFromShell,
cloudCanUseShell: shellFolder && !cloudFromShell)
}
@@ -284,18 +292,30 @@ public struct ShellHostConfig: Sendable {
onPickShellCloud: { [weak self] in self.map { model in Task { await model.pickShellCloudNow() } } },
onUseShellCloud: { [weak self] id in self?.useShellCloudSaves(id) },
onClearShellData: { [weak self] in self?.clearShellData() },
- onClearShellCloud: { [weak self] in self?.clearShellCloud() })
+ onClearShellCloud: { [weak self] in self?.clearShellCloud() },
+ onGlobalPadMapChange: { [weak self] setting, value in
+ guard let self else { return }
+ if setting == "swapAB" { self.shellSettings.setPadSwapAB(value == "1") }
+ else { self.shellSettings.setPadButton(setting, to: value) }
+ self.refreshAll()
+ },
+ onGlobalPadMapReset: { [weak self] in self?.shellSettings.resetPadMap(); self?.refreshAll() })
}
public func change(_ id: String, setting: String, value: String) {
guard let profile = entry(id)?.profile else { return }
- GameSettingsStore(profile: profile, defaults: config.defaults(id), shell: shellSettings.gameDefaults).set(setting, to: value)
+ if setting.hasPrefix("pad.") {
+ GamePadMapStore(defaults: config.defaults(id)).change(setting, value: value)
+ } else {
+ GameSettingsStore(profile: profile, defaults: config.defaults(id), shell: shellSettings.gameDefaults).set(setting, to: value)
+ }
refresh(id)
}
public func resetDefaults(_ id: String) {
guard let profile = entry(id)?.profile else { return }
GameSettingsStore(profile: profile, defaults: config.defaults(id)).reset()
+ GamePadMapStore(defaults: config.defaults(id)).reset()
refresh(id)
}
@@ -416,6 +436,11 @@ public struct ShellHostConfig: Sendable {
func launchEnvironment(profile: LauncherProfile, id: String) -> [String: String] {
var env = GameSettingsStore(profile: profile, defaults: config.defaults(id), shell: shellSettings.gameDefaults).values()
for (key, value) in shellSettings.gameDefaults where env[key] == nil { env[key] = value }
+ // A launcher.json DM_PAD_MAP row is authoritative, including an empty value.
+ if !profile.settings.contains(where: { $0.env == "DM_PAD_MAP" }) {
+ env["DM_PAD_MAP"] = PadMap.merged(global: shellSettings.padMap,
+ game: GamePadMapStore(defaults: config.defaults(id)).entries).envValue
+ }
return env
}
diff --git a/frontend-ios/Sources/ShellHost/ShellHostView.swift b/frontend-ios/Sources/ShellHost/ShellHostView.swift
index 26399e6e..dc1cabbd 100644
--- a/frontend-ios/Sources/ShellHost/ShellHostView.swift
+++ b/frontend-ios/Sources/ShellHost/ShellHostView.swift
@@ -6,15 +6,17 @@ import ShellUI
public struct ShellHostView: View {
@Bindable private var model: ShellHostModel
private let initialSelection: String?
+ private let initialDetailOpen: Bool
- public init(model: ShellHostModel, initialSelection: String? = nil) {
+ public init(model: ShellHostModel, initialSelection: String? = nil, initialDetailOpen: Bool = false) {
self.model = model
self.initialSelection = initialSelection
+ self.initialDetailOpen = initialDetailOpen
}
public var body: some View {
LibraryView(games: model.details, controllers: model.controllers, actions: model.actions, input: model.input,
- initialSelection: initialSelection)
+ initialSelection: initialSelection, initialDetailOpen: initialDetailOpen, globalPadMap: model.globalPadMap)
.sheet(item: $model.log) { LogView(log: $0) }
.alert(Text(verbatim: hostText("Shell")), isPresented: Binding(get: { model.notice != nil }, set: { if !$0 { model.notice = nil } })) {
Button(hostText("OK")) { model.notice = nil }
diff --git a/frontend-ios/Sources/ShellUI/ChoicePicker.swift b/frontend-ios/Sources/ShellUI/ChoicePicker.swift
index ac4b9a5a..90f62fcf 100644
--- a/frontend-ios/Sources/ShellUI/ChoicePicker.swift
+++ b/frontend-ios/Sources/ShellUI/ChoicePicker.swift
@@ -73,6 +73,7 @@ struct ChoicePickerView: View {
let request: ChoiceRequest
let pick: (String) -> Void
let close: () -> Void
+ private var prefix: String { request.gameID == ControllersView.mappingID ? "ctl.pick." : "pick." }
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.shellFocus) private var focus
@@ -108,7 +109,7 @@ struct ChoicePickerView: View {
.buttonStyle(.plain)
.accessibilityLabel(ShellStrings.text("Close"))
.accessibilityIdentifier("choice.close")
- .shellTarget("pick.close", radius: 22, action: close)
+ .shellTarget("\(prefix)close", radius: 22, action: close)
}
.padding(.horizontal, 20).padding(.top, 14).padding(.bottom, 8)
Rectangle().fill(ShellPalette.hairline).frame(height: 1)
@@ -116,11 +117,11 @@ struct ChoicePickerView: View {
ScrollViewReader { proxy in
ScrollView { list }
.scrollIndicators(.hidden)
- .onAppear { proxy.scrollTo("pick.\(request.row.value)", anchor: .center) }
+ .onAppear { proxy.scrollTo("\(prefix)\(request.row.value)", anchor: .center) }
.onChange(of: focus.id) { _, id in
- guard let id, id.hasPrefix("pick.") else { return }
+ guard let id, id.hasPrefix(prefix) else { return }
withAnimation(reduceMotion ? nil : .easeOut(duration: 0.15)) {
- proxy.scrollTo(id, anchor: id == "pick.close" ? .top : .center)
+ proxy.scrollTo(id, anchor: id == "\(prefix)close" ? .top : .center)
}
}
}
@@ -149,7 +150,7 @@ struct ChoicePickerView: View {
.accessibilityLabel(option.label)
.accessibilityAddTraits(chosen ? .isSelected : [])
.accessibilityIdentifier("choice.option.\(option.id)")
- .shellTarget("pick.\(option.id)", radius: 10) { pick(option.id) }
+ .shellTarget("\(prefix)\(option.id)", radius: 10) { pick(option.id) }
}
}
.padding(10)
diff --git a/frontend-ios/Sources/ShellUI/ControllersView.swift b/frontend-ios/Sources/ShellUI/ControllersView.swift
index 659f4c55..6b784cb8 100644
--- a/frontend-ios/Sources/ShellUI/ControllersView.swift
+++ b/frontend-ios/Sources/ShellUI/ControllersView.swift
@@ -2,15 +2,26 @@ import SwiftUI
/// Connected controllers with their player and battery, and the buttons the shell listens to.
public struct ControllersView: View {
+ static let mappingID = "global-pad"
+ public var padMap: PadMap
+ public var onChange: (String, String) -> Void
+ public var onReset: () -> Void
+ @Environment(\.shellFocus) private var focus
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
public var controllers: [ControllerInfo]
public var onBack: () -> Void
- public init(controllers: [ControllerInfo], onBack: @escaping () -> Void = {}) {
+ public init(controllers: [ControllerInfo], onBack: @escaping () -> Void = {}, padMap: PadMap = PadMap(),
+ onChange: @escaping (String, String) -> Void = { _, _ in }, onReset: @escaping () -> Void = {}) {
+ self.padMap = padMap
+ self.onChange = onChange
+ self.onReset = onReset
self.controllers = controllers
self.onBack = onBack
}
public var body: some View {
// Scrolls under the home indicator to the bottom edge, with room for the last row to clear it.
GeometryReader { geometry in
+ ScrollViewReader { proxy in
ScrollView {
VStack(alignment: .leading, spacing: 30) {
HStack(alignment: .center) {
@@ -21,7 +32,7 @@ public struct ControllersView: View {
.buttonStyle(RoundIconButtonStyle(size: 44))
.accessibilityLabel(ShellStrings.text("Close controllers"))
.accessibilityIdentifier("controllers.close")
- .shellTarget("ctl.close", radius: 22, action: onBack)
+ .shellTarget("ctl.close", radius: 22, action: onBack).id("ctl.close")
}
if controllers.isEmpty {
VStack(alignment: .leading, spacing: 12) {
@@ -43,6 +54,7 @@ public struct ControllersView: View {
.background(ShellPalette.surface, in: RoundedRectangle(cornerRadius: 16))
.overlay(RoundedRectangle(cornerRadius: 16).strokeBorder(ShellPalette.hairline))
}
+ mapping
VStack(alignment: .leading, spacing: 14) {
SectionHeading(title: ShellStrings.text("On a controller"))
hint(Image(systemName: "dpad"), ShellStrings.text("Move between controls"))
@@ -56,9 +68,35 @@ public struct ControllersView: View {
}
.scrollIndicators(.hidden)
.ignoresSafeArea(edges: .bottom)
+ .onChange(of: focus.id) { _, id in
+ guard let id, id.hasPrefix("ctl."), !id.hasPrefix("ctl.pick.") else { return }
+ withAnimation(reduceMotion ? nil : .easeOut(duration: 0.15)) {
+ proxy.scrollTo(id, anchor: id == "ctl.close" ? .top : .center)
+ }
+ }
+ }
}
.foregroundStyle(.white).preferredColorScheme(.dark)
}
+ private var mapping: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ SectionHeading(title: ShellStrings.text("Button mapping"))
+ let swap = SettingRow(id: "swapAB", label: ShellStrings.text("Swap A and B"),
+ note: ShellStrings.text("Only affects physical controllers in games, not shell menus. Each game can override these settings."),
+ kind: .toggle(on: "1", off: "0"), value: padMap.swapAB ? "1" : "0")
+ SettingControl(gameID: Self.mappingID, row: swap, targetPrefix: "ctl.row.") { onChange("swapAB", $0) }
+ .accessibilityIdentifier("ctl.swapAB").id("ctl.row.swapAB")
+ ForEach(PadMap.buttons, id: \.self) { button in
+ let row = SettingRow(id: button, label: PadMap.label(button), kind: .choice(PadMap.options), value: padMap.output(for: button))
+ SettingControl(gameID: Self.mappingID, row: row, targetPrefix: "ctl.row.") { onChange(button, $0) }
+ .accessibilityIdentifier("ctl.\(button)").id("ctl.row.\(button)")
+ }
+ Button(action: onReset) { Text(ShellStrings.text("Reset to default")) }
+ .buttonStyle(ChipButtonStyle()).accessibilityIdentifier("ctl.reset")
+ .shellTarget("ctl.reset", action: onReset).id("ctl.reset")
+ }
+ }
+
private func hint(_ icon: some View, _ label: String) -> some View {
HStack(spacing: 14) {
icon.frame(width: 22).foregroundStyle(.white.opacity(0.75))
diff --git a/frontend-ios/Sources/ShellUI/LibraryView.swift b/frontend-ios/Sources/ShellUI/LibraryView.swift
index 27b8a353..48bacdd7 100644
--- a/frontend-ios/Sources/ShellUI/LibraryView.swift
+++ b/frontend-ios/Sources/ShellUI/LibraryView.swift
@@ -31,6 +31,7 @@ enum ShellLayout: Equatable {
public struct LibraryView: View {
public let games: [GameDetail]
public let controllers: [ControllerInfo]
+ public let globalPadMap: PadMap
public var actions: ShellActions
public var input: ShellInput?
@State private var selectedID: String?
@@ -60,9 +61,11 @@ public struct LibraryView: View {
public init(games: [GameDetail], controllers: [ControllerInfo] = [], actions: ShellActions = ShellActions(),
input: ShellInput? = nil, initialSelection: String? = nil, initialDetailOpen: Bool = false,
- initialControllersOpen: Bool = false, initialShellSettingsOpen: Bool = false, initialFocusVisible: Bool = false) {
+ initialControllersOpen: Bool = false, initialShellSettingsOpen: Bool = false, initialFocusVisible: Bool = false,
+ globalPadMap: PadMap = PadMap()) {
self.games = games
self.controllers = controllers
+ self.globalPadMap = globalPadMap
self.actions = actions
self.input = input
let first = initialSelection ?? games.first?.id
@@ -146,19 +149,12 @@ public struct LibraryView: View {
.accessibilityAddTraits(.isModal)
.transition(.opacity.combined(with: .scale(scale: 0.96)))
}
- if let choice {
- Color.black.opacity(0.55).ignoresSafeArea().accessibilityHidden(true)
- .onTapGesture { closeChoice() }
- .transition(.opacity)
- ChoicePickerView(request: choice, pick: pickChoice, close: closeChoice)
- .padding(.horizontal, 16).padding(.vertical, 12)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .transition(.opacity.combined(with: .scale(scale: 0.96)))
- }
if controllersOpen {
Color.black.opacity(0.55 * (1 - min(1, edgeDrag / min(width, 520)))).ignoresSafeArea().accessibilityHidden(true)
.onTapGesture { back() }
- ControllersView(controllers: controllers, onBack: back)
+ ControllersView(controllers: controllers, onBack: back, padMap: globalPadMap,
+ onChange: actions.onGlobalPadMapChange, onReset: actions.onGlobalPadMapReset)
+ .accessibilityHidden(choice != nil)
.frame(width: min(width, 520))
.frame(maxHeight: .infinity)
.background { ShellPalette.background.ignoresSafeArea() }
@@ -181,13 +177,22 @@ public struct LibraryView: View {
.accessibilityAddTraits(.isModal)
.transition(.move(edge: .trailing).combined(with: .opacity))
}
+ if let choice {
+ Color.black.opacity(0.55).ignoresSafeArea().accessibilityHidden(true)
+ .onTapGesture { closeChoice() }
+ .transition(.opacity)
+ ChoicePickerView(request: choice, pick: pickChoice, close: closeChoice)
+ .padding(.horizontal, 16).padding(.vertical, 12)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .transition(.opacity.combined(with: .scale(scale: 0.96)))
+ }
}
.transformPreference(FocusTargets.self) { values in
values = values.filter { target in
+ if let choice { return target.id.hasPrefix(choice.gameID == ControllersView.mappingID ? "ctl.pick." : "pick.") }
if controllersOpen { return target.id.hasPrefix("ctl.") }
if shellSettingsOpen { return target.id.hasPrefix("shs.") }
if helpGameID != nil { return target.id.hasPrefix("help.") }
- if choice != nil { return target.id.hasPrefix("pick.") }
return !target.id.hasPrefix("ctl.") && !target.id.hasPrefix("help.") && !target.id.hasPrefix("pick.") && !target.id.hasPrefix("shs.")
}
}
@@ -357,18 +362,19 @@ public struct LibraryView: View {
noteTouch()
returnFocus = focus.id
choice = request
- focus.id = "pick.\(request.row.value)"
+ focus.id = (request.gameID == ControllersView.mappingID ? "ctl.pick." : "pick.") + request.row.value
}
private func closeChoice() {
guard let request = choice else { return }
choice = nil
- focus.id = (request.gameID == ShellSettingsRows.gameID ? ShellSettingsRows.targetPrefix : "set.row.") + request.row.id
+ focus.id = (request.gameID == ControllersView.mappingID ? "ctl.row." : request.gameID == ShellSettingsRows.gameID ? ShellSettingsRows.targetPrefix : "set.row.") + request.row.id
}
private func pickChoice(_ value: String) {
noteTouch()
guard let request = choice else { return }
if value != request.row.value {
- if request.gameID == ShellSettingsRows.gameID { ShellSettingsRows.apply(request.row.id, value: value, to: .current) }
+ if request.gameID == ControllersView.mappingID { actions.onGlobalPadMapChange(request.row.id, value) }
+ else if request.gameID == ShellSettingsRows.gameID { ShellSettingsRows.apply(request.row.id, value: value, to: .current) }
else { actions.onChange(request.gameID, request.row.id, value) }
}
closeChoice()
@@ -416,7 +422,7 @@ public struct LibraryView: View {
if let id = focus.id, id.hasPrefix("lib.tile.") { select(String(id.dropFirst("lib.tile.".count))) }
}
private var defaultFocus: String? {
- if let choice { return "pick.\(choice.row.value)" }
+ if let choice { return (choice.gameID == ControllersView.mappingID ? "ctl.pick." : "pick.") + choice.row.value }
if helpGameID != nil { return "help.done" }
if controllersOpen { return "ctl.close" }
if shellSettingsOpen { return "shs.close" }
diff --git a/frontend-ios/Sources/ShellUI/PadMap.swift b/frontend-ios/Sources/ShellUI/PadMap.swift
new file mode 100644
index 00000000..61a0985b
--- /dev/null
+++ b/frontend-ios/Sources/ShellUI/PadMap.swift
@@ -0,0 +1,51 @@
+import Foundation
+
+/// Physical controller buttons in the engine's input_map.h order. Sticks and shell navigation are unaffected.
+public struct PadMap: Equatable, Sendable {
+ public static let buttons = ["A", "B", "X", "Y", "LS", "RS", "L", "R", "ZL", "ZR", "Plus", "Minus", "Left", "Up", "Right", "Down"]
+ public private(set) var entries: [String: String]
+
+ public init(_ entries: [String: String] = [:]) {
+ self.entries = Self.validated(entries).filter { $0.key != $0.value }
+ }
+
+ /// Game overrides keep identities, since A=A must be able to override a global A=B.
+ public static func validated(_ entries: [String: String]) -> [String: String] {
+ entries.filter { buttons.contains($0.key) && (buttons.contains($0.value) || $0.value == "none") }
+ }
+
+ public func output(for button: String) -> String { entries[button] ?? button }
+ public var swapAB: Bool { output(for: "A") == "B" && output(for: "B") == "A" }
+ public var envValue: String? {
+ let pairs = Self.buttons.compactMap { key in entries[key].map { "\(key)=\($0)" } }
+ return pairs.isEmpty ? nil : pairs.joined(separator: ",")
+ }
+ public mutating func set(_ button: String, to output: String) {
+ guard Self.validated([button: output])[button] != nil else { return }
+ entries[button] = output == button ? nil : output
+ }
+ public mutating func setSwapAB(_ on: Bool) {
+ set("A", to: on ? "B" : "A")
+ set("B", to: on ? "A" : "B")
+ }
+ public static func merged(global: PadMap, game: [String: String]) -> PadMap {
+ PadMap(global.entries.merging(validated(game)) { _, game in game })
+ }
+
+ /// Nintendo names presented to the player, localized in ShellUI for both mapping pages.
+ public static func label(_ button: String) -> String {
+ switch button {
+ case "Plus": "+"
+ case "Minus": "−"
+ case "LS": ShellStrings.text("Left stick press")
+ case "RS": ShellStrings.text("Right stick press")
+ case "Left": ShellStrings.text("D-pad left")
+ case "Up": ShellStrings.text("D-pad up")
+ case "Right": ShellStrings.text("D-pad right")
+ case "Down": ShellStrings.text("D-pad down")
+ case "none": ShellStrings.text("None")
+ default: button
+ }
+ }
+ public static var options: [SettingOption] { (buttons + ["none"]).map { SettingOption($0, label($0)) } }
+}
diff --git a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings
index 54790553..f426cde9 100644
--- a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings
+++ b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings
@@ -1072,7 +1072,183 @@
}
}
}
+ },
+ "Button mapping": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Button mapping"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "按键映射"
+ }
+ }
+ }
+ },
+ "Swap A and B": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Swap A and B"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "交换 A 和 B"
+ }
+ }
+ }
+ },
+ "None": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "None"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无"
+ }
+ }
+ }
+ },
+ "Reset to default": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Reset to default"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "恢复默认"
+ }
+ }
+ }
+ },
+ "Left stick press": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Left stick press"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "左摇杆按下"
+ }
+ }
+ }
+ },
+ "Right stick press": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Right stick press"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "右摇杆按下"
+ }
+ }
+ }
+ },
+ "D-pad left": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "D-pad left"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "十字键左"
+ }
+ }
+ }
+ },
+ "D-pad up": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "D-pad up"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "十字键上"
+ }
+ }
+ }
+ },
+ "D-pad right": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "D-pad right"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "十字键右"
+ }
+ }
+ }
+ },
+ "D-pad down": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "D-pad down"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "十字键下"
+ }
+ }
+ }
+ },
+ "Only affects physical controllers in games, not shell menus. Each game can override these settings.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Only affects physical controllers in games, not shell menus. Each game can override these settings."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "仅影响游戏内的实体手柄,不影响 shell 菜单。每个游戏可以单独设置。"
+ }
+ }
+ }
}
},
"version": "1.0"
-}
\ No newline at end of file
+}
diff --git a/frontend-ios/Sources/ShellUI/ShellInputs.swift b/frontend-ios/Sources/ShellUI/ShellInputs.swift
index eb5c6d24..b5782fc7 100644
--- a/frontend-ios/Sources/ShellUI/ShellInputs.swift
+++ b/frontend-ios/Sources/ShellUI/ShellInputs.swift
@@ -174,6 +174,8 @@ public struct ShellActions {
public var onUseShellCloud: (String) -> Void
public var onClearShellData: () -> Void
public var onClearShellCloud: () -> Void
+ public var onGlobalPadMapChange: (String, String) -> Void
+ public var onGlobalPadMapReset: () -> Void
public init(onSelect: @escaping (String) -> Void = { _ in }, onPlay: @escaping (String) -> Void = { _ in },
onChange: @escaping (String, String, String) -> Void = { _, _, _ in },
onPickGameData: @escaping (String) -> Void = { _ in }, onUseAppData: @escaping (String) -> Void = { _ in },
@@ -182,7 +184,9 @@ public struct ShellActions {
onAppUpdate: @escaping () -> Void = {}, onBack: @escaping () -> Void = {},
onPickShellData: @escaping () -> Void = {}, onPickShellCloud: @escaping () -> Void = {},
onUseShellCloud: @escaping (String) -> Void = { _ in }, onClearShellData: @escaping () -> Void = {},
- onClearShellCloud: @escaping () -> Void = {}) {
+ onClearShellCloud: @escaping () -> Void = {},
+ onGlobalPadMapChange: @escaping (String, String) -> Void = { _, _ in },
+ onGlobalPadMapReset: @escaping () -> Void = {}) {
self.onSelect = onSelect
self.onPlay = onPlay
self.onChange = onChange
@@ -199,5 +203,7 @@ public struct ShellActions {
self.onUseShellCloud = onUseShellCloud
self.onClearShellData = onClearShellData
self.onClearShellCloud = onClearShellCloud
+ self.onGlobalPadMapChange = onGlobalPadMapChange
+ self.onGlobalPadMapReset = onGlobalPadMapReset
}
}
diff --git a/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift b/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift
index b0ace987..d0d3a417 100644
--- a/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift
+++ b/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift
@@ -4,6 +4,7 @@ import Foundation
/// and the default performance HUD. A game's own settings and bookmarks win over these, and
/// these win over the built-in defaults (ShellSettingsStore priority: game > shell > built-in).
public final class ShellSettingsStore: @unchecked Sendable {
+ public static let padMapKey = "padMap"
public static let suiteName = "shell-settings"
public static let dataFolderKey = "globalDataBookmark"
public static let cloudSavesKey = "globalCloudSavesBookmark"
@@ -36,6 +37,20 @@ public final class ShellSettingsStore: @unchecked Sendable {
public func clearCloudSavesFolderName() { defaults.removeObject(forKey: Self.cloudSavesNameKey) }
public func storePerformanceHUD(_ on: Bool) { defaults.set(on, forKey: Self.performanceHUDKey) }
+ public var padMap: PadMap { PadMap(defaults.dictionary(forKey: Self.padMapKey) as? [String: String] ?? [:]) }
+ public func setPadButton(_ button: String, to output: String) {
+ var map = padMap
+ map.set(button, to: output)
+ defaults.set(map.entries, forKey: Self.padMapKey)
+ }
+ public func setPadSwapAB(_ on: Bool) {
+ var map = padMap
+ map.setSwapAB(on)
+ defaults.set(map.entries, forKey: Self.padMapKey)
+ }
+ public func resetPadMap() { defaults.removeObject(forKey: Self.padMapKey) }
+
+ /// DM_PAD_MAP is deliberately excluded. The host merges it per button at launch.
/// The shell's value for each `DM_*` switch a game's own settings leave alone.
public var gameDefaults: [String: String] {
performanceHUD.map { ["DM_METAL_HUD": $0 ? "1" : "0"] } ?? [:]
diff --git a/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift
index 2e15ae95..9ff88f9a 100644
--- a/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift
+++ b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift
@@ -30,6 +30,92 @@ final class Clock: @unchecked Sendable { var date: Date; init(_ d: Date) { date
try detail(model, game).sections.flatMap(\.rows).first { $0.id == setting }?.value
}
+ @Test func padOverridesPersistMergeAndReset() async throws {
+ let box = try Sandbox()
+ try box.giveAppData()
+ let shell = shellSettings()
+ let launcher = RecordingLauncher()
+ let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shell)
+ func row(_ id: String) throws -> SettingRow {
+ try #require(detail(model).sections.flatMap(\.rows).first { $0.id == id })
+ }
+ #expect(try row("pad.A").fromShell && row("pad.swapAB").value == "follow")
+ await model.playNow(Fixtures.orbit)
+ #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == nil)
+ model.actions.onGlobalPadMapChange("swapAB", "1")
+ #expect(model.globalPadMap.swapAB)
+ #expect(try !detail(model).hasModifiedSettings)
+ if case .choice(let options) = try row("pad.A").kind { #expect(options.first?.label == "Follow global (B)") }
+ await model.playNow(Fixtures.orbit)
+ #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == "A=B,B=A")
+ model.actions.onChange(Fixtures.orbit, "pad.A", "Y")
+ let gameStore = GamePadMapStore(defaults: box.defaults(Fixtures.orbit))
+ #expect(gameStore.entries == ["A": "Y"] && gameStore.swapValue == "custom")
+ #expect(try !row("pad.A").fromShell && row("pad.B").fromShell && detail(model).hasModifiedSettings)
+ await model.playNow(Fixtures.orbit)
+ #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == "A=Y,B=A")
+ model.actions.onChange(Fixtures.orbit, "pad.swapAB", "off")
+ #expect(gameStore.entries == ["A": "A", "B": "B"])
+ await model.playNow(Fixtures.orbit)
+ #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == nil)
+ let again = ShellHostModel(config: box.config(), shellSettings: shell)
+ #expect(try detail(again).hasModifiedSettings)
+ model.actions.onChange(Fixtures.orbit, "pad.X", "none")
+ model.actions.onChange(Fixtures.orbit, "pad.swapAB", "follow")
+ #expect(gameStore.entries == ["X": "none"])
+ await model.playNow(Fixtures.orbit)
+ #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == "A=B,B=A,X=none")
+ #expect(GamePadMapStore(defaults: box.defaults(Fixtures.chain)).entries.isEmpty)
+ model.actions.onResetDefaults(Fixtures.orbit)
+ #expect(gameStore.entries.isEmpty)
+ #expect(try !detail(model).hasModifiedSettings && row("pad.X").fromShell)
+ model.actions.onGlobalPadMapReset()
+ #expect(model.globalPadMap.entries.isEmpty)
+ await model.playNow(Fixtures.orbit)
+ #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == nil)
+ }
+
+ @Test func padRowsFollowGlobalChangesAndRejectInvalidValues() throws {
+ let box = try Sandbox()
+ let shell = shellSettings()
+ let model = ShellHostModel(config: box.config(), shellSettings: shell)
+ model.actions.onGlobalPadMapChange("X", "none")
+ for detail in model.details where detail.sections.contains(where: { $0.id == "pad" }) {
+ let row = try #require(detail.sections.flatMap(\.rows).first { $0.id == "pad.X" })
+ #expect(row.fromShell)
+ if case .choice(let options) = row.kind { #expect(options.first?.label == "Follow global (None)") }
+ }
+ let store = GamePadMapStore(defaults: box.defaults(Fixtures.orbit))
+ model.change(Fixtures.orbit, setting: "pad.unknown", value: "A")
+ model.change(Fixtures.orbit, setting: "pad.A", value: "bad")
+ #expect(store.entries.isEmpty)
+ model.change(Fixtures.orbit, setting: "pad.A", value: "A")
+ #expect(store.entries == ["A": "A"])
+ model.change(Fixtures.orbit, setting: "pad.A", value: "follow")
+ #expect(store.entries.isEmpty)
+ model.change(Fixtures.orbit, setting: "pad.swapAB", value: "on")
+ #expect(store.swapValue == "on")
+ }
+
+ @Test func profilePadMapRowWinsShellMapping() throws {
+ let box = try Sandbox()
+ let file = box.games.appendingPathComponent(Fixtures.orbit).appendingPathComponent("launcher.json")
+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any])
+ var settings = try #require(json["settings"] as? [[String: Any]])
+ settings.append(["env": "DM_PAD_MAP", "kind": "choice", "label": "Buttons", "note": "", "default": "X=Y",
+ "options": [["X=Y", "Custom"], ["", "Default"]]])
+ json["settings"] = settings
+ try JSONSerialization.data(withJSONObject: json).write(to: file)
+ let profile = try LauncherProfile.parse(Data(contentsOf: file))
+ let shell = shellSettings()
+ shell.setPadSwapAB(true)
+ let model = ShellHostModel(config: box.config(), shellSettings: shell)
+ #expect(model.launchEnvironment(profile: profile, id: Fixtures.orbit)["DM_PAD_MAP"] == "X=Y")
+ #expect(try !detail(model).sections.contains { $0.id == "pad" })
+ model.change(Fixtures.orbit, setting: "DM_PAD_MAP", value: "")
+ #expect(model.launchEnvironment(profile: profile, id: Fixtures.orbit)["DM_PAD_MAP"] == "")
+ }
+
@Test func buildsTilesAndDetailsFromTheBundles() throws {
let box = try Sandbox()
let model = ShellHostModel(config: box.config())
@@ -37,7 +123,7 @@ final class Clock: @unchecked Sendable { var date: Date; init(_ d: Date) { date
let orbit = try detail(model)
#expect(orbit.game.title == "Orbit Fixture" && orbit.game.subtitle == "Version 1.0.0" && orbit.game.recentlyPlayed == nil)
#expect(orbit.game.state == .needsGameData)
- #expect(orbit.sections.map(\.title) == ["Game", "Performance"])
+ #expect(orbit.sections.map(\.title) == ["Game", "Performance", "Controller"])
#expect(orbit.dataSource == "" && !orbit.dataNote.isEmpty)
#expect(orbit.cloudSaves == nil && orbit.dlc == "No additional content")
#expect(try detail(model, Fixtures.chain).game.state == .needsAppUpdate)
diff --git a/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift b/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift
index 1ef2e5e8..a770ce09 100644
--- a/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift
+++ b/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift
@@ -6,6 +6,25 @@ import ShellUI
@Suite struct ShellSettingsStoreTests {
private func shell() -> ShellSettingsStore { ShellSettingsStore(defaults: UserDefaults(suiteName: "t-shell-\(UUID().uuidString)")!) }
+ @Test func padMapPersistsAndResetsWithoutChangingOtherSettings() {
+ let store = shell()
+ #expect(store.padMap.envValue == nil)
+ store.storePerformanceHUD(true)
+ store.setPadSwapAB(true)
+ store.setPadButton("X", to: "none")
+ let again = ShellSettingsStore(defaults: store.defaults)
+ #expect(again.padMap.envValue == "A=B,B=A,X=none")
+ #expect(again.gameDefaults["DM_PAD_MAP"] == nil)
+ store.setPadSwapAB(false)
+ #expect(again.padMap.envValue == "X=none")
+ store.setPadButton("X", to: "X")
+ #expect(again.padMap.envValue == nil)
+ store.setPadButton("A", to: "Y")
+ store.resetPadMap()
+ #expect(again.padMap.entries.isEmpty && again.performanceHUD == true)
+ #expect(store.defaults.object(forKey: ShellSettingsStore.padMapKey) == nil)
+ }
+
@Test func theOverlayChoiceIsNilUntilThePlayerMakesOne() {
let store = shell()
#expect(store.performanceHUD == nil && store.gameDefaults.isEmpty)
diff --git a/frontend-ios/Tests/ShellUITests/PadMapTests.swift b/frontend-ios/Tests/ShellUITests/PadMapTests.swift
new file mode 100644
index 00000000..bc3091d9
--- /dev/null
+++ b/frontend-ios/Tests/ShellUITests/PadMapTests.swift
@@ -0,0 +1,33 @@
+import Testing
+@testable import ShellUI
+
+@Suite struct PadMapTests {
+ @Test func defaultsAndValidation() {
+ #expect(PadMap().envValue == nil)
+ #expect(PadMap(["A": "A", "Nope": "B", "X": "bad"]).entries.isEmpty)
+ #expect(PadMap(["A": "B"]).swapAB == false)
+ #expect(PadMap(["B": "A"]).swapAB == false)
+ #expect(PadMap(["A": "B", "B": "A", "X": "none"]).swapAB)
+ }
+ @Test func stableEngineOrderAndNone() {
+ let map = PadMap(["Down": "none", "Up": "Down", "LS": "A", "B": "A", "A": "B", "ZR": "ZL"])
+ #expect(map.envValue == "A=B,B=A,LS=A,ZR=ZL,Up=Down,Down=none")
+ var all = PadMap()
+ for button in PadMap.buttons { all.set(button, to: "none") }
+ #expect(all.envValue == PadMap.buttons.map { "\($0)=none" }.joined(separator: ","))
+ }
+ @Test func eachGameButtonWinsAndIdentityCancelsGlobal() {
+ let global = PadMap(["A": "B", "B": "A", "X": "none"])
+ #expect(PadMap.merged(global: global, game: [:]) == global)
+ #expect(PadMap.merged(global: global, game: ["A": "Y"]).envValue == "A=Y,B=A,X=none")
+ #expect(PadMap.merged(global: global, game: ["A": "A", "B": "B"]).envValue == "X=none")
+ #expect(PadMap.merged(global: PadMap(["A": "B", "B": "A"]), game: ["A": "A", "B": "B"]).envValue == nil)
+ }
+ @Test func swapSetterPreservesOtherButtons() {
+ var map = PadMap(["X": "none"])
+ map.setSwapAB(true)
+ #expect(map.swapAB && map.output(for: "X") == "none")
+ map.setSwapAB(false)
+ #expect(map.envValue == "X=none")
+ }
+}
diff --git a/frontend-ios/UITests/ShellCaptureTests.swift b/frontend-ios/UITests/ShellCaptureTests.swift
index 5258b8c3..f3d6bb6d 100644
--- a/frontend-ios/UITests/ShellCaptureTests.swift
+++ b/frontend-ios/UITests/ShellCaptureTests.swift
@@ -57,6 +57,23 @@ import XCTest
shot("shell-settings")
}
+ /// The two mapping entry points, including the real host's per-game rows.
+ func testCapturePadMapping() {
+ XCUIDevice.shared.orientation = .portrait
+ launch(["--screen", "controllers"])
+ let globalSwap = app.descendants(matching: .any).matching(identifier: "ctl.swapAB").firstMatch
+ XCTAssertTrue(globalSwap.waitForExistence(timeout: 5))
+ for _ in 0..<3 where !globalSwap.isHittable { app.scrollViews.element(boundBy: app.scrollViews.count - 1).swipeUp() }
+ XCTAssertTrue(globalSwap.isHittable)
+ shot("controllers-button-mapping")
+ launch(["--host", "--screen", "settings", "--select", "0100000000010000"])
+ let gameSwap = app.descendants(matching: .any).matching(identifier: "setting.pad.swapAB").firstMatch
+ XCTAssertTrue(gameSwap.waitForExistence(timeout: 5))
+ for _ in 0..<5 where !gameSwap.isHittable { app.scrollViews.element(boundBy: app.scrollViews.count - 1).swipeUp() }
+ XCTAssertTrue(gameSwap.isHittable)
+ shot("game-controller-mapping")
+ }
+
func testCaptureMatrix() {
for orientation in [UIDeviceOrientation.portrait, .landscapeLeft] {
XCUIDevice.shared.orientation = orientation
diff --git a/patches/0056-ios-apply-controller-button-mappings-to-physical.patch b/patches/0056-ios-apply-controller-button-mappings-to-physical.patch
new file mode 100644
index 00000000..858b6dae
--- /dev/null
+++ b/patches/0056-ios-apply-controller-button-mappings-to-physical.patch
@@ -0,0 +1,51 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Haseenesss <[email protected]>
+Date: Mon, 2 Nov 2026 17:58:55 +0900
+Subject: [PATCH] ios: apply controller button mappings to physical gamepads
+
+Upstream-Status: pending
+Reason: the iOS host ignores DM_PAD_MAP, so the shell's button mapping (global and per game) never reaches physical controllers. The Mac host applies it already
+Issue: LNPANDY/NX2Apple#494
+
+---
+ dm/ios/Sources/DmGamepad.m | 6 ++++++
+ 1 file changed, 6 insertions(+)
+
+diff --git a/dm/ios/Sources/DmGamepad.m b/dm/ios/Sources/DmGamepad.m
+index 3747fc9..f607c0e 100644
+--- a/dm/ios/Sources/DmGamepad.m
++++ b/dm/ios/Sources/DmGamepad.m
+@@ -27,6 +27,7 @@
+ #include "motion_fusion.h"
+ #include "pad_apple.h"
+ #include "pad_slots.h"
++#include "input_map.h"
+ #include <stdatomic.h>
+
+ enum { B_A = 0, B_B, B_X, B_Y, B_LS, B_RS, B_L, B_R, B_ZL, B_ZR, B_PLUS, B_MINUS, B_LEFT, B_UP, B_RIGHT, B_DOWN, B_N };
+@@ -462,6 +463,7 @@ - (void)refresh { // pressed state → fill, sticks → knob position
+ static pad_slots g_slots;
+ static GCController *g_held[DM_PLAYERS]; // the controller of each slot, kept alive while it holds it (the slot table keys on its pointer)
+ static int g_merge;
++static pad_map g_padmap; // DM_PAD_MAP affects physical controllers only
+ static int32_t axis(float v) { return (int32_t)(fmaxf(-1.f, fminf(1.f, v)) * 32767); }
+ static void read_pad(GCExtendedGamepad *g) {
+ int p = g_merge ? 0 : pad_slot_of(&g_slots, (__bridge const void *)g.controller); if (p < 0) return;
+@@ -474,6 +476,7 @@ static void read_pad(GCExtendedGamepad *g) {
+ if (g.leftThumbstickButton) K(g.leftThumbstickButton, B_LS); if (g.rightThumbstickButton) K(g.rightThumbstickButton, B_RS);
+ K(g.dpad.left, B_LEFT); K(g.dpad.up, B_UP); K(g.dpad.right, B_RIGHT); K(g.dpad.down, B_DOWN);
+ #undef K
++ m = pad_map_apply(&g_padmap, m);
+ dm_pad_set_player(p, m, axis(g.leftThumbstick.xAxis.value), axis(g.leftThumbstick.yAxis.value), axis(g.rightThumbstick.xAxis.value), axis(g.rightThumbstick.yAxis.value));
+ }
+ // Home and Capture: without this iOS takes them as system gestures (Home opens the Games overlay, Capture a screenshot); the app gives them no function
+@@ -481,6 +484,9 @@ static void read_pad(GCExtendedGamepad *g) {
+ static const char *pad_name(GCController *c) { return c.vendorName.UTF8String ?: "?"; }
+ static void npad_name(int p, char *out, size_t cap) { uint32_t id = dm_player_npad(p); if (id == 0x20) snprintf(out, cap, "handheld"); else snprintf(out, cap, "%u", id); }
+ static void pads_start(void) {
++ pad_map_default(&g_padmap);
++ const char *pm = getenv("DM_PAD_MAP");
++ if (pm && *pm) { int bad = pad_map_parse(&g_padmap, pm); LOG("front end: controller buttons from DM_PAD_MAP (%s)%s", pm, bad ? ", malformed entries left out" : ""); }
+ const char *e = getenv("DM_PAD_MERGE"); g_merge = e && atoi(e);
+ LOG("front end: %s", g_merge ? "every controller is player 1 (DM_PAD_MERGE)" : "each controller is a player of its own, the touch gamepad plays with player 1");
+ }
diff --git a/patches/series b/patches/series
index fa77602e..040316d2 100644
--- a/patches/series
+++ b/patches/series
@@ -33,3 +33,4 @@
0053-runtime-profile-every-site.patch
0054-front-mac-start-with-the-pointer-hidden-when-the.patch
0055-ios-shell-declare-en-and-zh-hans-in-cfbundleloca.patch
+0056-ios-apply-controller-button-mappings-to-physical.patch