Skip to content

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

Record frame times from a game's launch options, and chart them

subyoung4bc4534a428e
diff --git a/frontend/Sources/NSPortBuilder/FrameTimes.swift b/frontend/Sources/NSPortBuilder/FrameTimes.swift
new file mode 100644
index 00000000..0abe9d16
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/FrameTimes.swift
@@ -0,0 +1,104 @@
+import Foundation
+
+// Frame-time recordings from the launcher. The host already writes a timing row per frame when DM_NVN_TSV names a file
+// (dm/gfx/nvn/hle_nvn.c, the rows scripts/bench.py reads); this is that switch for players: on in a game's launch options,
+// Play passes DM_NVN_TSV (with DM_NVN_TSV_CALLS=0, timing rows only) to a new file in <library>/frame-times/<title ID>/,
+// and the launch options sum the recordings up and chart them, so a stutter or a slow place can be seen and reported
+// without the command line. The numbers are counted as bench.py counts them (nearest-rank percentiles).
+
+enum FrameTimes {
+ /// One frame's timing rows: @t_s (seconds from the start), @frame_ms (start to start), @presented_ms (on screen;
+ /// -1 when the frame was never shown), @gpu_ms.
+ struct Frame: Equatable {
+ var number: Int
+ var time: Double
+ var frameMs: Double
+ var presentedMs: Double?
+ var gpuMs: Double?
+ }
+
+ /// The frames of a recording that have a time and a frame time, in frame order; other rows (the call counts, a line
+ /// the host is still writing) are skipped.
+ static func parse(_ text: String) -> [Frame] {
+ var rows: [Int: [String: Double]] = [:]
+ for line in text.split(whereSeparator: \.isNewline) {
+ let c = line.split(separator: "\t", omittingEmptySubsequences: false)
+ guard c.count == 3, c[1].hasPrefix("@"), let n = Int(c[0].trimmingCharacters(in: .whitespaces)),
+ let v = Double(c[2].trimmingCharacters(in: .whitespaces)) else { continue }
+ rows[n, default: [:]][String(c[1])] = v
+ }
+ return rows.keys.sorted().compactMap { n in
+ let r = rows[n]!
+ guard let t = r["@t_s"], let f = r["@frame_ms"] else { return nil }
+ return Frame(number: n, time: t, frameMs: f, presentedMs: r["@presented_ms"], gpuMs: r["@gpu_ms"])
+ }
+ }
+
+ /// Nearest-rank percentile, as scripts/bench.py's pct.
+ static func percentile(_ xs: [Double], _ p: Double) -> Double? {
+ guard !xs.isEmpty else { return nil }
+ let s = xs.sorted()
+ return s[min(s.count - 1, max(0, Int((p / 100 * Double(s.count)).rounded(.up)) - 1))]
+ }
+
+ struct Summary: Equatable {
+ static let hitchMs = 50.0 // a frame this long is felt as a hitch
+ var frames, dropped, hitches: Int
+ var seconds, frameP50, frameP95, frameP99, frameMax: Double
+ var fps: Double { seconds > 0 ? Double(frames) / seconds : 0 }
+
+ init?(_ frames: [Frame]) {
+ let ft = frames.map(\.frameMs).filter { $0 > 0 }
+ guard let first = frames.first, let last = frames.last, !ft.isEmpty else { return nil }
+ self.frames = frames.count
+ dropped = frames.filter { $0.presentedMs == -1 }.count
+ hitches = ft.filter { $0 > Self.hitchMs }.count
+ seconds = last.time - first.time
+ frameP50 = FrameTimes.percentile(ft, 50)!
+ frameP95 = FrameTimes.percentile(ft, 95)!
+ frameP99 = FrameTimes.percentile(ft, 99)!
+ frameMax = ft.max()!
+ }
+ }
+
+ /// What Play passes for a recording: the file, and timing rows only (the call-count rows make the file large).
+ static func environment(recordTo file: URL?) -> [String: String] {
+ guard let file else { return [:] }
+ return ["DM_NVN_TSV": file.path, "DM_NVN_TSV_CALLS": "0"]
+ }
+
+ /// What Play adds for a game whose recording is on (a new file in its folder), whichever way it starts: the desktop
+ /// Play (LauncherView) and console mode (LiveConsoleDriver) both call this. Empty while off, or when the folder cannot be made.
+ static func recordingEnvironment(for game: LibraryGame, library: String) -> [String: String] {
+ guard enabled(titleID: game.titleID) else { return [:] }
+ return environment(recordTo: try? newRecording(in: folder(titleID: game.titleID, library: library)))
+ }
+
+ /// A game's recordings, beside its mods (GameMod.folder).
+ static func folder(titleID: String, library: String) -> URL {
+ let root = library.isEmpty
+ ? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("NS Port Builder")
+ : URL(fileURLWithPath: library)
+ return root.appendingPathComponent("frame-times").appendingPathComponent(titleID)
+ }
+
+ /// The file for a new recording, named by its start time; the folder is made.
+ static func newRecording(in folder: URL, at date: Date = Date()) throws -> URL {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ let f = DateFormatter()
+ f.locale = Locale(identifier: "en_US_POSIX")
+ f.dateFormat = "yyyy-MM-dd HH-mm-ss"
+ return folder.appendingPathComponent(f.string(from: date)).appendingPathExtension("tsv")
+ }
+
+ /// The recordings in a folder, newest first.
+ static func recordings(in folder: URL) -> [URL] {
+ let files = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []
+ return files.filter { $0.pathExtension == "tsv" }.sorted { $0.lastPathComponent > $1.lastPathComponent }
+ }
+
+ static func defaultsKey(titleID: String) -> String { "recordFrameTimes." + titleID }
+ /// Off unless switched on for the game.
+ static func enabled(titleID: String) -> Bool { UserDefaults.standard.bool(forKey: defaultsKey(titleID: titleID)) }
+ static func setEnabled(_ on: Bool, titleID: String) { UserDefaults.standard.set(on, forKey: defaultsKey(titleID: titleID)) }
+}
diff --git a/frontend/Sources/NSPortBuilder/FrameTimesView.swift b/frontend/Sources/NSPortBuilder/FrameTimesView.swift
new file mode 100644
index 00000000..a89dd29c
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/FrameTimesView.swift
@@ -0,0 +1,48 @@
+import Charts
+import SwiftUI
+
+/// One recording (FrameTimes.swift): its numbers in a line and its frame times over the session, the hitches marked.
+struct FrameTimesRecordingView: View {
+ let file: URL
+ let t: (String) -> String
+ @State private var frames: [FrameTimes.Frame] = []
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack {
+ Text(file.deletingPathExtension().lastPathComponent).font(.manrope(13, .medium))
+ Spacer()
+ }
+ if let s = FrameTimes.Summary(frames) {
+ Text(String(format: t("launch.frameTimesSummary"), s.frames, s.fps, s.frameP50, s.frameP99, s.frameMax, s.hitches, s.dropped))
+ .font(.manrope(12)).foregroundStyle(.secondary).monospacedDigit()
+ Chart {
+ ForEach(thinned, id: \.number) { f in
+ LineMark(x: .value("s", f.time), y: .value("ms", f.frameMs)).interpolationMethod(.linear)
+ }
+ ForEach(frames.filter { $0.frameMs > FrameTimes.Summary.hitchMs }, id: \.number) { f in
+ PointMark(x: .value("s", f.time), y: .value("ms", f.frameMs)).foregroundStyle(.red).symbolSize(14)
+ }
+ RuleMark(y: .value("ms", s.frameP50)).foregroundStyle(.secondary.opacity(0.5)).lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 3]))
+ }
+ .chartXScale(domain: (frames.first?.time ?? 0)...max((frames.last?.time ?? 1), (frames.first?.time ?? 0) + 1))
+ .chartXAxisLabel("s").chartYAxisLabel("ms")
+ .frame(height: 120)
+ } else {
+ Text(t("launch.frameTimesEmpty")).font(.manrope(12)).foregroundStyle(.secondary)
+ }
+ }
+ .padding(.horizontal, 18).padding(.vertical, 12)
+ .task(id: file) { frames = FrameTimes.parse((try? String(contentsOf: file, encoding: .utf8)) ?? "") }
+ }
+
+ /// At most about 2,000 points on the line (a long session has hundreds of thousands of frames): every n-th frame,
+ /// each one the slowest of its stretch, so a hitch is never thinned away.
+ private var thinned: [FrameTimes.Frame] {
+ let step = max(1, frames.count / 2000)
+ guard step > 1 else { return frames }
+ return stride(from: 0, to: frames.count, by: step).map { i in
+ frames[i..<min(frames.count, i + step)].max { $0.frameMs < $1.frameMs }!
+ }
+ }
+}
diff --git a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift
index 0b8d37de..38cb5f1f 100644
--- a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift
+++ b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift
@@ -13,6 +13,7 @@ struct LaunchOptionsView: View {
@State private var advancedOpen = false
@State private var choicesRevision = 0 // bumped by a change: the values are read from the store again
@State private var modsRevision = 0 // bumped by Refresh: the folder is read again
+ @State private var frameTimesRevision = 0 // bumped by the switch and Refresh: the recordings are read again
@EnvironmentObject private var focus: PadFocus
private var game: LibraryGame? { library.games.first { $0.id == gameID } }
@@ -49,6 +50,7 @@ struct LaunchOptionsView: View {
VStack(alignment: .leading, spacing: 24) {
groups(settings.filter(\.isBasic), game, all: settings)
modsSection(game)
+ frameTimesSection(game)
let advanced = settings.filter { !$0.isBasic }
if !advanced.isEmpty {
card {
@@ -283,6 +285,56 @@ struct LaunchOptionsView: View {
}
}
+ // ---- frame times ----
+
+ /// Recording frame times (FrameTimes.swift): the switch for the next Play, and the last recordings with their numbers.
+ @ViewBuilder private func frameTimesSection(_ game: LibraryGame) -> some View {
+ let _ = frameTimesRevision
+ let folder = FrameTimes.folder(titleID: game.titleID, library: library.folder)
+ let recent = Array(FrameTimes.recordings(in: folder).prefix(3))
+ let on = Binding(get: { _ = frameTimesRevision; return FrameTimes.enabled(titleID: game.titleID) },
+ set: { FrameTimes.setEnabled($0, titleID: game.titleID); frameTimesRevision += 1 })
+ VStack(alignment: .leading, spacing: 10) {
+ heading(m.t("launch.frameTimes"))
+ card {
+ HStack(spacing: 16) {
+ Text(m.t("launch.frameTimesRecord")).font(.manrope(14, .medium))
+ Spacer(minLength: 12)
+ Toggle("", isOn: on).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ }
+ .padding(.horizontal, 18).padding(.vertical, 13).frame(minHeight: 52)
+ .padTarget("frameTimes.record", scope: "launch", radius: 10,
+ activate: { on.wrappedValue.toggle() }, adjust: { _ in on.wrappedValue.toggle() })
+ divider
+ if recent.isEmpty {
+ Text(m.t("launch.frameTimesNone")).font(.manrope(13)).foregroundStyle(.secondary)
+ .padding(.horizontal, 18).padding(.vertical, 12)
+ divider
+ }
+ ForEach(recent, id: \.self) { file in
+ FrameTimesRecordingView(file: file, t: m.t)
+ divider
+ }
+ HStack(spacing: 10) {
+ Spacer()
+ Button(m.t("launch.modsRefresh")) { frameTimesRevision += 1 }
+ .padTarget("frameTimes.refresh", scope: "launch") { frameTimesRevision += 1 }
+ Button(m.t("launch.frameTimesOpen")) { openFolder(folder) }
+ .padTarget("frameTimes.open", scope: "launch") { openFolder(folder) }
+ }
+ .buttonStyle(LauncherSecondaryButtonStyle())
+ .padding(.horizontal, 18).padding(.vertical, 12)
+ }
+ Text(m.t("launch.frameTimesNote")).font(.manrope(12)).foregroundStyle(.secondary)
+ .padding(.leading, 2).fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ private func openFolder(_ folder: URL) {
+ try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ NSWorkspace.shared.open(folder)
+ }
+
private func openModsFolder() {
guard let folder = modsFolder else { return }
try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 4a3c3227..107458e9 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -805,7 +805,8 @@ struct ContentView: View {
// The keyboard and controller layout (Settings → Controls) goes to every game; a build whose host does not read it plays with the default keys.
// They stay launch overrides (the environment) for now: DM_KEYMAP and DM_PAD_MAP become saved choices only when seedds/nxnative#386 merges.
let environment = GameStart.environment(for: game, library: library, controls: controls, repo: m.repoPath, labels: m.t) // GameStart.swift: the console mode starts games with the same
- if !environment.isEmpty { configuration.environment = environment }
+ let withRecording = environment.merging(FrameTimes.recordingEnvironment(for: game, library: library.folder)) { $1 } // FrameTimes.swift, as console mode does
+ if !withRecording.isEmpty { configuration.environment = withRecording }
NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: game.appPath), configuration: configuration) { _, error in
DispatchQueue.main.async {
launching = false
diff --git a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
index 5801699a..546e22ab 100644
--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift
@@ -222,6 +222,7 @@ struct ConsolePadSnapshot: Equatable {
state.play(gameID)
guard state.startingGameID == gameID, let game = library.games.first(where: { $0.id.uuidString == gameID }) else { return }
let environment = GameStart.environment(for: game, library: library, controls: controls, repo: repo(), labels: labels)
+ .merging(FrameTimes.recordingEnvironment(for: game, library: library.folder)) { $1 } // a frame-time recording, as the desktop Play adds (FrameTimes.swift)
state.starting = .preparing
launch(game, environment) { [weak self] pid, error in
DispatchQueue.main.async {
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 7530c640..473ce409 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -626,6 +626,13 @@ enum L10n {
"onboarding.error.xcode": ("Xcode 设置未能完成。", "Xcode setup could not finish."),
"onboarding.error.metal": ("Metal 工具链未能下载。请检查网络后重试。", "The Metal Toolchain could not be downloaded. Check your connection and try again."),
"onboarding.error.ios": ("iOS 平台未能下载。请检查网络和磁盘空间后重试。", "The iOS platform could not be downloaded. Check your connection and disk space, then try again."),
+ "launch.frameTimes": ("帧时间", "Frame times"),
+ "launch.frameTimesRecord": ("录制帧时间", "Record frame times"),
+ "launch.frameTimesNote": ("开着时每次 Play 都记一份:每帧一行,帧时间、上屏时间和 GPU 时间,用来找卡顿和慢的地方。关着时不记录。", "While on, every Play writes one: a row per frame with its frame time, time on screen and GPU time, to find stutters and slow places. Nothing is recorded while off."),
+ "launch.frameTimesNone": ("还没有记录", "No recordings yet"),
+ "launch.frameTimesEmpty": ("这份记录还没有帧(游戏刚开始,或没有画面)", "No frames in this recording yet (the game just started, or showed nothing)"),
+ "launch.frameTimesOpen": ("打开文件夹", "Open folder"),
+ "launch.frameTimesSummary": ("%d 帧 · %.0f fps · 中位 %.1f ms · 99%% %.1f ms · 最慢 %.0f ms · 卡顿 %d · 丢帧 %d", "%d frames · %.0f fps · median %.1f ms · 99%% %.1f ms · slowest %.0f ms · hitches %d · dropped %d"),
"settings.notify": ("构建完成时通知", "Notify when a build ends"),
"settings.notifyNote": ("仅在 NX2Apple 不在前台时,构建完成或失败都会通知", "When a build finishes or fails while NX2Apple is in the background"),
"settings.notifyUnbundled": ("需要 NX2Apple.app:用 swift run 启动时没有通知", "Needs NX2Apple.app: no notifications when started with swift run"),
@@ -1023,6 +1030,13 @@ enum L10n {
"settings.language.zh": "Kinesiska",
"settings.language.en": "English",
"settings.language.sv": "Svenska",
+ "launch.frameTimes": "Bildtider",
+ "launch.frameTimesRecord": "Spela in bildtider",
+ "launch.frameTimesNote": "När det är på sparas en inspelning för varje Spela: en rad per bildruta med dess bildtid, tid på skärmen och GPU-tid, för att hitta hack och långsamma ställen. Inget spelas in när det är av.",
+ "launch.frameTimesNone": "Inga inspelningar ännu",
+ "launch.frameTimesEmpty": "Inga bildrutor i den här inspelningen ännu (spelet har just startat eller visade ingenting)",
+ "launch.frameTimesOpen": "Öppna mapp",
+ "launch.frameTimesSummary": "%d bildrutor · %.0f fps · median %.1f ms · 99 %% %.1f ms · långsammast %.0f ms · hack %d · tappade %d",
"settings.heading": "Inställningar",
"onboarding.welcome.title": "Välkommen.",
"onboarding.welcome.note": "Spela dina Switch-spel direkt på din Mac på ungefär 15 minuter.",
diff --git a/frontend/Tests/NSPortBuilderTests/FrameTimesTests.swift b/frontend/Tests/NSPortBuilderTests/FrameTimesTests.swift
new file mode 100644
index 00000000..e30a9b39
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/FrameTimesTests.swift
@@ -0,0 +1,178 @@
+import XCTest
+import SwiftUI
+@testable import NSPortBuilder
+
+/// Frame-time recordings (DM_NVN_TSV): reading the host's timing rows and summing them up as scripts/bench.py does.
+final class FrameTimesTests: XCTestCase {
+ /// Rows as the host writes them (dm/gfx/nvn/hle_nvn.c): frame, @metric, value; call-count rows and junk in between.
+ private let tsv = """
+ 1\t@t_s\t0.000
+ 1\t@frame_ms\t16.6
+ 1\t@presented_ms\t16.7
+ 1\t@gpu_ms\t4.0
+ 1\tnvnQueueSubmitCommands\t3
+ 2\t@t_s\t0.017
+ 2\t@frame_ms\t16.8
+ 2\t@presented_ms\t-1
+ 2\t@gpu_ms\t4.2
+ 3\t@t_s\t0.100
+ 3\t@frame_ms\t83.0
+ 3\t@presented_ms\t83.3
+ 3\t@gpu_ms\t30.0
+ not a row
+ 4\t@t_s\t0.117
+ 4\t@frame_ms\t16.7
+ 4\t@presented_ms\t16.6
+ 5\t@t_s
+ """
+
+ func testReadsTheTimingRowsInFrameOrder() {
+ let frames = FrameTimes.parse(tsv)
+ XCTAssertEqual(frames.map(\.number), [1, 2, 3, 4])
+ XCTAssertEqual(frames[2], FrameTimes.Frame(number: 3, time: 0.100, frameMs: 83.0, presentedMs: 83.3, gpuMs: 30.0))
+ XCTAssertNil(frames[3].gpuMs, "a frame without a GPU row")
+ XCTAssertTrue(FrameTimes.parse("").isEmpty)
+ }
+
+ func testTheSummaryCountsLikeBenchPy() throws {
+ let s = try XCTUnwrap(FrameTimes.Summary(FrameTimes.parse(tsv)))
+ XCTAssertEqual(s.frames, 4)
+ XCTAssertEqual(s.dropped, 1, "@presented_ms -1 is a frame never shown")
+ XCTAssertEqual(s.frameP50, 16.7, accuracy: 0.001) // nearest rank: sorted 16.6 16.7 16.8 83.0
+ XCTAssertEqual(s.frameP95, 83.0, accuracy: 0.001)
+ XCTAssertEqual(s.frameMax, 83.0, accuracy: 0.001)
+ XCTAssertEqual(s.hitches, 1, "frames over 50 ms")
+ XCTAssertEqual(s.seconds, 0.117, accuracy: 0.001)
+ XCTAssertNil(FrameTimes.Summary([]))
+ }
+
+ func testNearestRankPercentile() {
+ XCTAssertEqual(FrameTimes.percentile([5, 1, 3, 2, 4], 50), 3)
+ XCTAssertEqual(FrameTimes.percentile([5, 1, 3, 2, 4], 99), 5)
+ XCTAssertEqual(FrameTimes.percentile([7], 1), 7)
+ XCTAssertNil(FrameTimes.percentile([], 50))
+ }
+
+ func testTheEnvironmentAsksForTimingRowsOnly() {
+ let file = URL(fileURLWithPath: "/tmp/lib/frame-times/0100A/2026-10-28 03-30-00.tsv")
+ XCTAssertEqual(FrameTimes.environment(recordTo: file), ["DM_NVN_TSV": file.path, "DM_NVN_TSV_CALLS": "0"])
+ XCTAssertEqual(FrameTimes.environment(recordTo: nil), [:])
+ }
+
+ func testRecordingsLiveBesideTheModsAndAreListedNewestFirst() throws {
+ let lib = FileManager.default.temporaryDirectory.appendingPathComponent("ft-\(UUID().uuidString)")
+ let folder = FrameTimes.folder(titleID: "010015100B514000", library: lib.path)
+ XCTAssertEqual(folder.path, lib.appendingPathComponent("frame-times/010015100B514000").path)
+ let a = try FrameTimes.newRecording(in: folder, at: Date(timeIntervalSince1970: 1_800_000_000))
+ let b = try FrameTimes.newRecording(in: folder, at: Date(timeIntervalSince1970: 1_800_000_100))
+ XCTAssertEqual(a.pathExtension, "tsv")
+ for f in [a, b] { try Data("1\t@t_s\t0\n".utf8).write(to: f) }
+ XCTAssertEqual(FrameTimes.recordings(in: folder).map(\.lastPathComponent), [b.lastPathComponent, a.lastPathComponent])
+ XCTAssertTrue(FrameTimes.recordings(in: lib.appendingPathComponent("none")).isEmpty)
+ }
+
+ func testRecordingIsOffUntilSwitchedOnPerGame() {
+ let key = FrameTimes.defaultsKey(titleID: "0100TEST")
+ let saved = UserDefaults.standard.object(forKey: key)
+ defer { UserDefaults.standard.set(saved, forKey: key) }
+ UserDefaults.standard.removeObject(forKey: key)
+ XCTAssertFalse(FrameTimes.enabled(titleID: "0100TEST"))
+ FrameTimes.setEnabled(true, titleID: "0100TEST")
+ XCTAssertTrue(FrameTimes.enabled(titleID: "0100TEST"))
+ XCTAssertFalse(FrameTimes.enabled(titleID: "0100OTHER"))
+ }
+
+ func testTheStringsAreInEveryLanguage() {
+ for key in ["launch.frameTimes", "launch.frameTimesRecord", "launch.frameTimesNote", "launch.frameTimesNone",
+ "launch.frameTimesEmpty", "launch.frameTimesOpen", "launch.frameTimesSummary"] {
+ XCTAssertNotEqual(L10n.string(key, .en), key, key)
+ XCTAssertNotEqual(L10n.string(key, .zh), key, key)
+ XCTAssertNotEqual(L10n.string(key, .sv), L10n.string(key, .en), "\(key): a Swedish entry, not the English fallback")
+ }
+ XCTAssertEqual(String(format: L10n.string("launch.frameTimesSummary", .sv), 10, 60.0, 16.7, 20.0, 50.0, 1, 0).contains("10 bildrutor"), true)
+ }
+
+ /// The desktop Play and console mode add the same recording: nothing while off, a new file in the game's folder while on.
+ func testBothWaysOfStartingAGameRecordTheSame() throws {
+ let lib = FileManager.default.temporaryDirectory.appendingPathComponent("frametimes-start-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: lib) }
+ let game = LibraryGame(titleID: "0100TESTSTART", name: "Demo")
+ let key = FrameTimes.defaultsKey(titleID: game.titleID)
+ let saved = UserDefaults.standard.object(forKey: key)
+ defer { UserDefaults.standard.set(saved, forKey: key) }
+ FrameTimes.setEnabled(false, titleID: game.titleID)
+ XCTAssertEqual(FrameTimes.recordingEnvironment(for: game, library: lib.path), [:])
+ FrameTimes.setEnabled(true, titleID: game.titleID)
+ let env = FrameTimes.recordingEnvironment(for: game, library: lib.path)
+ let file = try XCTUnwrap(env["DM_NVN_TSV"])
+ XCTAssertEqual(env["DM_NVN_TSV_CALLS"], "0")
+ XCTAssertTrue(file.hasPrefix(FrameTimes.folder(titleID: game.titleID, library: lib.path).path), file)
+ XCTAssertTrue(FileManager.default.fileExists(atPath: FrameTimes.folder(titleID: game.titleID, library: lib.path).path), "the folder is made")
+ }
+
+ /// The launch options with the Frame times section and two recordings, for visual QA (NX_LAUNCHER_CAPTURE_DIR).
+ func testCaptureLaunchOptionsWithFrameTimes() 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)
+ NSApplication.shared.setActivationPolicy(.accessory)
+ let temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-frametimes-" + UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: temporary) }
+ let titleID = "010015100B514000"
+ let app = temporary.appendingPathComponent("Game.app")
+ let dm = app.appendingPathComponent("Contents/Resources/dm")
+ try FileManager.default.createDirectory(at: dm, withIntermediateDirectories: true)
+ let fps = #"{"env": "DM_FPS_TARGET", "kind": "choice", "label": "Frame rate", "note": "", "default": "60", "section": "Game", "options": [["30", "30"], ["60", "60"]]}"#
+ try #"{"game": "\#(titleID)", "settings": [\#(fps)]}"#.write(to: dm.appendingPathComponent("launcher.json"), atomically: true, encoding: .utf8)
+ let libraryFolder = temporary.appendingPathComponent("Library")
+ let folder = FrameTimes.folder(titleID: titleID, library: libraryFolder.path)
+ for (i, start) in [1_800_000_000.0, 1_800_000_600.0].enumerated() {
+ var rows = ""
+ var t = 0.0
+ for n in 1...3600 { // a minute at 60 fps, a hitch every ten seconds, the second run slower
+ let ms = n % 600 == 0 ? 95.0 : (i == 0 ? 16.7 : 21.0) + Double(n % 7) * 0.3
+ rows += "\(n)\t@t_s\t\(t)\n\(n)\t@frame_ms\t\(ms)\n\(n)\t@presented_ms\t\(ms)\n"
+ t += ms / 1000
+ }
+ try rows.write(to: try FrameTimes.newRecording(in: folder, at: Date(timeIntervalSince1970: start)), atomically: true, encoding: .utf8)
+ }
+ var game = LibraryGame(titleID: titleID, name: "Super Mario Bros. Wonder")
+ game.appPath = app.path
+ struct Snapshot: Codable { let games: [LibraryGame]; let folder: String }
+ let file = temporary.appendingPathComponent("library.json")
+ try JSONEncoder().encode(Snapshot(games: [game], folder: libraryFolder.path)).write(to: file)
+ let library = GameLibrary(file: file)
+ XCTAssertEqual(library.games.count, 1)
+ let key = FrameTimes.defaultsKey(titleID: titleID)
+ let saved = UserDefaults.standard.object(forKey: key)
+ defer { UserDefaults.standard.set(saved, forKey: key) }
+ FrameTimes.setEnabled(true, titleID: titleID)
+ let model = BuildModel()
+ model.lang = .en
+ let host = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: library.games[0].id).environmentObject(PadFocus()))
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 900, height: 1300), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
+ window.contentView = host
+ window.orderFront(nil)
+ RunLoop.main.run(until: Date().addingTimeInterval(1.0))
+ 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("launch-options-frame-times.png"))
+ window.orderOut(nil)
+ // The section's rows below the fold: the two recordings as the sheet draws them
+ let rows = NSHostingView(rootView: VStack(spacing: 0) {
+ ForEach(FrameTimes.recordings(in: folder), id: \.self) { FrameTimesRecordingView(file: $0, t: model.t) }
+ }.frame(width: 760).background(Color(white: 0.09)))
+ let rowsWindow = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 760, height: 520), styleMask: [.titled], backing: .buffered, defer: false)
+ rowsWindow.contentView = rows
+ rowsWindow.orderFront(nil)
+ RunLoop.main.run(until: Date().addingTimeInterval(1.0))
+ rowsWindow.setContentSize(rows.fittingSize)
+ RunLoop.main.run(until: Date().addingTimeInterval(0.3))
+ rows.layoutSubtreeIfNeeded()
+ let rowsRep = try XCTUnwrap(rows.bitmapImageRepForCachingDisplay(in: rows.bounds))
+ rows.cacheDisplay(in: rows.bounds, to: rowsRep)
+ try XCTUnwrap(rowsRep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("launch-options-frame-times-rows.png"))
+ rowsWindow.orderOut(nil)
+ }
+}