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
25 changes: 25 additions & 0 deletions frontend/Sources/NSPortBuilder/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1489,8 +1489,10 @@ struct BuilderView: View {
var controlChanges = 0
@State private var extrasOpen = false
@State private var logOpen = false
@EnvironmentObject private var padFocus: PadFocus

var body: some View {
ScrollViewReader { proxy in
ScrollView(.vertical) {
VStack(alignment: .leading, spacing: 34) {
if settings { settingsPage } else { buildPage }
Expand All @@ -1499,6 +1501,10 @@ struct BuilderView: View {
.frame(maxWidth: 900)
.frame(maxWidth: .infinity)
}
.onChange(of: padFocus.focused) { id in // a controller's focus on this page scrolls into view
if let id, id.hasPrefix("set.") { withAnimation(.easeInOut(duration: 0.2)) { proxy.scrollTo(id, anchor: .center) } }
}
}
.buttonStyle(LauncherSecondaryButtonStyle())
}

Expand Down Expand Up @@ -1838,13 +1844,16 @@ struct BuilderView: View {
if library.scanning { ProgressView().controlSize(.small) }
if !library.folder.isEmpty {
Button(m.t("library.rescan")) { library.discover() }.disabled(library.scanning)
.padTarget("set.rescan", scope: "main") { if !library.scanning { library.discover() } }
}
Button(m.t("library.chooseFolder"), action: onChooseLibraryFolder)
.padTarget("set.folder", scope: "main") { onChooseLibraryFolder() }
}
}
group(m.t("section.controls"), footnote: m.t("controls.settingsHint")) {
row(m.t("controls.row"), detail: controlChanges == 0 ? m.t("controls.defaultLayout") : String(format: m.t("controls.changes"), controlChanges)) {
Button(m.t("controls.customize"), action: onOpenControls)
.padTarget("set.controls", scope: "main") { onOpenControls() }
}
}
tools
Expand All @@ -1863,18 +1872,30 @@ struct BuilderView: View {
m.lang = Lang.initial()
}
.frame(width: Self.settingsButtonWidth)
.padTarget("set.language", scope: "main", activate: { cycleLanguage(1) }, adjust: { cycleLanguage($0) })
}
divider
row("NX2Apple", detail: String(format: m.t("app.version"), BuildModel.appVersion)) {
if let u = m.appUpdate {
Button(String(format: m.t("app.updateBtn"), u.tag)) { m.performAppUpdate() }.disabled(m.appBusy)
.padTarget("set.appUpdate", scope: "main") { if !m.appBusy { m.performAppUpdate() } }
} else {
Button(m.t("repo.check")) { m.checkAppUpdate() }.disabled(m.appBusy)
.padTarget("set.appCheck", scope: "main") { if !m.appBusy { m.checkAppUpdate() } }
}
}
}
}

/// The interface language one step on (a controller's left / right on the language list).
private func cycleLanguage(_ by: Int) {
let values = ["", "zh", "en"]
let at = values.firstIndex(of: Lang.saved.map { $0.rawValue } ?? "") ?? 0
let v = values[(at + by + values.count) % values.count]
Lang.saved = v.isEmpty ? nil : Lang(rawValue: v)
m.lang = Lang.initial()
}

private var tools: some View {
group(m.t("section.tools"), footnote: m.repoStatus.isEmpty ? (m.repoOK ? "" : m.t("repo.firstHint")) : m.repoStatus) {
row(m.t("repo.title"),
Expand All @@ -1886,10 +1907,13 @@ struct BuilderView: View {
if m.repoIsGit {
if let n = m.repoBehind, n > 0 {
Button(m.t("repo.pull")) { m.pullRepo() }.disabled(m.repoBusy || m.running)
.padTarget("set.repoPull", scope: "main") { if !(m.repoBusy || m.running) { m.pullRepo() } }
}
Button(m.t("repo.check")) { m.checkRepoUpdates() }.disabled(m.repoBusy || m.running)
.padTarget("set.repoCheck", scope: "main") { if !(m.repoBusy || m.running) { m.checkRepoUpdates() } }
} else {
Button(m.t("repo.adopt")) { m.adoptRepoAsGit() }.disabled(m.repoBusy || m.running)
.padTarget("set.repoAdopt", scope: "main") { if !(m.repoBusy || m.running) { m.adoptRepoAsGit() } }
}
} else {
Button(m.t("repo.choose")) { pickRepo() }
Expand Down Expand Up @@ -1919,6 +1943,7 @@ struct BuilderView: View {
open: m.depsOpen) {
if !m.depsChecked { ProgressView().controlSize(.small) }
Button(m.t("dep.recheck")) { m.checkDeps() }
.padTarget("set.deps", scope: "main") { m.checkDeps() }
}
.contentShape(Rectangle())
}
Expand Down
20 changes: 17 additions & 3 deletions frontend/Sources/NSPortBuilder/Controls.swift
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ struct ControlsView: View {
@Environment(\.dismiss) private var dismiss
@State private var listening: String?
@State private var monitor: Any?
@EnvironmentObject private var focus: PadFocus

var body: some View {
VStack(alignment: .leading, spacing: 0) {
Expand All @@ -116,6 +117,7 @@ struct ControlsView: View {
Text(m.t("controls.note")).font(.manrope(14)).foregroundStyle(.secondary)
}
.padding(.horizontal, 30).padding(.top, 28).padding(.bottom, 20)
ScrollViewReader { proxy in
ScrollView {
VStack(alignment: .leading, spacing: 24) {
section(m.t("controls.sticks"), ControlLayout.functions.filter(\.isDirection)) { keyRow($0) }
Expand All @@ -124,23 +126,28 @@ struct ControlsView: View {
}
.padding(.horizontal, 30).padding(.bottom, 24)
}
.onChange(of: focus.focused) { id in if let id { withAnimation(.easeInOut(duration: 0.2)) { proxy.scrollTo(id, anchor: .center) } } }
}
Divider().opacity(0.3)
HStack(spacing: 14) {
Text(m.t("controls.applied")).font(.manrope(12)).foregroundStyle(.secondary).lineLimit(2)
Spacer(minLength: 8)
if !layout.isDefault {
Button(m.t("controls.reset")) { stopListening(); layout.resetKeyboard(); layout.resetController() }
.buttonStyle(LauncherSecondaryButtonStyle())
.padTarget("controls.reset", scope: "controls") { stopListening(); layout.resetKeyboard(); layout.resetController() }
}
Button { stopListening(); dismiss() } label: {
Text(m.t("launch.done")).font(.manrope(13.5, .bold)).foregroundStyle(.black)
.padding(.horizontal, 22).padding(.vertical, 9)
.background(LauncherPalette.cream, in: Capsule())
}
.buttonStyle(.plain).keyboardShortcut(listening == nil ? .defaultAction : nil)
.padTarget("controls.done", scope: "controls", radius: 20) { stopListening(); dismiss() }
}
.padding(.horizontal, 30).padding(.vertical, 16)
}
.padScope("controls", focus)
.frame(width: 600, height: 700)
.background(LauncherPalette.background)
.font(.manrope(13))
Expand All @@ -166,20 +173,22 @@ struct ControlsView: View {
}
}

private func line<Trailing: View>(_ title: String, @ViewBuilder trailing: () -> Trailing) -> some View {
private func line<Trailing: View>(_ title: String, target: String, activate: (() -> Void)? = nil, adjust: ((Int) -> Void)? = nil,
@ViewBuilder trailing: () -> Trailing) -> some View {
HStack(spacing: 16) {
Text(title).font(.manrope(14, .medium))
Spacer(minLength: 12)
trailing().frame(width: LaunchControl.width, alignment: .trailing)
}
.padding(.horizontal, 18).padding(.vertical, 9)
.frame(minHeight: 46)
.padTarget(target, scope: "controls", radius: 10, activate: activate, adjust: adjust)
}

private func keyRow(_ f: ControlLayout.Function) -> some View {
let on = listening == f.id
let key = layout.key(f)
return line(m.t("controls.fn." + f.id)) {
return line(m.t("controls.fn." + f.id), target: "key." + f.id, activate: { on ? stopListening() : listen(f) }) {
HStack(spacing: 6) {
if key != nil && !on {
Button { layout.assign(f, key: nil) } label: {
Expand All @@ -204,7 +213,12 @@ struct ControlsView: View {
}

private func padRow(_ button: String) -> some View {
line(m.t("controls.fn." + button)) {
let choices = ControlLayout.buttons + ["none"]
return line(m.t("controls.fn." + button), target: "pad." + button,
adjust: { by in
let at = choices.firstIndex(of: layout.sends(button)) ?? 0
layout.setSends(button, choices[(at + by + choices.count) % choices.count])
}) {
LauncherMenuPicker(options: ControlLayout.buttons.map { (value: $0, label: m.t("controls.fn." + $0)) } + [(value: "none", label: m.t("controls.none"))],
selection: layout.sends(button), fill: true) { layout.setSends(button, $0) }
.frame(width: 168) // the keyboard rows' width (× and key field), and "Right stick press" fits
Expand Down
70 changes: 70 additions & 0 deletions frontend/Sources/NSPortBuilder/Gamepad.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import AppKit
import GameController

/// A game controller drives the launcher, so a Mac on a TV needs no keyboard (PadFocus moves the focus). The buttons are
/// named as the game names them, by position (dm/host/front_mac.m pad_read): A on the right, B at the bottom, X at the
/// top, Y on the left. The D-pad or left stick moves (held, it repeats), A activates, B goes back, X opens the selected
/// game's launch options, L and R switch the pages. Input counts only while the launcher is the active app: a game it
/// started is in front then, and GameController gives a controller's input to the app in front, so the launcher never
/// acts behind a running game.
final class LauncherGamepad: ObservableObject {
enum Action: Equatable { case left, right, up, down, a, b, x, y, l, r }

@Published private(set) var connected = false
var perform: (Action) -> Void = { _ in }
private var held: Set<String> = [] // edges, not levels: one press, one action
private var observers: [NSObjectProtocol] = []
private var repeatTimer: Timer?
private var repeating: Action?

init() {
let center = NotificationCenter.default
observers = [NSNotification.Name.GCControllerDidConnect, .GCControllerDidDisconnect].map {
center.addObserver(forName: $0, object: nil, queue: .main) { [weak self] _ in self?.attach() }
}
attach()
}

deinit { observers.forEach(NotificationCenter.default.removeObserver); repeatTimer?.invalidate() }

private func attach() {
let pads = GCController.controllers().compactMap(\.extendedGamepad)
connected = !pads.isEmpty
for pad in pads { pad.valueChangedHandler = { [weak self] pad, _ in self?.read(pad) } }
}

private func read(_ pad: GCExtendedGamepad) {
let x = pad.dpad.xAxis.value != 0 ? pad.dpad.xAxis.value : pad.leftThumbstick.xAxis.value
let y = pad.dpad.yAxis.value != 0 ? pad.dpad.yAxis.value : pad.leftThumbstick.yAxis.value
let state: [(String, Bool, Action)] = [
("left", x < -0.5, .left), ("right", x > 0.5, .right), ("up", y > 0.5, .up), ("down", y < -0.5, .down),
("a", pad.buttonB.isPressed, .a), ("b", pad.buttonA.isPressed, .b), // by position: right A, bottom B, top X, left Y
("x", pad.buttonY.isPressed, .x), ("y", pad.buttonX.isPressed, .y),
("l", pad.leftShoulder.isPressed, .l), ("r", pad.rightShoulder.isPressed, .r),
]
for (key, down, action) in state {
if down, !held.contains(key) {
held.insert(key)
DispatchQueue.main.async { self.fire(action) }
if [.left, .right, .up, .down].contains(action) { DispatchQueue.main.async { self.startRepeat(action) } }
} else if !down, held.contains(key) {
held.remove(key)
DispatchQueue.main.async { if self.repeating == action { self.stopRepeat() } }
}
}
}

private func fire(_ action: Action) { if NSApp.isActive { perform(action) } }

/// A held direction repeats after 0.4 s, every 0.12 s.
private func startRepeat(_ action: Action) {
stopRepeat()
repeating = action
repeatTimer = Timer.scheduledTimer(withTimeInterval: 0.4, repeats: false) { [weak self] _ in
guard let self, self.repeating == action else { return }
self.repeatTimer = Timer.scheduledTimer(withTimeInterval: 0.12, repeats: true) { [weak self] _ in self?.fire(action) }
}
}

private func stopRepeat() { repeatTimer?.invalidate(); repeatTimer = nil; repeating = nil }
}
Loading