Skip to content

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

Launcher: Copy diagnostics with fork patches, Xcode, Metal and SDK, and Manage > Show game log

v0lumehi5a9a2365f5fd
diff --git a/frontend/README.md b/frontend/README.md
index de48c966..3e417582 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -41,7 +41,10 @@ the app.
bug report. It holds the app and macOS versions and the chip, the repository (its commit and
branch and how far it is behind `upstream/main` and `origin/main` as of the last fetch, since
nothing is fetched), the Python and .NET the builds run with and the dependency
-check, and this session's last build command and the last 50 lines of its log. The home
+check, the fork patches in the checkout (`dm/fork_patches.txt`), the selected Xcode and its
+version, both Metal compilers beside the versions `dm/gfx/tools/dmsh_chain.lock` pins, the iOS SDK,
+and this session's last build command and the last 50 lines of its log. For the selected
+game it adds its built app's patches and the last 200 lines of its log. The home
folder is shown as `~`, a log line holding key material (`name = <hex>`, as in
`prod.keys`) keeps only its name, and no environment variables are included.
@@ -80,6 +83,10 @@ unsigned IPA as before. The devices and teams are read with `devicectl list
devices` and `security find-identity`. The team is the certificate's
organizational unit, not the code in its name.
+**Manage > Show game log** opens the game's latest log in Console. It is `<library folder>/log/<title ID>.log`
+when the app's folder holds the library marker (`.nx2apple-library`), else
+`~/Library/Logs/nxnative/<title ID>.log` (`dm/mac/launcher.c`), and the row is off with a tooltip until the game has run.
+
## Saves
**Manage > Saves…** (a controller's Y) shows a game's save on this Mac
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index e41360fc..ffa20448 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -3022,7 +3022,7 @@ struct BuilderView: View {
}
}
divider
- row(m.t("diag.title"), detail: m.t("diag.note")) { DiagnosticsButton(m: m, width: Self.settingsButtonWidth) }
+ row(m.t("diag.title"), detail: m.t("diag.note")) { DiagnosticsButton(m: m, game: library.selected, width: Self.settingsButtonWidth) }
}
}
diff --git a/frontend/Sources/NSPortBuilder/Diagnostics.swift b/frontend/Sources/NSPortBuilder/Diagnostics.swift
index 40d44cc6..d4927395 100644
--- a/frontend/Sources/NSPortBuilder/Diagnostics.swift
+++ b/frontend/Sources/NSPortBuilder/Diagnostics.swift
@@ -27,11 +27,34 @@ struct Diagnostics {
var dotnetVersion: String?
var depsChecked = true
var deps: [Dependency] = []
+ var forkPatches: [String]? // dm/fork_patches.txt of the checkout; nil when the file is not there
+ var toolchain = Toolchain()
+ var game: GameInfo? // the library's selected game
var lastCommand: [String] = [] // the last build's, this session
var log = "" // the build log the Builds page shows
var home = NSHomeDirectory()
}
+ /// What Xcode and its compilers say, for the build-problem form. A nil is a tool that did not answer.
+ struct Toolchain: Equatable {
+ var xcodePath: String?
+ var xcodeVersion: String?
+ var metalMac: String?
+ var metalIOS: String?
+ var metalPinMac: String? // dm/gfx/tools/dmsh_chain.lock
+ var metalPinIOS: String?
+ var iosSDK: String?
+ }
+
+ /// The selected game, for the game-problem form: what its app was built with and the end of its log.
+ struct GameInfo: Equatable {
+ var name: String
+ var titleID: String
+ var builtForkPatches: String? // DMForkPatches of the built Mac app; nil when the app has none
+ var logPath: String? // nil: the game was never run
+ var log: [String] = []
+ }
+
static let logLines = 50
static func report(_ i: Inputs) -> String {
@@ -60,6 +83,12 @@ struct Diagnostics {
out.append("- Dependencies: " + (missing.isEmpty ? "all present" : "\(missing.count) missing"))
for d in i.deps { out.append(" - \(d.present ? "ok" : "MISSING") \(d.name)" + (d.detail.isEmpty ? "" : ": \(d.detail)")) }
}
+ out.append("- Fork patches: " + patches(i.forkPatches))
+ let t = i.toolchain
+ out.append("- Xcode: " + (t.xcodePath ?? "not found") + parenthesized([t.xcodeVersion]))
+ out.append("- Metal compiler (macOS): " + metal(t.metalMac, pin: t.metalPinMac))
+ out.append("- Metal compiler (iOS): " + metal(t.metalIOS, pin: t.metalPinIOS))
+ out.append("- iOS SDK: " + (t.iosSDK ?? "not installed"))
out.append("")
out.append("#### Last build")
out.append("")
@@ -79,9 +108,44 @@ struct Diagnostics {
out += tail.map(redact)
out.append("````")
}
+ if let g = i.game {
+ out.append("")
+ out.append("#### Selected game")
+ out.append("")
+ out.append("- Game: \(g.name) (\(g.titleID))")
+ out.append("- Fork patches of the built app: " + (g.builtForkPatches.map { $0.isEmpty ? "none" : $0.replacingOccurrences(of: ",", with: ", ") } ?? "no Mac app built"))
+ if g.logPath == nil {
+ out.append("- Game log: none yet, the game was not run")
+ } else {
+ out.append("- Game log: \(g.logPath ?? "")")
+ let lines = tailOf(g.log, GameLog.lines)
+ if !lines.isEmpty {
+ out.append("")
+ out.append("Last \(lines.count) game log lines:")
+ out.append("")
+ out.append("````text")
+ out += lines.map(redact)
+ out.append("````")
+ }
+ }
+ }
return shortenHome(out.joined(separator: "\n") + "\n", home: i.home)
}
+ private static func tailOf(_ lines: [String], _ n: Int) -> [String] { Array(lines.suffix(n)) }
+
+ private static func patches(_ list: [String]?) -> String {
+ guard let list else { return "not found" }
+ return list.isEmpty ? "none" : list.joined(separator: ", ")
+ }
+
+ /// A compiler's version beside the one the translation chain was built with.
+ private static func metal(_ found: String?, pin: String?) -> String {
+ guard let found else { return "not installed" + (pin.map { " (pin: \($0))" } ?? "") }
+ guard let pin else { return found }
+ return found + (found == pin ? " (matches the pin)" : " (pin: \(pin))")
+ }
+
/// The home folder as ~ wherever it starts a path, and only there: /Users/jo becomes ~, /Users/joanna stays.
static func shortenHome(_ text: String, home: String) -> String {
let home = home.hasSuffix("/") ? String(home.dropLast()) : home
@@ -165,6 +229,55 @@ struct Diagnostics {
return (commit, branch, behind, fetched)
}
+ /// The checkout's fork patch names, one per line (dm/fork_patches.txt), blanks left out, as pack_app.py reads them.
+ static func patchList(_ text: String) -> [String] {
+ text.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
+ }
+
+ /// The Metal compiler versions the chain was built with: `metal_macosx` and `metal_iphoneos` of dmsh_chain.lock (tab-separated).
+ static func chainPins(_ lock: String) -> (mac: String?, ios: String?) {
+ var pins: [String: String] = [:]
+ for line in lock.split(separator: "\n") where !line.hasPrefix("#") {
+ let parts = line.split(separator: "\t", maxSplits: 1).map(String.init)
+ if parts.count == 2 { pins[parts[0]] = parts[1].trimmingCharacters(in: .whitespaces) }
+ }
+ return (pins["metal_macosx"], pins["metal_iphoneos"])
+ }
+
+ /// A command's output when it exits 0, trimmed; nil when it fails or prints nothing. The tests stand in for BuildModel.runQuiet.
+ typealias Probe = (_ args: [String]) -> String?
+
+ static func probe(env: [String: String] = ["HOME": NSHomeDirectory(), "PATH": "/usr/bin:/bin", "TMPDIR": NSTemporaryDirectory()]) -> Probe {
+ { args in
+ guard FileManager.default.isExecutableFile(atPath: args[0]) else { return nil }
+ let r = BuildModel.runQuiet(args, env: env)
+ let s = r.out.trimmingCharacters(in: .whitespacesAndNewlines)
+ return r.ok && !s.isEmpty ? s : nil
+ }
+ }
+
+ /// Xcode's path and version, both Metal compilers and the iOS SDK, by the same tools the dependency check runs. Only the
+ /// first line of a compiler's answer is kept: the rest names the toolchain's folder.
+ static func toolchain(xcrun: String = "/usr/bin/xcrun", pins: (mac: String?, ios: String?) = (nil, nil), run: Probe) -> Toolchain {
+ func first(_ s: String?) -> String? { s?.split(separator: "\n").first.map(String.init) }
+ return Toolchain(
+ xcodePath: first(run(["/usr/bin/xcode-select", "-p"])),
+ xcodeVersion: run(["/usr/bin/xcodebuild", "-version"]).map { $0.split(separator: "\n").map(String.init).joined(separator: ", ") },
+ metalMac: first(run([xcrun, "-sdk", "macosx", "metal", "--version"])),
+ metalIOS: first(run([xcrun, "-sdk", "iphoneos", "metal", "--version"])),
+ metalPinMac: pins.mac, metalPinIOS: pins.ios,
+ iosSDK: first(run([xcrun, "--sdk", "iphoneos", "--show-sdk-version"])))
+ }
+
+ /// The selected game's section: the built app's DMForkPatches and the end of its latest log.
+ static func gameInfo(_ game: LibraryGame, home: String = NSHomeDirectory(), lines: Int = GameLog.lines) -> GameInfo {
+ let info = NSDictionary(contentsOfFile: game.appPath + "/Contents/Info.plist")
+ let log = GameLog.latest(titleID: game.titleID, appPath: game.appPath, home: home)
+ return GameInfo(name: game.name, titleID: game.titleID,
+ builtForkPatches: info.map { ($0["DMForkPatches"] as? String) ?? "" },
+ logPath: log?.path, log: log.flatMap { GameLog.tail($0, lines: lines) } ?? [])
+ }
+
/// What a tool prints for its version, nil when it does not run.
static func version(_ tool: String, _ args: [String], env: [String: String]) -> String? {
guard FileManager.default.isExecutableFile(atPath: tool) else { return nil }
@@ -176,15 +289,17 @@ struct Diagnostics {
extension BuildModel {
/// The report, read in the background and handed back on the main thread.
- func diagnostics(_ done: @escaping (String) -> Void) {
+ func diagnostics(game: LibraryGame? = nil, _ done: @escaping (String) -> Void) {
let repo = repoOK ? repoPath : "", python = pythonPath.isEmpty ? Self.findPython().path : pythonPath, dotnet = dotnetPath
let rows = depsChecked ? deps.map(Diagnostics.dependency) : [], checked = depsChecked
- let command = lastBuildCommand, log = logTail
+ let command = lastBuildCommand, log = logTail, xcrun = xcrunPath
DispatchQueue.global(qos: .userInitiated).async {
let git = Diagnostics.git(repo)
let env = ["HOME": NSHomeDirectory(), "PATH": "/usr/bin:/bin", "TMPDIR": NSTemporaryDirectory()]
var dotnetEnv = env
if !dotnet.isEmpty { dotnetEnv["DOTNET_ROOT"] = (dotnet as NSString).deletingLastPathComponent }
+ let read = { (file: String) in try? String(contentsOfFile: repo + "/" + file, encoding: .utf8) }
+ let pins = read("dm/gfx/tools/dmsh_chain.lock").map(Diagnostics.chainPins) ?? (nil, nil)
let inputs = Diagnostics.Inputs(
appVersion: Self.appVersion,
macOS: ProcessInfo.processInfo.operatingSystemVersionString,
@@ -195,7 +310,11 @@ extension BuildModel {
pythonIsVenv: python == Self.venvPython(),
dotnet: dotnet,
dotnetVersion: dotnet.isEmpty ? nil : Diagnostics.version(dotnet, ["--version"], env: dotnetEnv),
- depsChecked: checked, deps: rows, lastCommand: command, log: log)
+ depsChecked: checked, deps: rows,
+ forkPatches: repo.isEmpty ? nil : read("dm/fork_patches.txt").map(Diagnostics.patchList),
+ toolchain: Diagnostics.toolchain(xcrun: xcrun, pins: pins, run: Diagnostics.probe(env: env)),
+ game: game.map { Diagnostics.gameInfo($0) },
+ lastCommand: command, log: log)
let report = Diagnostics.report(inputs)
DispatchQueue.main.async { done(report) }
}
@@ -205,6 +324,7 @@ extension BuildModel {
/// Settings' Copy diagnostics: the report goes to the clipboard and the button says Copied for a moment.
struct DiagnosticsButton: View {
@ObservedObject var m: BuildModel
+ var game: LibraryGame? // the library's selected game: its log goes in the report
let width: CGFloat
var showCopied = false // the visual QA's confirmation
@State private var busy = false
@@ -221,7 +341,7 @@ struct DiagnosticsButton: View {
private func copy() {
busy = true
- m.diagnostics { report in
+ m.diagnostics(game: game) { report in
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(report, forType: .string)
busy = false
diff --git a/frontend/Sources/NSPortBuilder/GameLog.swift b/frontend/Sources/NSPortBuilder/GameLog.swift
new file mode 100644
index 00000000..2f18faba
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/GameLog.swift
@@ -0,0 +1,62 @@
+import AppKit
+
+/// Where a Mac game app writes its log, and its last lines. The rule is dm/mac/launcher.c's: a game app that sits in a folder
+/// holding the library marker (`.nx2apple-library`, written by the launcher's build) logs to `<that folder>/log/<title ID>.log`,
+/// any other copy to `~/Library/Logs/nxnative/<title ID>.log`. The launcher renames the last session's log to `.prev.log`
+/// when it starts, so `.log` is the newest while it exists. A library whose folder was moved may still hold the older
+/// ~/Library log from before the move, so both places are looked in and the newest file wins.
+enum GameLog {
+ /// The lines Copy diagnostics takes from the end of the log.
+ static let lines = 200
+ /// How much of the end of a log file is read to find them, so a log of hundreds of megabytes costs a short read.
+ static let readLimit = 256 * 1024
+ static let marker = ".nx2apple-library"
+
+ /// The folders the log of this app can be in, the one launcher.c writes to now first.
+ static func folders(appPath: String, home: String = NSHomeDirectory()) -> [URL] {
+ var folders: [URL] = []
+ if !appPath.isEmpty {
+ let library = URL(fileURLWithPath: appPath).deletingLastPathComponent()
+ if FileManager.default.fileExists(atPath: library.appendingPathComponent(marker).path) {
+ folders.append(library.appendingPathComponent("log"))
+ }
+ }
+ folders.append(URL(fileURLWithPath: home).appendingPathComponent("Library/Logs/nxnative"))
+ return folders
+ }
+
+ /// The newest existing log of the game (`<id>.log` or `<id>.prev.log`), or nil when it was never run.
+ static func latest(titleID: String, appPath: String, home: String = NSHomeDirectory()) -> URL? {
+ let candidates = folders(appPath: appPath, home: home).flatMap { folder in
+ [folder.appendingPathComponent(titleID + ".log"), folder.appendingPathComponent(titleID + ".prev.log")]
+ }
+ let found = candidates.compactMap { url -> (url: URL, date: Date)? in
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path), (attributes[.type] as? FileAttributeType) == .typeRegular
+ else { return nil }
+ return (url, attributes[.modificationDate] as? Date ?? .distantPast)
+ }
+ // max(by:) keeps the first of equal dates: the order above breaks ties, current log before previous, library before ~/Library.
+ return found.enumerated().max { ($0.element.date, -$0.offset) < ($1.element.date, -$1.offset) }?.element.url
+ }
+
+ /// The last `count` lines of a file, without trailing blank ones; nil when it cannot be read.
+ static func tail(_ url: URL, lines count: Int = lines, readLimit: Int = readLimit) -> [String]? {
+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }
+ defer { try? handle.close() }
+ guard let size = try? handle.seekToEnd() else { return nil }
+ let start = size > UInt64(readLimit) ? size - UInt64(readLimit) : 0
+ guard (try? handle.seek(toOffset: start)) != nil, let data = try? handle.readToEnd() else { return nil }
+ var text = String(decoding: data, as: UTF8.self)
+ if start > 0, let newline = text.firstIndex(of: "\n") { text = String(text[text.index(after: newline)...]) } // the first line is cut
+ return Diagnostics.tail(text, lines: count)
+ }
+
+ /// Shows the log in Console.app, or in the Finder when Console cannot be found.
+ static func show(_ url: URL) {
+ if let console = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Console") {
+ NSWorkspace.shared.open([url], withApplicationAt: console, configuration: NSWorkspace.OpenConfiguration())
+ } else {
+ NSWorkspace.shared.activateFileViewerSelecting([url])
+ }
+ }
+}
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 6e844631..48f835a3 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -636,10 +636,12 @@ struct ContentView: View {
private func manageItems(_ game: LibraryGame) -> [ManageItem] {
ManageItem.list(game: game, labels: m.t, running: m.running, olderTools: toolsAge.older.contains(game.id), activeBuildID: activeBuildID,
hasBuildFolder: BuildFolder.location(for: game) != nil,
+ hasLog: GameLog.latest(titleID: game.titleID, appPath: game.appPath) != nil,
actions: ManageActions(
rebuild: { configureBuild(game) }, options: { optionsFor = game.id }, saves: { savesFor = game.id },
changeArtwork: { chooseArtwork(game) }, resetArtwork: { library.setArtwork("", for: game.id) },
reveal: { if let path = game.revealTarget { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)]) } },
+ showLog: { if let log = GameLog.latest(titleID: game.titleID, appPath: game.appPath) { GameLog.show(log) } },
freeSpace: { freeSpaceFor = game.id }, remove: { removing = game }))
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 1f1f7954..f6804b8b 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -535,7 +535,7 @@ enum L10n {
"dep.installAll": ("一键安装全部缺失项", "Install all missing"),
// ---- Copy diagnostics (Diagnostics.swift); the report itself is in English, for the issue ----
"diag.title": ("诊断信息", "Diagnostics"),
- "diag.note": ("用于问题报告:版本、工具和上次构建的日志,不含密钥。", "For a bug report: versions, tools, the last build’s log. No keys."),
+ "diag.note": ("用于问题报告:版本、工具、上次构建的日志和所选游戏的日志,不含密钥。", "For a bug report: versions, tools, the last build’s log and the selected game’s log. No keys."),
"diag.copy": ("复制诊断信息", "Copy diagnostics"),
"diag.copied": ("已复制", "Copied"),
"dep.recheck": ("重新检测", "Check again"),
@@ -636,6 +636,8 @@ enum L10n {
"install.step2": ("2\t把上面的 romfs 文件夹整个拷到游戏 App 的 Documents 里(文件 App → 我的 iPhone → 游戏名)",
"2\tCopy the whole romfs folder above into the game app's Documents (Files → On My iPhone → game name)"),
"install.step3": ("3\t启动游戏", "3\tLaunch the game"),
+ "library.showLog": ("显示游戏日志", "Show game log"),
+ "library.showLog.none": ("这个游戏还没有日志,运行一次就会生成", "No game log yet. Play the game once to create it"),
"install.reveal": ("在访达中显示", "Reveal in Finder"),
// ---- build messages ----
diff --git a/frontend/Sources/NSPortBuilder/ManageMenu.swift b/frontend/Sources/NSPortBuilder/ManageMenu.swift
index 3f676407..0b27b733 100644
--- a/frontend/Sources/NSPortBuilder/ManageMenu.swift
+++ b/frontend/Sources/NSPortBuilder/ManageMenu.swift
@@ -9,6 +9,7 @@ struct ManageActions {
var changeArtwork: () -> Void = {}
var resetArtwork: () -> Void = {}
var reveal: () -> Void = {}
+ var showLog: () -> Void = {}
var freeSpace: () -> Void = {}
var remove: () -> Void = {}
}
@@ -21,12 +22,13 @@ struct ManageItem: Identifiable {
var enabled = true
var destructive = false
var separatorBefore = false
+ var hint: String? // the tooltip, set on a row that is off to say why
let run: () -> Void
/// The menu's rows, in order, built in one place: a new item is one line here. The rules are the ones the system menu had:
/// Build again is off while a build runs or with no recorded inputs, Remove while this game is the one building.
static func list(game: LibraryGame, labels t: (String) -> String, running: Bool, olderTools: Bool, activeBuildID: UUID?,
- hasBuildFolder: Bool, actions a: ManageActions) -> [ManageItem] {
+ hasBuildFolder: Bool, hasLog: Bool = false, actions a: ManageActions) -> [ManageItem] {
var items = [ManageItem(id: "rebuild", symbol: "arrow.clockwise", title: t(olderTools ? "library.rebuild" : "library.buildAgain"),
enabled: !running && !game.inputs["base", default: []].isEmpty, run: a.rebuild)]
if game.isReady { items.append(.init(id: "options", symbol: "slider.horizontal.3", title: t("launch.title"), run: a.options)) }
@@ -34,6 +36,10 @@ struct ManageItem: Identifiable {
items.append(.init(id: "artwork", symbol: "photo", title: t("library.changeArtwork"), run: a.changeArtwork))
if !game.artworkPath.isEmpty { items.append(.init(id: "resetArtwork", symbol: "arrow.uturn.backward", title: t("library.resetArtwork"), run: a.resetArtwork)) }
if game.revealTarget != nil { items.append(.init(id: "reveal", symbol: "folder", title: t("install.reveal"), run: a.reveal)) }
+ if game.isReady {
+ items.append(.init(id: "log", symbol: "doc.text.magnifyingglass", title: t("library.showLog"), enabled: hasLog,
+ hint: hasLog ? nil : t("library.showLog.none"), run: a.showLog))
+ }
if hasBuildFolder { items.append(.init(id: "freeSpace", symbol: "externaldrive", title: t("free.menu"), run: a.freeSpace)) }
items.append(.init(id: "remove", symbol: "trash", title: t("library.remove"), enabled: game.id != activeBuildID,
destructive: true, separatorBefore: true, run: a.remove))
@@ -161,6 +167,7 @@ struct ManageMenuPanel: View {
}
.buttonStyle(.plain)
.disabled(!item.enabled)
+ .help(item.hint ?? "")
.onHover { inside in if inside && item.enabled { highlighted = index } else if !inside && highlighted == index { highlighted = nil } }
.accessibilityLabel(item.title)
.padTarget(item.padID, scope: "manage", radius: 8) { activate(item) }
diff --git a/frontend/Tests/NSPortBuilderTests/DiagnosticsTests.swift b/frontend/Tests/NSPortBuilderTests/DiagnosticsTests.swift
index 782fae3c..04c354b6 100644
--- a/frontend/Tests/NSPortBuilderTests/DiagnosticsTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/DiagnosticsTests.swift
@@ -106,4 +106,92 @@ final class DiagnosticsTests: XCTestCase {
let zstd = BuildModel.Dep(id: "brew:zstd", name: "dep.zstd", hint: "dep.zstd.hint", present: true, detail: "/opt/homebrew/bin/zstd", installCmd: [])
XCTAssertEqual(Diagnostics.dependency(zstd).detail, "/opt/homebrew/bin/zstd")
}
+
+ // ---- fork patches, Xcode and Metal, and the selected game's log ----
+
+ private func fakeProbe(_ answers: [String: String]) -> Diagnostics.Probe {
+ { args in answers[args.joined(separator: " ")] }
+ }
+
+ private let metal = "Apple metal version 32023.921 (metalfe-32023.921.6)"
+ private let probes = [
+ "/usr/bin/xcode-select -p": "/Applications/Xcode.app/Contents/Developer\n",
+ "/usr/bin/xcodebuild -version": "Xcode 26.1\nBuild version 17B55\n",
+ "/usr/bin/xcrun -sdk macosx metal --version": "Apple metal version 32023.921 (metalfe-32023.921.6)\nTarget: air64-apple-darwin25.1.0\nInstalledDir: /Users/jo/x",
+ "/usr/bin/xcrun -sdk iphoneos metal --version": "Apple metal version 32023.800 (metalfe-32023.800.1)\nTarget: air64",
+ "/usr/bin/xcrun --sdk iphoneos --show-sdk-version": "26.1\n",
+ ]
+
+ func testTheToolchainComesFromTheProbesAndKeepsOnlyTheCompilersFirstLine() {
+ let t = Diagnostics.toolchain(pins: (metal, metal), run: fakeProbe(probes))
+ XCTAssertEqual(t.xcodePath, "/Applications/Xcode.app/Contents/Developer")
+ XCTAssertEqual(t.xcodeVersion, "Xcode 26.1, Build version 17B55")
+ XCTAssertEqual(t.metalMac, metal)
+ XCTAssertEqual(t.metalIOS, "Apple metal version 32023.800 (metalfe-32023.800.1)")
+ XCTAssertEqual(t.iosSDK, "26.1")
+ XCTAssertEqual(Diagnostics.toolchain(run: fakeProbe([:])), Diagnostics.Toolchain(), "nothing answers: nothing is invented")
+ }
+
+ func testTheReportNamesForkPatchesXcodeMetalAgainstThePinAndTheSDK() {
+ var i = inputs()
+ i.forkPatches = Diagnostics.patchList("runtime-profile\nromfsarc\n\n")
+ i.toolchain = Diagnostics.toolchain(pins: (metal, metal), run: fakeProbe(probes))
+ let report = Diagnostics.report(i)
+ for expected in [
+ "- Fork patches: runtime-profile, romfsarc",
+ "- Xcode: /Applications/Xcode.app/Contents/Developer (Xcode 26.1, Build version 17B55)",
+ "- Metal compiler (macOS): \(metal) (matches the pin)",
+ "- Metal compiler (iOS): Apple metal version 32023.800 (metalfe-32023.800.1) (pin: \(metal))",
+ "- iOS SDK: 26.1",
+ ] { XCTAssertTrue(report.contains(expected + "\n"), expected) }
+ }
+
+ func testTheReportSaysWhatIsMissing() {
+ let report = Diagnostics.report(inputs()) // nothing probed
+ XCTAssertTrue(report.contains("- Fork patches: not found\n"))
+ XCTAssertTrue(report.contains("- Xcode: not found\n"))
+ XCTAssertTrue(report.contains("- Metal compiler (macOS): not installed\n"))
+ XCTAssertTrue(report.contains("- iOS SDK: not installed\n"))
+ var i = inputs()
+ i.forkPatches = []
+ XCTAssertTrue(Diagnostics.report(i).contains("- Fork patches: none\n"))
+ XCTAssertFalse(report.contains("#### Selected game"), "no game selected")
+ }
+
+ func testThePinsAreReadFromTheChainLock() {
+ let lock = "# Translation chain\ndmsh_xlate.dll\tdbc483247a4cb22d\nmetal_macosx\t\(metal)\nmetal_iphoneos\tApple metal version 1 (x)\n"
+ XCTAssertEqual(Diagnostics.chainPins(lock).mac, metal)
+ XCTAssertEqual(Diagnostics.chainPins(lock).ios, "Apple metal version 1 (x)")
+ XCTAssertNil(Diagnostics.chainPins("dmsh_xlate.dll\tabc").mac)
+ }
+
+ func testTheSelectedGamesSectionHasItsBuiltPatchesAndARedactedLogTail() {
+ var i = inputs()
+ var lines = (1...300).map { "game line \($0)" }
+ lines[299] = "title_key = 0123456789abcdef0123456789abcdef"
+ i.game = Diagnostics.GameInfo(name: "Hades", titleID: "0100535012974000", builtForkPatches: "runtime-profile,romfsarc",
+ logPath: "/Users/jo/Library/Logs/nxnative/0100535012974000.log", log: lines)
+ let report = Diagnostics.report(i)
+ XCTAssertTrue(report.contains("- Game: Hades (0100535012974000)\n"))
+ XCTAssertTrue(report.contains("- Fork patches of the built app: runtime-profile, romfsarc\n"))
+ XCTAssertTrue(report.contains("- Game log: ~/Library/Logs/nxnative/0100535012974000.log\n"))
+ XCTAssertTrue(report.contains("Last 200 game log lines:"))
+ XCTAssertTrue(report.contains("````text\ngame line 101\n"))
+ XCTAssertFalse(report.contains("game line 100\n"))
+ XCTAssertTrue(report.contains("title_key = [redacted]\n"))
+ XCTAssertFalse(report.contains("0123456789abcdef0123456789abcdef"))
+ i.game?.logPath = nil; i.game?.log = []; i.game?.builtForkPatches = nil
+ let none = Diagnostics.report(i)
+ XCTAssertTrue(none.contains("- Game log: none yet, the game was not run\n"))
+ XCTAssertTrue(none.contains("- Fork patches of the built app: no Mac app built\n"))
+ }
+
+ func testNoNewReportTextHasASemicolonInAnUserFacingString() {
+ for key in ["diag.note", "library.showLog", "library.showLog.none"] {
+ for lang in [Lang.en, .zh] {
+ let text = L10n.string(key, lang)
+ XCTAssertFalse(text.contains(";") || text.contains("\u{FF1B}"), "\(key) \(lang)")
+ }
+ }
+ }
}
diff --git a/frontend/Tests/NSPortBuilderTests/GameLogTests.swift b/frontend/Tests/NSPortBuilderTests/GameLogTests.swift
new file mode 100644
index 00000000..0ec952b7
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/GameLogTests.swift
@@ -0,0 +1,96 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// Show game log and the log in Copy diagnostics: where dm/mac/launcher.c puts a game's log, which file is the latest, and
+/// that only the end of a large log is read.
+final class GameLogTests: XCTestCase {
+ private var temporary: URL!
+ private let id = "0100535012974000"
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-gamelog-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws { try FileManager.default.removeItem(at: temporary) }
+
+ private var home: String { temporary.appendingPathComponent("home").path }
+ private var library: URL { temporary.appendingPathComponent("Library folder") }
+
+ @discardableResult
+ private func write(_ url: URL, _ text: String = "x\n", age: TimeInterval = 0) throws -> URL {
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try text.write(to: url, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.modificationDate: Date().addingTimeInterval(-age)], ofItemAtPath: url.path)
+ return url
+ }
+
+ func testAnAppOutsideALibraryLogsUnderLibraryLogs() {
+ let app = temporary.appendingPathComponent("Apps/Hades.app").path
+ XCTAssertEqual(GameLog.folders(appPath: app, home: home).map(\.path), [home + "/Library/Logs/nxnative"])
+ XCTAssertEqual(GameLog.folders(appPath: "", home: home).map(\.path), [home + "/Library/Logs/nxnative"])
+ }
+
+ func testAnAppInALibraryFolderWithTheMarkerLogsBesideItFirst() throws {
+ try write(library.appendingPathComponent(GameLog.marker), "")
+ let folders = GameLog.folders(appPath: library.appendingPathComponent("Hades.app").path, home: home)
+ XCTAssertEqual(folders.map(\.path), [library.path + "/log", home + "/Library/Logs/nxnative"])
+ }
+
+ func testTheLatestLogIsTheNewestFileAndNilWhenThereIsNone() throws {
+ let app = library.appendingPathComponent("Hades.app").path
+ XCTAssertNil(GameLog.latest(titleID: id, appPath: app, home: home))
+ try write(library.appendingPathComponent(GameLog.marker), "")
+ let old = try write(URL(fileURLWithPath: home + "/Library/Logs/nxnative/\(id).log"), age: 500)
+ XCTAssertEqual(GameLog.latest(titleID: id, appPath: app, home: home), old, "the log from before the folder moved")
+ let prev = try write(library.appendingPathComponent("log/\(id).prev.log"), age: 100)
+ XCTAssertEqual(GameLog.latest(titleID: id, appPath: app, home: home), prev)
+ let current = try write(library.appendingPathComponent("log/\(id).log"), age: 10)
+ XCTAssertEqual(GameLog.latest(titleID: id, appPath: app, home: home), current)
+ XCTAssertNil(GameLog.latest(titleID: "0100000000010000", appPath: app, home: home), "another game's log is not this one's")
+ }
+
+ func testEqualDatesPreferTheCurrentLogToThePreviousOne() throws {
+ let stamp = Date()
+ let folder = URL(fileURLWithPath: home + "/Library/Logs/nxnative")
+ let prev = try write(folder.appendingPathComponent("\(id).prev.log"))
+ let current = try write(folder.appendingPathComponent("\(id).log"))
+ for url in [prev, current] { try FileManager.default.setAttributes([.modificationDate: stamp], ofItemAtPath: url.path) }
+ XCTAssertEqual(GameLog.latest(titleID: id, appPath: "", home: home), current)
+ }
+
+ func testTheTailIsCappedAtTheLineLimit() throws {
+ let log = try write(temporary.appendingPathComponent("a.log"), (1...500).map { "line \($0)" }.joined(separator: "\n") + "\n\n")
+ let lines = try XCTUnwrap(GameLog.tail(log))
+ XCTAssertEqual(lines.count, GameLog.lines)
+ XCTAssertEqual(lines.first, "line 301")
+ XCTAssertEqual(lines.last, "line 500")
+ XCTAssertEqual(try XCTUnwrap(GameLog.tail(log, lines: 3)), ["line 498", "line 499", "line 500"])
+ XCTAssertNil(GameLog.tail(temporary.appendingPathComponent("missing.log")))
+ }
+
+ func testOnlyTheEndOfAHugeLogIsRead() throws {
+ let log = try write(temporary.appendingPathComponent("big.log"), (1...20000).map { "line number \($0)" }.joined(separator: "\n") + "\n")
+ let lines = try XCTUnwrap(GameLog.tail(log, lines: 100_000, readLimit: 1000))
+ XCTAssertLessThan(lines.count, 100)
+ XCTAssertEqual(lines.last, "line number 20000")
+ XCTAssertTrue(lines.allSatisfy { $0.hasPrefix("line number ") }, "a cut first line is dropped")
+ }
+
+ func testTheGameSectionReadsTheBuiltAppAndItsLog() throws {
+ let app = library.appendingPathComponent("Hades.app")
+ try write(app.appendingPathComponent("Contents/Info.plist"), "")
+ let info: [String: Any] = ["DMForkPatches": "runtime-profile,romfsarc"]
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))
+ try write(library.appendingPathComponent(GameLog.marker), "")
+ try write(library.appendingPathComponent("log/\(id).log"), "fork patches: runtime-profile,romfsarc\nlauncher: Hades\n")
+ let game = LibraryGame(titleID: id, name: "Hades", appPath: app.path)
+ let section = Diagnostics.gameInfo(game, home: home)
+ XCTAssertEqual(section.builtForkPatches, "runtime-profile,romfsarc")
+ XCTAssertEqual(section.logPath, library.path + "/log/\(id).log")
+ XCTAssertEqual(section.log, ["fork patches: runtime-profile,romfsarc", "launcher: Hades"])
+ let unbuilt = Diagnostics.gameInfo(LibraryGame(titleID: id, name: "Hades"), home: home + "-none")
+ XCTAssertNil(unbuilt.builtForkPatches)
+ XCTAssertNil(unbuilt.logPath)
+ }
+}
diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
index 622b8e57..37964038 100644
--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
@@ -700,6 +700,10 @@ final class LibraryTests: XCTestCase {
let examples = [(titleID, "Hades"), ("01007EF00011E000", "The Legend of Zelda: Breath of the Wild"),
("0100000000010000", "Super Mario Odyssey"), ("010093801237C000", "Metroid Dread")]
for (id, name) in examples.prefix(3) { _ = try library.addApp(makeApp(id, name: name)) }
+ // The selected game (Hades) has run: its log is beside the app, so Manage > Show game log is on in the capture.
+ try Data().write(to: temporary.appendingPathComponent(GameLog.marker))
+ try FileManager.default.createDirectory(at: temporary.appendingPathComponent("log"), withIntermediateDirectories: true)
+ try Data("fork patches: none\n".utf8).write(to: temporary.appendingPathComponent("log/\(titleID).log"))
model.slots[0].paths = ["/preview/Metroid Dread [010093801237C000].nsp"]
_ = library.rememberInputs(model)
model.slots[0].paths = []
diff --git a/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swift b/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swift
index defef5be..eb8f0897 100644
--- a/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swift
@@ -29,18 +29,18 @@ final class ManageMenuTests: XCTestCase {
return game
}
- private func items(_ game: LibraryGame, running: Bool = false, older: Bool = false, active: UUID? = nil, folder: Bool = false,
+ private func items(_ game: LibraryGame, running: Bool = false, older: Bool = false, active: UUID? = nil, folder: Bool = false, log: Bool = false,
actions: ManageActions = ManageActions()) -> [ManageItem] {
ManageItem.list(game: game, labels: { L10n.string($0, .en) }, running: running, olderTools: older, activeBuildID: active,
- hasBuildFolder: folder, actions: actions)
+ hasBuildFolder: folder, hasLog: log, actions: actions)
}
func testAReadyGameHasEveryRowInTheOldOrderAndRemoveLastInRed() throws {
var game = try readyGame()
game.artworkPath = "/art.png"
- let list = items(game, folder: true)
- XCTAssertEqual(list.map(\.id), ["rebuild", "options", "saves", "artwork", "resetArtwork", "reveal", "freeSpace", "remove"])
- XCTAssertEqual(list.map(\.title), ["library.buildAgain", "launch.title", "saves.menu", "library.changeArtwork", "library.resetArtwork", "install.reveal", "free.menu", "library.remove"]
+ let list = items(game, folder: true, log: true)
+ XCTAssertEqual(list.map(\.id), ["rebuild", "options", "saves", "artwork", "resetArtwork", "reveal", "log", "freeSpace", "remove"])
+ XCTAssertEqual(list.map(\.title), ["library.buildAgain", "launch.title", "saves.menu", "library.changeArtwork", "library.resetArtwork", "install.reveal", "library.showLog", "free.menu", "library.remove"]
.map { L10n.string($0, .en) })
XCTAssertTrue(list.allSatisfy(\.enabled))
XCTAssertEqual(list.last?.destructive, true)
@@ -76,14 +76,28 @@ final class ManageMenuTests: XCTestCase {
XCTAssertEqual(items(game, older: true)[0].title, L10n.string("library.rebuild", .en))
}
+ func testShowGameLogIsOffWithATooltipUntilTheGameHasALog() throws {
+ let game = try readyGame()
+ let none = try XCTUnwrap(items(game).first { $0.id == "log" })
+ XCTAssertFalse(none.enabled)
+ XCTAssertEqual(none.hint, L10n.string("library.showLog.none", .en))
+ let some = try XCTUnwrap(items(game, log: true).first { $0.id == "log" })
+ XCTAssertTrue(some.enabled)
+ XCTAssertNil(some.hint)
+ XCTAssertNil(items(LibraryGame(titleID: titleID, name: "Hades")).first { $0.id == "log" }, "no Mac app, no log row")
+ for key in ["library.showLog", "library.showLog.none"] {
+ for lang in [Lang.en, .zh] { XCTAssertFalse(L10n.string(key, lang).contains(";") || L10n.string(key, lang).contains("\u{FF1B}"), key) }
+ }
+ }
+
func testRowsRunTheirActions() throws {
let game = try readyGame()
var log: [String] = []
let actions = ManageActions(rebuild: { log.append("rebuild") }, options: { log.append("options") }, saves: { log.append("saves") },
- changeArtwork: { log.append("artwork") }, resetArtwork: { log.append("reset") }, reveal: { log.append("reveal") },
+ changeArtwork: { log.append("artwork") }, resetArtwork: { log.append("reset") }, reveal: { log.append("reveal") }, showLog: { log.append("log") },
freeSpace: { log.append("free") }, remove: { log.append("remove") })
- for item in items(game, folder: true, actions: actions) { item.run() }
- XCTAssertEqual(log, ["rebuild", "options", "saves", "artwork", "reveal", "free", "remove"])
+ for item in items(game, folder: true, log: true, actions: actions) { item.run() }
+ XCTAssertEqual(log, ["rebuild", "options", "saves", "artwork", "reveal", "log", "free", "remove"])
}
func testTheControllerLandsOnTheFirstUsableRow() throws {