Skip to content

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

Home button: one width per button in every language (#336)

v0lumehi676c42a87750
diff --git a/frontend/Sources/NX2Apple/ConsoleView.swift b/frontend/Sources/NX2Apple/ConsoleView.swift
index 1a8bd613..77be114a 100644
--- a/frontend/Sources/NX2Apple/ConsoleView.swift
+++ b/frontend/Sources/NX2Apple/ConsoleView.swift
@@ -361,13 +361,17 @@ enum ConsoleInput {
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)
+ // Both buttons take the sheet's full width, so their width never follows the label or the language (ConsoleButtonWidths)
VStack(spacing: 14) {
primaryButton(t("console.homeHint.open"), id: "console.homeHint.open", scope: "console.homeHint") { driver.openHomeButtonSettings() }
+ .background(ConsoleButtonWidths.reader("console.homeHint.open"))
Button { driver.back() } label: {
Text(t("console.homeHint.later")).font(.manrope(21, .semibold)).foregroundStyle(.white.opacity(0.85))
+ .multilineTextAlignment(.center).lineLimit(2).minimumScaleFactor(0.8).padding(.horizontal, 20)
.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() })
+ .background(ConsoleButtonWidths.reader("console.homeHint.later"))
}
}
.padding(compact ? 24 : 40)
@@ -423,6 +427,7 @@ enum ConsoleInput {
private func primaryButton(_ label: String, id: String, scope: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
Text(label).font(.manrope(21, .bold)).foregroundStyle(LauncherPalette.background)
+ .multilineTextAlignment(.center).lineLimit(2).minimumScaleFactor(0.8).padding(.horizontal, 20) // a long label wraps or shrinks, the button keeps its width
.frame(maxWidth: .infinity, minHeight: 60).background(LauncherPalette.cream, in: Capsule()).contentShape(Capsule())
}
.buttonStyle(.plain).padTarget(id, scope: scope, radius: 32, activate: action)
@@ -500,6 +505,13 @@ struct ConsoleArtwork: View {
}
}
+/// The width each button of the Home button hint was drawn at, by its pad id: ConsoleTests checks that it is the same in every language.
+struct ConsoleButtonWidths: PreferenceKey {
+ static var defaultValue: [String: CGFloat] = [:]
+ static func reduce(value: inout [String: CGFloat], nextValue: () -> [String: CGFloat]) { value.merge(nextValue()) { _, new in new } }
+ static func reader(_ id: String) -> some View { GeometryReader { g in Color.clear.preference(key: ConsoleButtonWidths.self, value: [id: g.size.width]) } }
+}
+
private struct ConsoleTileFramesKey: PreferenceKey {
static var defaultValue: [String: CGRect] = [:]
static func reduce(value: inout [String: CGRect], nextValue: () -> [String: CGRect]) { value.merge(nextValue()) { _, new in new } }
diff --git a/frontend/Tests/NX2AppleTests/HomeButtonCaptureTests.swift b/frontend/Tests/NX2AppleTests/HomeButtonCaptureTests.swift
index 86c2c4b5..f1610003 100644
--- a/frontend/Tests/NX2AppleTests/HomeButtonCaptureTests.swift
+++ b/frontend/Tests/NX2AppleTests/HomeButtonCaptureTests.swift
@@ -6,29 +6,109 @@ import XCTest
@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).
+/// #336: the buttons this feature adds keep one width per role in every language, at the default text size and a larger one, and
+/// their label fits or wraps inside. Settings > Controls: "Open Settings" is a row control like its neighbours (LauncherControl.width).
+/// Console mode: the hint's "Open Settings" and "Not now" take the sheet's width. Set NX_LAUNCHER_CAPTURE_DIR to keep PNGs of both
+/// in English, German, Chinese and the language whose label is longest.
@MainActor final class HomeButtonCaptureTests: XCTestCase {
- func testRenderControlsCard() throws {
+ private final class Box<T> { var value: T; init(_ value: T) { self.value = value } }
+ private let typeSizes: [DynamicTypeSize] = [.large, .xxxLarge]
+
+ private func controlsCard(_ lang: Lang, open: (() -> Void)?) -> some View {
+ let localizer = LauncherStores().localizer; localizer.lang = lang
+ return ControlsCard(controlChanges: 0, padMerge: .constant(false), consolePrompt: .constant(true), startInConsole: .constant(false),
+ onOpenControls: {}, onOpenControllers: {}, onOpenHomeSettings: open)
+ .buttonStyle(LauncherSecondaryButtonStyle()) // as on the Settings page (LauncherPageScroll)
+ .environmentObject(localizer).environmentObject(PadFocus())
+ .padding(24).frame(width: 760).background(LauncherPalette.background).preferredColorScheme(.dark)
+ }
+
+ private func hint(_ lang: Lang) -> some View {
+ let driver = MockConsoleDriver(scenario: .full, lang: lang, animated: false)
+ driver.state.showHomeButtonHint()
+ return ConsoleView(driver: driver, lang: lang).transaction { $0.disablesAnimations = true }
+ }
+
+ /// Draws `view` offscreen at `size` and returns the host after layout.
+ private func draw<V: View>(_ view: V, size: NSSize, run: TimeInterval = 0.15) -> (NSHostingView<V>, OffscreenWindow) {
+ let host = NSHostingView(rootView: view)
+ let window = OffscreenWindow(size: size, styleMask: [.borderless])
+ window.contentView = host
+ window.orderBack(nil)
+ RunLoop.main.run(until: Date().addingTimeInterval(run))
+ host.layoutSubtreeIfNeeded()
+ return (host, window)
+ }
+
+ func testOpenSettingsInControlsHasTheRowControlWidthInEveryLanguage() throws {
+ NSApplication.shared.setActivationPolicy(.accessory)
+ for typeSize in typeSizes {
+ for lang in Lang.all {
+ let samples = Box<[LauncherControlSample]>([])
+ let view = controlsCard(lang, open: {}).dynamicTypeSize(typeSize).environment(\.measuresLauncherControls, true)
+ .onPreferenceChange(LauncherControlSamples.self) { samples.value = $0 }
+ let (_, window) = draw(view, size: NSSize(width: 760, height: 1000))
+ defer { window.orderOut(nil); window.close() }
+ let at = "\(lang.code), \(typeSize)"
+ XCTAssertGreaterThanOrEqual(samples.value.count, 3, "\(at): Customize, Open and Open Settings")
+ for (index, sample) in samples.value.enumerated() {
+ XCTAssertEqual(sample.size.width, LauncherControl.width, "\(at), button \(index): the same width as its neighbours, whatever the label")
+ XCTAssertEqual(sample.size.height, LauncherControl.height, "\(at), button \(index)")
+ XCTAssertLessThanOrEqual(sample.labelWidth, sample.room, "\(at), button \(index): the label fits on one line")
+ }
+ }
+ }
+ }
+
+ func testHintButtonsKeepOneWidthInEveryLanguage() throws {
+ NSApplication.shared.setActivationPolicy(.accessory)
+ for (name, width, height) in [("tv", 1920.0, 1080.0), ("mac", 1280.0, 800.0), ("compact", 390.0, 844.0)] {
+ var first: CGFloat?
+ for typeSize in typeSizes {
+ for lang in Lang.all {
+ let widths = Box<[String: CGFloat]>([:])
+ let view = hint(lang).dynamicTypeSize(typeSize).frame(width: width, height: height)
+ .onPreferenceChange(ConsoleButtonWidths.self) { widths.value = $0 }
+ let (_, window) = draw(view, size: NSSize(width: width, height: height))
+ defer { window.orderOut(nil); window.close() }
+ let at = "\(name), \(lang.code), \(typeSize)"
+ let open = try XCTUnwrap(widths.value["console.homeHint.open"], at), later = try XCTUnwrap(widths.value["console.homeHint.later"], at)
+ XCTAssertEqual(open, later, accuracy: 0.5, "\(at): both buttons are as wide as each other")
+ if let first { XCTAssertEqual(open, first, accuracy: 0.5, "\(at): the same width as in every other language") } else { first = open }
+ }
+ }
+ }
+ }
+
+ func testRenderHomeButtonViews() 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()
+ NSApplication.shared.setActivationPolicy(.accessory)
+ // the language whose "Open Settings" is longest, beside English, German and Chinese
+ let font = try XCTUnwrap(Typography.manropeFont(size: 21, weight: .bold))
+ func length(_ lang: Lang) -> CGFloat {
+ CTLineGetTypographicBounds(CTLineCreateWithAttributedString(NSAttributedString(string: L10n.string("console.homeHint.open", lang), attributes: [.font: font])), nil, nil, nil)
+ }
+ let longest = try XCTUnwrap(Lang.all.max { length($0) < length($1) })
+ var langs: [Lang] = []
+ for lang in [Lang.en, Lang.find("de"), Lang.zh, longest].compactMap({ $0 }) where !langs.contains(lang) { langs.append(lang) }
+ func save(_ host: NSView, _ name: String) throws {
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()
+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent(name + ".png"))
+ }
+ for lang in langs {
+ for (suffix, open) in [("macos27", { } as (() -> Void)?), ("macos26", nil)] {
+ let (host, window) = draw(controlsCard(lang, open: open), size: NSSize(width: 760, height: 1000), run: 0.2)
+ host.setFrameSize(host.fittingSize); host.layoutSubtreeIfNeeded()
+ try save(host, "controls-\(suffix)-\(lang.code)")
+ window.orderOut(nil); window.close()
+ }
+ let (host, window) = draw(hint(lang).frame(width: 1920, height: 1080), size: NSSize(width: 1920, height: 1080))
+ try save(host, "console-hint-\(lang.code)")
+ window.orderOut(nil); window.close()
}
+ print("home button captures: \(langs.map(\.code)), longest Open Settings: \(longest.code)")
}
}
diff --git a/patches/0063-mac-host-quit-a-game-by-holding-the-controller-s.patch b/patches/0063-mac-host-quit-a-game-by-holding-the-controller-s.patch
index 141ea228..de0fde7e 100644
--- a/patches/0063-mac-host-quit-a-game-by-holding-the-controller-s.patch
+++ b/patches/0063-mac-host-quit-a-game-by-holding-the-controller-s.patch
@@ -26,17 +26,16 @@ tested without a controller or a window (t_home_quit, t_home_quit_mac).
Upstream-Status: forwarded seedds/nxnative#1084
Reason: Quit a game with the controller's Home button on macOS 27, the launcher's console mode needs it (#336)
Issue: LNPANDY/NX2Apple#336
-
---
dm/host/Makefile | 2 +-
dm/host/front_mac.m | 130 ++++++++++++++++++++++++++++++--
dm/host/home_quit.h | 93 +++++++++++++++++++++++
- dm/host/home_quit_mac.h | 91 ++++++++++++++++++++++
+ dm/host/home_quit_mac.h | 110 +++++++++++++++++++++++++++
dm/host/tests/Makefile | 7 ++
dm/host/tests/t_home_quit.c | 87 +++++++++++++++++++++
- dm/host/tests/t_home_quit_mac.m | 87 +++++++++++++++++++++
+ dm/host/tests/t_home_quit_mac.m | 107 ++++++++++++++++++++++++++
docs/env_switches.tsv | 3 +
- 8 files changed, 494 insertions(+), 6 deletions(-)
+ 8 files changed, 533 insertions(+), 6 deletions(-)
create mode 100644 dm/host/home_quit.h
create mode 100644 dm/host/home_quit_mac.h
create mode 100644 dm/host/tests/t_home_quit.c
@@ -356,10 +355,10 @@ index 0000000..9a92182
+}
diff --git a/dm/host/home_quit_mac.h b/dm/host/home_quit_mac.h
new file mode 100644
-index 0000000..dd6c613
+index 0000000..9904584
--- /dev/null
+++ b/dm/host/home_quit_mac.h
-@@ -0,0 +1,91 @@
+@@ -0,0 +1,110 @@
+// The views of the Home button's quit prompt (home_quit.h), drawn over the game's view by front_mac.m: AppKit views, so they draw while the game runs, and built here
+// alone so tests/t_home_quit_mac.m can build and draw them without a window or a controller. The look is the launcher's console mode: its dark surface and cream
+// accent, the primary action as a cream pill with the controller's own button glyph. Sizes follow the view's height, so the prompt reads from a couch on a TV and
@@ -391,15 +390,34 @@ index 0000000..dd6c613
+ v.contentTintColor = c; v.translatesAutoresizingMaskIntoConstraints = NO;
+ return v;
+}
-+// One action of the prompt: glyph and label, the primary one on a cream pill
++// Every action is this wide (points at a 720-high view), whatever its label and language: the longest of the launcher's six languages
++// ("Abbrechen", "Annuler") fits at full size, and a longer label gets a smaller font, then is cut, so the pills never change width
++#define HQ_ACTION_W 220
++// The font size that fits text into room on one line: size, or smaller down to 70 % of it
++static CGFloat hq_fit(NSString *text, CGFloat size, CGFloat room) {
++ CGFloat w = [text sizeWithAttributes:@{NSFontAttributeName: [NSFont systemFontOfSize:size weight:NSFontWeightSemibold]}].width;
++ if (w <= room) return size;
++ CGFloat s = floor(size * room / w * 10) / 10;
++ return s < size * 0.7 ? size * 0.7 : s;
++}
++// One action of the prompt: glyph and label centred in a pill of a fixed size, the primary one cream
+static NSView *hq_action(NSString *symbol, NSString *fallback, NSString *label, int primary, CGFloat k) {
+ NSColor *fg = primary ? HQ_BACKGROUND : [NSColor colorWithWhite:1 alpha:0.8];
-+ NSStackView *row = [NSStackView stackViewWithViews:@[hq_glyph(symbol, fallback, 24 * k, fg), hq_label(label, 22 * k, NSFontWeightSemibold, fg, 0)]];
-+ row.spacing = 10 * k; row.edgeInsets = NSEdgeInsetsMake(0, 24 * k, 0, 24 * k); row.translatesAutoresizingMaskIntoConstraints = NO;
-+ row.wantsLayer = YES; row.layer.cornerRadius = 28 * k;
-+ if (primary) row.layer.backgroundColor = HQ_CREAM.CGColor;
-+ [row.heightAnchor constraintEqualToConstant:56 * k].active = YES;
-+ return row;
++ CGFloat w = HQ_ACTION_W * k, glyph = 24 * k, gap = 10 * k, inset = 20 * k, room = w - 2 * inset - glyph - gap;
++ NSTextField *t = hq_label(label, hq_fit(label, 22 * k, room), NSFontWeightSemibold, fg, 0);
++ t.lineBreakMode = NSLineBreakByTruncatingTail;
++ [t setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
++ NSStackView *row = [NSStackView stackViewWithViews:@[hq_glyph(symbol, fallback, glyph, fg), t]];
++ row.spacing = gap; row.translatesAutoresizingMaskIntoConstraints = NO;
++ NSView *pill = [NSView new]; pill.translatesAutoresizingMaskIntoConstraints = NO;
++ pill.wantsLayer = YES; pill.layer.cornerRadius = 28 * k;
++ if (primary) pill.layer.backgroundColor = HQ_CREAM.CGColor;
++ [pill addSubview:row];
++ [NSLayoutConstraint activateConstraints:@[[pill.widthAnchor constraintEqualToConstant:w], [pill.heightAnchor constraintEqualToConstant:56 * k],
++ [row.centerXAnchor constraintEqualToAnchor:pill.centerXAnchor], [row.centerYAnchor constraintEqualToAnchor:pill.centerYAnchor],
++ [row.widthAnchor constraintLessThanOrEqualToConstant:w - 2 * inset]]];
++ pill.accessibilityElement = YES; pill.accessibilityRole = NSAccessibilityButtonRole; pill.accessibilityLabel = label;
++ return pill;
+}
+
+// The prompt over the whole view: a dim scrim, and in its middle the card with the title, the note and the two actions (A quits, B cancels).
@@ -571,10 +589,10 @@ index 0000000..c7a84bd
+}
diff --git a/dm/host/tests/t_home_quit_mac.m b/dm/host/tests/t_home_quit_mac.m
new file mode 100644
-index 0000000..2713b98
+index 0000000..6455250
--- /dev/null
+++ b/dm/host/tests/t_home_quit_mac.m
-@@ -0,0 +1,87 @@
+@@ -0,0 +1,107 @@
+// The views of the Home button's quit prompt (home_quit_mac.h), built without a game, a window or a controller: the texts are shown, the card stays inside a small
+// window and a TV-sized one, a long title wraps instead of widening the card, and a glyph the system does not have falls back to the plain letter.
+// DM_HOME_QUIT_CAPTURE=<folder> also draws both views over a stand-in picture into PNG files there (the pull request's screenshots), in an offscreen window.
@@ -640,6 +658,25 @@ index 0000000..2713b98
+ CHECK(card_of(plong).frame.size.width == w720 && NSContainsRect(plong.bounds, card_of(plong).frame), "a long title wraps, the card keeps its width");
+ CHECK(first_image(plong).image.size.width > 0, "a symbol the system does not have falls back to the letter");
+
++ // The two actions keep one width in every language the launcher passes (DM_HOME_QUIT_TEXT: en, zh, de, sv, fr, it), and a label far longer than any
++ // of them shrinks or is cut instead of widening its pill
++ NSArray<NSArray<NSString *> *> *labels = @[@[@"Quit", @"Cancel"], @[@"退出", @"取消"], @[@"Beenden", @"Abbrechen"], @[@"Avsluta", @"Avbryt"],
++ @[@"Quitter", @"Annuler"], @[@"Esci", @"Annulla"], @[@"Quit this game right now please", @"Cancel and go back to the game"]];
++ for (NSValue *size in @[[NSValue valueWithRect:small], [NSValue valueWithRect:tv]]) {
++ NSRect r = size.rectValue; CGFloat want = HQ_ACTION_W * hq_scale(r.size);
++ for (NSArray<NSString *> *l in labels) {
++ NSView *pv = hq_prompt_view(r, @"Quit Hades?", @"n", l[0], l[1], nil, nil);
++ [pv layoutSubtreeIfNeeded];
++ NSStackView *actions = (NSStackView *)((NSStackView *)card_of(pv)).arrangedSubviews.lastObject;
++ CHECK(actions.arrangedSubviews.count == 2, "two actions");
++ for (NSView *a in actions.arrangedSubviews) CHECK(fabs(a.frame.size.width - want) < 0.5 && fabs(a.frame.size.height - 56 * hq_scale(r.size)) < 0.5, l[0].UTF8String);
++ for (NSView *a in actions.arrangedSubviews) {
++ NSStackView *row = (NSStackView *)a.subviews.firstObject;
++ CHECK(NSContainsRect(a.bounds, row.frame), "the glyph and the label stay inside their pill");
++ }
++ }
++ }
++
+ CAShapeLayer *ring = nil;
+ NSView *h = hq_hold_view(small, @"Keep holding to quit", &ring);
+ [h layoutSubtreeIfNeeded];
@@ -657,6 +694,7 @@ index 0000000..2713b98
+ CAShapeLayer *r = nil; NSView *hv = hq_hold_view(tv, @"Keep holding to quit", &r); hq_hold_set(r, 0.6);
+ capture(hv, tv.size, dir, "home-quit-hold.png");
+ capture(hq_prompt_view(tv, @"Super Mario Odyssey beenden?", @"Nicht gesicherter Fortschritt geht verloren.", @"Beenden", @"Abbrechen", @"xmark.circle", @"circle.circle"), tv.size, dir, "home-quit-prompt-de.png");
++ capture(hq_prompt_view(tv, @"退出Super Mario Odyssey?", @"未保存的进度将会丢失。", @"退出", @"取消", @"a.circle", @"b.circle"), tv.size, dir, "home-quit-prompt-zh.png");
+ }
+ }
+ printf("t_home_quit_mac: %d checks, %d failed\n", checks, fails);