Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,22 @@ reads through `dm/host/input_map.h` — upstream's
while it is open, and listed in `docs/env_switches.tsv`. A host built before the carrier
has 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.

## Artwork

The launcher shows, in this order: a custom image chosen under **Manage > Change
Expand Down
96 changes: 96 additions & 0 deletions frontend/Sources/NSPortBuilder/ControlPresets.swift
Original file line number Diff line number Diff line change
@@ -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])
}
}
39 changes: 31 additions & 8 deletions frontend/Sources/NSPortBuilder/Controls.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.connectedCategory
private 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 = 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)) }
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 }
Expand All @@ -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 : to
save()
}

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).
Expand Down Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions frontend/Sources/NSPortBuilder/Localization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,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"),
Expand Down
Loading
Loading