Skip to content

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

Launcher: every row control is one line high, tests cover every language and page

v0lumehie46e2cd3738a
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index b4beadf5..50213833 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -3166,7 +3166,6 @@ struct BuilderView: View {
detail: m.gameDir.isEmpty ? m.t("build.folderNote") : m.shortPath(m.gameDir), help: m.gameDir) {
Text(m.t(m.gameDir.isEmpty ? "data.choose" : "data.change"))
.font(.manrope(13, .semibold)).foregroundStyle(.black)
- .padding(.horizontal, 16).padding(.vertical, 8)
.launcherRowControlFrame()
.background(LauncherPalette.cream, in: Capsule())
}
diff --git a/frontend/Sources/NSPortBuilder/LauncherDropdown.swift b/frontend/Sources/NSPortBuilder/LauncherDropdown.swift
index a6e64a96..aac1f224 100644
--- a/frontend/Sources/NSPortBuilder/LauncherDropdown.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherDropdown.swift
@@ -215,7 +215,7 @@ struct LauncherDropdownList: View {
/// The launcher's dropdown: a button with the current choice that opens a list drawn in the app's own style
/// (its dark surface, Manrope, a checkmark on the chosen row). It never cuts the label short unless it is given
-/// `fill` (the width of its container). Inside a setting row it is exactly LauncherControl.width wide, its choice at
+/// `fill` (the width of its container). Inside a setting row it is exactly LauncherControl.width wide and LauncherControl.height high, its choice at
/// the left and the chevron at the right, the choice a little smaller when it does not fit.
/// `label` names the setting for VoiceOver, which then reads the choice as the value.
struct LauncherDropdown: View {
@@ -251,12 +251,13 @@ struct LauncherDropdown: View {
.rotationEffect(.degrees(open ? 180 : 0))
}
.padding(.horizontal, rounded ? 15 : 14).padding(.vertical, rounded ? 9 : 7)
- .frame(width: width)
+ .frame(width: width, height: width == nil ? nil : LauncherControl.height)
.frame(maxWidth: fill ? .infinity : nil)
.background(Color.white.opacity(open ? 0.13 : (rounded ? 0.055 : 0.06)), in: shape)
.overlay(shape.strokeBorder(Color.white.opacity(open ? 0.18 : 0.10)))
.foregroundStyle(Color.white.opacity(0.92))
.contentShape(shape)
+ .launcherMeasured(label: Text(current).font(.manrope(rounded ? 13 : 12.5, .semibold)), room: LauncherControl.choiceWidth)
}
fileprivate func accessible<V: View>(_ view: V) -> some View {
diff --git a/frontend/Sources/NSPortBuilder/LauncherStyles.swift b/frontend/Sources/NSPortBuilder/LauncherStyles.swift
index 8d5e2870..b27596d5 100644
--- a/frontend/Sources/NSPortBuilder/LauncherStyles.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherStyles.swift
@@ -71,6 +71,62 @@ enum LauncherControl {
static let width: CGFloat = 184
/// What the label of a button may take.
static let buttonLabelWidth: CGFloat = width - 2 * 15
+ /// One line of 13 pt Manrope semibold plus 9 pt of padding above and below. A button or dropdown in a row is exactly this
+ /// high, so a label can never make one taller than its neighbours.
+ static let height: CGFloat = 36
+ /// A label that is a little too long shrinks to this share of its size before it is cut.
+ static let minimumLabelScale: CGFloat = 0.85
+ /// The room a dropdown's choice has beside its chevron and the gap to it.
+ static let choiceWidth: CGFloat = buttonLabelWidth - 8 - 10
+}
+
+/// What one button or dropdown in a setting row measured when it was drawn: the width its label wants on a single line, the width
+/// it has, and the size of the whole control. Only collected when `measuresLauncherControls` is set (LauncherControlWidthTests
+/// renders the real pages in every language with it), so the check covers every control a page shows without a list of labels.
+struct LauncherControlSample: Equatable {
+ var labelWidth: CGFloat
+ var room: CGFloat
+ var size: CGSize
+}
+
+struct LauncherControlSamples: PreferenceKey {
+ static var defaultValue: [LauncherControlSample] = []
+ static func reduce(value: inout [LauncherControlSample], nextValue: () -> [LauncherControlSample]) { value += nextValue() }
+}
+
+private struct MeasuresLauncherControlsKey: EnvironmentKey { static let defaultValue = false }
+
+extension EnvironmentValues {
+ var measuresLauncherControls: Bool {
+ get { self[MeasuresLauncherControlsKey.self] }
+ set { self[MeasuresLauncherControlsKey.self] = newValue }
+ }
+}
+
+private struct LauncherControlMeasure<Label: View>: ViewModifier {
+ let label: Label
+ let room: CGFloat
+ @Environment(\.measuresLauncherControls) private var measures
+ @Environment(\.launcherControlWidth) private var width
+ @ViewBuilder func body(content: Content) -> some View {
+ if measures && width != nil {
+ content.background(GeometryReader { box in
+ label.fixedSize().hidden().background(GeometryReader { text in
+ Color.clear.preference(key: LauncherControlSamples.self,
+ value: [LauncherControlSample(labelWidth: text.size.width, room: room, size: box.size)])
+ })
+ })
+ } else {
+ content
+ }
+ }
+}
+
+extension View {
+ /// Reports this control, when it stands in a setting row, and the width its `label` wants (see LauncherControlSample) when a test asks for it.
+ func launcherMeasured<Label: View>(label: Label, room: CGFloat) -> some View {
+ modifier(LauncherControlMeasure(label: label, room: room))
+ }
}
private struct LauncherControlWidthKey: EnvironmentKey { static let defaultValue: CGFloat? = nil }
@@ -87,34 +143,42 @@ extension View {
/// The trailing controls of a setting row: buttons and dropdowns take LauncherControl.width.
func launcherRowControls() -> some View { environment(\.launcherControlWidth, LauncherControl.width) }
- /// This view as wide as a button of a setting row (for a control drawn by hand, like the cream capsule).
+ /// This text as wide and as high as a button of a setting row, on one line (for a control drawn by hand, like the cream capsule).
func launcherRowControlFrame() -> some View { modifier(LauncherRowControlFrame()) }
}
private struct LauncherRowControlFrame: ViewModifier {
@Environment(\.launcherControlWidth) private var width
- func body(content: Content) -> some View { content.frame(width: width) }
+ func body(content: Content) -> some View {
+ content
+ .lineLimit(1).minimumScaleFactor(width == nil ? 1 : LauncherControl.minimumLabelScale)
+ .padding(.horizontal, 15)
+ .frame(width: width, height: width == nil ? nil : LauncherControl.height)
+ .launcherMeasured(label: content, room: LauncherControl.buttonLabelWidth)
+ }
}
struct LauncherSecondaryButtonStyle: ButtonStyle {
/// Text and border in this colour (the build bar's Stop); plain white otherwise.
var accent: Color? = nil
- /// Inside a setting row the button is exactly LauncherControl.width wide, its label centred and wrapped to a second
- /// line when it does not fit: the buttons of a page line up in one column.
+ /// Inside a setting row the button is exactly LauncherControl.width wide and LauncherControl.height high, its label centred on
+ /// one line (a little smaller when it does not fit): the buttons of a page line up in one column and are equally high.
@Environment(\.launcherControlWidth) private var width
@Environment(\.isEnabled) private var enabled
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.manrope(13, .semibold))
.multilineTextAlignment(.center)
- .lineLimit(width == nil ? 1 : 2)
+ .lineLimit(1)
+ .minimumScaleFactor(width == nil ? 1 : LauncherControl.minimumLabelScale)
.padding(.horizontal, 15).padding(.vertical, 9)
- .frame(width: width)
+ .frame(width: width, height: width == nil ? nil : LauncherControl.height)
.background(Color.white.opacity(configuration.isPressed ? 0.13 : 0.055), in: RoundedRectangle(cornerRadius: 9))
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(accent?.opacity(0.75) ?? Color.white.opacity(0.10)))
.foregroundStyle(enabled ? (accent ?? Color.white.opacity(0.92)) : .gray)
.opacity(enabled ? 1 : 0.55)
.contentShape(RoundedRectangle(cornerRadius: 9))
+ .launcherMeasured(label: configuration.label.font(.manrope(13, .semibold)), room: LauncherControl.buttonLabelWidth)
}
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index de02eebe..22354811 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -8,7 +8,7 @@ import Foundation
// cannot drift apart. Additional language overlays use English as an explicit safe fallback while
// they are filled, which lets a new language be added without changing every view first.
-enum Lang: String {
+enum Lang: String, CaseIterable {
case zh, en, sv, de
/// Chinese, Swedish and German devices use their matching catalog; every other device gets English.
@@ -522,20 +522,20 @@ enum L10n {
"repo.manualHint": ("网络不顺也可以手动:打开", "Flaky network? Do it by hand: open"),
"repo.manualHint2": ("→ 点绿色 Code 按钮 → Download ZIP,解压后点「选择仓库…」选中解压出的文件夹",
"→ the green Code button → Download ZIP, unzip, then pick the unzipped folder with Choose repository…"),
- "repo.noGit": ("这是 ZIP 下载的副本(无 git 历史),构建不受影响,点「接入 git」转为可更新",
+ "repo.noGit": ("这是 ZIP 下载的副本(无 git 历史),构建不受影响,点「设为可更新」接入 git",
"This is a ZIP copy (no git history), and builds work fine. Make updatable connects it to git"),
- "repo.adopt": ("接入 git(可更新)", "Make updatable (git)"),
+ "repo.adopt": ("设为可更新", "Make updatable"),
"repo.adopting": ("正在接入 git…", "Connecting git…"),
"repo.adopted": ("已接入 git,可以更新了,原来的文件保存在分支 %@", "Connected — updates work now. Your previous files are kept on branch %@"),
"repo.adoptFail": ("接入失败——详情见日志", "Connect failed — see the log"),
"repo.adoptedAuto": ("打开时已接入 git 并更新到最新版本,原来的文件保存在分支 %@", "Connected to git and updated when the app opened. Your previous files are kept on branch %@"),
- "repo.adoptFailAuto": ("打开时未能接入 git(网络不通?详情见日志)——点「接入 git」重试",
+ "repo.adoptFailAuto": ("打开时未能接入 git(网络不通?详情见日志)——点「设为可更新」重试",
"Could not connect to git when the app opened (offline? see the log) — try Make updatable"),
- "repo.zipWaits": ("构建运行中,暂不接入 git——构建结束后重启 App 或点「接入 git」",
+ "repo.zipWaits": ("构建运行中,暂不接入 git——构建结束后重启 App 或点「设为可更新」",
"A build is running, so the copy is not connected to git yet — restart the app after it, or use Make updatable"),
- "repo.zipNoAuto": ("这是 ZIP 副本,无法自行更新,构建工具可能比 App 旧:点「接入 git」,或打开「打开时自动更新」",
+ "repo.zipNoAuto": ("这是 ZIP 副本,无法自行更新,构建工具可能比 App 旧:点「设为可更新」,或打开「打开时自动更新」",
"This ZIP copy cannot update itself, so its build tools may be older than the app: use Make updatable, or turn on “Update automatically when the app opens”"),
- "repo.toolsOld": ("构建工具比本 App 旧(缺少 %@)——请更新(点「接入 git」或「拉取更新」)",
+ "repo.toolsOld": ("构建工具比本 App 旧(缺少 %@)——请更新(点「设为可更新」或「拉取更新」)",
"The build tools are older than this app (missing %@) — update them (Make updatable or Pull updates)"),
"library.toolsAdopted": ("构建工具已接入 git 并更新", "Build tools connected to git and updated"),
"msg.toolsOld": ("构建工具比本 App 旧(缺少 %@),构建未开始——先在设置 → 构建工具中更新",
@@ -1390,7 +1390,7 @@ enum L10n {
"repo.download": "Hämta förrådet",
"repo.downloadDone": "Förrådet hämtades till %@",
"repo.manualHint": "Instabil anslutning? Gör det manuellt: öppna",
- "repo.adopt": "Gör uppdateringsbart (git)",
+ "repo.adopt": "Gör uppdateringsbart",
"repo.adopting": "Ansluter git …",
"repo.adopted": "Ansluten – uppdateringar fungerar nu. Dina tidigare filer finns kvar på grenen %@",
"repo.adoptFail": "Anslutningen misslyckades – se loggen",
@@ -2235,7 +2235,7 @@ enum L10n {
"repo.manualHint": "Netzwerk instabil? Erledige es von Hand: Öffne",
"repo.manualHint2": "→ die grüne Schaltfläche „Code“ → „Download ZIP“, entpacke es und wähle dann den entpackten Ordner mit „Repository wählen …“",
"repo.noGit": "Dies ist eine ZIP-Kopie (ohne git-Verlauf), und Builds funktionieren damit einwandfrei. „Updatefähig machen“ verbindet sie mit git",
- "repo.adopt": "Updatefähig machen (git)",
+ "repo.adopt": "Updatefähig machen",
"repo.adopting": "git wird verbunden …",
"repo.adopted": "Verbunden. Updates funktionieren jetzt. Deine bisherigen Dateien bleiben im Branch %@ erhalten",
"repo.adoptFail": "Verbinden fehlgeschlagen. Siehe Protokoll",
diff --git a/frontend/Tests/NSPortBuilderTests/LauncherControlWidthTests.swift b/frontend/Tests/NSPortBuilderTests/LauncherControlWidthTests.swift
index 7cd8fe62..0e63a306 100644
--- a/frontend/Tests/NSPortBuilderTests/LauncherControlWidthTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LauncherControlWidthTests.swift
@@ -1,59 +1,225 @@
import CoreText
+import SwiftUI
import XCTest
@testable import NSPortBuilder
-/// The buttons and dropdowns in the setting rows share one width (LauncherControl.width). These measure the labels the
-/// launcher ships in every language against it, in the face and size the controls use.
+/// The buttons and dropdowns in the setting rows share one width and one height (LauncherControl) and show their label on one
+/// line. Nothing here lists labels: the real Settings and Builds pages are drawn in every language the launcher has, and each
+/// control reports what it measured (LauncherControlSample), so a new button, a new string or a new language is checked as soon as
+/// a page shows it.
final class LauncherControlWidthTests: XCTestCase {
- private let languages: [Lang] = [.zh, .en, .sv, .de]
-
- /// The labels of the buttons at the end of a setting row.
- private let buttonKeys = [
- "library.rescan", "library.chooseFolder", "controls.customize", "console.controllersOpen", "settings.setupBtn",
- "app.restartNow", "repo.check", "repo.pull", "repo.adopt", "repo.choose", "repo.download", "dep.recheck", "dep.install",
- "dep.openAppStore", "dep.xcode.fix", "build.setup", "data.choose", "data.change", "install.reveal", "build.showLibrary",
- "diag.copy", "diag.copied",
- ]
-
- /// Longer than one line in some language: they wrap to a second line, which the button has room for.
- private let wrapping: Set<String> = ["repo.adopt"]
-
- /// The names of the dropdown choices in the Settings cards.
- private let choiceKeys = [
- "settings.language.system", "settings.language.zh", "settings.language.en", "settings.language.sv", "settings.language.de",
- ]
-
- private func width(_ text: String) throws -> CGFloat {
- let font = try XCTUnwrap(Typography.manropeFont(size: 13, weight: .semibold))
+ private func width(_ text: String, size: CGFloat = 13) throws -> CGFloat {
+ let font = try XCTUnwrap(Typography.manropeFont(size: size, weight: .semibold))
let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [.font: font]))
return CTLineGetTypographicBounds(line, nil, nil, nil)
}
- func testButtonLabelsFitOnOneLine() throws {
- for key in buttonKeys where !wrapping.contains(key) {
- for lang in languages {
+ // MARK: Languages
+
+ func testThePickerOffersEveryLanguage() {
+ let offered = Set(BuilderView.languageCodes.filter { !$0.isEmpty })
+ XCTAssertEqual(offered, Set(Lang.allCases.map(\.rawValue)), "Settings > Language lists the launcher's languages")
+ }
+
+ func testDropdownChoicesFitBesideTheChevron() throws {
+ for code in BuilderView.languageCodes {
+ let key = "settings.language." + (code.isEmpty ? "system" : code)
+ XCTAssertNotNil(L10n.table[key], key)
+ for lang in Lang.allCases {
let text = L10n.string(key, lang)
- XCTAssertLessThanOrEqual(try width(text), LauncherControl.buttonLabelWidth, "\(lang) \(key): \(text)")
+ XCTAssertLessThanOrEqual(try width(text), LauncherControl.choiceWidth, "\(lang) \(key): \(text)")
}
}
}
- func testTheLongestLabelsFitOnTwoLines() throws {
- for key in buttonKeys {
- for lang in languages {
- let text = L10n.string(key, lang)
- XCTAssertLessThanOrEqual(try width(text), 2 * LauncherControl.buttonLabelWidth - 40, "\(lang) \(key): \(text)")
- }
+ // MARK: Real pages
+
+ private final class Samples { var all: [LauncherControlSample] = [] }
+
+ private struct Scenario {
+ let name: String
+ let page: LauncherPage
+ /// The controls this state must show at least, so that a page that draws nothing cannot pass.
+ let atLeast: Int
+ let set: (BuildModel, GameLibrary, URL) throws -> Void
+ }
+
+ private func makeRepo(_ directory: URL, git: Bool) throws -> String {
+ let repo = directory.appendingPathComponent(git ? "clone" : "zip")
+ let program = repo.appendingPathComponent("dm/tools/nx_extract/Program.cs")
+ try FileManager.default.createDirectory(at: program.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: program)
+ if git { try FileManager.default.createDirectory(at: repo.appendingPathComponent(".git"), withIntermediateDirectories: true) }
+ return repo.path
+ }
+
+ private var scenarios: [Scenario] {
+ let device = AppleDevice(id: "00008150-AAAA", name: "iPhone", model: "iPhone 17 Pro Max", os: "27.0", reachable: true)
+ // The names of devices and teams are the user's own, so the scenarios use short ones: only the launcher's words are measured.
+ let team = SigningTeam(id: "E75GJAP35S", identity: "Apple Development: Mia (ABCDE12345)")
+ let release = AppUpdate.Release(tag: "v9.9.9", url: "https://example.org/app.zip", digest: nil)
+ func missing(_ id: String, action: String = "", command: [String] = []) -> BuildModel.Dep {
+ BuildModel.Dep(id: id, name: "dep.xcode", hint: "dep.xcode.hint", present: false, actionLabel: action, installCmd: command)
}
+ return [
+ Scenario(name: "settings without a repository", page: .settings, atLeast: 4) { m, _, _ in
+ m.repoPath = ""
+ m.appInstallability = .ok
+ },
+ Scenario(name: "settings with a ZIP copy and a library folder", page: .settings, atLeast: 6) { m, library, directory in
+ m.repoPath = try self.makeRepo(directory, git: false)
+ m.appInstallability = .ok
+ m.depsChecked = true
+ m.deps = [BuildModel.Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: [])]
+ library.setFolder(directory)
+ },
+ Scenario(name: "settings with a clone that is behind and an app update", page: .settings, atLeast: 6) { m, _, directory in
+ m.repoPath = try self.makeRepo(directory, git: true)
+ m.repoBehind = 2
+ m.appInstallability = .ok
+ m.appUpdate = release
+ },
+ Scenario(name: "settings with an update ready to restart into", page: .settings, atLeast: 4) { m, _, directory in
+ m.repoPath = try self.makeRepo(directory, git: true)
+ m.appInstallability = .ok
+ m.appStaged = AppUpdate.Staged(release: release, app: directory.appendingPathComponent("NX2Apple.app"))
+ },
+ Scenario(name: "settings with every kind of missing tool", page: .settings, atLeast: 6) { m, _, directory in
+ m.repoPath = try self.makeRepo(directory, git: true)
+ m.depsChecked = true
+ m.deps = [missing("a"), missing("b", command: ["brew", "install", "x"]), missing("c", action: "dep.xcode.fix", command: ["x"])]
+ m.depsExpanded = true
+ },
+ Scenario(name: "builds without a repository", page: .builds, atLeast: 4) { m, _, _ in
+ m.repoPath = ""
+ m.target = "mac-app"
+ },
+ Scenario(name: "builds with files chosen for a Mac app", page: .builds, atLeast: 5) { m, _, directory in
+ m.repoPath = try self.makeRepo(directory, git: true)
+ m.target = "mac-app"
+ m.gameDir = directory.path
+ m.outDir = directory.path
+ m.slots[0].paths = [directory.appendingPathComponent("Hades [0100535012974000].nsp").path]
+ m.slots[1].paths = [directory.appendingPathComponent("Hades update [0100535012974800].nsp").path]
+ },
+ Scenario(name: "builds for an iPhone with a device and a team", page: .builds, atLeast: 6) { m, _, directory in
+ m.repoPath = try self.makeRepo(directory, git: true)
+ m.target = "ios"
+ m.devicesChecked = true
+ m.devices = [device]
+ m.teams = [team]
+ m.installDevice = device.id
+ m.signingTeam = team.id
+ },
+ Scenario(name: "a finished Mac app build", page: .builds, atLeast: 6) { m, _, directory in
+ m.repoPath = try self.makeRepo(directory, git: true)
+ m.target = "mac-app"
+ m.done = true
+ m.macAppPath = directory.appendingPathComponent("Hades.app").path
+ },
+ Scenario(name: "a build installed on an iPhone", page: .builds, atLeast: 6) { m, _, directory in
+ m.repoPath = try self.makeRepo(directory, git: true)
+ m.target = "ios"
+ m.done = true
+ m.devicesChecked = true
+ m.devices = [device]
+ m.installedOn = device.id
+ m.archivePath = directory.appendingPathComponent("romfs").path
+ },
+ Scenario(name: "a finished iPhone build without an install", page: .builds, atLeast: 6) { m, _, directory in
+ m.repoPath = try self.makeRepo(directory, git: true)
+ m.target = "ios"
+ m.done = true
+ m.devicesChecked = true
+ m.ipaPath = directory.appendingPathComponent("Hades.ipa").path
+ m.archivePath = directory.appendingPathComponent("romfs").path
+ },
+ ]
}
- func testDropdownChoicesFitBesideTheChevron() throws {
- let chevron: CGFloat = 8 + 10
- for key in choiceKeys {
- for lang in languages {
- let text = L10n.string(key, lang)
- XCTAssertLessThanOrEqual(try width(text), LauncherControl.buttonLabelWidth - chevron, "\(lang) \(key): \(text)")
+ @MainActor private func measure(_ scenario: Scenario, _ lang: Lang) throws -> [LauncherControlSample] {
+ NSApplication.shared.setActivationPolicy(.accessory)
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("control-width-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = BuildModel()
+ let library = GameLibrary(file: directory.appendingPathComponent("library.json"))
+ try scenario.set(model, library, directory)
+ model.lang = lang
+ let samples = Samples()
+ let view = ContentView(model: model, library: library, initialPage: scenario.page, activeBuildID: nil, performStartupChecks: false,
+ search: nil, olderTools: [], manageOpen: false, padRing: false)
+ .environment(\.measuresLauncherControls, true)
+ .onPreferenceChange(LauncherControlSamples.self) { samples.all = $0 }
+ let host = NSHostingView(rootView: view)
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 2600), styleMask: [.titled], backing: .buffered, defer: false)
+ window.contentView = host
+ window.orderFront(nil)
+ defer { window.orderOut(nil) }
+ RunLoop.main.run(until: Date().addingTimeInterval(0.5))
+ host.layoutSubtreeIfNeeded()
+ return samples.all
+ }
+
+ /// Settings and Builds, in every language: each button and dropdown of a row is LauncherControl.width wide and
+ /// LauncherControl.height high, and its label fits on one line.
+ @MainActor func testEveryRowControlOnTheRealPagesFitsInEveryLanguage() throws {
+ let keys = ["repoPath", "depsExpanded", "buildTarget", "installDevice", "signingTeam", "buildOutputDirectory", "autoUpdateRepo"]
+ let saved = keys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
+ defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
+ for scenario in scenarios {
+ for lang in Lang.allCases {
+ let samples = try measure(scenario, lang)
+ let at = "\(lang), \(scenario.name)"
+ XCTAssertGreaterThanOrEqual(samples.count, scenario.atLeast, "\(at): the page showed fewer controls than expected")
+ for (index, sample) in samples.enumerated() {
+ XCTAssertEqual(sample.size.width, LauncherControl.width, "\(at), control \(index)")
+ XCTAssertEqual(sample.size.height, LauncherControl.height, "\(at), control \(index)")
+ XCTAssertLessThanOrEqual(sample.labelWidth, sample.room,
+ "\(at), control \(index): its label needs \(sample.labelWidth) pt on one line, the control has \(sample.room)")
+ }
}
}
}
+
+ // MARK: The style itself
+
+ private let tooLong = "A label far longer than any button in a setting row could hold on one line"
+
+ @MainActor private func samples<V: View>(of view: V) throws -> [LauncherControlSample] {
+ let samples = Samples()
+ let host = NSHostingView(rootView: view.launcherRowControls().environment(\.measuresLauncherControls, true)
+ .onPreferenceChange(LauncherControlSamples.self) { samples.all = $0 }.frame(width: 400, height: 200))
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 200), styleMask: [.titled], backing: .buffered, defer: false)
+ window.contentView = host
+ window.orderFront(nil)
+ defer { window.orderOut(nil) }
+ RunLoop.main.run(until: Date().addingTimeInterval(0.3))
+ host.layoutSubtreeIfNeeded()
+ return samples.all
+ }
+
+ /// The probe reports a label that does not fit, so the page test above can fail.
+ @MainActor func testTheProbeSeesALabelThatDoesNotFit() throws {
+ let found = try samples(of: Button(tooLong) {}.buttonStyle(LauncherSecondaryButtonStyle()))
+ XCTAssertEqual(found.count, 1)
+ XCTAssertGreaterThan(try XCTUnwrap(found.first).labelWidth, LauncherControl.buttonLabelWidth)
+ }
+
+ /// Whatever the label, a button, a dropdown and the cream capsule are one size, so none can be taller than its neighbours.
+ @MainActor func testAControlNeverGrowsWithItsLabel() throws {
+ let controls: [(String, AnyView)] = [
+ ("button", AnyView(Button(tooLong) {}.buttonStyle(LauncherSecondaryButtonStyle()))),
+ ("short button", AnyView(Button("OK") {}.buttonStyle(LauncherSecondaryButtonStyle()))),
+ ("dropdown", AnyView(LauncherDropdown(options: [("a", tooLong)], selection: "a", style: .button) { _ in })),
+ ("cream button", AnyView(Text(tooLong).font(.manrope(13, .semibold)).launcherRowControlFrame()
+ .background(LauncherPalette.cream, in: Capsule()))),
+ ]
+ for (name, control) in controls {
+ let found = try samples(of: control)
+ let size = try XCTUnwrap(found.first, name).size
+ XCTAssertEqual(size.width, LauncherControl.width, name)
+ XCTAssertEqual(size.height, LauncherControl.height, name)
+ }
+ }
}