Skip to content

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

Mac launcher: Home button hint in console mode and a Settings row (#336)

v0lumehif448844f6196
diff --git a/frontend/Sources/NX2Apple/ConsoleControllersView.swift b/frontend/Sources/NX2Apple/ConsoleControllersView.swift
index 2d9fa32c..17944d42 100644
--- a/frontend/Sources/NX2Apple/ConsoleControllersView.swift
+++ b/frontend/Sources/NX2Apple/ConsoleControllersView.swift
@@ -29,6 +29,7 @@ import NXLauncher
func exitToDesktop() { base.exitToDesktop() }
func returnFromGame() { base.returnFromGame() }
func consumePress(controllerID: String, isBack: Bool) -> Bool { base.consumePress(controllerID: controllerID, isBack: isBack) }
+ func openHomeButtonSettings() { base.openHomeButtonSettings() }
}
/// The battery drawn as the iOS status bar does: an outline with a nub and a fill exactly as wide as the level, red at 20 percent
diff --git a/frontend/Sources/NX2Apple/ConsoleState.swift b/frontend/Sources/NX2Apple/ConsoleState.swift
index 623db7b3..73043588 100644
--- a/frontend/Sources/NX2Apple/ConsoleState.swift
+++ b/frontend/Sources/NX2Apple/ConsoleState.swift
@@ -99,12 +99,14 @@ enum ConsoleStarting: Equatable {
}
enum ConsoleSheet: Equatable {
- case options(String), controllers, explanation(String)
+ /// homeButtonHint: the system keeps the controller's Home button, so a game cannot be quit with it (#336, shown once)
+ case options(String), controllers, explanation(String), homeButtonHint
var scope: String {
switch self {
case .options: return "console.options"
case .controllers: return "console.controllers"
case .explanation: return "console.explanation"
+ case .homeButtonHint: return "console.homeHint"
}
}
}
@@ -151,6 +153,11 @@ struct ConsoleState {
guard !exited, startingGameID == nil, presentedSheet != .controllers else { return }
sheets.append(.controllers)
}
+ /// The Home button hint (HomeButtonHint.swift), over the home screen after a game quit.
+ mutating func showHomeButtonHint() {
+ guard !exited, startingGameID == nil, presentedSheet != .homeButtonHint else { return }
+ sheets.append(.homeButtonHint)
+ }
mutating func back() {
guard !exited else { return }
if startingGameID != nil { return } // the driver ends Starting when the game window appears
@@ -197,9 +204,14 @@ struct ConsoleState {
func returnFromGame()
/// A press from a controller: true when the driver used it (player assignment), so it does not also navigate.
func consumePress(controllerID: String, isBack: Bool) -> Bool
+ /// The Home button hint's button: opens the system's Home button settings and closes the hint.
+ func openHomeButtonSettings()
}
-extension ConsoleDriver { func consumePress(controllerID: String, isBack: Bool) -> Bool { false } }
+extension ConsoleDriver {
+ func consumePress(controllerID: String, isBack: Bool) -> Bool { false }
+ func openHomeButtonSettings() { back() }
+}
/// Shared choice/range/toggle stepping for mouse, d-pad and keyboard. No settings store is touched.
enum ConsoleOption {
diff --git a/frontend/Sources/NX2Apple/ConsoleView.swift b/frontend/Sources/NX2Apple/ConsoleView.swift
index 81ddb011..1a8bd613 100644
--- a/frontend/Sources/NX2Apple/ConsoleView.swift
+++ b/frontend/Sources/NX2Apple/ConsoleView.swift
@@ -277,6 +277,7 @@ enum ConsoleInput {
case .controllers: controllers(compact: compact)
case let .explanation(id):
if let game = state.games.first(where: { $0.id == id }) { explanation(game, compact: compact) }
+ case .homeButtonHint: homeButtonHint(compact: compact)
}
}
.padScope(sheet.scope, pad)
@@ -351,6 +352,27 @@ enum ConsoleInput {
.padding(compact ? 24 : 40)
}
+ /// Shown once, after a game quit, when that game reported that the system keeps the Home button for itself (#336): what the
+ /// button does in a game, why it does not now, and the way to the setting. A opens Settings, B or "Not now" closes it.
+ private func homeButtonHint(compact: Bool) -> some View {
+ VStack(alignment: .leading, spacing: 24) {
+ Image(systemName: "house.circle").font(.system(size: compact ? 44 : 60, weight: .light))
+ .foregroundStyle(LauncherPalette.cream).accessibilityHidden(true)
+ Text(t("console.homeHint.body")).font(.manrope(compact ? 20 : 26)).fixedSize(horizontal: false, vertical: true)
+ Text(t("console.homeHint.how")).font(.manrope(compact ? 17 : 21)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ Spacer(minLength: 24)
+ VStack(spacing: 14) {
+ primaryButton(t("console.homeHint.open"), id: "console.homeHint.open", scope: "console.homeHint") { driver.openHomeButtonSettings() }
+ Button { driver.back() } label: {
+ Text(t("console.homeHint.later")).font(.manrope(21, .semibold)).foregroundStyle(.white.opacity(0.85))
+ .frame(maxWidth: .infinity, minHeight: 60).background(.white.opacity(0.08), in: Capsule()).contentShape(Capsule())
+ }
+ .buttonStyle(.plain).padTarget("console.homeHint.later", scope: "console.homeHint", radius: 32, activate: { driver.back() })
+ }
+ }
+ .padding(compact ? 24 : 40)
+ }
+
private func empty(compact: Bool) -> some View {
VStack(spacing: 24) {
Image(systemName: "rectangle.stack").font(.system(size: compact ? 44 : 64, weight: .light)).foregroundStyle(LauncherPalette.cream.opacity(0.65)).accessibilityHidden(true)
@@ -410,6 +432,7 @@ enum ConsoleInput {
case .controllers: return "console.controllers"
case .options: return "console.options"
case .explanation: return "console.explanationTitle"
+ case .homeButtonHint: return "console.homeHint.title"
}
}
private func resetFocus() {
@@ -419,6 +442,7 @@ enum ConsoleInput {
case let .options(id): pad.focused = state.games.first { $0.id == id }?.visibleSettings.first.map { "console.option." + $0.env } ?? "console.options.play"
case .controllers: pad.focused = "console.player.\(state.assigningPlayer ?? 1)"
case .explanation: pad.focused = "console.explanation.desktop"
+ case .homeButtonHint: pad.focused = "console.homeHint.open"
case nil: pad.focused = state.exited ? "console.return" : state.focusedGame.map { "console.game." + $0.id } ?? "console.empty.desktop"
}
}
diff --git a/frontend/Sources/NX2Apple/GameStart.swift b/frontend/Sources/NX2Apple/GameStart.swift
index 2460d4d8..d1b54e8a 100644
--- a/frontend/Sources/NX2Apple/GameStart.swift
+++ b/frontend/Sources/NX2Apple/GameStart.swift
@@ -20,6 +20,7 @@ enum GameStart {
appReadsStore: SavedChoices.appReadsStore(app: game.appPath))
if fullscreen, settings.contains(where: { $0.env == "DM_FULLSCREEN" }) { environment["DM_FULLSCREEN"] = "1" }
if let id = displayID(of: screen) { environment["DM_SCREEN"] = String(id) }
+ environment["DM_HOME_QUIT_TEXT"] = HomeButtonHint.promptText(gameName: game.name, labels: labels) // the game's Home button quit prompt in the launcher's language (#336)
return environment
}
diff --git a/frontend/Sources/NX2Apple/HomeButtonSettings.swift b/frontend/Sources/NX2Apple/HomeButtonSettings.swift
new file mode 100644
index 00000000..a6ae4742
--- /dev/null
+++ b/frontend/Sources/NX2Apple/HomeButtonSettings.swift
@@ -0,0 +1,35 @@
+import AppKit
+import GameController
+import os
+import NXCore
+
+/// The system's Home button setting for apps (#336): opening its screen in System Settings, and what a game's last session found
+/// (HomeButtonHint reads the game's log). GameControllerHomeButtonSettingsManager is macOS 27 only, and opens the screen only while a
+/// controller is connected: otherwise System Settings opens at its start and the player finds Game Controllers there.
+enum HomeButtonSettings {
+ private static let log = Logger(subsystem: "NX2Apple", category: "console.home")
+
+ static var available: Bool {
+ if #available(macOS 27.0, *) { return true }
+ return false
+ }
+
+ @MainActor static func open() {
+ if #available(macOS 27.0, *) {
+ do { try GCControllerHomeButtonSettingsManager().openControllerHomeButtonSettings(for: .customizeInAppAction); return }
+ catch { log.notice("Home button settings did not open: \(error.localizedDescription, privacy: .public)") }
+ }
+ NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Applications/System Settings.app"))
+ }
+
+ /// The setting the game wrote to its log in its last session, nil when it wrote none. The game writes it when the first controller
+ /// is there: at its start (the first megabyte of the log) or when one connects later (the end of the log). A log of hundreds of
+ /// megabytes is not read whole.
+ static func reported(by game: LibraryGame) -> String? {
+ guard let url = GameLog.latest(titleID: game.titleID, appPath: game.appPath) else { return nil }
+ if let lines = GameLog.tail(url, lines: 100_000), let found = HomeButtonHint.setting(fromLog: lines.joined(separator: "\n")) { return found }
+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }
+ defer { try? handle.close() }
+ return (try? handle.read(upToCount: 1 << 20)).flatMap { HomeButtonHint.setting(fromLog: String(decoding: $0, as: UTF8.self)) }
+ }
+}
diff --git a/frontend/Sources/NX2Apple/LiveConsoleDriver.swift b/frontend/Sources/NX2Apple/LiveConsoleDriver.swift
index 82f5a7cb..d3b2cca8 100644
--- a/frontend/Sources/NX2Apple/LiveConsoleDriver.swift
+++ b/frontend/Sources/NX2Apple/LiveConsoleDriver.swift
@@ -242,6 +242,7 @@ struct ConsolePadSnapshot: Equatable {
guard let self, self.state.startingGameID == gameID else { return }
if let error { self.state.returnFromGame(); self.gameEnded(); self.showToast(error.localizedDescription); return }
self.launchedPID = pid
+ self.launchedGame = game
if let pid { GameReturnWatcher.shared.didStart(pid: pid) { [weak self] in self?.gameDidTerminate(pid: pid) } } // the launcher's one watcher and its switch (ReturnAfterPlay.swift)
self.state.starting = .opening
self.timeoutTask?.cancel()
@@ -278,6 +279,30 @@ struct ConsolePadSnapshot: Equatable {
timeoutTask?.cancel()
state.returnFromGame()
gameEnded()
+ if let game = launchedGame { launchedGame = nil; offerHomeButtonHint(after: game) }
+ }
+
+ // MARK: Home button (#336)
+
+ private var launchedGame: LibraryGame?
+ /// The Home button setting the game's last session wrote to its log (HomeButtonHint), the switch "already shown", whether this
+ /// is macOS 27 and the way to the setting. Tests replace them.
+ var homeButtonReported: (LibraryGame) -> String? = { HomeButtonSettings.reported(by: $0) }
+ var homeHintDefaults: UserDefaults = .standard
+ var isMacOS27 = HomeButtonSettings.available
+ var openHomeSettings: () -> Void = { HomeButtonSettings.open() }
+
+ /// After a game quit: the hint, once, when that game found that the system keeps the Home button for itself.
+ private func offerHomeButtonHint(after game: LibraryGame) {
+ let shown = homeHintDefaults.bool(forKey: HomeButtonHint.shownKey)
+ guard HomeButtonHint.shouldShow(setting: homeButtonReported(game), shown: shown, macOS27: isMacOS27) else { return }
+ homeHintDefaults.set(true, forKey: HomeButtonHint.shownKey)
+ state.showHomeButtonHint()
+ }
+
+ func openHomeButtonSettings() {
+ state.back()
+ openHomeSettings()
}
// MARK: Options
diff --git a/frontend/Sources/NX2Apple/SettingsPage.swift b/frontend/Sources/NX2Apple/SettingsPage.swift
index 01c94bf1..d921064d 100644
--- a/frontend/Sources/NX2Apple/SettingsPage.swift
+++ b/frontend/Sources/NX2Apple/SettingsPage.swift
@@ -30,7 +30,8 @@ struct SettingsPage: View {
CardPageHeading(loc.t("settings.heading"), note: loc.t("settings.note"))
LibraryCard(library: library, onChooseFolder: onChooseLibraryFolder)
ControlsCard(controlChanges: controlChanges, padMerge: padMerge, consolePrompt: $consolePromptOn,
- startInConsole: $startInConsole, onOpenControls: onOpenControls, onOpenControllers: onOpenControllers)
+ startInConsole: $startInConsole, onOpenControls: onOpenControls, onOpenControllers: onOpenControllers,
+ onOpenHomeSettings: HomeButtonSettings.available ? { HomeButtonSettings.open() } : nil) // HomeButtonSettings.swift (#336)
ToolsCard(repo: repo, engine: engine, dependencies: dependencies, buildRunning: build.running,
shellCachePath: build.shellCachePath, revealFolder: { build.revealFolder($0) }) {
DiagnosticsButton(report: diagnostics, game: library.selected)
diff --git a/frontend/Sources/NXCore/HomeButtonHint.swift b/frontend/Sources/NXCore/HomeButtonHint.swift
new file mode 100644
index 00000000..a4e33d7b
--- /dev/null
+++ b/frontend/Sources/NXCore/HomeButtonHint.swift
@@ -0,0 +1,34 @@
+import Foundation
+
+/// Quitting a game with the controller's Home button (#336, engine patch "Mac host: quit a game by holding the controller's Home
+/// button"). The game claims Home and shows its own quit prompt on macOS 27. That works only when the system's Home button setting for
+/// apps lets the app decide. The game reads that setting and writes it to its log once (`front end: Home button in apps: <word>`), and
+/// the launcher shows its hint once in console mode when the word is `system`: the system keeps Home for itself there.
+/// The setting is read in the game's process because it may differ per app. The launcher only reads the game's log.
+package enum HomeButtonHint {
+ package static let shownKey = "homeButtonHintShown"
+ /// The line front_mac.m writes, up to the word.
+ static let marker = "Home button in apps: "
+
+ /// The setting's word in the last line of a game's log that names it, nil when no line does (macOS 26, an older game, no controller).
+ package static func setting(fromLog text: String) -> String? {
+ guard let range = text.range(of: marker, options: .backwards) else { return nil }
+ let word = text[range.upperBound...].prefix { $0.isLetter }
+ return word.isEmpty ? nil : String(word)
+ }
+
+ /// The hint shows once: on macOS 27, when the game reported that the system keeps Home, and only if it has not shown before.
+ package static func shouldShow(setting: String?, shown: Bool, macOS27: Bool) -> Bool {
+ macOS27 && !shown && setting == "system"
+ }
+
+ /// DM_HOME_QUIT_TEXT: the game's quit prompt in the launcher's language, one text per line, in the engine's order
+ /// (home_quit.h: the hold indicator, the title, the note, the quit button, the cancel button). Lines never hold a newline.
+ package static func promptText(gameName: String, labels: (String) -> String) -> String {
+ let name = gameName.replacingOccurrences(of: "\n", with: " ")
+ return [labels("homeQuit.hold"), String(format: labels("homeQuit.title"), name), labels("homeQuit.note"),
+ labels("homeQuit.quit"), labels("homeQuit.cancel")]
+ .map { $0.replacingOccurrences(of: "\n", with: " ") }
+ .joined(separator: "\n")
+ }
+}
diff --git a/frontend/Sources/NXLauncher/ControlsCard.swift b/frontend/Sources/NXLauncher/ControlsCard.swift
index 7122b151..a15b294e 100644
--- a/frontend/Sources/NXLauncher/ControlsCard.swift
+++ b/frontend/Sources/NXLauncher/ControlsCard.swift
@@ -11,16 +11,19 @@ package struct ControlsCard: View {
let startInConsole: Binding<Bool> // "Start in console mode" (#336)
let onOpenControls: () -> Void
let onOpenControllers: () -> Void // the Controllers sheet (the console mode's list, with the player-mode setting)
+ let onOpenHomeSettings: (() -> Void)? // the system's Home button settings (#336): nil before macOS 27, where the Home button cannot quit a game
@EnvironmentObject var loc: Localizer
package init(controlChanges: Int, padMerge: Binding<Bool>, consolePrompt: Binding<Bool>,
- startInConsole: Binding<Bool>, onOpenControls: @escaping () -> Void, onOpenControllers: @escaping () -> Void) {
+ startInConsole: Binding<Bool>, onOpenControls: @escaping () -> Void, onOpenControllers: @escaping () -> Void,
+ onOpenHomeSettings: (() -> Void)? = nil) {
self.controlChanges = controlChanges
self.padMerge = padMerge
self.consolePrompt = consolePrompt
self.startInConsole = startInConsole
self.onOpenControls = onOpenControls
self.onOpenControllers = onOpenControllers
+ self.onOpenHomeSettings = onOpenHomeSettings
}
package var body: some View {
@@ -49,6 +52,13 @@ package struct ControlsCard: View {
Toggle("", isOn: startInConsole).labelsHidden().toggleStyle(LauncherSwitchStyle())
.padTarget("set.consoleStart", scope: "main") { startInConsole.wrappedValue.toggle() }
}
+ CardDivider()
+ CardRow(loc.t("controls.homeQuit"), detail: loc.t(onOpenHomeSettings == nil ? "controls.homeQuitOld" : "controls.homeQuitNote")) {
+ if let onOpenHomeSettings {
+ Button(loc.t("console.homeHint.open"), action: onOpenHomeSettings)
+ .padTarget("set.homeQuit", scope: "main") { onOpenHomeSettings() }
+ }
+ }
}
}
}
diff --git a/frontend/Tests/NX2AppleTests/ConsoleLiveTests.swift b/frontend/Tests/NX2AppleTests/ConsoleLiveTests.swift
index 177bf878..a87802ee 100644
--- a/frontend/Tests/NX2AppleTests/ConsoleLiveTests.swift
+++ b/frontend/Tests/NX2AppleTests/ConsoleLiveTests.swift
@@ -82,7 +82,7 @@ import SwiftUI
if let main = NSScreen.main { XCTAssertEqual(launches.first?.environment["DM_SCREEN"], GameStart.displayID(of: main).map(String.init), "the game opens on the launcher's display") }
XCTAssertEqual(launches.first?.environment["DM_FULLSCREEN"], "1", "console mode plays fullscreen whatever Display says")
XCTAssertEqual(launches.first?.game.titleID, titleID)
- let expected = launches.first.map { GameStart.environment(for: $0.game, library: GameLibrary(file: temporary.appendingPathComponent("other.json")), controls: layout, repo: "", labels: { $0 }, fullscreen: true) }
+ let expected = launches.first.map { GameStart.environment(for: $0.game, library: GameLibrary(file: temporary.appendingPathComponent("other.json")), controls: layout, repo: "", labels: { L10n.string($0, .en) }, fullscreen: true) }
XCTAssertEqual(launches.first?.environment, expected, "the same function the desktop Play uses, with the console's fullscreen")
}
@@ -128,6 +128,51 @@ import SwiftUI
XCTAssertEqual(driver.state.focusedGameID, id, "the selected game is kept")
}
+ /// #336: a game that found the system keeping the Home button for itself gets the hint once, after it quit, in console mode.
+ func testHomeButtonHintShowsOnceWhenTheSystemKeepsHome() async throws {
+ let (driver, _, _) = try makeDriver()
+ let defaults = try XCTUnwrap(UserDefaults(suiteName: "ConsoleLiveTests-home-" + UUID().uuidString))
+ var reported: String? = "system", opened = 0
+ driver.homeButtonReported = { _ in reported }
+ driver.homeHintDefaults = defaults
+ driver.isMacOS27 = true
+ driver.openHomeSettings = { opened += 1 }
+ let id = try XCTUnwrap(driver.state.games.first?.id)
+ func playAndQuit() async throws {
+ driver.play(id)
+ for _ in 0..<50 where driver.state.starting != .opening { try await Task.sleep(nanoseconds: 20_000_000) }
+ driver.gameDidTerminate(pid: 4242)
+ }
+ try await playAndQuit()
+ XCTAssertEqual(driver.state.presentedSheet, .homeButtonHint)
+ XCTAssertTrue(defaults.bool(forKey: HomeButtonHint.shownKey))
+ driver.openHomeButtonSettings()
+ XCTAssertEqual(opened, 1, "the button opens the setting")
+ XCTAssertNil(driver.state.presentedSheet, "and closes the hint")
+ try await playAndQuit()
+ XCTAssertNil(driver.state.presentedSheet, "once only")
+
+ defaults.removeObject(forKey: HomeButtonHint.shownKey)
+ reported = "app"
+ try await playAndQuit()
+ XCTAssertNil(driver.state.presentedSheet, "the app decides: no hint")
+ reported = nil
+ try await playAndQuit()
+ XCTAssertNil(driver.state.presentedSheet, "an older game or macOS 26 wrote nothing: no hint")
+ reported = "system"; driver.isMacOS27 = false
+ try await playAndQuit()
+ XCTAssertNil(driver.state.presentedSheet, "before macOS 27 the Home button does not quit, so there is nothing to explain")
+ }
+
+ /// #336: the game's quit prompt gets its texts in the launcher's language, with the game's name.
+ func testPlayPassesTheHomeQuitTexts() throws {
+ var launches: [Launch] = []
+ let (driver, _, _) = try makeDriver { launches.append($0) }
+ driver.play(try XCTUnwrap(driver.state.games.first?.id))
+ let text = try XCTUnwrap(launches.first?.environment["DM_HOME_QUIT_TEXT"])
+ XCTAssertEqual(text.components(separatedBy: "\n"), ["Keep holding to quit", "Quit Hades?", "Unsaved progress will be lost.", "Quit", "Cancel"])
+ }
+
func testOptionsRoundTripThroughSavedChoices() throws {
let (driver, library, _) = try makeDriver()
let game = try XCTUnwrap(library.games.first)
diff --git a/frontend/Tests/NX2AppleTests/ConsoleTests.swift b/frontend/Tests/NX2AppleTests/ConsoleTests.swift
index 248b7625..e69d202e 100644
--- a/frontend/Tests/NX2AppleTests/ConsoleTests.swift
+++ b/frontend/Tests/NX2AppleTests/ConsoleTests.swift
@@ -240,7 +240,7 @@ import NXModel
let sizes: [(String, CGFloat, CGFloat)] = [("tv", 1920, 1080), ("mac", 1280, 800), ("compact", 390, 844)]
for lang in CaptureLanguage.all([.en, .zh]) {
for (name, width, height) in sizes {
- for screen in ["full", "few", "empty", "controllers", "controllersMixed", "mixedHome", "controllerDesktop", "connectedToast", "starting", "options", "needsBuild", "needsData", "broken", "desktop", "prompt"] {
+ for screen in ["full", "few", "empty", "controllers", "controllersMixed", "mixedHome", "controllerDesktop", "connectedToast", "starting", "options", "needsBuild", "needsData", "broken", "desktop", "prompt", "homeHint"] {
let driver = MockConsoleDriver(scenario: MockConsoleDriver.Scenario(rawValue: screen) ?? (screen == "mixedHome" || screen == "controllerDesktop" || screen == "connectedToast" ? .controllersMixed : .full), lang: lang, animated: false)
switch screen {
case "mixedHome": driver.back()
@@ -250,6 +250,7 @@ import NXModel
case "needsData": driver.focus("demo.5"); driver.play("demo.5")
case "broken": driver.focus("demo.7"); driver.play("demo.7")
case "desktop": driver.exitToDesktop()
+ case "homeHint": driver.state.showHomeButtonHint()
default: break
}
let view: AnyView
diff --git a/frontend/Tests/NX2AppleTests/HomeButtonCaptureTests.swift b/frontend/Tests/NX2AppleTests/HomeButtonCaptureTests.swift
new file mode 100644
index 00000000..86c2c4b5
--- /dev/null
+++ b/frontend/Tests/NX2AppleTests/HomeButtonCaptureTests.swift
@@ -0,0 +1,34 @@
+import AppKit
+import SwiftUI
+import XCTest
+@testable import NX2Apple
+@testable import NXCore
+@testable import NXLauncher
+@testable import NXModel
+
+/// #336: Settings > Controls with its Home button row, as on macOS 27 and before it. Set NX_LAUNCHER_CAPTURE_DIR to keep the PNGs
+/// (NX_CAPTURE_LANG picks the language).
+@MainActor final class HomeButtonCaptureTests: XCTestCase {
+ func testRenderControlsCard() throws {
+ guard let directory = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_DIR"] else { throw XCTSkip("Set NX_LAUNCHER_CAPTURE_DIR to capture native views") }
+ let output = URL(fileURLWithPath: directory)
+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
+ let lang = CaptureLanguage.current(.en)
+ let stores = LauncherStores(); stores.localizer.lang = lang
+ for (name, open) in [("controls-macos27", { } as (() -> Void)?), ("controls-macos26", nil)] {
+ let card = ControlsCard(controlChanges: 0, padMerge: .constant(false), consolePrompt: .constant(true), startInConsole: .constant(false),
+ onOpenControls: {}, onOpenControllers: {}, onOpenHomeSettings: open)
+ .environmentObject(stores.localizer).environmentObject(PadFocus()).padding(24).frame(width: 760).background(LauncherPalette.background).preferredColorScheme(.dark)
+ let host = NSHostingView(rootView: card)
+ let window = OffscreenWindow(size: NSSize(width: 760, height: 700), styleMask: [.borderless])
+ window.contentView = host
+ window.orderBack(nil)
+ RunLoop.main.run(until: Date().addingTimeInterval(0.2))
+ host.setFrameSize(host.fittingSize); host.layoutSubtreeIfNeeded()
+ let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
+ host.cacheDisplay(in: host.bounds, to: rep)
+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("\(name)-\(lang.code).png"))
+ window.orderOut(nil); window.contentView = nil; window.close()
+ }
+ }
+}
diff --git a/frontend/Tests/NXCoreTests/HomeButtonHintTests.swift b/frontend/Tests/NXCoreTests/HomeButtonHintTests.swift
new file mode 100644
index 00000000..0fa6a30a
--- /dev/null
+++ b/frontend/Tests/NXCoreTests/HomeButtonHintTests.swift
@@ -0,0 +1,40 @@
+import XCTest
+@testable import NXCore
+
+/// #336: the Home button setting a game writes to its log, when the launcher's hint shows, and the texts of the game's quit prompt.
+final class HomeButtonHintTests: XCTestCase {
+ func testSettingFromTheGamesLog() {
+ let log = """
+ [dm] front end: hold the Home button to quit is on
+ [dm] controller 'Xbox Wireless Controller' connected: player 1 (npad 0)
+ [dm] front end: Home button in apps: system (the system's default)
+ [dm] guest thread finished
+ """
+ XCTAssertEqual(HomeButtonHint.setting(fromLog: log), "system")
+ XCTAssertEqual(HomeButtonHint.setting(fromLog: log + "\n[dm] front end: Home button in apps: app (set by the player)"), "app", "the last line wins")
+ XCTAssertEqual(HomeButtonHint.setting(fromLog: "[dm] front end: Home button in apps: unavailable (the system's default), error"), "unavailable")
+ XCTAssertNil(HomeButtonHint.setting(fromLog: "[dm] front end: hold the Home button to quit needs macOS 27, quit with ⌘Q"), "macOS 26 writes no setting")
+ XCTAssertNil(HomeButtonHint.setting(fromLog: ""))
+ XCTAssertNil(HomeButtonHint.setting(fromLog: "[dm] front end: Home button in apps: "), "a cut line")
+ }
+
+ func testHintShowsOnceWhenTheSystemKeepsHome() {
+ XCTAssertTrue(HomeButtonHint.shouldShow(setting: "system", shown: false, macOS27: true))
+ XCTAssertFalse(HomeButtonHint.shouldShow(setting: "system", shown: true, macOS27: true), "once")
+ XCTAssertFalse(HomeButtonHint.shouldShow(setting: "system", shown: false, macOS27: false), "macOS 26 keeps Cmd+Q")
+ for other in ["app", "off", "unavailable", nil] as [String?] {
+ XCTAssertFalse(HomeButtonHint.shouldShow(setting: other, shown: false, macOS27: true), "\(other ?? "nil")")
+ }
+ }
+
+ func testPromptTextIsOneLinePerTextInTheEnginesOrder() {
+ let labels: [String: String] = ["homeQuit.hold": "Hold", "homeQuit.title": "Quit %@?", "homeQuit.note": "Note", "homeQuit.quit": "Quit", "homeQuit.cancel": "Cancel"]
+ let text = HomeButtonHint.promptText(gameName: "Zelda\nTOTK", labels: { labels[$0] ?? $0 })
+ XCTAssertEqual(text.components(separatedBy: "\n"), ["Hold", "Quit Zelda TOTK?", "Note", "Quit", "Cancel"], "a newline in the name would shift the lines")
+ for lang in Lang.all {
+ let lines = HomeButtonHint.promptText(gameName: "Hades", labels: { L10n.string($0, lang) }).components(separatedBy: "\n")
+ XCTAssertEqual(lines.count, 5, lang.code)
+ XCTAssertTrue(lines[1].contains("Hades"), "\(lang.code): the title names the game")
+ }
+ }
+}
diff --git a/frontend/l10n/de.json b/frontend/l10n/de.json
index 42b02c39..985dd9af 100644
--- a/frontend/l10n/de.json
+++ b/frontend/l10n/de.json
@@ -156,6 +156,11 @@
"console.fps30": "30 fps",
"console.fps60": "60 fps",
"console.frameRate": "Bildrate",
+ "console.homeHint.body": "Halte im Spiel die Home-Taste 2 Sekunden lang gedrückt, um es zu beenden. Im Moment behält dein Mac die Home-Taste für sich.",
+ "console.homeHint.how": "Lege in den Einstellungen für Gamecontroller fest, dass Apps entscheiden, was die Home-Taste tut.",
+ "console.homeHint.later": "Später",
+ "console.homeHint.open": "Einstellungen öffnen",
+ "console.homeHint.title": "Mit der Home-Taste beenden",
"console.identify": "Erkennen",
"console.identifying": "Wird erkannt …",
"console.identifyingName": "%@ wird erkannt …",
@@ -243,6 +248,9 @@
"controls.fn.Y": "Y",
"controls.fn.ZL": "ZL",
"controls.fn.ZR": "ZR",
+ "controls.homeQuit": "Mit der Home-Taste beenden",
+ "controls.homeQuitNote": "Halte im Spiel die Home-Taste 2 Sekunden lang gedrückt und drücke dann A. Dein Mac muss Apps die Home-Taste überlassen.",
+ "controls.homeQuitOld": "Erfordert macOS 27. Auf diesem Mac beendest du ein Spiel mit ⌘Q.",
"controls.keyButtons": "Tastatur: Tasten",
"controls.mode": "Controller: Belegung",
"controls.mode.auto": "Automatisch",
@@ -589,6 +597,11 @@
"free.running": "Ein Build läuft. Build-Dateien lassen sich entfernen, sobald er fertig ist.",
"free.selected": "%@ ausgewählt",
"free.title": "Speicherplatz freigeben",
+ "homeQuit.cancel": "Abbrechen",
+ "homeQuit.hold": "Zum Beenden gedrückt halten",
+ "homeQuit.note": "Nicht gesicherter Fortschritt geht verloren.",
+ "homeQuit.quit": "Beenden",
+ "homeQuit.title": "%@ beenden?",
"install.reveal": "Im Finder zeigen",
"ios.host.deleteFailed": "Einige Dateien von %@ konnten nicht gelöscht werden.",
"ios.host.padOff": "Aus",
diff --git a/frontend/l10n/en.json b/frontend/l10n/en.json
index 32e52638..603d2415 100644
--- a/frontend/l10n/en.json
+++ b/frontend/l10n/en.json
@@ -154,6 +154,11 @@
"console.fps30": "30 fps",
"console.fps60": "60 fps",
"console.frameRate": "Frame rate",
+ "console.homeHint.body": "In a game, hold the Home button for 2 seconds to quit it. Right now your Mac keeps the Home button for itself.",
+ "console.homeHint.how": "In Game Controllers settings, let apps decide what the Home button does.",
+ "console.homeHint.later": "Not now",
+ "console.homeHint.open": "Open Settings",
+ "console.homeHint.title": "Quit with the Home button",
"console.identify": "Identify",
"console.identifying": "Identifying…",
"console.identifyingName": "Identifying %@…",
@@ -241,6 +246,9 @@
"controls.fn.Y": "Y",
"controls.fn.ZL": "ZL",
"controls.fn.ZR": "ZR",
+ "controls.homeQuit": "Quit with the Home button",
+ "controls.homeQuitNote": "In a game, hold the Home button for 2 seconds, then press A to quit. Your Mac has to let apps use the Home button.",
+ "controls.homeQuitOld": "Needs macOS 27. On this Mac, quit a game with ⌘Q.",
"controls.keyButtons": "Keyboard: buttons",
"controls.mode": "Controller: layout",
"controls.mode.auto": "Auto",
@@ -587,6 +595,11 @@
"free.running": "A build is running. Build files can be removed when it has finished.",
"free.selected": "%@ selected",
"free.title": "Free space",
+ "homeQuit.cancel": "Cancel",
+ "homeQuit.hold": "Keep holding to quit",
+ "homeQuit.note": "Unsaved progress will be lost.",
+ "homeQuit.quit": "Quit",
+ "homeQuit.title": "Quit %@?",
"install.reveal": "Reveal in Finder",
"ios.host.additionalContentPacks": "%lld additional content packs",
"ios.host.appFolder": "This app's folder",
diff --git a/frontend/l10n/fr.json b/frontend/l10n/fr.json
index 7509a532..75bf3a16 100644
--- a/frontend/l10n/fr.json
+++ b/frontend/l10n/fr.json
@@ -155,6 +155,11 @@
"console.fps30": "30 i/s",
"console.fps60": "60 i/s",
"console.frameRate": "Fréquence d’images",
+ "console.homeHint.body": "Dans un jeu, maintenez le bouton Home pendant 2 secondes pour le quitter. Pour l’instant, votre Mac garde le bouton Home pour lui.",
+ "console.homeHint.how": "Dans les réglages Manettes de jeu, laissez les apps décider de ce que fait le bouton Home.",
+ "console.homeHint.later": "Plus tard",
+ "console.homeHint.open": "Ouvrir les Réglages",
+ "console.homeHint.title": "Quitter avec le bouton Home",
"console.identify": "Identifier",
"console.identifying": "Identification…",
"console.identifyingName": "Identification de %@…",
@@ -242,6 +247,9 @@
"controls.fn.Y": "Y",
"controls.fn.ZL": "ZL",
"controls.fn.ZR": "ZR",
+ "controls.homeQuit": "Quitter avec le bouton Home",
+ "controls.homeQuitNote": "Dans un jeu, maintenez le bouton Home pendant 2 secondes, puis appuyez sur A pour quitter. Votre Mac doit laisser les apps utiliser le bouton Home.",
+ "controls.homeQuitOld": "Nécessite macOS 27. Sur ce Mac, quittez un jeu avec ⌘Q.",
"controls.keyButtons": "Clavier : boutons",
"controls.mode": "Manette : disposition",
"controls.mode.auto": "Auto",
@@ -588,6 +596,11 @@
"free.running": "Une compilation est en cours. Les fichiers de compilation pourront être supprimés une fois terminée.",
"free.selected": "%@ sélectionnés",
"free.title": "Libérer de l’espace",
+ "homeQuit.cancel": "Annuler",
+ "homeQuit.hold": "Maintenez pour quitter",
+ "homeQuit.note": "La progression non sauvegardée sera perdue.",
+ "homeQuit.quit": "Quitter",
+ "homeQuit.title": "Quitter %@ ?",
"install.reveal": "Afficher dans le Finder",
"ios.host.deleteFailed": "Certains fichiers de %@ n’ont pas pu être supprimés.",
"ios.host.padController": "Manette",
diff --git a/frontend/l10n/it.json b/frontend/l10n/it.json
index b8907b36..2e0ba899 100644
--- a/frontend/l10n/it.json
+++ b/frontend/l10n/it.json
@@ -155,6 +155,11 @@
"console.fps30": "30 fps",
"console.fps60": "60 fps",
"console.frameRate": "Frequenza fotogrammi",
+ "console.homeHint.body": "In un gioco, tieni premuto il tasto Home per 2 secondi per uscire. Al momento il Mac riserva il tasto Home al sistema.",
+ "console.homeHint.how": "Nelle impostazioni dei controller di gioco, lascia che siano le app a decidere cosa fa il tasto Home.",
+ "console.homeHint.later": "Non ora",
+ "console.homeHint.open": "Apri Impostazioni",
+ "console.homeHint.title": "Esci con il tasto Home",
"console.identify": "Identifica",
"console.identifying": "Identificazione…",
"console.identifyingName": "Identificazione di %@…",
@@ -242,6 +247,9 @@
"controls.fn.Y": "Y",
"controls.fn.ZL": "ZL",
"controls.fn.ZR": "ZR",
+ "controls.homeQuit": "Esci con il tasto Home",
+ "controls.homeQuitNote": "In un gioco, tieni premuto il tasto Home per 2 secondi, poi premi A per uscire. Il Mac deve lasciare il tasto Home alle app.",
+ "controls.homeQuitOld": "Richiede macOS 27. Su questo Mac esci da un gioco con ⌘Q.",
"controls.keyButtons": "Tastiera: pulsanti",
"controls.mode": "Controller: configurazione",
"controls.mode.auto": "Automatica",
@@ -588,6 +596,11 @@
"free.running": "È in corso una build. I file di build si potranno rimuovere quando sarà terminata.",
"free.selected": "%@ selezionati",
"free.title": "Libera spazio",
+ "homeQuit.cancel": "Annulla",
+ "homeQuit.hold": "Tieni premuto per uscire",
+ "homeQuit.note": "I progressi non salvati andranno persi.",
+ "homeQuit.quit": "Esci",
+ "homeQuit.title": "Uscire da %@?",
"install.reveal": "Mostra nel Finder",
"ios.host.deleteFailed": "Alcuni file di %@ non sono stati eliminati.",
"ios.host.padController": "Controller",
diff --git a/frontend/l10n/sv.json b/frontend/l10n/sv.json
index 1312a647..fdef15b0 100644
--- a/frontend/l10n/sv.json
+++ b/frontend/l10n/sv.json
@@ -114,6 +114,11 @@
"cloud.state.waiting": "En nyare sparfil har inte skickats än. Den skickas vid nästa start.",
"cloud.title": "Molnsparfiler",
"cloud.turnOff": "Stäng av",
+ "console.homeHint.body": "Håll in hemknappen i 2 sekunder i ett spel för att avsluta det. Just nu behåller din Mac hemknappen för sig själv.",
+ "console.homeHint.how": "Låt appar bestämma vad hemknappen gör i inställningarna för spelkontroller.",
+ "console.homeHint.later": "Inte nu",
+ "console.homeHint.open": "Öppna Inställningar",
+ "console.homeHint.title": "Avsluta med hemknappen",
"console.startInConsole": "Starta i konsolläge",
"console.startInConsoleNote": "Öppnar konsolläget varje gång launchern startar, med eller utan handkontroll. Lämna det från menyn Visa.",
"controls.applied": "Tillämpas nästa gång du väljer Spela här. Äldre byggen ignorerar det.",
@@ -147,6 +152,9 @@
"controls.fn.Y": "Y",
"controls.fn.ZL": "ZL",
"controls.fn.ZR": "ZR",
+ "controls.homeQuit": "Avsluta med hemknappen",
+ "controls.homeQuitNote": "Håll in hemknappen i 2 sekunder i ett spel och tryck sedan på A för att avsluta. Din Mac måste låta appar använda hemknappen.",
+ "controls.homeQuitOld": "Kräver macOS 27. På den här Macen avslutar du ett spel med ⌘Q.",
"controls.keyButtons": "Tangentbord: knappar",
"controls.mode": "Handkontroll: layout",
"controls.mode.auto": "Automatisk",
@@ -430,6 +438,11 @@
"free.running": "Ett bygge körs. Byggfilerna kan tas bort när det är klart.",
"free.selected": "%@ valt",
"free.title": "Frigör utrymme",
+ "homeQuit.cancel": "Avbryt",
+ "homeQuit.hold": "Fortsätt hålla in för att avsluta",
+ "homeQuit.note": "Osparade framsteg går förlorade.",
+ "homeQuit.quit": "Avsluta",
+ "homeQuit.title": "Avsluta %@?",
"install.reveal": "Visa i Finder",
"ios.host.deleteFailed": "Några filer för %@ kunde inte raderas.",
"ios.host.padController": "Handkontroll",
diff --git a/frontend/l10n/zh.json b/frontend/l10n/zh.json
index 4884f1c1..1c08176a 100644
--- a/frontend/l10n/zh.json
+++ b/frontend/l10n/zh.json
@@ -155,6 +155,11 @@
"console.fps30": "30 帧/秒",
"console.fps60": "60 帧/秒",
"console.frameRate": "帧率",
+ "console.homeHint.body": "在游戏中按住 Home 键 2 秒即可退出。目前你的 Mac 把 Home 键留给系统自己使用。",
+ "console.homeHint.how": "在「游戏控制器」设置中,让应用决定 Home 键的作用。",
+ "console.homeHint.later": "以后再说",
+ "console.homeHint.open": "打开设置",
+ "console.homeHint.title": "用 Home 键退出游戏",
"console.identify": "识别",
"console.identifying": "正在识别…",
"console.identifyingName": "正在识别 %@…",
@@ -242,6 +247,9 @@
"controls.fn.Y": "Y",
"controls.fn.ZL": "ZL",
"controls.fn.ZR": "ZR",
+ "controls.homeQuit": "用 Home 键退出游戏",
+ "controls.homeQuitNote": "在游戏中按住 Home 键 2 秒,然后按 A 退出。Mac 需要允许应用使用 Home 键。",
+ "controls.homeQuitOld": "需要 macOS 27。在这台 Mac 上请用 ⌘Q 退出游戏。",
"controls.keyButtons": "键盘:按钮",
"controls.mode": "手柄:布局",
"controls.mode.auto": "自动",
@@ -588,6 +596,11 @@
"free.running": "正在构建。构建完成后才能删除构建文件。",
"free.selected": "已选 %@",
"free.title": "释放空间",
+ "homeQuit.cancel": "取消",
+ "homeQuit.hold": "继续按住即可退出",
+ "homeQuit.note": "未保存的进度将会丢失。",
+ "homeQuit.quit": "退出",
+ "homeQuit.title": "退出%@?",
"install.reveal": "在访达中显示",
"ios.host.additionalContentPacks": "%lld 个附加内容包",
"ios.host.appFolder": "本 App 的文件夹",