From af1ccd4cc9a7deda39ccc5d2275cafc72d52cdcd Mon Sep 17 00:00:00 2001 From: abgitdev <266600699+abgitdev@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:47:13 +0000 Subject: [PATCH 1/7] Start every Steam game itself instead of through steam.exe -applaunch A profile made by Add Steam Game for a game outside the verified list ran steam.exe -applaunch APP_ID. Wine returns as soon as Steam accepts the request, and the game then inherits Steam's environment instead of the session's BASALT_CONTROL path, so the headset stayed black and the session ended at once. BottleManager.profileLaunchCommand now resolves every such profile to the game's own executable (SteamDirectLaunch): the verified list first, then Steam's launch options from appcache/appinfo.vdf (versions 39 to 42, read by SteamAppInfo), then the game folder. The game starts with SteamAppId, SteamGameId and the session's environment, so existing profiles need no change. The OpenXR runtime says once why a session stays headless, and the session log names the executable started directly and adds a hint when the game ends within 15 seconds of starting. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 + docs/BOTTLES.md | 19 + docs/MANAGEMENT.md | 6 +- runtime/pe/control.cpp | 38 +- .../BasaltBottleKit/BottleManager.swift | 44 +- .../BasaltBottleKit/SteamAppInfo.swift | 327 +++++++++++ .../BasaltBottleKit/SteamDirectLaunch.swift | 434 +++++++++++++++ streamer/Sources/BasaltManager/AppModel.swift | 13 + .../Localization/L10nKey.swift | 2 + .../Localization/Strings+de.swift | 2 + .../Localization/Strings+en.swift | 2 + .../Localization/Strings+es.swift | 2 + .../Localization/Strings+fr.swift | 2 + .../Localization/Strings+it.swift | 2 + .../Localization/Strings+ja.swift | 2 + .../Localization/Strings+ko.swift | 2 + .../Localization/Strings+pl.swift | 2 + .../Localization/Strings+ru.swift | 2 + .../Localization/Strings+uk.swift | 2 + .../BasaltManagerKit/SteamInstallation.swift | 11 +- .../SteamDirectLaunchTests.swift | 520 ++++++++++++++++++ 21 files changed, 1416 insertions(+), 30 deletions(-) create mode 100644 streamer/Sources/BasaltBottleKit/SteamAppInfo.swift create mode 100644 streamer/Sources/BasaltBottleKit/SteamDirectLaunch.swift create mode 100644 streamer/Tests/BasaltBottleKitTests/SteamDirectLaunchTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e381f1..7eb3727 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ All notable changes to TrailBridge VR are documented here. +## Unreleased + +- Every Steam game starts in the headset, not only the verified ones. A profile made by Add Steam + Game for any other game used to run `steam.exe -applaunch APP_ID`: Steam then started the game + without the session's environment, so the OpenXR runtime could not reach the streamer, the + headset stayed black and the session ended at once. TrailBridge now starts the game's own + executable, chosen from Steam's launch options in `appinfo.vdf` or from the game folder, with + `SteamAppId` set. Existing profiles need no change. +- The session log says why a session stays headless: the OpenXR runtime names the missing + environment, DXMT build or connection, and the app adds a hint when the started file ends within + seconds, as a launcher that opens the game separately does. + ## 0.2.1 — 2026-11-15 - Setup recognises Rosetta 2 on every macOS version: the check now runs Intel code, as diff --git a/docs/BOTTLES.md b/docs/BOTTLES.md index ccfe22a..a691c6a 100644 --- a/docs/BOTTLES.md +++ b/docs/BOTTLES.md @@ -69,6 +69,25 @@ swift run --package-path streamer basaltctl profile show beat-saber-steam Repeat `--arg VALUE` and `--env KEY=VALUE` as needed. `--cwd HOST_PATH` optionally selects the Wine process's host working directory. +A `steam` profile whose arguments contain `-applaunch APP_ID` is not started through Steam: +`steam.exe -applaunch` only hands the AppID to the running Steam client, which would start the +game with its own environment, without `BASALT_CONTROL`, so the headset would stay black. At each +launch the profile is resolved to the game's own executable (`SteamDirectLaunch`): + +1. the executable TrailBridge verified for the game, for the verified games; +2. else Steam's launch option for the app in `appcache/appinfo.vdf` (versions 39 to 42): the + SteamVR option first, then the default and numbered ones, never options for other systems, beta + branches, servers or editors; its arguments come first; +3. else the game folder from the app's `appmanifest_APP_ID.acf` in any library listed in + `libraryfolders.vdf`: a Unity player (`Game.exe` beside `Game_Data`), the `.exe` named like the + folder, an Unreal `*-Win64-Shipping.exe`, or the only probable game. + +An Unreal launcher at the top of the folder is replaced by the game binary it starts, since the +session lasts as long as the started process. Arguments before `-applaunch` are the Steam client's +and are dropped; those after the AppID follow. `SteamAppId` and `SteamGameId` are set, so +Steamworks does not restart the game through Steam. When no file is clearly the game, the launch +fails with a message asking for the executable in Edit Launch Profile…. + ## OpenComposite OpenComposite is a separate GPL-3.0 project by its authors and is never bundled with TrailBridge. diff --git a/docs/MANAGEMENT.md b/docs/MANAGEMENT.md index 377680b..6fded57 100644 --- a/docs/MANAGEMENT.md +++ b/docs/MANAGEMENT.md @@ -49,7 +49,11 @@ shows the session state with a Stop button. with the Steam identity and BSIPA `winhttp` override already set. Toolbar search plus VR-only and tool filters are included; playable games sort first in each section. Existing profiles and direct Beat Saber detections appear alongside Steam and BSManager games. Steam games in a managed bottle can become `-applaunch APP_ID` profiles - without re-entering paths. **Add Game…** (toolbar, `plus`) adds any other Windows game, such as + without re-entering paths. Such a profile is never passed to Steam as it is: at each launch + TrailBridge starts the game's own executable, chosen from Steam's launch options in + `appcache/appinfo.vdf` or, without them, from the game folder (see + [Bottles](BOTTLES.md#profiles)), so the game gets the session's OpenXR environment. + **Add Game…** (toolbar, `plus`) adds any other Windows game, such as one from GOG or itch.io: pick a Basalt bottle and the game's `.exe` inside its `drive_c` (install it first with Bottles → ⋯ → Run Windows Installer…). The name comes from the game folder, skipping build folders such as `Binaries/Win64` or `bin/win64`. The source is itch.io when a diff --git a/runtime/pe/control.cpp b/runtime/pe/control.cpp index bdfcc6e..5288311 100644 --- a/runtime/pe/control.cpp +++ b/runtime/pe/control.cpp @@ -195,6 +195,24 @@ bool basaltGateEnabled() { return length == 1 && value[0] == '1'; } +// A session that cannot reach TrailBridge stays headless: xrWaitFrame reports +// shouldRender == XR_FALSE, the game draws nothing and the headset stays +// black. Say why once per process, so the session log names a cause. +void logHeadlessSession(const char* reason) { + static LONG logged = 0; + if (InterlockedCompareExchange(&logged, 1, 0) == 0) { + std::fprintf(stderr, + "Basalt OpenXR: %s; the session runs headless and nothing reaches the " + "headset\n", + reason); + std::fflush(stderr); + } +} + +constexpr const char* kNotStartedByTrailBridge = + "TrailBridge VR did not start this game (a launcher such as Steam may have started it " + "without the session's environment)"; + XrTime monotonicTime() { LARGE_INTEGER counter{}; LARGE_INTEGER frequency{}; @@ -1155,19 +1173,32 @@ uint32_t queryTextureIOSurfaceId(ID3D11Texture2D* texture) { } void controlSessionCreated(XrSession session, ID3D11Device* device) { - if (!basaltGateEnabled() || !probeSessionIOSurface(device)) { + if (!basaltGateEnabled()) { + logHeadlessSession(kNotStartedByTrailBridge); + return; + } + if (!probeSessionIOSurface(device)) { + logHeadlessSession( + "the game's Direct3D 11 device cannot share frames with TrailBridge VR (the " + "environment's d3d11.dll is not TrailBridge's DXMT build)"); return; } uint16_t port = 0; char token[BASALT_CONTROL_TOKEN_LENGTH + 1]{}; if (!readControlFile(&port, token, nullptr, nullptr)) { + logHeadlessSession( + GetEnvironmentVariableA("BASALT_CONTROL", nullptr, 0) == 0 + ? kNotStartedByTrailBridge + : "the BASALT_CONTROL file is missing or invalid (the TrailBridge VR session " + "that started this game has ended)"); return; } ID3D11Device5* device5 = nullptr; if (FAILED(device->QueryInterface(IID_ID3D11Device5, reinterpret_cast(&device5)))) { + logHeadlessSession("the game's Direct3D 11 device has no ID3D11Device5 fences"); return; } ID3D11DeviceContext* context = nullptr; @@ -1178,6 +1209,7 @@ void controlSessionCreated(XrSession session, ID3D11Device* device) { context->Release(); if (FAILED(contextResult)) { device5->Release(); + logHeadlessSession("the game's Direct3D 11 device has no ID3D11DeviceContext4"); return; } ID3D11Fence* fence = nullptr; @@ -1186,6 +1218,7 @@ void controlSessionCreated(XrSession session, ID3D11Device* device) { device5->Release(); if (FAILED(fenceResult)) { context4->Release(); + logHeadlessSession("the game's Direct3D 11 device could not create a fence"); return; } @@ -1276,6 +1309,9 @@ void controlSessionCreated(XrSession session, ID3D11Device* device) { finishDisconnect(state, false); release(fence); release(context4); + logHeadlessSession( + "TrailBridge VR's streamer did not accept the runtime's connection (the session " + "may have ended, or another TrailBridge VR version started it)"); return; } ReleaseSRWLockExclusive(&gControlLock); diff --git a/streamer/Sources/BasaltBottleKit/BottleManager.swift b/streamer/Sources/BasaltBottleKit/BottleManager.swift index 548bf2a..ff96dad 100644 --- a/streamer/Sources/BasaltBottleKit/BottleManager.swift +++ b/streamer/Sources/BasaltBottleKit/BottleManager.swift @@ -148,6 +148,9 @@ public struct BottleLaunchCommand: Equatable, Sendable { /// Names of the profile's variables that were left out of `environment` /// (`BottleManager.withoutLoaderVariables`), sorted; for one log line. public var droppedEnvironment = [String]() + /// The game a `steam.exe -applaunch` profile was resolved to, or nil when + /// the profile names its executable itself; for one log line. + public var steamLaunch: SteamDirectLaunch? = nil public init(executable: URL, arguments: [String], environment: [String: String], currentDirectory: URL?) { @@ -1559,31 +1562,27 @@ public final class BottleManager: @unchecked Sendable { // A `steam.exe -applaunch` invocation is only a message to the already // running Steam client. Wine returns as soon as Steam accepts it, and // the eventual game inherits Steam's old environment instead of this - // session's BASALT_CONTROL path. Resolve the initial Beat Saber target - // to the actual executable so Basalt owns the real game lifetime and - // supplies the current OpenXR session environment. + // session's BASALT_CONTROL path, so its headset stays black. Resolve + // every such profile to the game's own executable (SteamDirectLaunch) + // so Basalt owns the real game lifetime and supplies the current + // OpenXR session environment. Arguments before `-applaunch` are the + // Steam client's; those after the AppID are the game's and follow + // the arguments of Steam's own launch option. + var steamLaunch: SteamDirectLaunch? if profile.source == .steam, let appLaunchIndex = profileArguments.firstIndex(of: "-applaunch"), - profileArguments.indices.contains(appLaunchIndex + 1), - profileArguments[appLaunchIndex + 1] == "620980" { + profileArguments.indices.contains(appLaunchIndex + 1) { + let appID = profileArguments[appLaunchIndex + 1] let prefix = URL(fileURLWithPath: bottle.prefixPath, isDirectory: true) - let candidates = [ - prefix.appendingPathComponent( - "drive_c/Program Files (x86)/Steam/steamapps/common/Beat Saber/Beat Saber.exe"), - prefix.appendingPathComponent( - "drive_c/Program Files/Steam/steamapps/common/Beat Saber/Beat Saber.exe"), - ] - guard let beatSaber = candidates.first(where: { - fileManager.fileExists(atPath: $0.path) - }) else { - throw BottleToolError( - "Steam reports Beat Saber, but its executable is missing from the managed bottle. Open Steam, finish any pending update, then try again.") - } - windowsExecutable = Self.winePath(for: beatSaber, prefix: prefix) - profileArguments.removeSubrange(appLaunchIndex...(appLaunchIndex + 1)) - workingDirectory = beatSaber.deletingLastPathComponent() - environment["SteamAppId"] = "620980" - environment["SteamGameId"] = "620980" + let launch = try SteamDirectLaunch.resolve( + appID: appID, prefix: prefix, gameRoot: try? hostGameRoot(profileName: name), + fileManager: fileManager) + windowsExecutable = Self.winePath(for: launch.executable, prefix: prefix) + profileArguments = launch.arguments + profileArguments.suffix(from: appLaunchIndex + 2) + workingDirectory = launch.workingDirectory + environment["SteamAppId"] = appID + environment["SteamGameId"] = appID + steamLaunch = launch } environment["DXMT_BASALT_IOSURFACE"] = "1" environment["BASALT_CONTROL"] = Self.winePath(for: controlFile, @@ -1624,6 +1623,7 @@ public final class BottleManager: @unchecked Sendable { currentDirectory: workingDirectory) command.frameTrace = trace command.droppedEnvironment = dropped + command.steamLaunch = steamLaunch return command } diff --git a/streamer/Sources/BasaltBottleKit/SteamAppInfo.swift b/streamer/Sources/BasaltBottleKit/SteamAppInfo.swift new file mode 100644 index 0000000..6f3dbf1 --- /dev/null +++ b/streamer/Sources/BasaltBottleKit/SteamAppInfo.swift @@ -0,0 +1,327 @@ +import Foundation + +/// One launch option Steam lists for an app: what the client starts when the +/// player presses Play (`config/launch/` in the app's information). +public struct SteamLaunchOption: Equatable, Sendable { + /// Relative to the game's install folder, as Steam stores it (`\` or `/`). + public var executable: String + /// One command line, as Steam passes it to the game. + public var arguments: String + /// Relative to the install folder; empty means the executable's folder. + public var workingDirectory: String + /// `default`, `option1`, `vr`, `server`, …; empty when Steam gives none. + public var type: String + /// Comma-separated `windows`, `macos`, `linux`; empty means every system. + public var operatingSystems: String + /// `64` or `32`; empty when Steam gives none. + public var architecture: String + /// The beta branch the option belongs to; empty for the default branch. + public var betaKey: String + /// `SteamGlobal` or `SteamChina`; empty for both. + public var realm: String + + public init(executable: String, arguments: String = "", workingDirectory: String = "", + type: String = "", operatingSystems: String = "", architecture: String = "", + betaKey: String = "", realm: String = "") { + self.executable = executable + self.arguments = arguments + self.workingDirectory = workingDirectory + self.type = type + self.operatingSystems = operatingSystems + self.architecture = architecture + self.betaKey = betaKey + self.realm = realm + } +} + +/// Reads one app's launch options from Steam's `appcache/appinfo.vdf`. +/// +/// The file is the client's binary cache of app information. Versions 39 to +/// 41 (magic `0x07564427`…`0x07564429`) hold a header, one entry per app (its +/// AppID, the entry's size in bytes, fixed fields, then the app's information +/// as binary KeyValues) and AppID 0 at the end; version 41 keeps every key +/// once in a table at the end of the file and refers to keys by index, the +/// older ones spell them inline. Version 42 (`0x0756442A`) is a shard: a +/// header, an index of apps, the key table, then the apps' data. Only the +/// requested app is decoded. Another version, a truncated file or an +/// inconsistent entry reads as nil, and callers then look at the game's +/// folder instead. +public enum SteamAppInfo { + static let format27: UInt32 = 0x0756_4427 + static let format28: UInt32 = 0x0756_4428 + static let format29: UInt32 = 0x0756_4429 + static let format2A: UInt32 = 0x0756_442A + /// Deeper nesting than Steam ever writes means a damaged file. + static let maximumDepth = 64 + + /// The app's launch options in Steam's order: nil when the file cannot be + /// read or does not list the app, empty when the app lists none. + public static func launchOptions(appID: UInt32, inFileAt url: URL) -> [SteamLaunchOption]? { + guard let data = try? Data(contentsOf: url, options: .alwaysMapped) else { return nil } + return launchOptions(appID: appID, in: data) + } + + public static func launchOptions(appID: UInt32, in data: Data) -> [SteamLaunchOption]? { + data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [SteamLaunchOption]? in + guard let information = appInformation(appID: appID, in: bytes) else { return nil } + return launchOptions(fromAppInformation: information) + } + } + + // MARK: - Binary KeyValues + + /// A binary KeyValues value. Numbers are kept as their decimal text, + /// since Steam writes a few launch fields either way; values a launch + /// does not need are `.other`. + enum Node { + case object([(key: String, value: Node)]) + case string(String) + case other + + var entries: [(key: String, value: Node)]? { + if case .object(let entries) = self { return entries } + return nil + } + } + + static func appInformation(appID: UInt32, + in bytes: UnsafeRawBufferPointer) -> [(key: String, value: Node)]? { + var cursor = ByteCursor(bytes: bytes) + guard let magic = cursor.uint32(), [format27, format28, format29, format2A].contains(magic), + cursor.uint32() != nil else { return nil } // the universe + if magic == format2A { return shardAppInformation(appID: appID, in: bytes, after: cursor) } + var keyTableOffset: Int? + if magic == format29 { + guard let offset = cursor.uint64(), offset < UInt64(bytes.count) else { return nil } + keyTableOffset = Int(offset) + } + // After `size`: info state, last update, PICS token, SHA-1 of the + // text form, change number and, from format 28, SHA-1 of the binary + // form. The app's KeyValues fill the rest of the entry. + let fixedFields = 4 + 4 + 8 + 20 + 4 + (magic == format27 ? 0 : 20) + while let id = cursor.uint32(), id != 0 { + guard let size = cursor.uint32(), Int(size) <= cursor.remaining else { return nil } + let start = cursor.offset + let end = start + Int(size) + guard id == appID else { + cursor.offset = end + continue + } + guard Int(size) > fixedFields else { return nil } + var keys: [String]? + if let keyTableOffset { + guard let table = keyTable(at: keyTableOffset, in: bytes) else { return nil } + keys = table + } + var information = ByteCursor(bytes: bytes, offset: start + fixedFields, end: end) + return object(&information, keys: keys, depth: 0) + } + return nil + } + + /// Version 42: after the universe, the shard's index and count, the + /// number of apps, the index's size, the number of keys, the key table's + /// size, the data's size and two CRC-32s. Each index entry holds the + /// AppID, the offset and size of its data from the start of the data + /// section, and the size of a summary that follows; an app's data is the + /// SHA-1 of its binary form, then its KeyValues. + static func shardAppInformation(appID: UInt32, in bytes: UnsafeRawBufferPointer, + after header: ByteCursor) -> [(key: String, value: Node)]? { + var cursor = header + var fields = [Int]() + for _ in 0..<9 { + guard let field = cursor.uint32() else { return nil } + fields.append(Int(field)) + } + let (appCount, indexSize, keyCount, keyTableSize) = (fields[2], fields[3], fields[4], fields[5]) + let indexStart = cursor.offset + let keyTableStart = indexStart + indexSize + let dataStart = keyTableStart + keyTableSize + guard dataStart <= bytes.count else { return nil } + var index = ByteCursor(bytes: bytes, offset: indexStart, end: keyTableStart) + for _ in 0.. 20, end <= bytes.count, + let keys = strings(keyCount, at: keyTableStart, end: dataStart, in: bytes) else { + return nil + } + var information = ByteCursor(bytes: bytes, offset: start + 20, end: end) + return object(&information, keys: keys, depth: 0) + } + return nil + } + + /// Version 41's key table: a count, then the keys. + static func keyTable(at offset: Int, in bytes: UnsafeRawBufferPointer) -> [String]? { + var cursor = ByteCursor(bytes: bytes, offset: offset) + guard let count = cursor.uint32() else { return nil } + return strings(Int(count), at: cursor.offset, end: bytes.count, in: bytes) + } + + /// `count` NUL-terminated UTF-8 strings from `offset`, all before `end`. + static func strings(_ count: Int, at offset: Int, end: Int, + in bytes: UnsafeRawBufferPointer) -> [String]? { + var cursor = ByteCursor(bytes: bytes, offset: offset, end: end) + // Every string takes at least its terminating NUL. + guard count >= 0, count <= cursor.remaining else { return nil } + var result = [String]() + result.reserveCapacity(count) + for _ in 0.. [(key: String, value: Node)]? { + guard depth < maximumDepth else { return nil } + var entries = [(key: String, value: Node)]() + while let type = cursor.byte() { + if type == 0x08 || type == 0x0B { return entries } + let key: String + if let keys { + guard let index = cursor.uint32(), Int(index) < keys.count else { return nil } + key = keys[Int(index)] + } else { + guard let name = cursor.cString() else { return nil } + key = name + } + switch type { + case 0x00: + guard let children = object(&cursor, keys: keys, depth: depth + 1) else { return nil } + entries.append((key: key, value: .object(children))) + case 0x01: + guard let text = cursor.cString() else { return nil } + entries.append((key: key, value: .string(text))) + case 0x02: + guard let value = cursor.uint32() else { return nil } + entries.append((key: key, value: .string(String(Int32(bitPattern: value))))) + case 0x07: + guard let value = cursor.uint64() else { return nil } + entries.append((key: key, value: .string(String(value)))) + case 0x0A: + guard let value = cursor.uint64() else { return nil } + entries.append((key: key, value: .string(String(Int64(bitPattern: value))))) + case 0x03, 0x04, 0x06: // float, pointer, colour + guard cursor.skip(4) else { return nil } + entries.append((key: key, value: .other)) + case 0x05: // UTF-16 text + guard cursor.skipWideString() else { return nil } + entries.append((key: key, value: .other)) + default: + return nil + } + } + return nil // the bytes ended inside the object + } + + static func launchOptions( + fromAppInformation root: [(key: String, value: Node)] + ) -> [SteamLaunchOption] { + // An entry holds one object, "appinfo"; its contents are accepted at + // the top as well. + let information = child(root, "appinfo")?.entries ?? root + guard let config = child(information, "config")?.entries, + let launch = child(config, "launch")?.entries else { return [] } + return launch.compactMap { option -> SteamLaunchOption? in + guard let fields = option.value.entries else { return nil } + let requirements = child(fields, "config")?.entries ?? [] + return SteamLaunchOption( + executable: text(fields, "executable"), + arguments: text(fields, "arguments"), + workingDirectory: text(fields, "workingdir"), + type: text(fields, "type"), + operatingSystems: text(requirements, "oslist"), + architecture: text(requirements, "osarch"), + betaKey: text(requirements, "betakey"), + realm: text(requirements, "realm")) + } + } + + private static func child(_ entries: [(key: String, value: Node)], _ key: String) -> Node? { + entries.first { $0.key.caseInsensitiveCompare(key) == .orderedSame }?.value + } + + private static func text(_ entries: [(key: String, value: Node)], _ key: String) -> String { + if case .string(let value)? = child(entries, key) { return value } + return "" + } +} + +/// Little-endian reads that never pass `end`; each returns nil, or false, +/// instead of reading out of bounds. +struct ByteCursor { + let bytes: UnsafeRawBufferPointer + var offset: Int + let end: Int + + init(bytes: UnsafeRawBufferPointer, offset: Int = 0, end: Int? = nil) { + self.bytes = bytes + self.offset = offset + self.end = min(end ?? bytes.count, bytes.count) + } + + var remaining: Int { max(0, end - offset) } + + mutating func byte() -> UInt8? { + guard offset >= 0, offset < end else { return nil } + defer { offset += 1 } + return bytes[offset] + } + + mutating func uint32() -> UInt32? { + guard offset >= 0, remaining >= 4 else { return nil } + var value: UInt32 = 0 + for index in 0..<4 { + value |= UInt32(bytes[offset + index]) << (8 * index) + } + offset += 4 + return value + } + + mutating func uint64() -> UInt64? { + guard offset >= 0, remaining >= 8 else { return nil } + var value: UInt64 = 0 + for index in 0..<8 { + value |= UInt64(bytes[offset + index]) << (8 * index) + } + offset += 8 + return value + } + + mutating func skip(_ count: Int) -> Bool { + guard count >= 0, offset >= 0, remaining >= count else { return false } + offset += count + return true + } + + /// NUL-terminated UTF-8 text. + mutating func cString() -> String? { + guard offset >= 0, offset < end else { return nil } + var terminator = offset + while terminator < end, bytes[terminator] != 0 { + terminator += 1 + } + guard terminator < end else { return nil } + let text = String(decoding: bytes[offset.. Bool { + while remaining >= 2 { + let low = bytes[offset] + let high = bytes[offset + 1] + offset += 2 + if low == 0 && high == 0 { return true } + } + return false + } +} diff --git a/streamer/Sources/BasaltBottleKit/SteamDirectLaunch.swift b/streamer/Sources/BasaltBottleKit/SteamDirectLaunch.swift new file mode 100644 index 0000000..e790982 --- /dev/null +++ b/streamer/Sources/BasaltBottleKit/SteamDirectLaunch.swift @@ -0,0 +1,434 @@ +import Foundation + +/// The game a Steam profile starts, found on disk instead of through the +/// Steam client. +/// +/// `steam.exe -applaunch APP_ID` only hands the AppID to the Steam client +/// that is already running: Wine returns at once, and Steam starts the game +/// with its own environment, without this session's `BASALT_CONTROL` and +/// `DXMT_BASALT_IOSURFACE`. The OpenXR runtime then cannot reach the +/// streamer, the game is told not to render and the headset stays black, +/// while the manager takes the returned launcher for the game's exit and +/// shuts the environment down. So TrailBridge starts the game's own +/// executable itself, the way Steam would: the verified executable for the +/// few games in `verifiedExecutables`, else the launch option Steam keeps +/// for the app in `appcache/appinfo.vdf`, else the game's folder (a Unity +/// player, an Unreal game, or its only `.exe`). +public struct SteamDirectLaunch: Equatable, Sendable { + public enum Origin: String, Equatable, Sendable { + /// `SteamDirectLaunch.verifiedExecutables`. + case verified + /// A launch option from Steam's `appinfo.vdf`. + case steamLaunchOptions + /// The game's folder. + case gameFolder + } + + /// The game's `.exe` on this Mac. + public var executable: URL + /// The arguments of Steam's launch option, if any; a profile's own + /// arguments come after them. + public var arguments: [String] + public var workingDirectory: URL + public var origin: Origin + + public init(executable: URL, arguments: [String] = [], workingDirectory: URL, + origin: Origin) { + self.executable = executable + self.arguments = arguments + self.workingDirectory = workingDirectory + self.origin = origin + } +} + +extension SteamDirectLaunch { + /// Executables verified in a headset, relative to the game's install + /// folder with "/" between components. They win over Steam's own launch + /// options: Blood Trail, for one, starts its Unreal game binary rather + /// than the launcher Steam names. + public static let verifiedExecutables: [String: String] = [ + "620980": "Beat Saber.exe", + "2669380": "BrutalistickVR.exe", + "1032430": "BTVR/Binaries/Win64/BTVR-Win64-Shipping.exe", + ] + + /// Install folders of verified games, for environments whose Steam + /// library has lost the game's manifest. + static let verifiedInstallFolders: [String: String] = ["620980": "Beat Saber"] + + /// The game `appID` names, inside `prefix`. `gameRoot` is the profile's + /// game folder, used when Steam's manifest does not name one. + public static func resolve(appID: String, prefix: URL, gameRoot: URL? = nil, + fileManager: FileManager = .default) throws -> SteamDirectLaunch { + guard !appID.isEmpty, appID.utf8.allSatisfy({ (48...57).contains($0) }), + let numericID = UInt32(appID) else { + throw BottleToolError("Steam AppID must contain ASCII digits only.") + } + let roots = steamRoots(in: prefix, fileManager: fileManager) + guard let install = installDirectory( + appID: appID, prefix: prefix, steamRoots: roots, gameRoot: gameRoot, + fileManager: fileManager) else { + throw BottleToolError( + "Steam app \(appID) is not installed in this environment. Open Steam, install the game or let its update finish, then try again.") + } + if let relative = verifiedExecutables[appID] { + guard let executable = existingItem( + relative, in: install, directory: false, fileManager: fileManager) else { + throw BottleToolError( + "Steam reports app \(appID), but \(relative) is missing from “\(install.lastPathComponent)”. Open Steam, finish any pending update or verify the game's files, then try again.") + } + return SteamDirectLaunch( + executable: executable, workingDirectory: executable.deletingLastPathComponent(), + origin: .verified) + } + if let launch = fromLaunchOptions( + appID: numericID, install: install, steamRoots: roots, fileManager: fileManager) { + return launch + } + if let found = gameExecutable(in: install, fileManager: fileManager) { + let executable = unrealGameBinary(launching: found, in: install, fileManager: fileManager) + ?? found + return SteamDirectLaunch( + executable: executable, workingDirectory: executable.deletingLastPathComponent(), + origin: .gameFolder) + } + throw BottleToolError( + "TrailBridge could not tell which .exe in “\(install.lastPathComponent)” is the game. In the Library, open the game's ⋯ menu → Edit Launch Profile… and choose the game's own .exe instead of steam.exe.") + } + + // MARK: - Steam's records + + static func steamRoots(in prefix: URL, fileManager: FileManager) -> [URL] { + let driveC = prefix.appendingPathComponent("drive_c", isDirectory: true) + return ["Program Files (x86)/Steam", "Program Files/Steam"] + .map { driveC.appendingPathComponent($0, isDirectory: true) } + .filter { isDirectory($0, fileManager: fileManager) } + } + + /// `steamapps/common/` from the app's manifest in any of the + /// bottle's Steam libraries, else the profile's game folder, else the + /// usual folder of a verified game. + static func installDirectory(appID: String, prefix: URL, steamRoots: [URL], gameRoot: URL?, + fileManager: FileManager) -> URL? { + for library in libraries(prefix: prefix, steamRoots: steamRoots, fileManager: fileManager) { + let manifest = library.appendingPathComponent("appmanifest_\(appID).acf") + guard let text = try? String(contentsOf: manifest, encoding: .utf8), + let folder = vdfValues("installdir", in: text).first, + isPlainName(folder) else { continue } + let install = library.appendingPathComponent("common", isDirectory: true) + .appendingPathComponent(folder, isDirectory: true) + if isDirectory(install, fileManager: fileManager) { return install } + } + if let gameRoot, isDirectory(gameRoot, fileManager: fileManager) { return gameRoot } + if let folder = verifiedInstallFolders[appID] { + for root in steamRoots { + let install = root.appendingPathComponent("steamapps", isDirectory: true) + .appendingPathComponent("common", isDirectory: true) + .appendingPathComponent(folder, isDirectory: true) + if isDirectory(install, fileManager: fileManager) { return install } + } + } + return nil + } + + /// Each Steam root's `steamapps` folder, then the libraries its + /// `libraryfolders.vdf` lists. + static func libraries(prefix: URL, steamRoots: [URL], fileManager: FileManager) -> [URL] { + var folders = [URL]() + for root in steamRoots { + let steamApps = root.appendingPathComponent("steamapps", isDirectory: true) + folders.append(steamApps) + let list = steamApps.appendingPathComponent("libraryfolders.vdf") + guard let text = try? String(contentsOf: list, encoding: .utf8) else { continue } + for path in vdfValues("path", in: text) { + if let library = hostURL(forWindowsPath: path, prefix: prefix, fileManager: fileManager) { + folders.append(library.appendingPathComponent("steamapps", isDirectory: true)) + } + } + } + var seen = Set() + return folders.filter { seen.insert($0.standardizedFileURL.path).inserted } + } + + /// The best launch option for TrailBridge whose executable exists: + /// SteamVR's own option first, then the default one, the numbered ones, + /// and the option for other VR systems last. Options for other systems, + /// beta branches, servers and editors are never used. + static func fromLaunchOptions(appID: UInt32, install: URL, steamRoots: [URL], + fileManager: FileManager) -> SteamDirectLaunch? { + for root in steamRoots { + let cache = root.appendingPathComponent("appcache", isDirectory: true) + .appendingPathComponent("appinfo.vdf") + guard let options = SteamAppInfo.launchOptions(appID: appID, inFileAt: cache) else { + continue + } + let ranked = options.enumerated() + .compactMap { item -> (rank: Int, index: Int, option: SteamLaunchOption)? in + guard let rank = launchRank(item.element) else { return nil } + return (rank: rank, index: item.offset, option: item.element) + } + .sorted { ($0.rank, $0.index) < ($1.rank, $1.index) } + for candidate in ranked { + let option = candidate.option + guard option.executable.lowercased().hasSuffix(".exe"), + let found = existingItem( + option.executable, in: install, directory: false, fileManager: fileManager) + else { continue } + if let game = unrealGameBinary(launching: found, in: install, fileManager: fileManager) { + return SteamDirectLaunch( + executable: game, arguments: commandLineArguments(option.arguments), + workingDirectory: game.deletingLastPathComponent(), + origin: .steamLaunchOptions) + } + let folder = option.workingDirectory.isEmpty ? nil : existingItem( + option.workingDirectory, in: install, directory: true, fileManager: fileManager) + return SteamDirectLaunch( + executable: found, arguments: commandLineArguments(option.arguments), + workingDirectory: folder ?? found.deletingLastPathComponent(), + origin: .steamLaunchOptions) + } + } + return nil + } + + /// Lower is better; nil means TrailBridge never starts the option. + static func launchRank(_ option: SteamLaunchOption) -> Int? { + let systems = option.operatingSystems.lowercased().split(separator: ",") + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + guard systems.isEmpty || systems.contains("windows"), + option.betaKey.isEmpty, + option.realm.lowercased() != "steamchina" else { return nil } + let rank: Int + switch option.type.lowercased() { + case "vr": rank = 0 + case "", "default": rank = 1 + case "server", "editor", "manual", "openvroverlay", "osvr": return nil + case "othervr": rank = 3 + default: rank = 2 // option1…option3 and none + } + return option.architecture == "32" ? rank + 10 : rank + } + + /// Splits one command line at spaces and tabs outside double quotes, the + /// way the game's C runtime will see it. + static func commandLineArguments(_ line: String) -> [String] { + var arguments = [String]() + var current = "" + var quoted = false + var started = false + for character in line { + if character == "\"" { + quoted.toggle() + started = true + } else if !quoted, character == " " || character == "\t" { + if started { + arguments.append(current) + current = "" + started = false + } + } else { + current.append(character) + started = true + } + } + if started { arguments.append(current) } + return arguments + } + + // MARK: - The game's folder + + /// A Unity player (`Game.exe` beside `Game_Data`), else the `.exe` named + /// like the folder, else an Unreal `*-Win64-Shipping.exe`, else the only + /// probable game. Nil when several files remain equally likely: starting + /// the wrong one would only look like another broken launch. + static func gameExecutable(in install: URL, fileManager: FileManager) -> URL? { + let scan = scanExecutables(in: install, fileManager: fileManager) + let games = scan.executables.filter { isProbableGame($0.relative) } + let unity = games.filter { candidate in + let stem = (candidate.name as NSString).deletingPathExtension + let data = candidate.folder.isEmpty ? stem + "_Data" : candidate.folder + "/" + stem + "_Data" + return scan.folders.contains(data.lowercased()) + } + if unity.count == 1 { return unity[0].url } + let pool = unity.isEmpty ? games : unity + let folderName = comparableName(install.lastPathComponent) + let named = pool.filter { + !folderName.isEmpty + && comparableName(($0.name as NSString).deletingPathExtension) == folderName + } + if named.count == 1 { return named[0].url } + if unity.isEmpty { + let shipping = games.filter { $0.name.lowercased().hasSuffix("-win64-shipping.exe") } + if shipping.count == 1 { return shipping[0].url } + } + return pool.count == 1 ? pool[0].url : nil + } + + /// Unreal's packaged game, `/Binaries/Win64/-Win64-Shipping.exe`, + /// when `executable` is the small launcher at the top of the install + /// folder that starts it. The session lasts as long as the started + /// process, so the game itself wins over its launcher. + static func unrealGameBinary(launching executable: URL, in install: URL, + fileManager: FileManager) -> URL? { + guard executable.deletingLastPathComponent().standardizedFileURL.path + == install.standardizedFileURL.path, + let names = try? fileManager.contentsOfDirectory(atPath: install.path) else { return nil } + let binaries = names + .filter { !$0.hasPrefix(".") && $0.lowercased() != "engine" } + .compactMap { + existingItem("\($0)/Binaries/Win64/\($0)-Win64-Shipping.exe", in: install, + directory: false, fileManager: fileManager) + } + return binaries.count == 1 ? binaries[0] : nil + } + + struct ExecutableCandidate { + let url: URL + /// Relative to the install folder, "/"-separated. + let relative: String + /// The folder part of `relative`; empty at the top. + let folder: String + let name: String + } + + struct ExecutableScan { + var executables = [ExecutableCandidate]() + /// Every folder seen, relative and lowercased. + var folders = Set() + } + + /// `.exe` files at most `maximumDepth` levels down, outside hidden + /// folders. A game folder with more entries than `maximumEntries` is + /// scanned only that far. + static func scanExecutables(in install: URL, fileManager: FileManager, maximumDepth: Int = 4, + maximumEntries: Int = 20_000) -> ExecutableScan { + var scan = ExecutableScan() + guard let enumerator = fileManager.enumerator(atPath: install.path) else { return scan } + var visited = 0 + while let relative = enumerator.nextObject() as? String { + visited += 1 + if visited > maximumEntries { break } + let name = (relative as NSString).lastPathComponent + let type = enumerator.fileAttributes?[.type] as? FileAttributeType + if name.hasPrefix(".") { + if type == .typeDirectory { enumerator.skipDescendants() } + continue + } + if type == .typeDirectory { + scan.folders.insert(relative.lowercased()) + if enumerator.level >= maximumDepth { enumerator.skipDescendants() } + continue + } + guard type == .typeRegular, (name as NSString).pathExtension.lowercased() == "exe" else { + continue + } + scan.executables.append(ExecutableCandidate( + url: install.appendingPathComponent(relative, isDirectory: false), + relative: relative, folder: (relative as NSString).deletingLastPathComponent, + name: name)) + } + return scan + } + + /// Not a crash reporter, runtime installer, uninstaller or setup program, + /// judged as Add Game from Folder judges them. + static func isProbableGame(_ relative: String) -> Bool { + let components = relative.split(separator: "/").map { $0.lowercased() } + guard let file = components.last else { return false } + if components.dropLast().contains(where: { helperFolders.contains($0) }) { return false } + let stem = (file as NSString).deletingPathExtension + if helperNames.contains(stem) || helperPrefixes.contains(where: { stem.hasPrefix($0) }) { + return false + } + return !installerWords.contains { stem.contains($0) } + } + + static let helperNames: Set = ["crashpad_handler", "dxsetup"] + static let helperPrefixes = [ + "unitycrashhandler", "crashreportclient", "crashreporter", "crashhandler", + "steamerrorreporter", "vc_redist", "vcredist", "dotnetfx", "ue4prereqsetup", + "ueprereqsetup", "unins", + ] + static let helperFolders: Set = ["_commonredist", "redist", "__installer"] + static let installerWords = ["setup", "install"] + + /// "Beat Saber.exe" in "Beat Saber", also "SomeGame.exe" in "Some Game": + /// case, accents, spaces and punctuation do not count. + static func comparableName(_ value: String) -> String { + let folded = value.folding( + options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: nil) + return String(String.UnicodeScalarView( + folded.unicodeScalars.filter { CharacterSet.alphanumerics.contains($0) })) + } + + // MARK: - Paths + + /// `relative` (Steam's `\` or `/` separators) inside `base`, matching + /// each name regardless of case as Windows does and spelled as on disk; + /// nil when it climbs out with `..`, names a drive, or is not there as a + /// file (or folder). + static func existingItem(_ relative: String, in base: URL, directory: Bool, + fileManager: FileManager) -> URL? { + let components = relative.split(whereSeparator: { $0 == "\\" || $0 == "/" }) + .map(String.init) + .filter { $0 != "." } + guard !components.isEmpty, !components.contains(".."), + !components.contains(where: { $0.contains(":") }) else { return nil } + var url = base + for (index, component) in components.enumerated() { + guard let names = try? fileManager.contentsOfDirectory(atPath: url.path) else { return nil } + let match = names.contains(component) + ? Optional(component) + : names.first(where: { $0.caseInsensitiveCompare(component) == .orderedSame }) + guard let name = match else { return nil } + url = url.appendingPathComponent(name, isDirectory: directory || index < components.count - 1) + } + var isFolder: ObjCBool = false + guard fileManager.fileExists(atPath: url.path, isDirectory: &isFolder), + isFolder.boolValue == directory else { return nil } + return url + } + + static func isDirectory(_ url: URL, fileManager: FileManager) -> Bool { + var isFolder: ObjCBool = false + return fileManager.fileExists(atPath: url.path, isDirectory: &isFolder) && isFolder.boolValue + } + + static func isPlainName(_ name: String) -> Bool { + !name.isEmpty && name != "." && name != ".." + && !name.contains("/") && !name.contains("\\") && !name.contains(":") + } + + /// `C:\…` inside the prefix's `drive_c`; another drive through the + /// prefix's `dosdevices` link. + static func hostURL(forWindowsPath path: String, prefix: URL, fileManager: FileManager) -> URL? { + let normalized = path.replacingOccurrences(of: "\\", with: "/") + guard normalized.count >= 3, let drive = normalized.first?.lowercased(), + normalized.dropFirst().hasPrefix(":/") else { return nil } + let rest = String(normalized.dropFirst(3)) + if drive == "c" { + return prefix.appendingPathComponent("drive_c", isDirectory: true) + .appendingPathComponent(rest, isDirectory: true) + } + let link = prefix.appendingPathComponent("dosdevices/\(drive):") + guard fileManager.fileExists(atPath: link.path) else { return nil } + return link.resolvingSymlinksInPath().appendingPathComponent(rest, isDirectory: true) + } + + /// The values of `key` in Valve's text KeyValues (`.acf`, `.vdf`), with + /// `\\` and `\"` unescaped. + static func vdfValues(_ key: String, in text: String) -> [String] { + let escaped = NSRegularExpression.escapedPattern(for: key) + guard let expression = try? NSRegularExpression( + pattern: #"\""# + escaped + #"\"\s*\"((?:\\.|[^\"])*)\""#, + options: [.caseInsensitive]) else { return [] } + return expression.matches(in: text, range: NSRange(text.startIndex..., in: text)) + .compactMap { match in + guard let range = Range(match.range(at: 1), in: text) else { return nil } + return String(text[range]) + .replacingOccurrences(of: #"\\"#, with: #"\"#) + .replacingOccurrences(of: #"\""#, with: #"""#) + } + } +} diff --git a/streamer/Sources/BasaltManager/AppModel.swift b/streamer/Sources/BasaltManager/AppModel.swift index 4e3754b..10f52d9 100644 --- a/streamer/Sources/BasaltManager/AppModel.swift +++ b/streamer/Sources/BasaltManager/AppModel.swift @@ -1593,6 +1593,9 @@ final class BasaltAppModel: ObservableObject { appendLog(L10n.string( .modelProfileVariablesDropped, command.droppedEnvironment.joined(separator: ", "))) } + if command.steamLaunch != nil, let executable = command.arguments.first { + appendLog(L10n.string(.modelSteamDirectLaunch, executable)) + } let game = Process() game.executableURL = command.executable game.arguments = command.arguments @@ -1612,10 +1615,20 @@ final class BasaltAppModel: ObservableObject { } game.environment = environment attachOutput(of: game, prefix: "game: ") + let gameStartedAt = Date() game.terminationHandler = { [weak self] game in Task { @MainActor in guard let self, self.gameProcess === game else { return } self.appendLog(L10n.string(.modelGameExited, String(game.terminationStatus))) + // A launcher that starts the game as another process, or + // a game that fails while loading, ends this soon; the + // session ends with it, so say what to try. + let seconds = Date().timeIntervalSince(gameStartedAt) + if seconds < 15 { + self.appendLog(L10n.string( + .modelGameExitedQuickly, String(Int(seconds.rounded())), + L10n.string(.libraryEditProfile))) + } self.gameProcess = nil self.finishSession(.ended) self.stop() diff --git a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift index e2e2c13..040a3c2 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift @@ -67,6 +67,8 @@ public enum L10nKey: String, CaseIterable, Sendable { case uninstallNone case modelGamePriority case modelGameExited + case modelGameExitedQuickly + case modelSteamDirectLaunch case modelGameBroughtForward case modelGameBringForwardFailed case modelWineCleanupFailed diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift index a9d41c7..f261856 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift @@ -70,6 +70,8 @@ final class StringsDE: LocalizationTable { .uninstallNone: "Keine", .modelGamePriority: "Priorität des Spielprozesses: hoch (user-interactive QoS)\n", .modelGameExited: "Spiel mit Status %1$@ beendet\n", + .modelGameExitedQuickly: "Das Spiel endete %1$@ s nach dem Start. Erschien nichts im Headset, ist die gestartete Datei vielleicht ein Launcher, der das Spiel als eigenen Prozess öffnet, oder das Spiel hat beim Laden aufgehört (siehe die „game:“-Zeilen oben). Um die .exe des Spiels selbst zu starten, diese unter Bibliothek → Spielkarte → ⋯ → %2$@ auswählen.\n", + .modelSteamDirectLaunch: "Das Spiel wird direkt gestartet, nicht über Steam: %1$@\n", .modelGameBroughtForward: "Das Spielfenster ist wieder vorne: Viele Spiele geben nur Ton aus, solange ihr Fenster auf dem Mac vorne ist.\n", .modelGameBringForwardFailed: "Das Spielfenster ließ sich nicht nach vorne holen. Wird das Headset stumm, auf dem Mac auf das Spielfenster klicken.\n", .modelWineCleanupFailed: "Wine-Bereinigung fehlgeschlagen: %1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift index b17ec3a..f30281a 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift @@ -70,6 +70,8 @@ final class StringsEN: LocalizationTable { .uninstallNone: "None", .modelGamePriority: "Game process priority: high (user-interactive QoS)\n", .modelGameExited: "Game exited with status %1$@\n", + .modelGameExitedQuickly: "The game ended %1$@ s after it started. If nothing appeared in the headset, the file started may be a launcher that opens the game as a separate process, or the game stopped while loading (see the “game:” lines above). To start the game's own .exe, choose it in Library → game card → ⋯ → %2$@\n", + .modelSteamDirectLaunch: "Starting the game itself rather than through Steam: %1$@\n", .modelGameBroughtForward: "Brought the game's window back to the front: many games play sound only while their window on the Mac is in front.\n", .modelGameBringForwardFailed: "Could not bring the game's window back to the front. If the headset goes silent, click the game's window on the Mac.\n", .modelWineCleanupFailed: "Wine cleanup failed: %1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift index 4bb84c2..6801ea9 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift @@ -70,6 +70,8 @@ final class StringsES: LocalizationTable { .uninstallNone: "Ninguno", .modelGamePriority: "Prioridad del proceso del juego: alta (user-interactive QoS)\n", .modelGameExited: "El juego terminó con el código %1$@\n", + .modelGameExitedQuickly: "El juego terminó %1$@ s después de iniciarse. Si no apareció nada en el visor, el archivo iniciado puede ser un lanzador que abre el juego en otro proceso, o el juego se detuvo al cargar (consulta las líneas «game:» de arriba). Para iniciar el .exe del propio juego, elígelo en Biblioteca → tarjeta del juego → ⋯ → %2$@\n", + .modelSteamDirectLaunch: "Iniciando el juego directamente, no a través de Steam: %1$@\n", .modelGameBroughtForward: "La ventana del juego vuelve a estar al frente: muchos juegos solo suenan mientras su ventana está al frente en el Mac.\n", .modelGameBringForwardFailed: "No se pudo traer al frente la ventana del juego. Si el visor se queda sin sonido, haz clic en la ventana del juego en el Mac.\n", .modelWineCleanupFailed: "Falló la limpieza de Wine: %1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift index 52c3e0e..0eb3c79 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift @@ -70,6 +70,8 @@ final class StringsFR: LocalizationTable { .uninstallNone: "Aucun", .modelGamePriority: "Priorité du processus du jeu : élevée (user-interactive QoS)\n", .modelGameExited: "Le jeu s’est arrêté avec le code %1$@\n", + .modelGameExitedQuickly: "Le jeu s’est arrêté %1$@ s après son lancement. Si rien n’est apparu dans le casque, le fichier lancé est peut-être un lanceur qui ouvre le jeu dans un processus séparé, ou le jeu s’est arrêté pendant le chargement (voir les lignes « game: » ci-dessus). Pour lancer le .exe du jeu lui-même, choisissez-le dans Bibliothèque → fiche du jeu → ⋯ → %2$@\n", + .modelSteamDirectLaunch: "Lancement direct du jeu, sans passer par Steam : %1$@\n", .modelGameBroughtForward: "La fenêtre du jeu est de nouveau au premier plan : beaucoup de jeux n’émettent du son que si leur fenêtre est au premier plan sur le Mac.\n", .modelGameBringForwardFailed: "Impossible de ramener la fenêtre du jeu au premier plan. Si le casque devient muet, cliquez sur la fenêtre du jeu sur le Mac.\n", .modelWineCleanupFailed: "Échec du nettoyage de Wine : %1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift index 4503523..4260f90 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift @@ -70,6 +70,8 @@ final class StringsIT: LocalizationTable { .uninstallNone: "Nessuno", .modelGamePriority: "Priorità del processo di gioco: alta (user-interactive QoS)\n", .modelGameExited: "Gioco terminato con codice %1$@\n", + .modelGameExitedQuickly: "Il gioco è terminato %1$@ s dopo l’avvio. Se nel visore non è apparso nulla, il file avviato può essere un launcher che apre il gioco in un processo separato, oppure il gioco si è fermato durante il caricamento (vedi le righe «game:» sopra). Per avviare l’.exe del gioco stesso, sceglilo in Libreria → scheda del gioco → ⋯ → %2$@\n", + .modelSteamDirectLaunch: "Avvio diretto del gioco, senza passare da Steam: %1$@\n", .modelGameBroughtForward: "La finestra del gioco è di nuovo in primo piano: molti giochi riproducono l’audio solo quando la loro finestra sul Mac è in primo piano.\n", .modelGameBringForwardFailed: "Impossibile riportare in primo piano la finestra del gioco. Se il visore resta senza audio, fai clic sulla finestra del gioco sul Mac.\n", .modelWineCleanupFailed: "Pulizia di Wine non riuscita: %1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift index fd0a160..a4a6f5e 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift @@ -70,6 +70,8 @@ final class StringsJA: LocalizationTable { .uninstallNone: "なし", .modelGamePriority: "ゲームプロセスの優先度:高(user-interactive QoS)\n", .modelGameExited: "ゲームがコード%1$@で終了しました\n", + .modelGameExitedQuickly: "ゲームは起動から%1$@秒後に終了しました。ヘッドセットに何も表示されなかった場合、起動したファイルがゲームを別のプロセスで開くランチャーであるか、読み込み中にゲームが停止した可能性があります(上の「game:」の行を確認してください)。ゲーム本体の.exeを起動するには、ライブラリ → ゲームカード → ⋯ → %2$@ で選択してください。\n", + .modelSteamDirectLaunch: "Steam経由ではなくゲーム本体を起動します:%1$@\n", .modelGameBroughtForward: "ゲームのウインドウを最前面に戻しました。多くのゲームは、Mac でウインドウが最前面にあるときだけ音を出します。\n", .modelGameBringForwardFailed: "ゲームのウインドウを最前面に戻せませんでした。ヘッドセットの音が消えたら、Mac でゲームのウインドウをクリックしてください。\n", .modelWineCleanupFailed: "Wineの整理に失敗しました:%1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift index bcc07b7..86adb25 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift @@ -70,6 +70,8 @@ final class StringsKO: LocalizationTable { .uninstallNone: "없음", .modelGamePriority: "게임 프로세스 우선순위: 높음(user-interactive QoS)\n", .modelGameExited: "게임 종료 코드: %1$@\n", + .modelGameExitedQuickly: "게임이 시작 후 %1$@초 만에 종료되었습니다. 헤드셋에 아무것도 나타나지 않았다면, 실행한 파일이 게임을 별도 프로세스로 여는 런처이거나 게임이 로딩 중에 멈췄을 수 있습니다(위의 “game:” 줄 참고). 게임 본체의 .exe를 실행하려면 라이브러리 → 게임 카드 → ⋯ → %2$@에서 선택하세요.\n", + .modelSteamDirectLaunch: "Steam을 거치지 않고 게임을 직접 실행합니다: %1$@\n", .modelGameBroughtForward: "게임 창을 다시 맨 앞으로 가져왔습니다. 많은 게임은 Mac에서 창이 맨 앞에 있을 때만 소리를 냅니다.\n", .modelGameBringForwardFailed: "게임 창을 맨 앞으로 가져오지 못했습니다. 헤드셋에서 소리가 사라지면 Mac에서 게임 창을 클릭하세요.\n", .modelWineCleanupFailed: "Wine 정리 실패: %1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift index 506e082..c003066 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift @@ -70,6 +70,8 @@ final class StringsPL: LocalizationTable { .uninstallNone: "Brak", .modelGamePriority: "Priorytet procesu gry: wysoki (user-interactive QoS)\n", .modelGameExited: "Gra zakończyła się z kodem %1$@\n", + .modelGameExitedQuickly: "Gra zakończyła się %1$@ s po uruchomieniu. Jeśli w goglach nic się nie pojawiło, uruchomiony plik może być launcherem, który otwiera grę jako osobny proces, albo gra zatrzymała się podczas ładowania (zobacz wiersze „game:” powyżej). Aby uruchamiać sam plik .exe gry, wybierz go w: Biblioteka → karta gry → ⋯ → %2$@\n", + .modelSteamDirectLaunch: "Uruchamianie samej gry, nie przez Steam: %1$@\n", .modelGameBroughtForward: "Okno gry znów jest na pierwszym planie: wiele gier gra dźwięk tylko wtedy, gdy ich okno na Macu jest na wierzchu.\n", .modelGameBringForwardFailed: "Nie udało się przywrócić okna gry na pierwszy plan. Jeśli w goglach zniknie dźwięk, kliknij okno gry na Macu.\n", .modelWineCleanupFailed: "Nie udało się posprzątać procesów Wine: %1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift index 49bd6ad..6ce7462 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift @@ -70,6 +70,8 @@ final class StringsRU: LocalizationTable { .uninstallNone: "Нет", .modelGamePriority: "Приоритет процесса игры: высокий (user-interactive QoS)\n", .modelGameExited: "Игра завершилась с кодом %1$@\n", + .modelGameExitedQuickly: "Игра завершилась через %1$@ с после запуска. Если в шлеме ничего не появилось, запущенный файл может быть лаунчером, который открывает игру отдельным процессом, или игра остановилась при загрузке (см. строки «game:» выше). Чтобы запускать сам .exe игры, выберите его: «Библиотека» → карточка игры → ⋯ → «%2$@».\n", + .modelSteamDirectLaunch: "Запускаем саму игру, а не через Steam: %1$@\n", .modelGameBroughtForward: "Окно игры снова впереди: многие игры звучат, только пока их окно на Mac впереди.\n", .modelGameBringForwardFailed: "Не удалось вернуть окно игры вперёд. Если в шлеме пропал звук, щёлкните окно игры на Mac.\n", .modelWineCleanupFailed: "Не удалось очистить процессы Wine: %1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift index 55026ce..fae07df 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift @@ -70,6 +70,8 @@ final class StringsUK: LocalizationTable { .uninstallNone: "Немає", .modelGamePriority: "Пріоритет процесу гри: високий (user-interactive QoS)\n", .modelGameExited: "Гра завершилася з кодом %1$@\n", + .modelGameExitedQuickly: "Гра завершилася через %1$@ с після запуску. Якщо в шоломі нічого не з’явилося, запущений файл може бути лаунчером, що відкриває гру окремим процесом, або гра зупинилася під час завантаження (див. рядки «game:» вище). Щоб запускати сам .exe гри, виберіть його: Бібліотека → картка гри → ⋯ → %2$@\n", + .modelSteamDirectLaunch: "Запускаємо саму гру, а не через Steam: %1$@\n", .modelGameBroughtForward: "Вікно гри знову попереду: багато ігор звучать, лише поки їхнє вікно на Mac попереду.\n", .modelGameBringForwardFailed: "Не вдалося повернути вікно гри наперед. Якщо в шоломі зник звук, клацніть вікно гри на Mac.\n", .modelWineCleanupFailed: "Не вдалося очистити процеси Wine: %1$@\n", diff --git a/streamer/Sources/BasaltManagerKit/SteamInstallation.swift b/streamer/Sources/BasaltManagerKit/SteamInstallation.swift index f0cca29..1cc1d78 100644 --- a/streamer/Sources/BasaltManagerKit/SteamInstallation.swift +++ b/streamer/Sources/BasaltManagerKit/SteamInstallation.swift @@ -61,17 +61,16 @@ public enum SteamInstallation { /// Keep ownership of the actual game process. Steam's -applaunch bootstrap /// can exit while a game is still running; Steam authentication remains a /// separate prerequisite handled by BottleManager's Steam bootstrap. + /// Verified games get their executable here. Every other game keeps + /// `steam.exe -applaunch APP_ID`, which `BottleManager.profileLaunchCommand` + /// resolves to the game's own executable at each launch + /// (`SteamDirectLaunch`), so a game update that renames it still starts. public static func gameProfile(named name: String, game: SteamGame, prefix: URL, fileManager: FileManager = .default) throws -> LaunchProfile { guard game.bottleOrigin == .managed else { throw BottleToolError("Copy the game into a TrailBridge bottle first.") } - let knownExecutables = [ - "620980": "Beat Saber.exe", - "2669380": "BrutalistickVR.exe", - "1032430": "BTVR/Binaries/Win64/BTVR-Win64-Shipping.exe", - ] - let relative = knownExecutables[game.appID] + let relative = SteamDirectLaunch.verifiedExecutables[game.appID] let target = relative.map { game.installDirectory.appendingPathComponent($0) } ?? game.steamExecutable let resolvedPrefix = prefix.resolvingSymlinksInPath().path + "/" diff --git a/streamer/Tests/BasaltBottleKitTests/SteamDirectLaunchTests.swift b/streamer/Tests/BasaltBottleKitTests/SteamDirectLaunchTests.swift new file mode 100644 index 0000000..81b6f8e --- /dev/null +++ b/streamer/Tests/BasaltBottleKitTests/SteamDirectLaunchTests.swift @@ -0,0 +1,520 @@ +import XCTest +@testable import BasaltBottleKit + +final class SteamDirectLaunchTests: XCTestCase { + // MARK: - appinfo.vdf + + func testReadsLaunchOptionsInEveryFormat() throws { + let formats = [SteamAppInfo.format27, SteamAppInfo.format28, SteamAppInfo.format29, + SteamAppInfo.format2A] + for format in formats { + let data = AppInfoFixture(format: format, apps: [ + (id: 480, information: Self.information(launch: [ + [("executable", .string("Spacewar.exe"))], + ])), + (id: 3_256_020, information: Self.information(launch: [ + [ + ("executable", .string("Game.exe")), + ("type", .string("default")), + ("config", .object([("oslist", .string("windows")), ("osarch", .int32(64))])), + ], + [ + ("executable", .string(#"bin\win64\GameVR.exe"#)), + ("arguments", .string(#"-vr -name "Two Words""#)), + ("workingdir", .string(#"bin\win64"#)), + ("type", .string("vr")), + ("config", .object([("BetaKey", .string("public-test"))])), + ], + ])), + ]).data() + + let options = try XCTUnwrap( + SteamAppInfo.launchOptions(appID: 3_256_020, in: data), "format \(format)") + XCTAssertEqual(options, [ + SteamLaunchOption(executable: "Game.exe", type: "default", + operatingSystems: "windows", architecture: "64"), + SteamLaunchOption(executable: #"bin\win64\GameVR.exe"#, + arguments: #"-vr -name "Two Words""#, + workingDirectory: #"bin\win64"#, type: "vr", + betaKey: "public-test"), + ], "format \(format)") + // The entry before it is skipped by its size, and read when asked for. + XCTAssertEqual(SteamAppInfo.launchOptions(appID: 480, in: data)?.map(\.executable), + ["Spacewar.exe"], "format \(format)") + XCTAssertNil(SteamAppInfo.launchOptions(appID: 1, in: data), "format \(format)") + } + } + + func testOtherFormatsAndDamagedFilesReadAsNothing() { + for format in [SteamAppInfo.format28, SteamAppInfo.format29, SteamAppInfo.format2A] { + let good = AppInfoFixture(format: format, apps: [ + (id: 7, information: Self.information(launch: [[("executable", .string("A.exe"))]])), + ]).data() + XCTAssertEqual(SteamAppInfo.launchOptions(appID: 7, in: good)?.map(\.executable), ["A.exe"], + "format \(format)") + + var unknownFormat = good + unknownFormat[unknownFormat.startIndex] = 0x26 + XCTAssertNil(SteamAppInfo.launchOptions(appID: 7, in: unknownFormat), "format \(format)") + // Only the terminating AppID 0 follows the last entry in formats 39 + // to 40, so 5 bytes short ends inside it, as in every format. + for length in [0, 3, 12, 20, good.count / 2, good.count - 5] { + XCTAssertNil(SteamAppInfo.launchOptions(appID: 7, in: good.prefix(length)), + "format \(format), \(length) bytes") + } + } + XCTAssertNil(SteamAppInfo.launchOptions( + appID: 7, inFileAt: URL(fileURLWithPath: "/nonexistent/appinfo.vdf"))) + } + + // MARK: - Choosing a launch option + + func testLaunchRankPrefersSteamVRThenTheDefaultAndNeverServersOrBetas() { + func rank(_ option: SteamLaunchOption) -> Int? { SteamDirectLaunch.launchRank(option) } + XCTAssertEqual(rank(SteamLaunchOption(executable: "a.exe", type: "vr")), 0) + XCTAssertEqual(rank(SteamLaunchOption(executable: "a.exe")), 1) + XCTAssertEqual(rank(SteamLaunchOption(executable: "a.exe", type: "Default")), 1) + XCTAssertEqual(rank(SteamLaunchOption(executable: "a.exe", type: "option1")), 2) + XCTAssertEqual(rank(SteamLaunchOption(executable: "a.exe", type: "othervr")), 3) + XCTAssertEqual(rank(SteamLaunchOption(executable: "a.exe", architecture: "32")), 11) + XCTAssertEqual(rank(SteamLaunchOption(executable: "a.exe", operatingSystems: "windows, macos")), 1) + for option in [ + SteamLaunchOption(executable: "a.exe", operatingSystems: "linux"), + SteamLaunchOption(executable: "a.exe", operatingSystems: "macos,linux"), + SteamLaunchOption(executable: "a.exe", betaKey: "beta"), + SteamLaunchOption(executable: "a.exe", type: "server"), + SteamLaunchOption(executable: "a.exe", type: "editor"), + SteamLaunchOption(executable: "a.exe", type: "manual"), + SteamLaunchOption(executable: "a.exe", realm: "SteamChina"), + ] { + XCTAssertNil(rank(option), "\(option)") + } + } + + func testCommandLineArgumentsKeepQuotedSpaces() { + XCTAssertEqual( + SteamDirectLaunch.commandLineArguments(" -vr\t -name \"Two Words\" -empty \"\" "), + ["-vr", "-name", "Two Words", "-empty", ""]) + XCTAssertEqual(SteamDirectLaunch.commandLineArguments(""), []) + } + + // MARK: - Finding the game on disk + + func testStartsSteamsVRLaunchOptionWithItsArguments() throws { + let steam = try SteamPrefix(test: self) + let install = try steam.install(appID: "3256020", folder: "Electrician Simulator VR", files: [ + "Electrician Simulator VR.exe", "Electrician Simulator VR_Data/", + "bin/win64/GameVR.exe", "UnityCrashHandler64.exe", + ]) + try steam.writeAppInfo(AppInfoFixture(format: SteamAppInfo.format29, apps: [ + (id: 3_256_020, information: Self.information(launch: [ + [("executable", .string("Electrician Simulator VR.exe")), ("type", .string("default"))], + [ + // Windows ignores case; the result is spelled as on disk. + ("executable", .string(#"BIN\Win64\gamevr.exe"#)), + ("arguments", .string("-vr -openxr")), + ("type", .string("vr")), + ("config", .object([("oslist", .string("windows"))])), + ], + [("executable", .string("Server.exe")), ("type", .string("server"))], + ])), + ]).data()) + + let launch = try SteamDirectLaunch.resolve(appID: "3256020", prefix: steam.prefix) + + XCTAssertEqual(launch.origin, .steamLaunchOptions) + XCTAssertEqual(launch.executable.standardizedFileURL.path, + install.appendingPathComponent("bin/win64/GameVR.exe").standardizedFileURL.path) + XCTAssertEqual(launch.arguments, ["-vr", "-openxr"]) + XCTAssertEqual(launch.workingDirectory.standardizedFileURL.path, + install.appendingPathComponent("bin/win64").standardizedFileURL.path) + } + + func testSkipsLaunchOptionsWhoseExecutableIsMissingOrOutsideTheGame() throws { + let steam = try SteamPrefix(test: self) + let install = try steam.install(appID: "10", folder: "Game", files: ["Game.exe", "Tool.exe"]) + try steam.writeAppInfo(AppInfoFixture(format: SteamAppInfo.format28, apps: [ + (id: 10, information: Self.information(launch: [ + [("executable", .string(#"..\..\..\steam.exe"#)), ("type", .string("vr"))], + [("executable", .string(#"C:\Windows\notepad.exe"#)), ("type", .string("vr"))], + [("executable", .string("Missing.exe")), ("type", .string("vr"))], + [("executable", .string("Game.exe")), ("arguments", .string("-vr"))], + ])), + ]).data()) + + let launch = try SteamDirectLaunch.resolve(appID: "10", prefix: steam.prefix) + + XCTAssertEqual(launch.executable.standardizedFileURL.path, + install.appendingPathComponent("Game.exe").standardizedFileURL.path) + XCTAssertEqual(launch.arguments, ["-vr"]) + } + + func testFindsTheUnityPlayerInTheGameFolder() throws { + let steam = try SteamPrefix(test: self) + _ = try steam.install(appID: "20", folder: "Some VR Game", files: [ + "Electrician.exe", "Electrician_Data/", "UnityCrashHandler64.exe", + "_CommonRedist/vcredist/vc_redist.x64.exe", "Tools/Setup.exe", "Tools/Editor.exe", + ]) + + let launch = try SteamDirectLaunch.resolve(appID: "20", prefix: steam.prefix) + + XCTAssertEqual(launch.origin, .gameFolder) + XCTAssertEqual(launch.executable.lastPathComponent, "Electrician.exe") + XCTAssertEqual(launch.arguments, []) + XCTAssertEqual(launch.workingDirectory.lastPathComponent, "Some VR Game") + } + + func testStartsTheUnrealGameBinaryInsteadOfItsLauncher() throws { + let steam = try SteamPrefix(test: self) + _ = try steam.install(appID: "30", folder: "Blade Runner", files: [ + "BladeRunner.exe", "BladeRunner/Binaries/Win64/BladeRunner-Win64-Shipping.exe", + "Engine/Binaries/Win64/CrashReportClient.exe", + ]) + + // Found in the game's folder… + var launch = try SteamDirectLaunch.resolve(appID: "30", prefix: steam.prefix) + XCTAssertEqual(launch.origin, .gameFolder) + XCTAssertEqual(launch.executable.lastPathComponent, "BladeRunner-Win64-Shipping.exe") + XCTAssertEqual(launch.workingDirectory.lastPathComponent, "Win64") + + // …and when Steam names the launcher, whose arguments the game keeps. + try steam.writeAppInfo(AppInfoFixture(format: SteamAppInfo.format29, apps: [ + (id: 30, information: Self.information(launch: [ + [("executable", .string("BladeRunner.exe")), ("arguments", .string("-vr"))], + ])), + ]).data()) + launch = try SteamDirectLaunch.resolve(appID: "30", prefix: steam.prefix) + XCTAssertEqual(launch.origin, .steamLaunchOptions) + XCTAssertEqual(launch.executable.lastPathComponent, "BladeRunner-Win64-Shipping.exe") + XCTAssertEqual(launch.arguments, ["-vr"]) + } + + func testFindsGamesInEveryLibraryOfTheEnvironment() throws { + let steam = try SteamPrefix(test: self) + let library = steam.prefix.appendingPathComponent("drive_c/SteamLibrary", isDirectory: true) + try steam.writeLibraryFolders(""" + "libraryfolders" + { + \t"0" + \t{ + \t\t"path"\t\t"C:\\\\Program Files (x86)\\\\Steam" + \t} + \t"1" + \t{ + \t\t"path"\t\t"C:\\\\SteamLibrary" + \t} + } + """) + let install = try steam.install(appID: "40", folder: "Far Game", files: ["FarGame.exe"], + library: library) + + let launch = try SteamDirectLaunch.resolve(appID: "40", prefix: steam.prefix) + + XCTAssertEqual(launch.executable.standardizedFileURL.path, + install.appendingPathComponent("FarGame.exe").standardizedFileURL.path) + } + + func testUsesTheProfilesGameFolderWhenSteamHasNoManifest() throws { + let steam = try SteamPrefix(test: self) + let folder = steam.steam.appendingPathComponent("steamapps/common/Copied Game", isDirectory: true) + try SteamPrefix.create(["CopiedGame.exe"], in: folder) + + let launch = try SteamDirectLaunch.resolve(appID: "50", prefix: steam.prefix, gameRoot: folder) + + XCTAssertEqual(launch.executable.lastPathComponent, "CopiedGame.exe") + } + + func testRefusesToGuessBetweenEquallyLikelyExecutables() throws { + let steam = try SteamPrefix(test: self) + _ = try steam.install(appID: "60", folder: "Two Tools", files: ["Alpha.exe", "Beta.exe"]) + + XCTAssertThrowsError(try SteamDirectLaunch.resolve(appID: "60", prefix: steam.prefix)) { + let message = ($0 as? BottleToolError)?.message ?? "" + XCTAssertTrue(message.contains("Two Tools"), message) + XCTAssertTrue(message.contains("Edit Launch Profile"), message) + } + // Not installed, and not an AppID at all. + XCTAssertThrowsError(try SteamDirectLaunch.resolve(appID: "61", prefix: steam.prefix)) { + XCTAssertTrue((($0 as? BottleToolError)?.message ?? "").contains("not installed")) + } + XCTAssertThrowsError(try SteamDirectLaunch.resolve(appID: "6a", prefix: steam.prefix)) + XCTAssertThrowsError(try SteamDirectLaunch.resolve(appID: "", prefix: steam.prefix)) + } + + // MARK: - A profile's launch + + func testAnySteamProfileStartsTheGameItselfWithTheSessionEnvironment() throws { + let steam = try SteamPrefix(test: self) + let install = try steam.install(appID: "3256020", folder: "Electrician Simulator VR", files: [ + "Electrician Simulator VR.exe", "Electrician Simulator VR_Data/", "UnityCrashHandler64.exe", + ]) + let manager = try steam.manager(bottleName: "Steam") + // What Add Steam Game saves for a game that is not verified. The + // Steam client's own arguments before -applaunch never reach the game. + try manager.saveProfile(LaunchProfile( + name: "electrician", bottleName: "Steam", source: .steam, + executable: #"C:\Program Files (x86)\Steam\steam.exe"#, + arguments: ["-silent", "-applaunch", "3256020", "-force-d3d11"], + workingDirectory: steam.steam.path, + gameRoot: #"C:\Program Files (x86)\Steam\steamapps\common\Electrician Simulator VR"#)) + let control = steam.root.appendingPathComponent("control") + try Data("123 token".utf8).write(to: control) + + let command = try manager.profileLaunchCommand("electrician", controlFile: control) + + XCTAssertEqual(command.arguments, [ + #"C:\Program Files (x86)\Steam\steamapps\common\Electrician Simulator VR\Electrician Simulator VR.exe"#, + "-force-d3d11", + ]) + XCTAssertEqual(command.currentDirectory?.standardizedFileURL.path, + install.standardizedFileURL.path) + XCTAssertEqual(command.environment["SteamAppId"], "3256020") + XCTAssertEqual(command.environment["SteamGameId"], "3256020") + XCTAssertEqual(command.environment["DXMT_BASALT_IOSURFACE"], "1") + XCTAssertEqual( + command.environment["BASALT_CONTROL"], + "Z:" + control.path.replacingOccurrences(of: "/", with: #"\"#)) + XCTAssertEqual(command.steamLaunch?.origin, .gameFolder) + + // A profile that names its executable is started as it is. + try manager.saveProfile(LaunchProfile( + name: "direct", bottleName: "Steam", source: .steam, + executable: #"C:\Program Files (x86)\Steam\steamapps\common\Electrician Simulator VR\Electrician Simulator VR.exe"#, + environment: ["SteamAppId": "3256020"])) + let direct = try manager.profileLaunchCommand("direct", controlFile: control) + XCTAssertNil(direct.steamLaunch) + XCTAssertEqual(direct.arguments.count, 1) + } + + func testSteamProfileForAMissingGameFailsBeforeAnythingStarts() throws { + let steam = try SteamPrefix(test: self) + let manager = try steam.manager(bottleName: "Steam") + try manager.saveProfile(LaunchProfile( + name: "gone", bottleName: "Steam", source: .steam, + executable: #"C:\Program Files (x86)\Steam\steam.exe"#, + arguments: ["-applaunch", "123456"])) + let control = steam.root.appendingPathComponent("control") + try Data("123 token".utf8).write(to: control) + + XCTAssertThrowsError(try manager.profileLaunchCommand("gone", controlFile: control)) { + XCTAssertTrue((($0 as? BottleToolError)?.message ?? "").contains("123456")) + } + } + + // MARK: - Fixtures + + /// An app's information with the given launch options, as Steam nests it. + static func information( + launch options: [[(String, AppInfoFixture.Value)]] + ) -> [(String, AppInfoFixture.Value)] { + let launch = options.enumerated().map { item -> (String, AppInfoFixture.Value) in + (String(item.offset), AppInfoFixture.Value.object(item.element)) + } + return [ + ("appid", .int32(1)), + ("common", .object([("name", .string("Game")), ("type", .string("Game"))])), + ("config", .object([("installdir", .string("Game")), ("launch", .object(launch))])), + ] + } +} + +/// Steam's binary `appinfo.vdf`, written the way the client writes it. +struct AppInfoFixture { + indirect enum Value { + case object([(String, Value)]) + case string(String) + case int32(Int32) + } + + var format: UInt32 + var apps: [(id: UInt32, information: [(String, Value)])] + + func data() -> Data { + var keys = [String]() + var indices = [String: UInt32]() + func key(_ name: String) -> [UInt8] { + guard format == SteamAppInfo.format29 || format == SteamAppInfo.format2A else { + return Array(name.utf8) + [0] + } + if let index = indices[name] { return Self.littleEndian(index) } + let index = UInt32(keys.count) + keys.append(name) + indices[name] = index + return Self.littleEndian(index) + } + func encode(_ entries: [(String, Value)]) -> [UInt8] { + var bytes = [UInt8]() + for (name, value) in entries { + switch value { + case .object(let children): + bytes.append(0x00) + bytes += key(name) + bytes += encode(children) + bytes.append(0x08) + case .string(let text): + bytes.append(0x01) + bytes += key(name) + bytes += Array(text.utf8) + bytes.append(0) + case .int32(let number): + bytes.append(0x02) + bytes += key(name) + bytes += Self.littleEndian(UInt32(bitPattern: number)) + } + } + return bytes + } + + if format == SteamAppInfo.format2A { return shard(encode: encode, keys: { keys }) } + var body = [UInt8]() + for app in apps { + // Info state, last update, PICS token, SHA-1, change number and, + // from format 28, the binary SHA-1. + let fixed = 4 + 4 + 8 + 20 + 4 + (format == SteamAppInfo.format27 ? 0 : 20) + var entry = [UInt8](repeating: 0xA5, count: fixed) + entry += encode([("appinfo", Value.object(app.information))]) + entry.append(0x08) + body += Self.littleEndian(app.id) + body += Self.littleEndian(UInt32(entry.count)) + body += entry + } + body += Self.littleEndian(UInt32(0)) + var header = Self.littleEndian(format) + header += Self.littleEndian(UInt32(1)) + guard format == SteamAppInfo.format29 else { return Data(header + body) } + header += Self.littleEndian(UInt64(header.count + 8 + body.count)) + var table = Self.littleEndian(UInt32(keys.count)) + for name in keys { + table += Array(name.utf8) + table.append(0) + } + return Data(header + body + table) + } + + /// Version 42: header, index with summaries, key table, then each app's + /// binary SHA-1 and KeyValues. + private func shard(encode: ([(String, Value)]) -> [UInt8], keys: () -> [String]) -> Data { + var index = [UInt8]() + var data = [UInt8]() + for app in apps { + var blob = [UInt8](repeating: 0x5A, count: 20) + blob += encode([("appinfo", Value.object(app.information))]) + blob.append(0x08) + // Change number, last update, PICS token, info state, SHA-1. + let summary = [UInt8](repeating: 0x11, count: 4 + 4 + 8 + 1 + 20) + index += Self.littleEndian(app.id) + index += Self.littleEndian(UInt32(data.count)) + index += Self.littleEndian(UInt32(blob.count)) + index += Self.littleEndian(UInt32(summary.count)) + index += summary + data += blob + } + let names = keys() + var table = [UInt8]() + for name in names { + table += Array(name.utf8) + table.append(0) + } + var header = Self.littleEndian(format) + let fields: [UInt32] = [ + 1, 0, 1, UInt32(apps.count), UInt32(index.count), UInt32(names.count), + UInt32(table.count), UInt32(data.count), 0, 0, + ] + for field in fields { header += Self.littleEndian(field) } + return Data(header + index + table + data) + } + + static func littleEndian(_ value: UInt32) -> [UInt8] { + (0..<4).map { UInt8(truncatingIfNeeded: value >> (8 * $0)) } + } + + static func littleEndian(_ value: UInt64) -> [UInt8] { + (0..<8).map { UInt8(truncatingIfNeeded: value >> (8 * $0)) } + } +} + +/// A Wine prefix with Steam in `C:\Program Files (x86)\Steam`. +struct SteamPrefix { + let root: URL + let prefix: URL + let steam: URL + + init(test: XCTestCase) throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + "BasaltSteamDirectLaunch-\(UUID().uuidString)", isDirectory: true) + test.addTeardownBlock { try? FileManager.default.removeItem(at: directory) } + root = directory + prefix = directory.appendingPathComponent("data/Bottles/Steam/prefix", isDirectory: true) + steam = prefix.appendingPathComponent("drive_c/Program Files (x86)/Steam", isDirectory: true) + try Self.create(["steam.exe", "steamapps/"], in: steam) + } + + /// Installs a game as Steam does: its manifest, then its files under + /// `steamapps/common/`. A path ending in "/" is a folder. + func install(appID: String, folder: String, files: [String], library: URL? = nil) throws -> URL { + let steamApps = (library ?? steam).appendingPathComponent("steamapps", isDirectory: true) + try FileManager.default.createDirectory(at: steamApps, withIntermediateDirectories: true) + try Data(""" + "AppState" + { + \t"appid"\t\t"\(appID)" + \t"name"\t\t"\(folder)" + \t"installdir"\t\t"\(folder)" + } + + """.utf8).write(to: steamApps.appendingPathComponent("appmanifest_\(appID).acf")) + let install = steamApps.appendingPathComponent("common", isDirectory: true) + .appendingPathComponent(folder, isDirectory: true) + try Self.create(files, in: install) + return install + } + + func writeAppInfo(_ data: Data) throws { + let cache = steam.appendingPathComponent("appcache", isDirectory: true) + try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: true) + try data.write(to: cache.appendingPathComponent("appinfo.vdf")) + } + + func writeLibraryFolders(_ text: String) throws { + try Data(text.utf8).write(to: steam.appendingPathComponent("steamapps/libraryfolders.vdf")) + } + + /// A managed bottle around the prefix, ready to launch. + func manager(bottleName: String) throws -> BottleManager { + let data = root.appendingPathComponent("data", isDirectory: true) + let directory = prefix.deletingLastPathComponent() + let engineRoot = directory.appendingPathComponent("engine", isDirectory: true) + let wine = engineRoot.appendingPathComponent("bin/wine") + try FileManager.default.createDirectory( + at: wine.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("#!/bin/sh\n".utf8).write(to: wine) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: wine.path) + let engine = BottleEngine( + id: "test-pinned", kind: .pinned, wineBinary: wine, + wineserverBinary: engineRoot.appendingPathComponent("bin/wineserver"), + root: engineRoot, supportsBasaltDXMT: true) + var bottle = ManagedBottle( + name: bottleName, engine: engine, prefix: prefix, + engineRoot: engineRoot, wineBinary: wine) + bottle.dxmtInstalled = true + bottle.runtimeInstalled = true + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + try encoder.encode(bottle).write(to: directory.appendingPathComponent("bottle.json")) + return BottleManager(root: data, repoRoot: root) + } + + static func create(_ files: [String], in folder: URL) throws { + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + for file in files { + let url = folder.appendingPathComponent(file) + if file.hasSuffix("/") { + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + } else { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data([0x4d, 0x5a]).write(to: url) + } + } + } +} From a5c85e5576370a43a4f2bffa4fb1a41f6a8be50d Mon Sep 17 00:00:00 2001 From: abgitdev <266600699+abgitdev@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:20:06 +0000 Subject: [PATCH 2/7] Setup checks for GStreamer, which Wine needs to play game videos Unity games play video through Media Foundation, which the pinned Wine 11.10 build implements with GStreamer. Without GStreamer.framework installed for all users, Electrician Simulator VR waited forever for its intro video and the headset stayed black, with nothing in the session log to say why. Setup gains a "Video in games (GStreamer)" row. It detects /Library/Frameworks/GStreamer.framework, shows the version from the framework's Info.plist and opens the official 1.28.1 package, the one the Wine build names. The version and link sit next to the Wine pin so they change together. The row is optional, so games still start without GStreamer, and the session log then warns once per game session. The diagnostic report lists the row like every other Setup check. README, the Setup docs, ReadMeFirst and the third-party notices name the package. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++ README.md | 3 ++ THIRD_PARTY_NOTICES.md | 7 ++- docs/ARCHITECTURE.md | 5 +- docs/MANAGEMENT.md | 6 ++- packaging/ReadMeFirst.txt | 7 +++ streamer/Sources/BasaltManager/AppModel.swift | 21 +++++--- .../Sources/BasaltManager/SetupView.swift | 15 +++++- .../GStreamerInstallation.swift | 30 ++++++++++++ .../Localization/L10nKey.swift | 8 ++++ .../Localization/Strings+de.swift | 10 +++- .../Localization/Strings+en.swift | 10 +++- .../Localization/Strings+es.swift | 10 +++- .../Localization/Strings+fr.swift | 10 +++- .../Localization/Strings+it.swift | 10 +++- .../Localization/Strings+ja.swift | 10 +++- .../Localization/Strings+ko.swift | 10 +++- .../Localization/Strings+pl.swift | 10 +++- .../Localization/Strings+ru.swift | 10 +++- .../Localization/Strings+uk.swift | 10 +++- .../BasaltManagerKit/ManagementModels.swift | 23 ++++++++- .../BasaltManagerKit/SessionConsole.swift | 9 ++++ .../BasaltManagerKit/WineInstaller.swift | 7 +++ .../DiagnosticsTests.swift | 35 +++++++++++++- .../GStreamerInstallationTests.swift | 37 ++++++++++++++ .../SessionConsoleTests.swift | 14 ++++++ .../SetupInspectorTests.swift | 48 +++++++++++++++++-- .../WineInstallerTests.swift | 6 +++ 28 files changed, 355 insertions(+), 29 deletions(-) create mode 100644 streamer/Sources/BasaltManagerKit/GStreamerInstallation.swift create mode 100644 streamer/Tests/BasaltManagerKitTests/GStreamerInstallationTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 7eb3727..c8c3150 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ All notable changes to TrailBridge VR are documented here. - The session log says why a session stays headless: the OpenXR runtime names the missing environment, DXMT build or connection, and the app adds a hint when the started file ends within seconds, as a launcher that opens the game separately does. +- Setup checks for GStreamer, which Wine uses to play videos in games, and links to the official + package. Diagnostic reports include its status and version when available. Games can still + start without it, with one warning per game session in the log. ## 0.2.1 — 2026-11-15 diff --git a/README.md b/README.md index 1b681b7..a6ae267 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,9 @@ VR does not promise stable operation on them. Other games may work but are not v ## Requirements - A Mac with Apple Silicon and macOS 14 or newer, with Rosetta 2. Intel Macs are not supported. +- Games that play videos need [GStreamer 1.28.1](https://gstreamer.freedesktop.org/data/pkg/osx/1.28.1/gstreamer-1.0-1.28.1-universal.pkg), + the package recommended for Wine 11.10. Install it with an administrator account, for all + users of this Mac. - A Meta Quest headset in developer mode. Only the Quest 3 is tested. - Your own Steam account and games you bought, or Windows VR games you own in a folder. - Free space on the disk with the data folder: about 720 MB for Wine, plus Steam and the games. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 2f01a12..9b32206 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -59,6 +59,9 @@ Only when you start that step, and only from the official source: SDK terms apply: https://developer.android.com/studio/terms - The BlackHole 2ch 0.7.1 installer from Existential Audio: an optional audio driver that you install yourself. GPL-3.0; not bundled. +- The GStreamer 1.28.1 installer from gstreamer.freedesktop.org: Wine uses it to play videos in + games. You install it for all users of the Mac. LGPL-2.1-or-later, with other licenses for some + plugins. Not bundled. ## The DMG @@ -106,5 +109,5 @@ Inside the app: are the ones of LLVM 15.0.7; the toolchain's own LLVM is newer and ships only the main LLVM license. -Not inside: Wine, Steam, ALVR, OpenComposite, BlackHole, Android platform tools, games and store -credentials. The app downloads Wine from Gcenx's releases when you start that step. +Not inside: Wine, Steam, ALVR, OpenComposite, BlackHole, GStreamer, Android platform tools, games +and store credentials. The app downloads Wine from Gcenx's releases when you start that step. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index dd91d92..8eba88a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -291,8 +291,9 @@ it reuses `BasaltBottleKit`, discovers Basalt/Whisky/CrossOver prefixes, parses manifests (including additional library folders), turns installed games into editable profiles, starts and owns wired or Wi-Fi streamer plus Wine game processes, and parses the existing two-second transport/Quest reports into bounded live chart history. Setup checks cover Apple -Silicon/macOS, Screen Recording, adb, the pinned Wine/DXMT artifacts, the OpenXR runtime, and -optional BlackHole audio. Global and per-profile stream settings persist through `UserDefaults`; +Silicon/macOS, Screen Recording, adb, the pinned Wine/DXMT artifacts, the OpenXR runtime, +GStreamer for video playback in games, and optional BlackHole audio. Global and per-profile +stream settings persist through `UserDefaults`; audio-enabled launches route output to the loopback for the owned session and restore it afterward. The Basalt data root is user-selectable. External prefixes remain read-only, with an explicit APFS-cloned import into an isolated pinned engine when a user wants VR support. An ad-hoc-signed diff --git a/docs/MANAGEMENT.md b/docs/MANAGEMENT.md index 6fded57..5be3dbe 100644 --- a/docs/MANAGEMENT.md +++ b/docs/MANAGEMENT.md @@ -27,7 +27,11 @@ Sections are also on ⌘1–⌘5, ⌘R rescans, ⌘. stops the active session, a shows the session state with a Stop button. 1. **Setup** checks Apple Silicon and macOS 14, adb, the pinned Wine/DXMT engine, the built OpenXR - runtime, optional Screen Recording permission, and optional BlackHole audio. The adb action + runtime, optional Screen Recording permission, and optional BlackHole audio. **Video in games + (GStreamer)** checks for the system framework and shows its version when available. Its action + opens the download of the official GStreamer 1.28.1 package that Wine 11.10 needs. Install it + with an administrator account, for all users of this Mac, then click **Refresh**. Games can + still launch when the framework is missing. The adb action opens the Headset page, which downloads Google's platform tools, and the BlackHole action downloads BlackHole's official installer. Build-related actions open the bottle guide because compiling the pinned runtime is a developer operation. diff --git a/packaging/ReadMeFirst.txt b/packaging/ReadMeFirst.txt index d290450..b2a22ad 100644 --- a/packaging/ReadMeFirst.txt +++ b/packaging/ReadMeFirst.txt @@ -40,6 +40,13 @@ GitHub into the data folder you choose. The data folder can be on this Mac's disk, an external disk or network storage. +GSTREAMER + +Wine uses GStreamer to play videos in games. In Setup, click Get GStreamer +to download the official 1.28.1 package. Install it with an administrator +account, for all users of this Mac, then click Refresh in TrailBridge VR. + + CHECK THE DOWNLOAD To make sure the disk image is the published one, run this in Terminal: diff --git a/streamer/Sources/BasaltManager/AppModel.swift b/streamer/Sources/BasaltManager/AppModel.swift index 10f52d9..21a3493 100644 --- a/streamer/Sources/BasaltManager/AppModel.swift +++ b/streamer/Sources/BasaltManager/AppModel.swift @@ -118,6 +118,8 @@ struct SettingsFileProblem: Equatable { @MainActor final class BasaltAppModel: ObservableObject { @Published var selection = ManagerSection.library + /// Updated before publishing the checks from the same scan. + private(set) var setupGStreamerVersion: String? @Published private(set) var setupChecks = [SetupCheck]() @Published private(set) var bottles = [ManagedBottle]() @Published private(set) var profiles = [LaunchProfile]() @@ -545,7 +547,7 @@ final class BasaltAppModel: ObservableObject { let repoRoot = repoRoot typealias RefreshResult = Result<( [ManagedBottle], [LaunchProfile], [DetectedGame], - [BottleEngine], [SetupCheck], [GameAudioDevice], + [BottleEngine], String?, [SetupCheck], [GameAudioDevice], [DiscoveredBottle], [SteamGame], [BSManagerInstance], [BSManagerInstallation], [DamagedItem], [DamagedItem] ), Error> @@ -558,7 +560,8 @@ final class BasaltAppModel: ObservableObject { let damagedBottles = try manager.listDamagedBottles() let damagedProfiles = try manager.listDamagedProfiles() let games = GameDetector().detect(bottles: bottles, profiles: profiles) - let checks = SetupInspector(repoRoot: repoRoot, manager: manager).inspect() + let (checks, gStreamerVersion) = SetupInspector( + repoRoot: repoRoot, manager: manager).inspectWithGStreamerVersion() let audio = (try? GameAudioDeviceDiscovery.inputDevices()) ?? [] let discovered = ExternalBottleDiscovery().discover(managed: bottles) let steam = SteamLibraryDiscovery().discover(in: discovered) @@ -568,7 +571,7 @@ final class BasaltAppModel: ObservableObject { let bsManagerApps = BSManagerInstallationDiscovery().discover( in: bottles) return RefreshResult.success( - (bottles, profiles, games, manager.engines(), checks, audio, + (bottles, profiles, games, manager.engines(), gStreamerVersion, checks, audio, discovered, steam, bsManager, bsManagerApps, damagedBottles, damagedProfiles)) } catch { @@ -577,7 +580,7 @@ final class BasaltAppModel: ObservableObject { }.value switch result { case .success(let values): - (bottles, profiles, games, engines, setupChecks, audioDevices, + (bottles, profiles, games, engines, setupGStreamerVersion, setupChecks, audioDevices, discoveredBottles, steamGames, bsManagerInstances, bsManagerInstallations, damagedBottles, damagedProfiles) = values print("BasaltVR library: \(discoveredBottles.count) bottle(s), " @@ -621,11 +624,12 @@ final class BasaltAppModel: ObservableObject { let manager = manager let repoRoot = repoRoot let root = dataRoot - let checks = await Task.detached { - SetupInspector(repoRoot: repoRoot, manager: manager).inspect() + let (checks, gStreamerVersion) = await Task.detached { + SetupInspector(repoRoot: repoRoot, manager: manager).inspectWithGStreamerVersion() }.value // A data folder changed meanwhile has its own `refresh()`. guard root == dataRoot, checks != setupChecks else { return } + setupGStreamerVersion = gStreamerVersion setupChecks = checks } @@ -1249,6 +1253,8 @@ final class BasaltAppModel: ObservableObject { // A failed download is tried again at once: the person has // already agreed to it. if case .failed = wineInstall { startWineDownload() } else { showingWineDownload = true } + case "gstreamer": + NSWorkspace.shared.open(PinnedWine.gStreamerPackageURL) case "rosetta": NSPasteboard.general.clearContents() rosettaCommandCopied = NSPasteboard.general.setString(Rosetta.installCommand, forType: .string) @@ -1636,6 +1642,9 @@ final class BasaltAppModel: ObservableObject { } // Replaces attachOutput's /dev/null stdin: hello_xr quits at its EOF. try HeldOpenStandardInput.run(game) + if let warning = console.gStreamerWarning(for: GStreamerInstallation.detect()) { + appendLog(warning) + } gameProcess = game gameFocusKeeper.start( gamePID: game.processIdentifier, diff --git a/streamer/Sources/BasaltManager/SetupView.swift b/streamer/Sources/BasaltManager/SetupView.swift index 2136b3a..54fda96 100644 --- a/streamer/Sources/BasaltManager/SetupView.swift +++ b/streamer/Sources/BasaltManager/SetupView.swift @@ -90,7 +90,8 @@ struct SetupView: View { .lineLimit(1).help(title(check)) Spacer(minLength: 0) Chip(text: statusTitle(check), kind: check.status == .ready ? .success - : check.status == .unavailable ? .failed : check.required ? .warning : .neutral) + : check.status == .unavailable ? .failed + : check.required || check.id == "gstreamer" ? .warning : .neutral) } HStack(alignment: .firstTextBaseline, spacing: 10) { DisclosureGroup { @@ -181,6 +182,7 @@ struct SetupView: View { case "mac": L(.setupMac) case "rosetta": L(.setupRosetta) case "wine": L(.setupEngine) + case "gstreamer": L(.setupGStreamer) case "runtime": L(.setupRuntime) case "dxmt": L(.setupGraphics) case "screen": L(.setupScreen) @@ -195,6 +197,7 @@ struct SetupView: View { case "mac": L(.setupMacHelp) case "rosetta": L(.setupRosettaHelp) case "wine": L(.setupEngineHelp) + case "gstreamer": L(.setupGStreamerHelp) case "runtime": L(.setupRuntimeHelp) case "dxmt": L(.setupGraphicsHelp) case "screen": L(.setupScreenHelp) @@ -213,6 +216,14 @@ struct SetupView: View { check.status == .ready ? L(.setupEngineAvailable) : check.offersWineDownload ? L(.setupEngineNotDownloaded, PinnedWine.download.version) : L(.setupEngineBuild) + case "gstreamer": + if check.status != .ready { + L(.setupGStreamerInstall, L(.menuRefresh)) + } else if let version = model.setupGStreamerVersion { + L(.setupGStreamerVersion, version) + } else { + L(.setupGStreamerInstalled) + } case "runtime": L(.setupRuntimeBuild) case "dxmt": L(.setupGraphicsBuild) case "screen": check.status == .ready ? L(.setupScreenGranted) : L(.setupScreenPrivacy) @@ -232,6 +243,7 @@ struct SetupView: View { case "rosetta": model.rosettaCommandCopied ? L(.diagnosticsCopied) : L(.setupRosettaCopy) case "wine" where check.offersWineDownload: if case .failed = model.wineInstall { L(.dataFolderRetry) } else { model.wineDownloadTitle } + case "gstreamer": L(.setupGStreamerPackage) case "wine", "runtime", "dxmt": L(.setupBuildHelp) default: check.action ?? "" } @@ -240,6 +252,7 @@ struct SetupView: View { private func statusTitle(_ check: SetupCheck) -> String { switch check.status { case .ready: L(.setupCheckReady) + case .actionNeeded where check.id == "gstreamer": L(.setupGStreamerMissing) case .actionNeeded: check.required ? L(.setupCheckNeeded) : L(.setupCheckOptional) case .unavailable: L(.setupCheckUnavailable) } diff --git a/streamer/Sources/BasaltManagerKit/GStreamerInstallation.swift b/streamer/Sources/BasaltManagerKit/GStreamerInstallation.swift new file mode 100644 index 0000000..bfb5980 --- /dev/null +++ b/streamer/Sources/BasaltManagerKit/GStreamerInstallation.swift @@ -0,0 +1,30 @@ +import Foundation + +/// Whether Wine's system video framework is installed, with the version when readable. +public enum GStreamerInstallation: Equatable, Sendable { + case missing + case installed(version: String?) + + public static let systemFramework = URL( + fileURLWithPath: "/Library/Frameworks/GStreamer.framework", isDirectory: true) + + /// Checks for the framework and reads its version from the local bundle metadata. + public static func detect(frameworkURL: URL = systemFramework, + fileManager: FileManager = .default) -> Self { + var isDirectory: ObjCBool = false + guard fileManager.fileExists(atPath: frameworkURL.path, isDirectory: &isDirectory), + isDirectory.boolValue else { return .missing } + + // The versioned directory can be named "1.0" even for a newer release. + // Read package metadata instead of inferring the version from that name. + for path in ["Resources/Info.plist", "Versions/Current/Resources/Info.plist", "Info.plist"] { + guard let data = fileManager.contents(atPath: frameworkURL.appendingPathComponent(path).path), + let info = try? PropertyListSerialization.propertyList(from: data, format: nil), + let version = (info as? [String: Any])?["CFBundleShortVersionString"] as? String + else { continue } + let trimmed = version.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { return .installed(version: trimmed) } + } + return .installed(version: nil) + } +} diff --git a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift index 040a3c2..19e5e48 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift @@ -65,6 +65,7 @@ public enum L10nKey: String, CaseIterable, Sendable { case uninstallBusy case uninstallFailed case uninstallNone + case modelGStreamerMissing case modelGamePriority case modelGameExited case modelGameExitedQuickly @@ -635,6 +636,13 @@ public enum L10nKey: String, CaseIterable, Sendable { case setupEngineHelp case setupEngineAvailable case setupEngineBuild + case setupGStreamer + case setupGStreamerMissing + case setupGStreamerInstalled + case setupGStreamerVersion + case setupGStreamerHelp + case setupGStreamerInstall + case setupGStreamerPackage case setupRuntime case setupRuntimeHelp case setupRuntimeBuild diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift index f261856..fbba1ad 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift @@ -68,6 +68,7 @@ final class StringsDE: LocalizationTable { .uninstallBusy: "Beende zuerst die VR-Sitzung.", .uninstallFailed: "Einige Dateien konnten nicht entfernt werden: %1$@", .uninstallNone: "Keine", + .modelGStreamerMissing: "GStreamer ist nicht installiert. Spiele, die Videos wie etwa Intros abspielen, können hängen bleiben. Lade das offizielle Paket von %1$@ und installiere es für alle Benutzer.\n", .modelGamePriority: "Priorität des Spielprozesses: hoch (user-interactive QoS)\n", .modelGameExited: "Spiel mit Status %1$@ beendet\n", .modelGameExitedQuickly: "Das Spiel endete %1$@ s nach dem Start. Erschien nichts im Headset, ist die gestartete Datei vielleicht ein Launcher, der das Spiel als eigenen Prozess öffnet, oder das Spiel hat beim Laden aufgehört (siehe die „game:“-Zeilen oben). Um die .exe des Spiels selbst zu starten, diese unter Bibliothek → Spielkarte → ⋯ → %2$@ auswählen.\n", @@ -614,7 +615,7 @@ final class StringsDE: LocalizationTable { .setupMissingGuidance: "Die Pflichtschritte abschließen, dann eine Umgebung erstellen und ein Spiel hinzufügen.", .setupBottle: "Umgebung einrichten", .setupRequiredHelp: "Diese Komponenten ermöglichen VR-Streaming. Wine lädt die App selbst; die Build-Anleitung ist für alle, die die App aus dem Quellcode bauen.", - .setupOptionalHelp: "USB-Tools bringen ALVR einmal auf das Headset, auch wenn später über Wi‑Fi gespielt wird. Bildschirmaufnahme ist nur für die Mac-Vorschau nötig, BlackHole nur, wenn du es für den Spielton wählst.", + .setupOptionalHelp: "USB-Tools bringen ALVR einmal auf das Headset, auch wenn später über Wi‑Fi gespielt wird. Bildschirmaufnahme ist nur für die Mac-Vorschau nötig, BlackHole nur, wenn du es für den Spielton wählst. GStreamer ist für Videos in Spielen nötig.", .setupMac: "Mac mit Apple Silicon", .setupMacHelp: "Apple Silicon und macOS 14 oder neuer.", .setupMacUnsupported: "TrailBridge erfordert Apple Silicon und macOS 14 oder neuer.", @@ -622,6 +623,13 @@ final class StringsDE: LocalizationTable { .setupEngineHelp: "Führt Windows-Spiele auf deinem Mac aus.", .setupEngineAvailable: "Die geprüfte Engine ist verfügbar.", .setupEngineBuild: "Die festgelegte M5-Engine und den Basalt-DXMT-Fork bauen.", + .setupGStreamer: "Videos in Spielen (GStreamer)", + .setupGStreamerMissing: "Fehlt", + .setupGStreamerInstalled: "Installiert", + .setupGStreamerVersion: "Installiert (Version %1$@)", + .setupGStreamerHelp: "Spielt Videos in Spielen ab.", + .setupGStreamerInstall: "Nicht installiert. Installiere das Paket mit einem Administratorkonto für alle Benutzer dieses Macs und klicke dann auf „%1$@“.", + .setupGStreamerPackage: "GStreamer laden…", .setupRuntime: "VR-Modul (OpenXR)", .setupRuntimeHelp: "Verbindet die VR-Ausgabe des Spiels mit dem Headset.", .setupRuntimeBuild: "Die Windows-OpenXR-Runtime wurde noch nicht gebaut.", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift index f30281a..768b82a 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift @@ -68,6 +68,7 @@ final class StringsEN: LocalizationTable { .uninstallBusy: "Stop the VR session first.", .uninstallFailed: "Some files could not be removed: %1$@", .uninstallNone: "None", + .modelGStreamerMissing: "GStreamer is not installed. Games that play videos, such as intros, can hang. Install the official package for all users from %1$@\n", .modelGamePriority: "Game process priority: high (user-interactive QoS)\n", .modelGameExited: "Game exited with status %1$@\n", .modelGameExitedQuickly: "The game ended %1$@ s after it started. If nothing appeared in the headset, the file started may be a launcher that opens the game as a separate process, or the game stopped while loading (see the “game:” lines above). To start the game's own .exe, choose it in Library → game card → ⋯ → %2$@\n", @@ -614,7 +615,7 @@ final class StringsEN: LocalizationTable { .setupMissingGuidance: "Finish the required steps, then create an environment and add a game.", .setupBottle: "Set up an environment", .setupRequiredHelp: "These components enable VR streaming. TrailBridge downloads Wine itself; the build instructions are for an app built from source.", - .setupOptionalHelp: "USB tools put ALVR on the headset once, even if you play over Wi-Fi later. Screen recording is only for the Mac preview; BlackHole is needed only if you choose it for game audio.", + .setupOptionalHelp: "USB tools put ALVR on the headset once, even if you play over Wi-Fi later. Screen recording is only for the Mac preview; BlackHole is needed only if you choose it for game audio. GStreamer is needed to play videos in games.", .setupMac: "Mac with Apple Silicon", .setupMacHelp: "Apple Silicon and macOS 14 or later.", .setupMacUnsupported: "TrailBridge requires Apple Silicon and macOS 14 or later.", @@ -622,6 +623,13 @@ final class StringsEN: LocalizationTable { .setupEngineHelp: "Runs Windows games on your Mac.", .setupEngineAvailable: "The verified engine is available.", .setupEngineBuild: "Build the pinned M5 engine and Basalt DXMT fork.", + .setupGStreamer: "Video in games (GStreamer)", + .setupGStreamerMissing: "Missing", + .setupGStreamerInstalled: "Installed", + .setupGStreamerVersion: "Installed (version %1$@)", + .setupGStreamerHelp: "Lets games play videos, such as intros.", + .setupGStreamerInstall: "Not installed. Install it with an administrator account, for all users of this Mac, then click “%1$@”.", + .setupGStreamerPackage: "Get GStreamer…", .setupRuntime: "VR module (OpenXR)", .setupRuntimeHelp: "Connects the game's VR output to the headset.", .setupRuntimeBuild: "The Windows OpenXR runtime has not been built.", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift index 6801ea9..dcb6dd4 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift @@ -68,6 +68,7 @@ final class StringsES: LocalizationTable { .uninstallBusy: "Detén primero la sesión de VR.", .uninstallFailed: "No se pudieron eliminar algunos archivos: %1$@", .uninstallNone: "Ninguno", + .modelGStreamerMissing: "GStreamer no está instalado. Los juegos que reproducen vídeos, como los de introducción, pueden quedarse bloqueados. Instala el paquete oficial para todos los usuarios desde %1$@\n", .modelGamePriority: "Prioridad del proceso del juego: alta (user-interactive QoS)\n", .modelGameExited: "El juego terminó con el código %1$@\n", .modelGameExitedQuickly: "El juego terminó %1$@ s después de iniciarse. Si no apareció nada en el visor, el archivo iniciado puede ser un lanzador que abre el juego en otro proceso, o el juego se detuvo al cargar (consulta las líneas «game:» de arriba). Para iniciar el .exe del propio juego, elígelo en Biblioteca → tarjeta del juego → ⋯ → %2$@\n", @@ -614,7 +615,7 @@ final class StringsES: LocalizationTable { .setupMissingGuidance: "Completa los pasos obligatorios, crea un entorno y añade un juego.", .setupBottle: "Preparar un entorno", .setupRequiredHelp: "Estos componentes permiten transmitir VR. La app descarga Wine por sí misma; las instrucciones de compilación son para quien compila la app desde el código fuente.", - .setupOptionalHelp: "Las herramientas USB instalan ALVR en el visor una sola vez, aunque luego juegues por Wi‑Fi. La grabación de pantalla es solo para la vista previa del Mac; BlackHole, solo si lo eliges para el audio del juego.", + .setupOptionalHelp: "Las herramientas USB instalan ALVR en el visor una sola vez, aunque luego juegues por Wi‑Fi. La grabación de pantalla es solo para la vista previa del Mac; BlackHole, solo si lo eliges para el audio del juego. GStreamer es necesario para reproducir vídeos en los juegos.", .setupMac: "Mac con Apple Silicon", .setupMacHelp: "Apple Silicon y macOS 14 o posterior.", .setupMacUnsupported: "TrailBridge requiere Apple Silicon y macOS 14 o posterior.", @@ -622,6 +623,13 @@ final class StringsES: LocalizationTable { .setupEngineHelp: "Ejecuta juegos de Windows en tu Mac.", .setupEngineAvailable: "El motor verificado está disponible.", .setupEngineBuild: "Compila el motor M5 fijado y el fork de Basalt DXMT.", + .setupGStreamer: "Vídeo en juegos (GStreamer)", + .setupGStreamerMissing: "No instalado", + .setupGStreamerInstalled: "Instalado", + .setupGStreamerVersion: "Instalado (versión %1$@)", + .setupGStreamerHelp: "Reproduce los vídeos de los juegos.", + .setupGStreamerInstall: "No instalado. Usa una cuenta de administrador para instalarlo para todos los usuarios de este Mac y después haz clic en «%1$@».", + .setupGStreamerPackage: "Descargar GStreamer…", .setupRuntime: "Módulo VR (OpenXR)", .setupRuntimeHelp: "Envía la imagen VR del juego al visor.", .setupRuntimeBuild: "El módulo OpenXR para Windows no está compilado.", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift index 0eb3c79..d217b85 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift @@ -68,6 +68,7 @@ final class StringsFR: LocalizationTable { .uninstallBusy: "Arrêtez d’abord la session VR.", .uninstallFailed: "Certains fichiers n’ont pas pu être supprimés : %1$@", .uninstallNone: "Aucun", + .modelGStreamerMissing: "GStreamer n’est pas installé. Les jeux qui lisent des vidéos, par exemple une cinématique d’introduction, peuvent se bloquer. Téléchargez le paquet officiel depuis %1$@ et installez-le pour tous les utilisateurs.\n", .modelGamePriority: "Priorité du processus du jeu : élevée (user-interactive QoS)\n", .modelGameExited: "Le jeu s’est arrêté avec le code %1$@\n", .modelGameExitedQuickly: "Le jeu s’est arrêté %1$@ s après son lancement. Si rien n’est apparu dans le casque, le fichier lancé est peut-être un lanceur qui ouvre le jeu dans un processus séparé, ou le jeu s’est arrêté pendant le chargement (voir les lignes « game: » ci-dessus). Pour lancer le .exe du jeu lui-même, choisissez-le dans Bibliothèque → fiche du jeu → ⋯ → %2$@\n", @@ -614,7 +615,7 @@ final class StringsFR: LocalizationTable { .setupMissingGuidance: "Terminez les étapes requises, puis créez un environnement et ajoutez un jeu.", .setupBottle: "Configurer un environnement", .setupRequiredHelp: "Ces composants permettent la diffusion VR. L’app télécharge Wine elle-même ; les instructions de compilation servent à ceux qui compilent l’app depuis le code source.", - .setupOptionalHelp: "Les outils USB installent ALVR sur le casque une seule fois, même si vous jouez ensuite en Wi‑Fi. L’enregistrement de l’écran sert uniquement à l’aperçu sur Mac ; BlackHole n’est utile que si vous le choisissez pour le son du jeu.", + .setupOptionalHelp: "Les outils USB installent ALVR sur le casque une seule fois, même si vous jouez ensuite en Wi‑Fi. L’enregistrement de l’écran sert uniquement à l’aperçu sur Mac ; BlackHole n’est utile que si vous le choisissez pour le son du jeu. GStreamer est nécessaire pour lire les vidéos dans les jeux.", .setupMac: "Mac avec Apple Silicon", .setupMacHelp: "Apple Silicon et macOS 14 ou ultérieur.", .setupMacUnsupported: "TrailBridge nécessite Apple Silicon et macOS 14 ou ultérieur.", @@ -622,6 +623,13 @@ final class StringsFR: LocalizationTable { .setupEngineHelp: "Exécute les jeux Windows sur votre Mac.", .setupEngineAvailable: "Le moteur vérifié est disponible.", .setupEngineBuild: "Compilez le moteur M5 prévu et le fork Basalt DXMT.", + .setupGStreamer: "Vidéos dans les jeux (GStreamer)", + .setupGStreamerMissing: "Absent", + .setupGStreamerInstalled: "Installé", + .setupGStreamerVersion: "Installé (version %1$@)", + .setupGStreamerHelp: "Permet de lire les vidéos des jeux.", + .setupGStreamerInstall: "Non installé. Utilisez un compte administrateur pour l’installer pour tous les utilisateurs de ce Mac, puis cliquez sur « %1$@ ».", + .setupGStreamerPackage: "Télécharger GStreamer…", .setupRuntime: "Module VR (OpenXR)", .setupRuntimeHelp: "Relie la sortie VR du jeu au casque.", .setupRuntimeBuild: "Le module OpenXR pour Windows n’a pas été compilé.", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift index 4260f90..db34948 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift @@ -68,6 +68,7 @@ final class StringsIT: LocalizationTable { .uninstallBusy: "Interrompi prima la sessione VR.", .uninstallFailed: "Impossibile rimuovere alcuni file: %1$@", .uninstallNone: "Nessuno", + .modelGStreamerMissing: "GStreamer non è installato. I giochi che riproducono video, ad esempio filmati introduttivi, possono bloccarsi. Scarica il pacchetto ufficiale da %1$@ e installalo per tutti gli utenti.\n", .modelGamePriority: "Priorità del processo di gioco: alta (user-interactive QoS)\n", .modelGameExited: "Gioco terminato con codice %1$@\n", .modelGameExitedQuickly: "Il gioco è terminato %1$@ s dopo l’avvio. Se nel visore non è apparso nulla, il file avviato può essere un launcher che apre il gioco in un processo separato, oppure il gioco si è fermato durante il caricamento (vedi le righe «game:» sopra). Per avviare l’.exe del gioco stesso, sceglilo in Libreria → scheda del gioco → ⋯ → %2$@\n", @@ -614,7 +615,7 @@ final class StringsIT: LocalizationTable { .setupMissingGuidance: "Completa i passaggi obbligatori, poi crea un ambiente e aggiungi un gioco.", .setupBottle: "Prepara un ambiente", .setupRequiredHelp: "Questi componenti abilitano lo streaming VR. L’app scarica Wine da sola; le istruzioni di compilazione servono a chi compila l’app dal codice sorgente.", - .setupOptionalHelp: "Gli strumenti USB installano ALVR sul visore una volta sola, anche se poi giochi in Wi‑Fi. La registrazione schermo serve solo per l’anteprima su Mac; BlackHole solo se lo scegli per l’audio di gioco.", + .setupOptionalHelp: "Gli strumenti USB installano ALVR sul visore una volta sola, anche se poi giochi in Wi‑Fi. La registrazione schermo serve solo per l’anteprima su Mac; BlackHole solo se lo scegli per l’audio di gioco. GStreamer serve per riprodurre i video nei giochi.", .setupMac: "Mac con Apple Silicon", .setupMacHelp: "Apple Silicon e macOS 14 o successivo.", .setupMacUnsupported: "TrailBridge richiede Apple Silicon e macOS 14 o successivo.", @@ -622,6 +623,13 @@ final class StringsIT: LocalizationTable { .setupEngineHelp: "Esegue i giochi Windows sul Mac.", .setupEngineAvailable: "Il motore verificato è disponibile.", .setupEngineBuild: "Compila il motore M5 previsto e il fork Basalt DXMT.", + .setupGStreamer: "Video nei giochi (GStreamer)", + .setupGStreamerMissing: "Non installato", + .setupGStreamerInstalled: "Installato", + .setupGStreamerVersion: "Installato (versione %1$@)", + .setupGStreamerHelp: "Riproduce i video nei giochi.", + .setupGStreamerInstall: "Non installato. Usa un account amministratore per installarlo per tutti gli utenti di questo Mac, poi fai clic su «%1$@».", + .setupGStreamerPackage: "Scarica GStreamer…", .setupRuntime: "Modulo VR (OpenXR)", .setupRuntimeHelp: "Trasmette l’immagine VR del gioco al visore.", .setupRuntimeBuild: "Il runtime OpenXR per Windows non è stato compilato.", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift index a4a6f5e..760ffec 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift @@ -68,6 +68,7 @@ final class StringsJA: LocalizationTable { .uninstallBusy: "先にVRセッションを停止してください。", .uninstallFailed: "一部のファイルを削除できませんでした:%1$@", .uninstallNone: "なし", + .modelGStreamerMissing: "GStreamerがインストールされていません。オープニングなどの動画を再生するゲームが途中で止まることがあります。%1$@から公式パッケージを入手し、すべてのユーザ向けにインストールしてください。\n", .modelGamePriority: "ゲームプロセスの優先度:高(user-interactive QoS)\n", .modelGameExited: "ゲームがコード%1$@で終了しました\n", .modelGameExitedQuickly: "ゲームは起動から%1$@秒後に終了しました。ヘッドセットに何も表示されなかった場合、起動したファイルがゲームを別のプロセスで開くランチャーであるか、読み込み中にゲームが停止した可能性があります(上の「game:」の行を確認してください)。ゲーム本体の.exeを起動するには、ライブラリ → ゲームカード → ⋯ → %2$@ で選択してください。\n", @@ -614,7 +615,7 @@ final class StringsJA: LocalizationTable { .setupMissingGuidance: "必須手順を完了してから、環境を作成してゲームを追加してください。", .setupBottle: "環境をセットアップ", .setupRequiredHelp: "VR配信に必要なコンポーネントです。Wineはアプリがダウンロードします。ビルド手順は、ソースコードからアプリをビルドする人向けです。", - .setupOptionalHelp: "USBツールは、あとでWi‑Fiで遊ぶ場合でも、ヘッドセットにALVRを入れるときに一度必要です。画面収録はMac上のプレビューにのみ、BlackHoleはゲーム音声に選んだ場合にのみ必要です。", + .setupOptionalHelp: "USBツールは、あとでWi‑Fiで遊ぶ場合でも、ヘッドセットにALVRを入れるときに一度必要です。画面収録はMac上のプレビューにのみ、BlackHoleはゲーム音声に選んだ場合にのみ必要です。ゲーム内の動画を再生するにはGStreamerが必要です。", .setupMac: "Apple Silicon搭載Mac", .setupMacHelp: "Apple SiliconとmacOS 14以降。", .setupMacUnsupported: "TrailBridgeにはApple SiliconとmacOS 14以降が必要です。", @@ -622,6 +623,13 @@ final class StringsJA: LocalizationTable { .setupEngineHelp: "MacでWindowsゲームを実行します。", .setupEngineAvailable: "検証済みエンジンが利用できます。", .setupEngineBuild: "指定バージョンのM5エンジンとBasalt DXMTフォークをビルドしてください。", + .setupGStreamer: "ゲーム内の動画(GStreamer)", + .setupGStreamerMissing: "未インストール", + .setupGStreamerInstalled: "インストール済み", + .setupGStreamerVersion: "インストール済み(バージョン %1$@)", + .setupGStreamerHelp: "ゲーム内の動画を再生できます。", + .setupGStreamerInstall: "未インストールです。管理者アカウントで、このMacのすべてのユーザ向けにインストールしてから「%1$@」をクリックしてください。", + .setupGStreamerPackage: "GStreamerを入手…", .setupRuntime: "VRモジュール(OpenXR)", .setupRuntimeHelp: "ゲームのVR映像をヘッドセットに送ります。", .setupRuntimeBuild: "Windows用OpenXRランタイムはまだビルドされていません。", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift index 86adb25..fc504e7 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift @@ -68,6 +68,7 @@ final class StringsKO: LocalizationTable { .uninstallBusy: "먼저 VR 세션을 중지하세요.", .uninstallFailed: "일부 파일을 제거하지 못했어요: %1$@", .uninstallNone: "없음", + .modelGStreamerMissing: "GStreamer가 설치되어 있지 않습니다. 시작 영상 등의 동영상을 재생하는 게임이 멈출 수 있습니다. %1$@에서 공식 패키지를 받아 모든 사용자용으로 설치하세요.\n", .modelGamePriority: "게임 프로세스 우선순위: 높음(user-interactive QoS)\n", .modelGameExited: "게임 종료 코드: %1$@\n", .modelGameExitedQuickly: "게임이 시작 후 %1$@초 만에 종료되었습니다. 헤드셋에 아무것도 나타나지 않았다면, 실행한 파일이 게임을 별도 프로세스로 여는 런처이거나 게임이 로딩 중에 멈췄을 수 있습니다(위의 “game:” 줄 참고). 게임 본체의 .exe를 실행하려면 라이브러리 → 게임 카드 → ⋯ → %2$@에서 선택하세요.\n", @@ -614,7 +615,7 @@ final class StringsKO: LocalizationTable { .setupMissingGuidance: "필수 단계를 완료한 뒤 환경을 만들고 게임을 추가하세요.", .setupBottle: "환경 설정", .setupRequiredHelp: "VR 스트리밍에 필요한 구성 요소예요. Wine은 앱이 직접 다운로드해요. 빌드 안내는 소스 코드로 앱을 빌드하는 분을 위한 거예요.", - .setupOptionalHelp: "USB 도구는 나중에 Wi‑Fi로 플레이하더라도 헤드셋에 ALVR을 설치할 때 한 번 필요해요. 화면 기록은 Mac 미리보기에만, BlackHole은 게임 오디오로 선택한 경우에만 필요해요.", + .setupOptionalHelp: "USB 도구는 나중에 Wi‑Fi로 플레이하더라도 헤드셋에 ALVR을 설치할 때 한 번 필요해요. 화면 기록은 Mac 미리보기에만, BlackHole은 게임 오디오로 선택한 경우에만 필요해요. 게임 내 동영상을 재생하려면 GStreamer가 필요해요.", .setupMac: "Apple Silicon 탑재 Mac", .setupMacHelp: "Apple Silicon 및 macOS 14 이상.", .setupMacUnsupported: "TrailBridge에는 Apple Silicon 및 macOS 14 이상이 필요해요.", @@ -622,6 +623,13 @@ final class StringsKO: LocalizationTable { .setupEngineHelp: "Mac에서 Windows 게임을 실행해요.", .setupEngineAvailable: "검증된 엔진을 사용할 수 있어요.", .setupEngineBuild: "지정 버전의 M5 엔진과 Basalt DXMT 포크를 빌드하세요.", + .setupGStreamer: "게임 내 동영상 (GStreamer)", + .setupGStreamerMissing: "설치되지 않음", + .setupGStreamerInstalled: "설치됨", + .setupGStreamerVersion: "설치됨(버전 %1$@)", + .setupGStreamerHelp: "시작 영상 등 게임 내 동영상을 재생해요.", + .setupGStreamerInstall: "설치되지 않았어요. 관리자 계정으로 이 Mac의 모든 사용자용으로 설치한 다음 ‘%1$@’을 클릭하세요.", + .setupGStreamerPackage: "GStreamer 다운로드…", .setupRuntime: "VR 모듈(OpenXR)", .setupRuntimeHelp: "게임의 VR 출력을 헤드셋으로 연결해요.", .setupRuntimeBuild: "Windows OpenXR 런타임이 아직 빌드되지 않았어요.", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift index c003066..fdbb3ce 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift @@ -68,6 +68,7 @@ final class StringsPL: LocalizationTable { .uninstallBusy: "Najpierw zatrzymaj sesję VR.", .uninstallFailed: "Nie udało się usunąć części plików: %1$@", .uninstallNone: "Brak", + .modelGStreamerMissing: "GStreamer nie jest zainstalowany. Gry odtwarzające filmy, na przykład intro, mogą się zawiesić. Pobierz oficjalny pakiet z %1$@ i zainstaluj go dla wszystkich użytkowników.\n", .modelGamePriority: "Priorytet procesu gry: wysoki (user-interactive QoS)\n", .modelGameExited: "Gra zakończyła się z kodem %1$@\n", .modelGameExitedQuickly: "Gra zakończyła się %1$@ s po uruchomieniu. Jeśli w goglach nic się nie pojawiło, uruchomiony plik może być launcherem, który otwiera grę jako osobny proces, albo gra zatrzymała się podczas ładowania (zobacz wiersze „game:” powyżej). Aby uruchamiać sam plik .exe gry, wybierz go w: Biblioteka → karta gry → ⋯ → %2$@\n", @@ -614,7 +615,7 @@ final class StringsPL: LocalizationTable { .setupMissingGuidance: "Wykonaj wymagane kroki, a następnie utwórz środowisko i dodaj grę.", .setupBottle: "Skonfiguruj środowisko", .setupRequiredHelp: "Te składniki umożliwiają transmisję VR. Aplikacja sama pobiera Wine; instrukcje budowania są dla osób, które budują aplikację z kodu źródłowego.", - .setupOptionalHelp: "Narzędzia USB instalują ALVR w goglach raz, nawet jeśli potem grasz przez Wi‑Fi. Nagrywanie ekranu służy tylko do podglądu na Macu, a BlackHole jest potrzebny tylko wtedy, gdy wybierzesz go do dźwięku gry.", + .setupOptionalHelp: "Narzędzia USB instalują ALVR w goglach raz, nawet jeśli potem grasz przez Wi‑Fi. Nagrywanie ekranu służy tylko do podglądu na Macu, a BlackHole jest potrzebny tylko wtedy, gdy wybierzesz go do dźwięku gry. GStreamer jest potrzebny do odtwarzania filmów w grach.", .setupMac: "Mac z Apple Silicon", .setupMacHelp: "Apple Silicon i macOS 14 lub nowszy.", .setupMacUnsupported: "TrailBridge wymaga Apple Silicon i macOS 14 lub nowszego.", @@ -622,6 +623,13 @@ final class StringsPL: LocalizationTable { .setupEngineHelp: "Uruchamia gry Windows na Macu.", .setupEngineAvailable: "Zweryfikowany silnik jest dostępny.", .setupEngineBuild: "Zbuduj ustaloną wersję silnika M5 i fork Basalt DXMT.", + .setupGStreamer: "Filmy w grach (GStreamer)", + .setupGStreamerMissing: "Brak", + .setupGStreamerInstalled: "Zainstalowano", + .setupGStreamerVersion: "Zainstalowano (wersja %1$@)", + .setupGStreamerHelp: "Odtwarza filmy w grach.", + .setupGStreamerInstall: "Brak instalacji. Użyj konta administratora, aby zainstalować pakiet dla wszystkich użytkowników tego Maca, a następnie kliknij „%1$@”.", + .setupGStreamerPackage: "Pobierz GStreamer…", .setupRuntime: "Moduł VR (OpenXR)", .setupRuntimeHelp: "Przekazuje obraz VR z gry do gogli.", .setupRuntimeBuild: "Nie zbudowano modułu OpenXR dla Windows.", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift index 6ce7462..e5ac0db 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift @@ -68,6 +68,7 @@ final class StringsRU: LocalizationTable { .uninstallBusy: "Сначала остановите сеанс VR.", .uninstallFailed: "Не удалось удалить часть файлов: %1$@", .uninstallNone: "Нет", + .modelGStreamerMissing: "GStreamer не установлен. Игры, которые показывают видео (например, заставку), могут зависнуть. Установите официальный пакет для всех пользователей по ссылке %1$@\n", .modelGamePriority: "Приоритет процесса игры: высокий (user-interactive QoS)\n", .modelGameExited: "Игра завершилась с кодом %1$@\n", .modelGameExitedQuickly: "Игра завершилась через %1$@ с после запуска. Если в шлеме ничего не появилось, запущенный файл может быть лаунчером, который открывает игру отдельным процессом, или игра остановилась при загрузке (см. строки «game:» выше). Чтобы запускать сам .exe игры, выберите его: «Библиотека» → карточка игры → ⋯ → «%2$@».\n", @@ -614,7 +615,7 @@ final class StringsRU: LocalizationTable { .setupMissingGuidance: "Выполните обязательные шаги, затем создайте окружение и добавьте игру.", .setupBottle: "Подготовить окружение", .setupRequiredHelp: "Эти компоненты нужны для VR. Wine приложение скачивает само; инструкция по сборке нужна тем, кто собирает приложение из исходного кода.", - .setupOptionalHelp: "Инструменты USB ставят ALVR на шлем — один раз, даже если потом играть по Wi‑Fi. Запись экрана нужна только для предпросмотра на Mac, а BlackHole — только если вы выберете его для звука игры.", + .setupOptionalHelp: "Инструменты USB ставят ALVR на шлем — один раз, даже если потом играть по Wi‑Fi. Запись экрана нужна только для предпросмотра на Mac, а BlackHole — только если вы выберете его для звука игры. GStreamer нужен для воспроизведения видео в играх.", .setupMac: "Mac с Apple Silicon", .setupMacHelp: "Apple Silicon и macOS 14 или новее.", .setupMacUnsupported: "Для TrailBridge нужны Apple Silicon и macOS 14 или новее.", @@ -622,6 +623,13 @@ final class StringsRU: LocalizationTable { .setupEngineHelp: "Запускает игры Windows на Mac.", .setupEngineAvailable: "Проверенный движок доступен.", .setupEngineBuild: "Соберите закреплённый движок M5 и форк Basalt DXMT.", + .setupGStreamer: "Видео в играх (GStreamer)", + .setupGStreamerMissing: "Не установлен", + .setupGStreamerInstalled: "Установлен", + .setupGStreamerVersion: "Установлен (версия %1$@)", + .setupGStreamerHelp: "Воспроизводит видео в играх.", + .setupGStreamerInstall: "Не установлен. С правами администратора установите пакет для всех пользователей этого Mac, затем нажмите «%1$@».", + .setupGStreamerPackage: "Скачать GStreamer…", .setupRuntime: "VR-модуль (OpenXR)", .setupRuntimeHelp: "Передаёт VR-изображение игры в шлем.", .setupRuntimeBuild: "Среда OpenXR для Windows ещё не собрана.", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift index fae07df..ae90420 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift @@ -68,6 +68,7 @@ final class StringsUK: LocalizationTable { .uninstallBusy: "Спершу зупиніть сеанс VR.", .uninstallFailed: "Не вдалося видалити частину файлів: %1$@", .uninstallNone: "Немає", + .modelGStreamerMissing: "GStreamer не встановлено. Ігри, які показують відео (наприклад, заставку), можуть зависнути. Установіть офіційний пакет для всіх користувачів за посиланням %1$@\n", .modelGamePriority: "Пріоритет процесу гри: високий (user-interactive QoS)\n", .modelGameExited: "Гра завершилася з кодом %1$@\n", .modelGameExitedQuickly: "Гра завершилася через %1$@ с після запуску. Якщо в шоломі нічого не з’явилося, запущений файл може бути лаунчером, що відкриває гру окремим процесом, або гра зупинилася під час завантаження (див. рядки «game:» вище). Щоб запускати сам .exe гри, виберіть його: Бібліотека → картка гри → ⋯ → %2$@\n", @@ -614,7 +615,7 @@ final class StringsUK: LocalizationTable { .setupMissingGuidance: "Виконайте обов’язкові кроки, потім створіть середовище й додайте гру.", .setupBottle: "Налаштувати середовище", .setupRequiredHelp: "Ці компоненти потрібні для трансляції VR. Wine програма завантажує сама; інструкції зі збирання потрібні тим, хто збирає програму з вихідного коду.", - .setupOptionalHelp: "Інструменти USB встановлюють ALVR на шолом — один раз, навіть якщо потім грати через Wi‑Fi. Запис екрана потрібен лише для перегляду на Mac, а BlackHole — лише якщо ви виберете його для звуку гри.", + .setupOptionalHelp: "Інструменти USB встановлюють ALVR на шолом — один раз, навіть якщо потім грати через Wi‑Fi. Запис екрана потрібен лише для перегляду на Mac, а BlackHole — лише якщо ви виберете його для звуку гри. GStreamer потрібен для відтворення відео в іграх.", .setupMac: "Mac з Apple Silicon", .setupMacHelp: "Apple Silicon і macOS 14 або новіша версія.", .setupMacUnsupported: "Для TrailBridge потрібні Apple Silicon і macOS 14 або новіша версія.", @@ -622,6 +623,13 @@ final class StringsUK: LocalizationTable { .setupEngineHelp: "Запускає ігри Windows на Mac.", .setupEngineAvailable: "Перевірений рушій доступний.", .setupEngineBuild: "Зберіть закріплений рушій M5 і форк Basalt DXMT.", + .setupGStreamer: "Відео в іграх (GStreamer)", + .setupGStreamerMissing: "Не встановлено", + .setupGStreamerInstalled: "Встановлено", + .setupGStreamerVersion: "Встановлено (версія %1$@)", + .setupGStreamerHelp: "Відтворює відео в іграх.", + .setupGStreamerInstall: "Не встановлено. З правами адміністратора встановіть пакет для всіх користувачів цього Mac, а потім натисніть «%1$@».", + .setupGStreamerPackage: "Завантажити GStreamer…", .setupRuntime: "Модуль VR (OpenXR)", .setupRuntimeHelp: "Передає VR-зображення гри на шолом.", .setupRuntimeBuild: "Модуль OpenXR для Windows ще не зібрано.", diff --git a/streamer/Sources/BasaltManagerKit/ManagementModels.swift b/streamer/Sources/BasaltManagerKit/ManagementModels.swift index 3b33a6c..ca29c86 100644 --- a/streamer/Sources/BasaltManagerKit/ManagementModels.swift +++ b/streamer/Sources/BasaltManagerKit/ManagementModels.swift @@ -49,17 +49,25 @@ public struct SetupInspector: @unchecked Sendable { public let manager: BottleManager private let fileManager: FileManager private let rosettaInstalled: @Sendable () -> Bool + private let gStreamerFramework: URL public init(repoRoot: URL, manager: BottleManager, fileManager: FileManager = .default, - rosettaInstalled: @escaping @Sendable () -> Bool = { Rosetta.isInstalled() }) { + rosettaInstalled: @escaping @Sendable () -> Bool = { Rosetta.isInstalled() }, + gStreamerFramework: URL = GStreamerInstallation.systemFramework) { self.repoRoot = repoRoot self.manager = manager self.fileManager = fileManager self.rosettaInstalled = rosettaInstalled + self.gStreamerFramework = gStreamerFramework } public func inspect() -> [SetupCheck] { + inspectWithGStreamerVersion().checks + } + + /// Keeps the detected version available for Setup's localized detail. + public func inspectWithGStreamerVersion() -> (checks: [SetupCheck], gStreamerVersion: String?) { let version = ProcessInfo.processInfo.operatingSystemVersion let supportedOS = version.majorVersion >= 14 let arm = ProcessInfo.processInfo.machineHardwareName == "arm64" @@ -81,7 +89,12 @@ public struct SetupInspector: @unchecked Sendable { $0.localizedCaseInsensitiveContains("BlackHole") } - return [ + let gStreamer = GStreamerInstallation.detect(frameworkURL: gStreamerFramework, fileManager: fileManager) + let gStreamerVersion: String? = if case .installed(let version) = gStreamer { version } else { nil } + let gStreamerDetail = gStreamer == .missing ? "Not installed" + : gStreamerVersion.map { "GStreamer \($0) is installed" } ?? "GStreamer is installed" + + let checks = [ SetupCheck( id: "mac", title: "Apple Silicon Mac", detail: arm && supportedOS @@ -115,6 +128,11 @@ public struct SetupInspector: @unchecked Sendable { status: pinnedEngine ? .ready : .actionNeeded, required: true, action: hasPinnedWine ? "Open Build Instructions" : Self.downloadWineAction), + // Only games that play video need this system package. + SetupCheck( + id: "gstreamer", title: "Video in games (GStreamer)", detail: gStreamerDetail, + status: gStreamer == .missing ? .actionNeeded : .ready, + required: false, action: gStreamer == .missing ? "Get GStreamer…" : nil), SetupCheck( id: "runtime", title: "OpenXR runtime", detail: fileManager.fileExists(atPath: runtime.path) @@ -137,6 +155,7 @@ public struct SetupInspector: @unchecked Sendable { status: hasBlackHole || GameAudioSource.macAudioSupported ? .ready : .actionNeeded, required: false, action: "Get BlackHole…"), ] + return (checks, gStreamerVersion) } public static func findExecutable( diff --git a/streamer/Sources/BasaltManagerKit/SessionConsole.swift b/streamer/Sources/BasaltManagerKit/SessionConsole.swift index 3e94199..f6a6da1 100644 --- a/streamer/Sources/BasaltManagerKit/SessionConsole.swift +++ b/streamer/Sources/BasaltManagerKit/SessionConsole.swift @@ -27,6 +27,7 @@ public final class SessionConsole: ObservableObject { /// into each other mid-line. private var partialLines = [ObjectIdentifier?: String]() private var deviceErrorCounts = [ObjectIdentifier?: Int]() + private var warnedAboutMissingGStreamer = false private var transcript: ConsoleTranscript? private var transcriptsBySource = [ObjectIdentifier: ConsoleTranscript]() @@ -62,9 +63,17 @@ public final class SessionConsole: ObservableObject { headsetDisconnected = false partialLines.removeAll() deviceErrorCounts.removeAll() + warnedAboutMissingGStreamer = false if clearingSamples { samples.removeAll() } } + /// Supplies the warning the first time a game launch finds GStreamer missing in this session. + public func gStreamerWarning(for installation: GStreamerInstallation) -> String? { + guard !warnedAboutMissingGStreamer, installation == .missing else { return nil } + warnedAboutMissingGStreamer = true + return L10n.string(.modelGStreamerMissing, PinnedWine.gStreamerPackageURL.absoluteString) + } + /// Appends raw output from `source`, logs the lines it completed with /// `prefix`, and returns them. An unfinished line waits for its source's /// next chunk or `finish`. diff --git a/streamer/Sources/BasaltManagerKit/WineInstaller.swift b/streamer/Sources/BasaltManagerKit/WineInstaller.swift index 676a286..14037a5 100644 --- a/streamer/Sources/BasaltManagerKit/WineInstaller.swift +++ b/streamer/Sources/BasaltManagerKit/WineInstaller.swift @@ -17,6 +17,13 @@ public enum PinnedWine { public static let releasePage = URL( string: "https://github.com/Gcenx/macOS_Wine_builds/releases/tag/11.10")! + /// The GStreamer version named in the pinned Wine build's requirements. + /// Update the version and package link together with the Wine pin. + static let gStreamerVersion = "1.28.1" + /// The official GStreamer installer for video playback through this Wine build. + public static let gStreamerPackageURL = URL( + string: "https://gstreamer.freedesktop.org/data/pkg/osx/\(gStreamerVersion)/gstreamer-1.0-\(gStreamerVersion)-universal.pkg")! + /// The archive's size as the app shows it, in the app's language. public static var archiveSizeText: String { sizeText(archiveBytes) } public static var unpackedSizeText: String { sizeText(unpackedBytes) } diff --git a/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift b/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift index 484ce59..41fc229 100644 --- a/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift @@ -225,6 +225,36 @@ final class DiagnosticsTests: XCTestCase { XCTAssertTrue(markdown.contains("### Session log\n\nNot included.")) } + func testReportSaysWhenSetupHasNotRun() { + let report = makeReport(log: nil, setupChecks: []) + XCTAssertTrue(report.setupChecks.isEmpty) + XCTAssertTrue(report.markdown(redactedWith: redactor).contains( + "### Setup\n\nNo setup checks have run.")) + } + + func testReportUsesTheEnglishGStreamerSetupCheck() throws { + let previous = L10n.language + defer { L10n.language = previous } + L10n.language = .ru + let root = try temporaryDirectory() + let framework = root.appendingPathComponent("GStreamer.framework") + try FileManager.default.createDirectory(at: framework, withIntermediateDirectories: true) + let plist = try PropertyListSerialization.data( + fromPropertyList: ["CFBundleShortVersionString": "1.28.1"], format: .xml, options: 0) + try plist.write(to: framework.appendingPathComponent("Info.plist")) + let checks = SetupInspector( + repoRoot: root, manager: BottleManager(root: root, repoRoot: root), + rosettaInstalled: { true }, gStreamerFramework: framework).inspect() + let report = makeReport(log: nil, setupChecks: checks) + let check = try XCTUnwrap(report.setupChecks.first { $0.id == "gstreamer" }) + XCTAssertEqual(check.title, "Video in games (GStreamer)") + XCTAssertEqual(check.status, SetupCheckStatus.ready.rawValue) + XCTAssertFalse(check.required) + XCTAssertEqual(check.detail, "GStreamer 1.28.1 is installed") + XCTAssertTrue(report.markdown(redactedWith: redactor).contains( + "- [x] **Video in games (GStreamer)** (optional) — GStreamer 1.28.1 is installed")) + } + func testLogTailKeepsTheLastLines() { let log = (1...(DiagnosticReport.maximumLogLines + 25)).map { "line \($0)" } .joined(separator: "\n") + "\n\n" @@ -286,7 +316,8 @@ final class DiagnosticsTests: XCTestCase { defaultAudioDevice: String? = nil, failureReason: String = "Steam is open but not signed in.", arguments: [String] = ["-applaunch", "620980"], - root: String = "/Users/ada/BasaltVR") -> DiagnosticReport { + root: String = "/Users/ada/BasaltVR", + setupChecks: [SetupCheck]? = nil) -> DiagnosticReport { let engineRoot = URL(fileURLWithPath: root + "/runtime/build/wine") let engine = BottleEngine( id: "pinned-wine", kind: .pinned, @@ -328,7 +359,7 @@ final class DiagnosticsTests: XCTestCase { operatingSystem: "macOS 26.0 (Build 25A1)", hardwareModel: "Mac15,8", chip: "Apple M3 Max", architecture: "arm64", memoryGigabytes: 36, processorCount: 14, thermalState: "nominal", lowPowerMode: false), - setupChecks: [ + setupChecks: setupChecks ?? [ SetupCheck(id: "runtime", title: "OpenXR runtime", detail: root + "/runtime/build/bin/basalt_openxr.dll", status: .ready, required: true), diff --git a/streamer/Tests/BasaltManagerKitTests/GStreamerInstallationTests.swift b/streamer/Tests/BasaltManagerKitTests/GStreamerInstallationTests.swift new file mode 100644 index 0000000..1f88ec0 --- /dev/null +++ b/streamer/Tests/BasaltManagerKitTests/GStreamerInstallationTests.swift @@ -0,0 +1,37 @@ +import XCTest +@testable import BasaltManagerKit + +final class GStreamerInstallationTests: XCTestCase { + func testMissingFrameworkRequiresADirectory() throws { + let framework = try temporaryDirectory().appendingPathComponent("GStreamer.framework") + let fileManager = FileManager() + XCTAssertEqual(GStreamerInstallation.detect(frameworkURL: framework, fileManager: fileManager), + .missing) + try Data().write(to: framework) + XCTAssertEqual(GStreamerInstallation.detect(frameworkURL: framework, fileManager: fileManager), + .missing) + } + + func testFrameworkWithoutReadableMetadataIsInstalledWithoutAVersion() throws { + let framework = try temporaryDirectory().appendingPathComponent("GStreamer.framework") + try FileManager.default.createDirectory(at: framework, withIntermediateDirectories: true) + XCTAssertEqual(GStreamerInstallation.detect(frameworkURL: framework), .installed(version: nil)) + try Data("invalid plist".utf8).write(to: framework.appendingPathComponent("Info.plist")) + XCTAssertEqual(GStreamerInstallation.detect(frameworkURL: framework), .installed(version: nil)) + } + + func testReadsTheVersionFromFrameworkMetadata() throws { + let fileManager = FileManager.default + let framework = try temporaryDirectory().appendingPathComponent("GStreamer.framework") + let resources = framework.appendingPathComponent("Versions/1.0/Resources") + try fileManager.createDirectory(at: resources, withIntermediateDirectories: true) + try fileManager.createSymbolicLink( + atPath: framework.appendingPathComponent("Versions/Current").path, withDestinationPath: "1.0") + XCTAssertEqual(GStreamerInstallation.detect(frameworkURL: framework), .installed(version: nil)) + + let plist = try PropertyListSerialization.data( + fromPropertyList: ["CFBundleShortVersionString": "1.28.1"], format: .xml, options: 0) + try plist.write(to: resources.appendingPathComponent("Info.plist")) + XCTAssertEqual(GStreamerInstallation.detect(frameworkURL: framework), .installed(version: "1.28.1")) + } +} diff --git a/streamer/Tests/BasaltManagerKitTests/SessionConsoleTests.swift b/streamer/Tests/BasaltManagerKitTests/SessionConsoleTests.swift index bab89a7..cc23662 100644 --- a/streamer/Tests/BasaltManagerKitTests/SessionConsoleTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/SessionConsoleTests.swift @@ -3,6 +3,20 @@ import XCTest @MainActor final class SessionConsoleTests: XCTestCase { + func testMissingGStreamerWarnsOncePerSession() throws { + let console = SessionConsole() + console.restart(with: "Starting the game…\n") + XCTAssertNil(console.gStreamerWarning(for: .installed(version: nil))) + let warning = try XCTUnwrap(console.gStreamerWarning(for: .missing)) + XCTAssertTrue(warning.contains(PinnedWine.gStreamerPackageURL.absoluteString)) + XCTAssertTrue(warning.hasSuffix("\n")) + XCTAssertNil(console.gStreamerWarning(for: .missing)) + XCTAssertEqual(console.log, "Starting the game…\n") + + console.restart() + XCTAssertEqual(console.gStreamerWarning(for: .missing), warning) + } + func testDeviceErrorFinalPartialLineIsCountedAndSourceCanBeReused() { let console = SessionConsole() let game = NSObject() diff --git a/streamer/Tests/BasaltManagerKitTests/SetupInspectorTests.swift b/streamer/Tests/BasaltManagerKitTests/SetupInspectorTests.swift index 6de0301..cca7925 100644 --- a/streamer/Tests/BasaltManagerKitTests/SetupInspectorTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/SetupInspectorTests.swift @@ -2,8 +2,7 @@ import XCTest @testable import BasaltBottleKit @testable import BasaltManagerKit -/// The Setup checks a packaged app adds: Rosetta, and the Wine it can -/// download itself. +/// The packaged app's dependency checks. final class SetupInspectorTests: XCTestCase { func testRosettaIsWhetherTheMacRunsIntelCode() { XCTAssertTrue(Rosetta.isInstalled(runsIntelCode: { true })) @@ -91,6 +90,44 @@ final class SetupInspectorTests: XCTestCase { XCTAssertTrue(missing.allSatisfy(\.isFixedOnSetupPage)) } + func testMissingGStreamerOffersThePackageWithoutBlockingReadiness() throws { + let fixture = try makeFixture() + let check = try XCTUnwrap(inspector(fixture).inspect().first { $0.id == "gstreamer" }) + XCTAssertEqual(check.title, "Video in games (GStreamer)") + XCTAssertEqual(check.detail, "Not installed") + XCTAssertEqual(check.status, .actionNeeded) + XCTAssertFalse(check.required) + XCTAssertFalse(check.isFixedOnSetupPage) + XCTAssertEqual(check.action, "Get GStreamer…") + + let mac = SetupCheck(id: "mac", title: "Mac", detail: "", status: .ready, required: true) + var snapshot = LearningReadinessSnapshot() + snapshot.setupChecks = [mac, check] + XCTAssertEqual(LearningReadiness(snapshot).row(.mac)?.status, .ready) + var facts = LearningFacts() + facts.setupChecks = snapshot.setupChecks + XCTAssertTrue(facts.macReady) + } + + func testInstalledGStreamerIsReadyWithOrWithoutAVersion() throws { + let fixture = try makeFixture() + let framework = gStreamerFramework(in: fixture.repo) + try FileManager.default.createDirectory(at: framework, withIntermediateDirectories: true) + let inspector = inspector(fixture) + let check = try XCTUnwrap(inspector.inspect().first { $0.id == "gstreamer" }) + XCTAssertEqual(check.status, .ready) + XCTAssertFalse(check.required) + XCTAssertNil(check.action) + XCTAssertEqual(check.detail, "GStreamer is installed") + + let plist = try PropertyListSerialization.data( + fromPropertyList: ["CFBundleShortVersionString": "1.28.2"], format: .xml, options: 0) + try plist.write(to: framework.appendingPathComponent("Info.plist")) + let (checks, version) = inspector.inspectWithGStreamerVersion() + XCTAssertEqual(version, "1.28.2") + XCTAssertEqual(checks.first { $0.id == "gstreamer" }?.detail, "GStreamer 1.28.2 is installed") + } + // MARK: - Fixtures private var isAppleSilicon: Bool { @@ -114,7 +151,12 @@ final class SetupInspectorTests: XCTestCase { private func inspector(_ fixture: (repo: URL, data: URL), rosetta: Bool = true) -> SetupInspector { SetupInspector(repoRoot: fixture.repo, manager: BottleManager(root: fixture.data, repoRoot: fixture.repo), - rosettaInstalled: { rosetta }) + rosettaInstalled: { rosetta }, + gStreamerFramework: gStreamerFramework(in: fixture.repo)) + } + + private func gStreamerFramework(in repo: URL) -> URL { + repo.appendingPathComponent("GStreamer.framework", isDirectory: true) } private func makeWine(at root: URL) throws { diff --git a/streamer/Tests/BasaltManagerKitTests/WineInstallerTests.swift b/streamer/Tests/BasaltManagerKitTests/WineInstallerTests.swift index d979cce..25f094d 100644 --- a/streamer/Tests/BasaltManagerKitTests/WineInstallerTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/WineInstallerTests.swift @@ -30,6 +30,12 @@ final class WineInstallerTests: XCTestCase { XCTAssertEqual(PinnedWine.unpackedSizeText, "720 MB") } + func testGStreamerPackageMatchesThePinnedWineRequirements() { + XCTAssertEqual(PinnedWine.gStreamerVersion, "1.28.1") + XCTAssertEqual(PinnedWine.gStreamerPackageURL.absoluteString, + "https://gstreamer.freedesktop.org/data/pkg/osx/1.28.1/gstreamer-1.0-1.28.1-universal.pkg") + } + func testInstallsWineWhereTheEngineIsLookedForAndCleansUp() async throws { let fixture = try makeFixture() let stages = Recorder() From 5586559da756cb39fc6a9d4d18e9184643746a09 Mon Sep 17 00:00:00 2001 From: abgitdev <266600699+abgitdev@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:50:41 +0000 Subject: [PATCH 3/7] Collapse GStreamer's harmless repeated warnings in the session log Once GStreamer is installed, Wine prints two harmless GLib messages: a pygobject initialization failure from the plugin loader, and a GStreamer-Video-CRITICAL assertion that a game can repeat thousands of times, each after a blank line. They buried the lines that matter. The session console now shows the first occurrence of each, drops the blank line GLib writes before them and counts the repeats: one total line per source when its output closes, and the open totals in a diagnostic report made during a session. Matching accepts any GLib program name, process id and timestamp. Saved transcripts keep every line and the final totals. SessionConsole.isKnownHarmlessNoise lets later log checks skip these lines. Repeated GPU device errors use the same per-source counting as before. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + streamer/Sources/BasaltManager/AppModel.swift | 2 +- .../Localization/L10nKey.swift | 1 + .../Localization/Strings+de.swift | 1 + .../Localization/Strings+en.swift | 1 + .../Localization/Strings+es.swift | 1 + .../Localization/Strings+fr.swift | 1 + .../Localization/Strings+it.swift | 1 + .../Localization/Strings+ja.swift | 1 + .../Localization/Strings+ko.swift | 1 + .../Localization/Strings+pl.swift | 1 + .../Localization/Strings+ru.swift | 1 + .../Localization/Strings+uk.swift | 1 + .../BasaltManagerKit/SessionConsole.swift | 180 +++++++++++++++--- .../DiagnosticsTests.swift | 17 ++ .../SessionConsoleTests.swift | 150 +++++++++++++++ 16 files changed, 336 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8c3150..814ebf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ All notable changes to TrailBridge VR are documented here. - Setup checks for GStreamer, which Wine uses to play videos in games, and links to the official package. Diagnostic reports include its status and version when available. Games can still start without it, with one warning per game session in the log. +- The session log shows the first occurrence of each known harmless GStreamer warning and totals + its repeats when the output closes. Diagnostic reports include repeat counts during a session, + and recordings keep the full output and final counts. ## 0.2.1 — 2026-11-15 diff --git a/streamer/Sources/BasaltManager/AppModel.swift b/streamer/Sources/BasaltManager/AppModel.swift index 21a3493..8b6f5be 100644 --- a/streamer/Sources/BasaltManager/AppModel.swift +++ b/streamer/Sources/BasaltManager/AppModel.swift @@ -2628,7 +2628,7 @@ final class BasaltAppModel: ObservableObject { profileName: openSession?.profileName, metrics: openSession?.metrics), recentSessions: sessionHistory, - log: includeLog ? console.log : nil) + log: includeLog ? console.diagnosticLog : nil) } func export(_ text: String, to url: URL) { diff --git a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift index 19e5e48..01f1349 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift @@ -66,6 +66,7 @@ public enum L10nKey: String, CaseIterable, Sendable { case uninstallFailed case uninstallNone case modelGStreamerMissing + case modelGStreamerWarningRepeats case modelGamePriority case modelGameExited case modelGameExitedQuickly diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift index fbba1ad..f79fbc8 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift @@ -69,6 +69,7 @@ final class StringsDE: LocalizationTable { .uninstallFailed: "Einige Dateien konnten nicht entfernt werden: %1$@", .uninstallNone: "Keine", .modelGStreamerMissing: "GStreamer ist nicht installiert. Spiele, die Videos wie etwa Intros abspielen, können hängen bleiben. Lade das offizielle Paket von %1$@ und installiere es für alle Benutzer.\n", + .modelGStreamerWarningRepeats: "Harmlose GStreamer-Warnung (%1$@), ausgeblendete Wiederholungen: %2$lld", .modelGamePriority: "Priorität des Spielprozesses: hoch (user-interactive QoS)\n", .modelGameExited: "Spiel mit Status %1$@ beendet\n", .modelGameExitedQuickly: "Das Spiel endete %1$@ s nach dem Start. Erschien nichts im Headset, ist die gestartete Datei vielleicht ein Launcher, der das Spiel als eigenen Prozess öffnet, oder das Spiel hat beim Laden aufgehört (siehe die „game:“-Zeilen oben). Um die .exe des Spiels selbst zu starten, diese unter Bibliothek → Spielkarte → ⋯ → %2$@ auswählen.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift index 768b82a..bd1826d 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift @@ -69,6 +69,7 @@ final class StringsEN: LocalizationTable { .uninstallFailed: "Some files could not be removed: %1$@", .uninstallNone: "None", .modelGStreamerMissing: "GStreamer is not installed. Games that play videos, such as intros, can hang. Install the official package for all users from %1$@\n", + .modelGStreamerWarningRepeats: "Harmless GStreamer warning (%1$@), repeats not shown: %2$lld", .modelGamePriority: "Game process priority: high (user-interactive QoS)\n", .modelGameExited: "Game exited with status %1$@\n", .modelGameExitedQuickly: "The game ended %1$@ s after it started. If nothing appeared in the headset, the file started may be a launcher that opens the game as a separate process, or the game stopped while loading (see the “game:” lines above). To start the game's own .exe, choose it in Library → game card → ⋯ → %2$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift index dcb6dd4..886d572 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift @@ -69,6 +69,7 @@ final class StringsES: LocalizationTable { .uninstallFailed: "No se pudieron eliminar algunos archivos: %1$@", .uninstallNone: "Ninguno", .modelGStreamerMissing: "GStreamer no está instalado. Los juegos que reproducen vídeos, como los de introducción, pueden quedarse bloqueados. Instala el paquete oficial para todos los usuarios desde %1$@\n", + .modelGStreamerWarningRepeats: "Aviso inofensivo de GStreamer (%1$@), repeticiones omitidas: %2$lld", .modelGamePriority: "Prioridad del proceso del juego: alta (user-interactive QoS)\n", .modelGameExited: "El juego terminó con el código %1$@\n", .modelGameExitedQuickly: "El juego terminó %1$@ s después de iniciarse. Si no apareció nada en el visor, el archivo iniciado puede ser un lanzador que abre el juego en otro proceso, o el juego se detuvo al cargar (consulta las líneas «game:» de arriba). Para iniciar el .exe del propio juego, elígelo en Biblioteca → tarjeta del juego → ⋯ → %2$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift index d217b85..cebbcd9 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift @@ -69,6 +69,7 @@ final class StringsFR: LocalizationTable { .uninstallFailed: "Certains fichiers n’ont pas pu être supprimés : %1$@", .uninstallNone: "Aucun", .modelGStreamerMissing: "GStreamer n’est pas installé. Les jeux qui lisent des vidéos, par exemple une cinématique d’introduction, peuvent se bloquer. Téléchargez le paquet officiel depuis %1$@ et installez-le pour tous les utilisateurs.\n", + .modelGStreamerWarningRepeats: "Avertissement sans conséquence de GStreamer (%1$@), répétitions masquées : %2$lld", .modelGamePriority: "Priorité du processus du jeu : élevée (user-interactive QoS)\n", .modelGameExited: "Le jeu s’est arrêté avec le code %1$@\n", .modelGameExitedQuickly: "Le jeu s’est arrêté %1$@ s après son lancement. Si rien n’est apparu dans le casque, le fichier lancé est peut-être un lanceur qui ouvre le jeu dans un processus séparé, ou le jeu s’est arrêté pendant le chargement (voir les lignes « game: » ci-dessus). Pour lancer le .exe du jeu lui-même, choisissez-le dans Bibliothèque → fiche du jeu → ⋯ → %2$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift index db34948..50b241d 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift @@ -69,6 +69,7 @@ final class StringsIT: LocalizationTable { .uninstallFailed: "Impossibile rimuovere alcuni file: %1$@", .uninstallNone: "Nessuno", .modelGStreamerMissing: "GStreamer non è installato. I giochi che riproducono video, ad esempio filmati introduttivi, possono bloccarsi. Scarica il pacchetto ufficiale da %1$@ e installalo per tutti gli utenti.\n", + .modelGStreamerWarningRepeats: "Avviso innocuo di GStreamer (%1$@), ripetizioni omesse: %2$lld", .modelGamePriority: "Priorità del processo di gioco: alta (user-interactive QoS)\n", .modelGameExited: "Gioco terminato con codice %1$@\n", .modelGameExitedQuickly: "Il gioco è terminato %1$@ s dopo l’avvio. Se nel visore non è apparso nulla, il file avviato può essere un launcher che apre il gioco in un processo separato, oppure il gioco si è fermato durante il caricamento (vedi le righe «game:» sopra). Per avviare l’.exe del gioco stesso, sceglilo in Libreria → scheda del gioco → ⋯ → %2$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift index 760ffec..eab6d24 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift @@ -69,6 +69,7 @@ final class StringsJA: LocalizationTable { .uninstallFailed: "一部のファイルを削除できませんでした:%1$@", .uninstallNone: "なし", .modelGStreamerMissing: "GStreamerがインストールされていません。オープニングなどの動画を再生するゲームが途中で止まることがあります。%1$@から公式パッケージを入手し、すべてのユーザ向けにインストールしてください。\n", + .modelGStreamerWarningRepeats: "無害なGStreamerの警告(%1$@)、省略した繰り返し回数:%2$lld", .modelGamePriority: "ゲームプロセスの優先度:高(user-interactive QoS)\n", .modelGameExited: "ゲームがコード%1$@で終了しました\n", .modelGameExitedQuickly: "ゲームは起動から%1$@秒後に終了しました。ヘッドセットに何も表示されなかった場合、起動したファイルがゲームを別のプロセスで開くランチャーであるか、読み込み中にゲームが停止した可能性があります(上の「game:」の行を確認してください)。ゲーム本体の.exeを起動するには、ライブラリ → ゲームカード → ⋯ → %2$@ で選択してください。\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift index fc504e7..364087c 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift @@ -69,6 +69,7 @@ final class StringsKO: LocalizationTable { .uninstallFailed: "일부 파일을 제거하지 못했어요: %1$@", .uninstallNone: "없음", .modelGStreamerMissing: "GStreamer가 설치되어 있지 않습니다. 시작 영상 등의 동영상을 재생하는 게임이 멈출 수 있습니다. %1$@에서 공식 패키지를 받아 모든 사용자용으로 설치하세요.\n", + .modelGStreamerWarningRepeats: "무해한 GStreamer 경고(%1$@), 생략된 반복 횟수: %2$lld", .modelGamePriority: "게임 프로세스 우선순위: 높음(user-interactive QoS)\n", .modelGameExited: "게임 종료 코드: %1$@\n", .modelGameExitedQuickly: "게임이 시작 후 %1$@초 만에 종료되었습니다. 헤드셋에 아무것도 나타나지 않았다면, 실행한 파일이 게임을 별도 프로세스로 여는 런처이거나 게임이 로딩 중에 멈췄을 수 있습니다(위의 “game:” 줄 참고). 게임 본체의 .exe를 실행하려면 라이브러리 → 게임 카드 → ⋯ → %2$@에서 선택하세요.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift index fdbb3ce..3e1c080 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift @@ -69,6 +69,7 @@ final class StringsPL: LocalizationTable { .uninstallFailed: "Nie udało się usunąć części plików: %1$@", .uninstallNone: "Brak", .modelGStreamerMissing: "GStreamer nie jest zainstalowany. Gry odtwarzające filmy, na przykład intro, mogą się zawiesić. Pobierz oficjalny pakiet z %1$@ i zainstaluj go dla wszystkich użytkowników.\n", + .modelGStreamerWarningRepeats: "Nieszkodliwe ostrzeżenie GStreamera (%1$@), pominięte powtórzenia: %2$lld", .modelGamePriority: "Priorytet procesu gry: wysoki (user-interactive QoS)\n", .modelGameExited: "Gra zakończyła się z kodem %1$@\n", .modelGameExitedQuickly: "Gra zakończyła się %1$@ s po uruchomieniu. Jeśli w goglach nic się nie pojawiło, uruchomiony plik może być launcherem, który otwiera grę jako osobny proces, albo gra zatrzymała się podczas ładowania (zobacz wiersze „game:” powyżej). Aby uruchamiać sam plik .exe gry, wybierz go w: Biblioteka → karta gry → ⋯ → %2$@\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift index e5ac0db..f530217 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift @@ -69,6 +69,7 @@ final class StringsRU: LocalizationTable { .uninstallFailed: "Не удалось удалить часть файлов: %1$@", .uninstallNone: "Нет", .modelGStreamerMissing: "GStreamer не установлен. Игры, которые показывают видео (например, заставку), могут зависнуть. Установите официальный пакет для всех пользователей по ссылке %1$@\n", + .modelGStreamerWarningRepeats: "Безвредное предупреждение GStreamer (%1$@), пропущено повторов: %2$lld", .modelGamePriority: "Приоритет процесса игры: высокий (user-interactive QoS)\n", .modelGameExited: "Игра завершилась с кодом %1$@\n", .modelGameExitedQuickly: "Игра завершилась через %1$@ с после запуска. Если в шлеме ничего не появилось, запущенный файл может быть лаунчером, который открывает игру отдельным процессом, или игра остановилась при загрузке (см. строки «game:» выше). Чтобы запускать сам .exe игры, выберите его: «Библиотека» → карточка игры → ⋯ → «%2$@».\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift index ae90420..6a335fe 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift @@ -69,6 +69,7 @@ final class StringsUK: LocalizationTable { .uninstallFailed: "Не вдалося видалити частину файлів: %1$@", .uninstallNone: "Немає", .modelGStreamerMissing: "GStreamer не встановлено. Ігри, які показують відео (наприклад, заставку), можуть зависнути. Установіть офіційний пакет для всіх користувачів за посиланням %1$@\n", + .modelGStreamerWarningRepeats: "Нешкідливе попередження GStreamer (%1$@), пропущено повторів: %2$lld", .modelGamePriority: "Пріоритет процесу гри: високий (user-interactive QoS)\n", .modelGameExited: "Гра завершилася з кодом %1$@\n", .modelGameExitedQuickly: "Гра завершилася через %1$@ с після запуску. Якщо в шоломі нічого не з’явилося, запущений файл може бути лаунчером, що відкриває гру окремим процесом, або гра зупинилася під час завантаження (див. рядки «game:» вище). Щоб запускати сам .exe гри, виберіть його: Бібліотека → картка гри → ⋯ → %2$@\n", diff --git a/streamer/Sources/BasaltManagerKit/SessionConsole.swift b/streamer/Sources/BasaltManagerKit/SessionConsole.swift index f6a6da1..fed5340 100644 --- a/streamer/Sources/BasaltManagerKit/SessionConsole.swift +++ b/streamer/Sources/BasaltManagerKit/SessionConsole.swift @@ -26,7 +26,60 @@ public final class SessionConsole: ObservableObject { /// nil for the app's own messages), so concurrent outputs never splice /// into each other mid-line. private var partialLines = [ObjectIdentifier?: String]() - private var deviceErrorCounts = [ObjectIdentifier?: Int]() + + /// Messages that can flood the log while a single output pipe is open. + private enum RepeatedLine: Hashable { + case deviceError + case gStreamerWarning(String) + } + + /// The counts and one line of lookahead for a pipe with a fixed display prefix. + private struct SourceOutput { + let prefix: String + var counts = [RepeatedLine: Int]() + var pendingBlank: String? + + mutating func count(_ line: RepeatedLine) -> Int { + counts[line, default: 0] += 1 + return counts[line, default: 0] + } + } + + /// Known harmless GLib messages, keyed by the names shown in repeat totals. + private nonisolated static let gStreamerWarnings: [(name: String, pattern: NSRegularExpression)] = { + let process = #"(?:\*\* )?\([^():\s]+:[0-9]+\): "# + let timestamp = #"(?:[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?: )?"# + let severityEnd = #" \*\*: "# + /// Wine's GStreamer support doesn't use the Python bindings. + let pygobject = (name: "pygobject", domainAndLevel: "CRITICAL", + message: #"pygobject initialization failed: could not import gobject \(error was: .*\)"#) + /// GStreamer can report unfixed caps during format negotiation and still play video. + let videoCaps = (name: "gst_video_info_from_caps", domainAndLevel: "GStreamer-Video-CRITICAL", + message: #"gst_video_info_from_caps: assertion 'gst_caps_is_fixed \(caps\)' failed"#) + return [pygobject, videoCaps].map { rule in + let pattern = "^" + process + rule.domainAndLevel + severityEnd + timestamp + rule.message + "$" + return (rule.name, try! NSRegularExpression(pattern: pattern)) + } + }() + + /// A log can contain totals written before the user changed the app language. + private nonisolated static let gStreamerTotalPattern: NSRegularExpression = { + let count = #"\p{Nd}+(?:[.,'’\p{Zs}]\p{Nd}+)*"# + let formats = AppLanguage.allCases.compactMap { + LocalizationTables.table(for: $0)?.strings[.modelGStreamerWarningRepeats] + } + let patterns = formats.flatMap { format in + gStreamerWarnings.map { warning in + format.replacingOccurrences(of: "%1$@", with: warning.name) + .components(separatedBy: "%2$lld") + .map(NSRegularExpression.escapedPattern(for:)) + .joined(separator: count) + } + } + return try! NSRegularExpression(pattern: "^(?:" + patterns.joined(separator: "|") + ")$") + }() + + private var outputBySource = [ObjectIdentifier?: SourceOutput]() private var warnedAboutMissingGStreamer = false private var transcript: ConsoleTranscript? private var transcriptsBySource = [ObjectIdentifier: ConsoleTranscript]() @@ -47,6 +100,19 @@ public final class SessionConsole: ObservableObject { return log[start...end].trimmingCharacters(in: .whitespaces) } + /// Repeat totals for sources that have yet to reach EOF. + public var openRepeatTotals: [String] { + outputBySource.values.flatMap(Self.repeatTotals(for:)).sorted() + } + + /// Puts live counts at the end so they survive the report's log tail limit. + public var diagnosticLog: String { + let totals = openRepeatTotals + guard !totals.isEmpty else { return log } + let separator = log.isEmpty || log.hasSuffix("\n") ? "" : "\n" + return log + separator + totals.joined(separator: "\n") + } + /// Starts a new log. A stream session also clears the samples; a Windows /// utility keeps the last stream's charts. The transcript file gets the /// same redaction as an exported log; the log on screen stays as it is. @@ -62,7 +128,7 @@ public final class SessionConsole: ObservableObject { log = firstLine headsetDisconnected = false partialLines.removeAll() - deviceErrorCounts.removeAll() + outputBySource.removeAll() warnedAboutMissingGStreamer = false if clearingSamples { samples.removeAll() } } @@ -92,7 +158,7 @@ public final class SessionConsole: ObservableObject { return commit(lines, from: source, prefix: prefix) } - /// Logs and returns the unfinished line `source` left when it closed. + /// Logs and returns the unfinished line and repeat totals when `source` closes. public func finish(_ source: ObjectIdentifier?, prefix: String = "") -> [String] { defer { if let source, let writer = transcriptsBySource.removeValue(forKey: source), @@ -101,20 +167,16 @@ public final class SessionConsole: ObservableObject { } } let lines = partialLines.removeValue(forKey: source).map { [$0] } ?? [] - let completed = commit(lines, from: source, prefix: prefix) - if let count = deviceErrorCounts.removeValue(forKey: source), count > 1 { - return completed + commit( - ["err: Device error: suppressed \(count - 1) repeated command buffer failures (total)"], - from: source, prefix: prefix) - } - return completed + return commit(lines, from: source, prefix: prefix, finishing: true) } - private func commit(_ lines: [String], from source: ObjectIdentifier?, prefix: String) -> [String] { - guard !lines.isEmpty else { return [] } + private func commit(_ lines: [String], from source: ObjectIdentifier?, prefix: String, + finishing: Bool = false) -> [String] { + guard !lines.isEmpty || finishing else { return [] } // Persist before the live console's flood suppression and tail trim. - // Every source line, including repeated GPU errors, reaches disk. - if let writer = source.flatMap({ transcriptsBySource[$0] }) ?? transcript { + // Every source line, including repeated GPU and GStreamer warnings, reaches disk. + let writer = source.flatMap({ transcriptsBySource[$0] }) ?? transcript + if !lines.isEmpty, let writer { writer.append(lines.map { prefix + $0 + "\n" }.joined()) } if prefix.isEmpty { @@ -126,18 +188,49 @@ public final class SessionConsole: ObservableObject { } } } - // A lost Metal device can reject every subsequent command buffer. Keep - // the first full error and logarithmically spaced counts so that this - // flood cannot evict the compiler errors that preceded it. Match only - // DXMT's raw error line, after assembling chunks and before prefixing. - let prefixed = lines.compactMap { line -> String? in - guard line.hasPrefix("err: Device error at frame ") else { return prefix + line } - let count = deviceErrorCounts[source, default: 0] + 1 - deviceErrorCounts[source] = count - if count == 1 { return prefix + line } - let repeats = count - 1 - guard repeats & (repeats - 1) == 0 else { return nil } - return prefix + "err: Device error: suppressed \(repeats) repeated command buffer failures" + var output = outputBySource.removeValue(forKey: source) ?? SourceOutput(prefix: prefix) + var prefixed = [String]() + for line in lines { + let displayLine = prefix + line + let message = line.drop(while: \.isWhitespace) + let precedingBlank = output.pendingBlank + output.pendingBlank = nil + if !prefix.isEmpty, message.isEmpty { + if let precedingBlank { prefixed.append(precedingBlank) } + output.pendingBlank = displayLine + continue + } + if let warning = Self.harmlessWarning(in: message) { + // GLib adds one blank immediately before its message. + if output.count(.gStreamerWarning(warning)) == 1 { prefixed.append(displayLine) } + continue + } + if let precedingBlank { prefixed.append(precedingBlank) } + + // A lost Metal device can reject every subsequent command buffer. + // Logarithmically spaced counts keep that flood from evicting the + // compiler errors that preceded it. Match only DXMT's raw error + // line, after assembling chunks and before prefixing. + if line.hasPrefix("err: Device error at frame ") { + let repeats = output.count(.deviceError) - 1 + if repeats == 0 { + prefixed.append(displayLine) + } else if repeats & (repeats - 1) == 0 { + prefixed.append(prefix + "err: Device error: suppressed \(repeats) repeated command buffer failures") + } + } else { + prefixed.append(displayLine) + } + } + if finishing { + if let pendingBlank = output.pendingBlank { prefixed.append(pendingBlank) } + let totals = Self.repeatTotals(for: output) + prefixed += totals + if !totals.isEmpty { + writer?.append(totals.joined(separator: "\n") + "\n") + } + } else { + outputBySource[source] = output } guard !prefixed.isEmpty else { return [] } log += prefixed.map { $0 + "\n" }.joined() @@ -145,6 +238,41 @@ public final class SessionConsole: ObservableObject { return prefixed } + private static func repeatTotals(for output: SourceOutput) -> [String] { + var totals = gStreamerWarnings.compactMap { warning -> String? in + guard let count = output.counts[.gStreamerWarning(warning.name)], count > 1 else { return nil } + return output.prefix + L10n.string(.modelGStreamerWarningRepeats, warning.name, Int64(count - 1)) + } + if let count = output.counts[.deviceError], count > 1 { + totals.append(output.prefix + "err: Device error: suppressed \(count - 1) repeated command buffer failures (total)") + } + return totals + } + + /// Recognizes known GStreamer warnings and their totals in raw or source-prefixed log lines. + public nonisolated static func isKnownHarmlessNoise(_ line: String) -> Bool { + func matches(_ message: Substring) -> Bool { + if harmlessWarning(in: message) != nil { return true } + let text = String(message) + let range = NSRange(text.startIndex..., in: text) + return gStreamerTotalPattern.firstMatch(in: text, range: range) != nil + } + + let message = line.drop(while: \.isWhitespace) + if matches(message) { return true } + guard let colon = message.firstIndex(of: ":") else { return false } + let content = message[message.index(after: colon)...] + guard content.first?.isWhitespace == true else { return false } + return matches(content.drop(while: \.isWhitespace)) + } + + private nonisolated static func harmlessWarning(in message: Substring) -> String? { + guard message.hasPrefix("(") || message.hasPrefix("** (") else { return nil } + let line = String(message) + let range = NSRange(line.startIndex..., in: line) + return gStreamerWarnings.first { $0.pattern.firstMatch(in: line, range: range) != nil }?.name + } + public func record(_ sample: StreamMetricSample) { samples.append(sample) if samples.count > Self.maximumSamples { diff --git a/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift b/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift index 41fc229..6c1fff4 100644 --- a/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift @@ -264,6 +264,23 @@ final class DiagnosticsTests: XCTestCase { XCTAssertEqual(tail.last, "line \(DiagnosticReport.maximumLogLines + 25)") } + @MainActor func testReportKeepsAnOpenGStreamerTotalWhenTheFirstWarningFallsOutOfTheTail() { + let console = SessionConsole(), pipe = NSObject() + let source = ObjectIdentifier(pipe) + let warning = "(process:42): GStreamer-Video-CRITICAL **: " + + "gst_video_info_from_caps: assertion 'gst_caps_is_fixed (caps)' failed" + _ = console.append(warning + "\n" + warning + "\n", from: source, prefix: "game: ") + _ = console.append(String(repeating: "Waiting for the game\n", count: DiagnosticReport.maximumLogLines)) + let total = "game: " + L10n.string(.modelGStreamerWarningRepeats, "gst_video_info_from_caps", Int64(1)) + + let report = makeReport(log: console.diagnosticLog) + XCTAssertEqual(report.logTail, Array(repeating: "Waiting for the game", count: DiagnosticReport.maximumLogLines - 1) + + [total]) + XCTAssertTrue(report.markdown(redactedWith: redactor).contains(total)) + XCTAssertTrue(console.log.hasPrefix("game: " + warning + "\n")) + XCTAssertEqual(console.openRepeatTotals, [total]) + } + func testSourceRevisionReadsLooseAndPackedReferences() throws { let repository = try temporaryDirectory() let git = repository.appendingPathComponent(".git", isDirectory: true) diff --git a/streamer/Tests/BasaltManagerKitTests/SessionConsoleTests.swift b/streamer/Tests/BasaltManagerKitTests/SessionConsoleTests.swift index cc23662..75866bd 100644 --- a/streamer/Tests/BasaltManagerKitTests/SessionConsoleTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/SessionConsoleTests.swift @@ -3,6 +3,9 @@ import XCTest @MainActor final class SessionConsoleTests: XCTestCase { + private let pygobjectWarning = #"** (wine:39619): CRITICAL **: 11:21:56.465: pygobject initialization failed: could not import gobject (error was: ModuleNotFoundError("No module named 'gi'"))"# + private let videoCapsWarning = "(wine:40051): GStreamer-Video-CRITICAL **: 11:22:28.693: gst_video_info_from_caps: assertion 'gst_caps_is_fixed (caps)' failed" + func testMissingGStreamerWarnsOncePerSession() throws { let console = SessionConsole() console.restart(with: "Starting the game…\n") @@ -66,6 +69,153 @@ final class SessionConsoleTests: XCTestCase { [error.trimmingCharacters(in: .newlines)]) } + func testGStreamerWarningsKeepTheFirstLineAndCountRepeatsAtEOF() { + let console = SessionConsole(), steam = NSObject(), game = NSObject() + let steamSource = ObjectIdentifier(steam), gameSource = ObjectIdentifier(game) + let pygobjectRepeat = pygobjectWarning.replacingOccurrences(of: "39619", with: "410") + .replacingOccurrences(of: "11:21:56.465", with: "15:02:04.019") + let videoCapsRepeat = videoCapsWarning.replacingOccurrences(of: "40051", with: "42") + .replacingOccurrences(of: "11:22:28.693", with: "01:00:00.007") + let steamTotal = "steam: " + L10n.string(.modelGStreamerWarningRepeats, "pygobject", Int64(1)) + let gameTotal = "game: " + L10n.string(.modelGStreamerWarningRepeats, "gst_video_info_from_caps", Int64(2)) + + XCTAssertEqual(console.append("\r\n", from: steamSource, prefix: "steam: "), []) + XCTAssertEqual(console.append(pygobjectWarning + "\r\n", from: steamSource, prefix: "steam: "), + ["steam: " + pygobjectWarning]) + XCTAssertEqual(console.append("\r\n" + pygobjectRepeat + "\r\n\r\n", from: steamSource, prefix: "steam: "), []) + XCTAssertEqual(console.append(videoCapsWarning + "\n", from: gameSource, prefix: "game: "), + ["game: " + videoCapsWarning]) + XCTAssertEqual(console.append(videoCapsRepeat + "\nLoading level\n" + videoCapsRepeat, + from: gameSource, prefix: "game: "), + ["game: Loading level"]) + XCTAssertEqual(console.finish(steamSource, prefix: "steam: "), ["steam: ", steamTotal]) + XCTAssertEqual(console.finish(gameSource, prefix: "game: "), [gameTotal]) + XCTAssertEqual(console.finish(gameSource, prefix: "game: "), []) + XCTAssertEqual(console.log, [ + "steam: " + pygobjectWarning, "game: " + videoCapsWarning, + "game: Loading level", "steam: ", steamTotal, gameTotal, + ].joined(separator: "\n") + "\n") + } + + func testGStreamerWarningTypesAndSourcesAreCountedIndependently() { + let console = SessionConsole(), steam = NSObject(), game = NSObject() + let steamSource = ObjectIdentifier(steam), gameSource = ObjectIdentifier(game) + let warnings = pygobjectWarning + "\n" + videoCapsWarning + "\n" + XCTAssertEqual(console.append(warnings + warnings, from: steamSource, prefix: "steam: "), + ["steam: " + pygobjectWarning, "steam: " + videoCapsWarning]) + XCTAssertEqual(console.append(warnings, from: gameSource, prefix: "game: "), + ["game: " + pygobjectWarning, "game: " + videoCapsWarning]) + XCTAssertEqual(console.finish(gameSource, prefix: "game: "), []) + XCTAssertEqual(console.finish(steamSource, prefix: "steam: "), [ + "steam: " + L10n.string(.modelGStreamerWarningRepeats, "pygobject", Int64(1)), + "steam: " + L10n.string(.modelGStreamerWarningRepeats, "gst_video_info_from_caps", Int64(1)), + ]) + + _ = console.append(warnings + warnings, from: steamSource, prefix: "steam: ") + console.restart() + XCTAssertEqual(console.append(warnings, from: steamSource, prefix: "steam: "), + ["steam: " + pygobjectWarning, "steam: " + videoCapsWarning]) + XCTAssertEqual(console.finish(steamSource, prefix: "steam: "), []) + } + + func testGStreamerWarningFilterKeepsUnrelatedBlankLinesAndErrors() { + let console = SessionConsole(), steam = NSObject(), game = NSObject(), wine = NSObject() + let steamSource = ObjectIdentifier(steam), gameSource = ObjectIdentifier(game) + let wineSource = ObjectIdentifier(wine) + let unrelatedError = videoCapsWarning.replacingOccurrences(of: "gst_caps_is_fixed", with: "gst_caps_is_empty") + _ = console.append("Updating\n\n", from: steamSource, prefix: "steam: ") + XCTAssertEqual(console.append("\n" + videoCapsWarning + "\n\n", from: gameSource, prefix: "game: "), + ["game: " + videoCapsWarning]) + XCTAssertEqual(console.append("Ready\n", from: steamSource, prefix: "steam: "), ["steam: ", "steam: Ready"]) + XCTAssertEqual(console.append(unrelatedError + "\n\n", from: gameSource, prefix: "game: "), + ["game: ", "game: " + unrelatedError]) + XCTAssertEqual(console.finish(gameSource, prefix: "game: "), ["game: "]) + XCTAssertEqual(console.append("\t\n \n " + pygobjectWarning + "\n", from: wineSource, prefix: "wine: "), + ["wine: \t", "wine: " + pygobjectWarning]) + XCTAssertEqual(console.append("\n"), [""]) + } + + func testGStreamerWarningsTolerateGLibHeadersAndPygobjectErrorDetails() { + let console = SessionConsole(), pipe = NSObject() + let source = ObjectIdentifier(pipe) + let pygobjectVariant = "** (wine64:42): CRITICAL **: " + + "pygobject initialization failed: could not import gobject (error was: ImportError('binding unavailable'))" + let capsVariant = videoCapsWarning.replacingOccurrences(of: "wine:40051", with: "wine64-preloader:42") + let capsWithoutTimestamp = videoCapsWarning.replacingOccurrences(of: "wine:40051", with: "process:7") + .replacingOccurrences(of: "11:22:28.693: ", with: "") + + XCTAssertEqual(console.append(pygobjectWarning + "\n" + pygobjectVariant + "\n", from: source, prefix: "wine: "), + ["wine: " + pygobjectWarning]) + XCTAssertEqual(console.append(capsVariant + "\n" + capsWithoutTimestamp + "\n", from: source, prefix: "wine: "), + ["wine: " + capsVariant]) + XCTAssertEqual(console.openRepeatTotals, [ + "wine: " + L10n.string(.modelGStreamerWarningRepeats, "gst_video_info_from_caps", Int64(1)), + "wine: " + L10n.string(.modelGStreamerWarningRepeats, "pygobject", Int64(1)), + ].sorted()) + } + + func testKnownHarmlessNoiseRecognizesPrefixedWarningsAndLocalizedTotals() { + let previous = L10n.language + defer { L10n.language = previous } + XCTAssertTrue(SessionConsole.isKnownHarmlessNoise(pygobjectWarning)) + XCTAssertTrue(SessionConsole.isKnownHarmlessNoise("wine: \t" + videoCapsWarning)) + XCTAssertFalse(SessionConsole.isKnownHarmlessNoise("wine: " + + videoCapsWarning.replacingOccurrences(of: "gst_caps_is_fixed", with: "gst_caps_is_empty"))) + XCTAssertFalse(SessionConsole.isKnownHarmlessNoise("game: GStreamer could not open the video")) + let totals = AppLanguage.allCases.map { language in + L10n.language = language + return L10n.string(.modelGStreamerWarningRepeats, "gst_video_info_from_caps", Int64(9_999)) + } + L10n.language = .en + for total in totals { + XCTAssertTrue(SessionConsole.isKnownHarmlessNoise(total), total) + XCTAssertTrue(SessionConsole.isKnownHarmlessNoise("other: " + total), total) + } + } + + func testGStreamerFloodKeepsOneWarningAndTheExactOpenAndFinalTotal() { + let console = SessionConsole(), pipe = NSObject() + let source = ObjectIdentifier(pipe) + let first = "game: " + videoCapsWarning + "\n" + let total = "game: " + L10n.string(.modelGStreamerWarningRepeats, "gst_video_info_from_caps", Int64(9_999)) + XCTAssertEqual(console.openRepeatTotals, []) + _ = console.append("\n" + videoCapsWarning + "\n", from: source, prefix: "game: ") + XCTAssertEqual(console.openRepeatTotals, []) + for _ in 1..<10_000 { + _ = console.append("\n" + videoCapsWarning + "\n", from: source, prefix: "game: ") + } + XCTAssertEqual(console.openRepeatTotals, [total]) + XCTAssertEqual(console.diagnosticLog, first + total) + XCTAssertEqual(console.log, first) + XCTAssertEqual(console.finish(source), [total]) + XCTAssertEqual(console.openRepeatTotals, []) + XCTAssertEqual(console.log, first + total + "\n") + XCTAssertEqual(console.diagnosticLog, console.log) + } + + func testTranscriptRetainsGStreamerWarningsAndIncludesTheFinalTotal() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let path = directory.appendingPathComponent("session.console.log") + XCTAssertTrue(FileManager.default.createFile(atPath: path.path, contents: nil)) + + let console = SessionConsole(), steam = NSObject() + let source = ObjectIdentifier(steam) + let repeatedWarning = pygobjectWarning.replacingOccurrences(of: "39619", with: "410") + console.restart(transcriptURL: path) + console.registerOutputSource(source) + _ = console.append("\n" + pygobjectWarning + "\n\n" + repeatedWarning + "\n", from: source, prefix: "steam: ") + let closed = expectation(description: "writer closed after EOF") + console.closeTranscript { closed.fulfill() } + let total = "steam: " + L10n.string(.modelGStreamerWarningRepeats, "pygobject", Int64(1)) + XCTAssertEqual(console.finish(source, prefix: "steam: "), [total]) + await fulfillment(of: [closed], timeout: 5) + XCTAssertEqual(try String(contentsOf: path), [ + "steam: ", "steam: " + pygobjectWarning, "steam: ", "steam: " + repeatedWarning, total, + ].joined(separator: "\n") + "\n") + } + func testReconnectStatusParsesCompleteStreamerLinesAndClears() { let console = SessionConsole() _ = console.append("Headset disconnected; waiting for it to recon") From 4a51e013f1f46966004756caf04c4326a519a3ad Mon Sep 17 00:00:00 2001 From: abgitdev <266600699+abgitdev@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:01:52 +0000 Subject: [PATCH 4/7] Keep a redacted excerpt of the game's own log with every session The cause of Electrician Simulator VR's black headset, a WindowsVideoMedia error, was only in the game's own Player.log, so the session log could not show it. After every session, once its Wine processes are gone, TrailBridge finds the game's log: Unity's Player.log, Player-prev.log or output_log.txt by way of _Data/app.info, and Unreal's Saved/Logs in AppData or, failing that, in the game folder. Only files changed since the game started count. Each file is opened without following links, must be a regular file, must resolve inside the prefix or the game folder, and must still be the file found when it is read. If Wine could not be stopped, the excerpt is still kept and says it may be incomplete. The excerpt keeps the last 200 lines and every error line, at most 64 KB, read as UTF-8 or UTF-16 and redacted before any line is clipped. The redactor now also hides user folders whose names contain spaces, complete values of identity fields, the user and computer names in Unreal's LogInit lines, and Steam2 and Steam3 IDs besides SteamID64. A game folder outside the prefix appears as [game folder]. The excerpt is saved atomically as .game.log in the Diagnostics folder, where the newest 50 standalone excerpts are kept. The session log names it by its redacted Windows path. Recent Sessions and the Diagnostics page show it, and the diagnostic report includes it unless that is turned off. The next launch, a report and quitting wait a few seconds at most for a capture still running. Nothing leaves the Mac. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 + docs/MANAGEMENT.md | 35 +- .../BasaltBottleKit/BottleManager.swift | 7 + .../BasaltBottleKit/FrameTraceSession.swift | 85 ++- .../BasaltBottleKit/GameLogSearch.swift | 307 +++++++++ streamer/Sources/BasaltManager/AppModel.swift | 194 +++++- .../BasaltManager/BasaltManagerApp.swift | 9 + .../BasaltManager/DiagnosticsView.swift | 13 +- streamer/Sources/BasaltManager/Sheets.swift | 28 +- .../Sources/BasaltManager/StreamView.swift | 78 ++- .../DiagnosticRecording.swift | 57 +- .../BasaltManagerKit/Diagnostics.swift | 111 +++- .../BasaltManagerKit/GameLogExcerpt.swift | 420 ++++++++++++ .../BasaltManagerKit/Localization/L10n.swift | 5 +- .../Localization/L10nKey.swift | 11 + .../Localization/Strings+de.swift | 13 +- .../Localization/Strings+en.swift | 13 +- .../Localization/Strings+es.swift | 13 +- .../Localization/Strings+fr.swift | 13 +- .../Localization/Strings+it.swift | 13 +- .../Localization/Strings+ja.swift | 13 +- .../Localization/Strings+ko.swift | 13 +- .../Localization/Strings+pl.swift | 13 +- .../Localization/Strings+ru.swift | 13 +- .../Localization/Strings+uk.swift | 13 +- .../BasaltManagerKit/SessionHistory.swift | 22 + .../BasaltManagerKit/SessionMarker.swift | 14 + .../FrameTraceSessionTests.swift | 48 ++ .../GameLogSearchTests.swift | 312 +++++++++ .../DiagnosticRecordingTests.swift | 6 + .../DiagnosticRedactionTests.swift | 72 +++ .../DiagnosticsTests.swift | 37 ++ .../GameLogExcerptTests.swift | 604 ++++++++++++++++++ .../SessionHistoryTests.swift | 30 + 34 files changed, 2556 insertions(+), 89 deletions(-) create mode 100644 streamer/Sources/BasaltBottleKit/GameLogSearch.swift create mode 100644 streamer/Sources/BasaltManagerKit/GameLogExcerpt.swift create mode 100644 streamer/Tests/BasaltBottleKitTests/GameLogSearchTests.swift create mode 100644 streamer/Tests/BasaltManagerKitTests/GameLogExcerptTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 814ebf8..2ec6b51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,16 @@ All notable changes to TrailBridge VR are documented here. - The session log shows the first occurrence of each known harmless GStreamer warning and totals its repeats when the output closes. Diagnostic reports include repeat counts during a session, and recordings keep the full output and final counts. +- Each session keeps an excerpt of the game's own log, where the reason for a black headset often + is: Electrician Simulator VR ran and sent frames while only its `Player.log` said that it could + not decode its video. When the session ends, TrailBridge reads a Unity player's `Player.log` + (`output_log.txt` in older versions) or an Unreal game's `Saved/Logs` and keeps the last 200 + lines and every line that reports an error, with personal data replaced. If Wine could not be + stopped, the excerpt is still kept and marked as possibly incomplete. The excerpt opens from the + session in Recent Sessions, is listed on the Diagnostics page and can be included in the + diagnostic report; it stays on the Mac. +- Diagnostic redaction covers more Steam ID formats, hides full names in account fields and shows + a game folder outside the Wine C: drive as `[game folder]`. ## 0.2.1 — 2026-11-15 diff --git a/docs/MANAGEMENT.md b/docs/MANAGEMENT.md index 5be3dbe..2d9ead0 100644 --- a/docs/MANAGEMENT.md +++ b/docs/MANAGEMENT.md @@ -86,15 +86,36 @@ shows the session state with a Stop button. duration, outcome (ended, stopped, or the failure reason), and whole-session FPS, latency, and wire-rate averages, including how often the headset ran below its target. The last 50 sessions are kept in `SessionHistory.json` in the data folder; a finished game can be replayed from its row. + Once a session has stopped, however it ended, and its Wine processes are gone, the app reads + the log the game wrote itself, which often says why a game that runs shows nothing in the + headset. A Unity player writes `Player.log` (and `Player-prev.log` for a run before it in the + same session) in `AppData/LocalLow//` of the prefix's Windows user, as named + in `_Data/app.info` (for a launcher, in the only other `*_Data/app.info` beside it); Unity + 2017.2 to 2018 wrote `output_log.txt` there, older versions `output_log.txt` in `_Data`. + An Unreal game writes `/Saved/Logs/*.log` in `AppData/Local`, or else in the game's + folder. Only regular files inside the prefix or the game's folder that were written since the + game started count; a binary file is skipped, UTF-16 with a byte order mark is read as such, + and of a log larger than 8 MB only the end is read. The excerpt keeps the last 200 lines and + every line that reports an error, in their order, with personal data replaced in whole lines as + in a copied log; a line is then cut after 1,000 bytes, and one over 16 KB is left out for a + note. All of it, headers and notes included, fits in 64 KB, so a long log loses some of the + last lines or of the errors too; notes say where lines were left out. It is saved as + `-.game.log` in the data folder's `Diagnostics` folder, beside the session's + recording when there is one; of the others the latest 50 are kept. The session log names the + game's log as the game does (`C:\users\[user]\…`), the session's row in Recent Sessions shows + the excerpt, and the next launch and a diagnostic report wait until it is saved. 8. **Settings** persists global stream defaults and per-profile overrides, selects audio and USB/Wi-Fi transport, and allows the managed Basalt data directory to be changed from the UI. 9. **Diagnostic Report** (Settings, or **Help › Diagnostic Report…**) previews a bug-report snapshot: app version, commit, and control protocol; Mac model, macOS, and power state; setup checks; engines, bottles, and profiles; stream settings; the current and recent sessions; and, - optionally, the end of the session log. It can be copied as Markdown for a GitHub issue or saved - as Markdown or JSON. The home folder and user name, email addresses, Steam IDs, headset serials - and host names, Mac host names, IP and MAC addresses, and long hex tokens are replaced before - anything is shown, and profile environment values are never included. Nothing is uploaded. + optionally, the end of the session log and the excerpt of the game's own log: read anew from + the running game, else the one saved with the latest session. It can be copied as Markdown for + a GitHub issue or saved as Markdown or JSON. The home folder and user name (also in Wine's + `C:/users/` and `Z:\Users\` paths and an Unreal log's `LogInit: User:` line), email + addresses, Steam IDs, headset serials and host names, Mac host names, IP and MAC addresses, and + long hex tokens are replaced before anything is shown, and profile environment values are never + included. Nothing is uploaded. OpenComposite is a separate GPL-3.0 project by its authors, never bundled with TrailBridge. Library → More → OpenVR Support… (also in Edit Launch Profile…) finds game DLLs inside the @@ -125,6 +146,8 @@ swift test --package-path streamer default/configured/explicit-location and managed-bottle launcher/instance discovery, Windows/host path mapping, Beat Saber scanning and source inference, duplicate resolution, stream argument generation, live-stat parsing, session history persistence and summaries, stream-health rules, -metric CSV export, diagnostic redaction, and report rendering. `BasaltBottleKitTests` verifies repository/support-root +metric CSV export, diagnostic redaction, report rendering, and the game log excerpt, its storage +and its place in the report. `BasaltBottleKitTests` verifies repository/support-root discovery, maintenance and VR launch commands, the BSManager Steam prerequisite, profile deletion, -and a real isolated import whose source remains unchanged. +where Unity and Unreal games write their logs inside a prefix, and a real isolated import whose +source remains unchanged. diff --git a/streamer/Sources/BasaltBottleKit/BottleManager.swift b/streamer/Sources/BasaltBottleKit/BottleManager.swift index ff96dad..6aa2f56 100644 --- a/streamer/Sources/BasaltBottleKit/BottleManager.swift +++ b/streamer/Sources/BasaltBottleKit/BottleManager.swift @@ -151,6 +151,9 @@ public struct BottleLaunchCommand: Equatable, Sendable { /// The game a `steam.exe -applaunch` profile was resolved to, or nil when /// the profile names its executable itself; for one log line. public var steamLaunch: SteamDirectLaunch? = nil + /// Where the started game writes its own log; nil when its executable + /// is not a path on this Mac. + public var gameLog: GameLogSearch? = nil public init(executable: URL, arguments: [String], environment: [String: String], currentDirectory: URL?) { @@ -1624,6 +1627,10 @@ public final class BottleManager: @unchecked Sendable { command.frameTrace = trace command.droppedEnvironment = dropped command.steamLaunch = steamLaunch + let gamePrefix = URL(fileURLWithPath: bottle.prefixPath, isDirectory: true) + command.gameLog = (steamLaunch?.executable ?? SteamDirectLaunch.hostURL( + forWindowsPath: windowsExecutable, prefix: gamePrefix, fileManager: fileManager)) + .map { GameLogSearch(prefix: gamePrefix, executable: $0) } return command } diff --git a/streamer/Sources/BasaltBottleKit/FrameTraceSession.swift b/streamer/Sources/BasaltBottleKit/FrameTraceSession.swift index 693e352..206b8a0 100644 --- a/streamer/Sources/BasaltBottleKit/FrameTraceSession.swift +++ b/streamer/Sources/BasaltBottleKit/FrameTraceSession.swift @@ -67,6 +67,9 @@ public struct FrameTraceSession: Equatable, Sendable { /// The streamer writes `video(codecExtension:)` and creates it itself. public let recordsVideo: Bool public var console: URL { csv.deletingPathExtension().appendingPathExtension("console.log") } + /// The excerpt of the game's own log, which the app saves once the game + /// has ended (`DiagnosticsStorage.saveGameLog`). + public var gameLog: URL { csv.deletingPathExtension().appendingPathExtension("game.log") } /// Raw encoded stream, named after its codec so tools can read it directly. public func video(codecExtension: String) -> URL { csv.deletingPathExtension().appendingPathExtension(codecExtension) @@ -96,16 +99,8 @@ public struct FrameTraceSession: Equatable, Sendable { let fd = DiagnosticsStorage.open(dataRoot: dataRoot, create: true) guard fd >= 0 else { return nil } defer { close(fd) } - let formatter = DateFormatter() - formatter.locale = Locale(identifier: "en_US_POSIX") - formatter.timeZone = TimeZone(secondsFromGMT: 0) - formatter.dateFormat = "yyyyMMdd'T'HHmmss" // O_EXCL protects even two launches within the clock's resolution. - for attempt in 0..<100 { - let micros = Int64((now.timeIntervalSince1970 * 1_000_000).rounded()) + Int64(attempt) - let seconds = Date(timeIntervalSince1970: Double(micros / 1_000_000)) - let stamp = formatter.string(from: seconds) + String(format: ".%06lldZ", micros % 1_000_000) - let stem = "\(stamp)-\(profile)" + for stem in names(profile: profile, at: now) { let csvName = stem + ".csv", consoleName = stem + ".console.log" if traces { let csvFD = openat(fd, csvName, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) @@ -128,9 +123,79 @@ public struct FrameTraceSession: Equatable, Sendable { return nil } + /// The names a launch at `date` may take, `-`, each a + /// microsecond after the one before; the first is nearly always free. + static func names(profile: String, at date: Date) -> some Sequence { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyyMMdd'T'HHmmss" + let start = Int64((date.timeIntervalSince1970 * 1_000_000).rounded()) + return (0..<100).lazy.map { attempt in + let micros = start + Int64(attempt) + let seconds = Date(timeIntervalSince1970: Double(micros / 1_000_000)) + let stamp = formatter.string(from: seconds) + String(format: ".%06lldZ", micros % 1_000_000) + return "\(stamp)-\(profile)" + } + } + /// Any entry, including a dangling symlink, or an unreadable directory. - private static func isTaken(_ name: String, in directory: Int32) -> Bool { + fileprivate static func isTaken(_ name: String, in directory: Int32) -> Bool { var info = stat() return fstatat(directory, name, &info, AT_SYMLINK_NOFOLLOW) == 0 || errno != ENOENT } } + +extension DiagnosticsStorage { + /// Saves the excerpt of a game's own log as `.game.log`, private to + /// the user. A launch that recorded something lends its name, so the + /// excerpt is listed with its other files; any other launch gets a new + /// `-` name from `startedAt`, as `FrameTraceSession` + /// would have given it. Never replaces a file; nil when nothing was saved. + public static func saveGameLog(_ contents: Data, dataRoot: URL, recording: FrameTraceSession?, + profile: String, startedAt: Date) -> URL? { + guard (try? BottleName.validate(profile, kind: "profile name")) != nil else { return nil } + let fd = open(dataRoot: dataRoot, create: true) + guard fd >= 0 else { return nil } + defer { close(fd) } + // Written whole under a hidden name first, so that the list of + // recordings and the session history never meet half an excerpt. + let temporary = ".game-log-\(UUID().uuidString).tmp" + let file = openat(fd, temporary, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard file >= 0 else { return nil } + let written = write(contents, to: file) + close(file) + defer { unlinkat(fd, temporary, 0) } + guard written else { return nil } + let stems: AnySequence = recording.map { + AnySequence([$0.csv.deletingPathExtension().lastPathComponent]) + } ?? AnySequence(FrameTraceSession.names(profile: profile, at: startedAt)) + for stem in stems { + // A new name never joins the files of another launch. + if recording == nil, FrameTraceSession.isTaken(stem + ".csv", in: fd) + || FrameTraceSession.isTaken(stem + ".console.log", in: fd) { + continue + } + let name = stem + ".game.log" + if renameatx_np(fd, temporary, fd, name, UInt32(RENAME_EXCL)) == 0 { + return directory(dataRoot: dataRoot).appendingPathComponent(name) + } + guard errno == EEXIST else { return nil } + } + return nil + } + + /// Writes all of `data`, again after a signal interrupts it. + private static func write(_ data: Data, to fd: Int32) -> Bool { + data.withUnsafeBytes { bytes in + var offset = 0 + while offset < bytes.count { + let count = Darwin.write(fd, bytes.baseAddress! + offset, bytes.count - offset) + if count < 0 && errno == EINTR { continue } + guard count > 0 else { return false } + offset += count + } + return true + } + } +} diff --git a/streamer/Sources/BasaltBottleKit/GameLogSearch.swift b/streamer/Sources/BasaltBottleKit/GameLogSearch.swift new file mode 100644 index 0000000..c539ff2 --- /dev/null +++ b/streamer/Sources/BasaltBottleKit/GameLogSearch.swift @@ -0,0 +1,307 @@ +// SPDX-License-Identifier: MIT +import Foundation +import Darwin + +/// A log that a Windows game wrote itself. +public struct GameLogFile: Equatable, Sendable { + public enum Engine: String, Equatable, Sendable { + case unity, unreal + } + + public let engine: Engine + /// On this Mac, for reading the log only: the path names the disk, the + /// Mac's user and the Wine user. + public let url: URL + public let modified: Date + /// The folder the log must stay inside once links are resolved: the + /// prefix, or the game's own folder. + public let root: URL + /// The same root after resolving links at discovery. + public let resolvedRoot: String + let device: dev_t + let inode: ino_t + let earliest: Date + + /// Opens the log for reading, checked again as when it was found, since + /// it may have been replaced since. + public func open() -> (handle: FileHandle, size: Int64)? { + guard let opened = Self.openRegularFile(url, inside: resolvedRoot) else { return nil } + let handle = FileHandle(fileDescriptor: opened.fd, closeOnDealloc: true) + guard opened.info.st_dev == device, opened.info.st_ino == inode, + Self.modificationDate(opened.info) >= earliest else { return nil } + return (handle, Int64(opened.info.st_size)) + } + + static func modificationDate(_ info: stat) -> Date { + let time = info.st_mtimespec + return Date(timeIntervalSince1970: Double(time.tv_sec) + Double(time.tv_nsec) / 1_000_000_000) + } + + /// Opens `url` without following a link at its end or waiting for a + /// writer on a pipe, and keeps it open only when it is a regular file + /// whose real path lies inside `root`, itself a real path. A link + /// further up, or a file swapped for a link, could otherwise hand any + /// file of the Mac to a report. + static func openRegularFile(_ url: URL, inside root: String) -> (fd: Int32, info: stat)? { + let fd = Darwin.open(url.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { return nil } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, + let path = realPath(of: fd), path.hasPrefix(root == "/" ? root : root + "/") else { + close(fd) + return nil + } + return (fd, info) + } + + /// Where an open file or folder is, every link resolved. + static func realPath(of fd: Int32) -> String? { + var buffer = [CChar](repeating: 0, count: Int(MAXPATHLEN)) + guard fcntl(fd, F_GETPATH, &buffer) != -1 else { return nil } + return String(cString: buffer) + } + + /// The real path of a folder, found the same way as that of a file in + /// it, so the two compare alike. + static func realPath(ofFolder url: URL) -> String? { + let fd = Darwin.open(url.path, O_RDONLY | O_DIRECTORY | O_CLOEXEC) + guard fd >= 0 else { return nil } + defer { close(fd) } + return realPath(of: fd) + } +} + +/// Where a game writes its own log. The session log has what Wine, the +/// runtime and the streamer print; why a game that runs and submits frames +/// still shows a black headset (a video it cannot decode, a file it cannot +/// load) is often only in the game's own log inside the prefix. Unity +/// players and Unreal games are known; other engines keep their logs +/// wherever they like. +public struct GameLogSearch: Equatable, Sendable { + /// A log time up to this much earlier than the game's start still + /// counts: HFS+ and many network disks keep file times to the second. + public static let timeSlack: TimeInterval = 2 + /// A larger `app.info` is not one. + static let maximumAppInfoBytes = 4096 + + /// The Wine prefix the game runs in. + public let prefix: URL + /// The game's `.exe` on this Mac. + public let executable: URL + + public init(prefix: URL, executable: URL) { + self.prefix = prefix.standardizedFileURL + self.executable = URL(fileURLWithPath: executable.path, isDirectory: false).standardizedFileURL + } + + /// The logs written since the game started, oldest first. Logs of + /// earlier runs are older: a Unity player moves the last run's + /// `Player.log` to `Player-prev.log`, an Unreal game renames its log + /// with a `-backup-` time, and a moved file keeps its time. + /// + /// - A Unity player (`Game.exe` beside `Game_Data`) names its company + /// and product in `Game_Data/app.info` and writes `Player.log` in + /// `AppData/LocalLow//` of the Windows user; Unity + /// 2017.2 to 2018 wrote `output_log.txt` there, older versions + /// `output_log.txt` in `Game_Data`. + /// - An Unreal game (`/Binaries/Win64/*.exe`, or a launcher + /// beside ``) writes `/Saved/Logs/*.log` in the + /// user's `AppData/Local`, or else in its own folder. + public func files(since start: Date, fileManager: FileManager = .default) -> [GameLogFile] { + readLogs(since: start, limit: .max, fileManager: fileManager) { $0 } + } + + /// The newest readable logs, returned oldest first. An Unreal game's + /// install folder is used only if none of its AppData logs can be read. + public func readLogs(since start: Date, limit: Int, fileManager: FileManager = .default, + reading read: (GameLogFile) -> Log?) -> [Log] { + guard limit > 0 else { return [] } + let earliest = start.addingTimeInterval(-Self.timeSlack) + var roots = [URL: String?]() + func logs(at locations: [Location]) -> [GameLogFile] { + Self.logs(at: locations, since: earliest, fileManager: fileManager, roots: &roots) + } + let users = Self.userFolders(in: prefix, fileManager: fileManager) + let unity = logs(at: unityLocations(users: users, fileManager: fileManager)) + let projects = unrealProjects(fileManager: fileManager) + let inAppData = projects.flatMap { project in + users.compactMap { user in + SteamDirectLaunch.existingItem( + "AppData/Local/\(project.name)/Saved/Logs", in: user, directory: true, fileManager: fileManager) + .map { Location(engine: .unreal, folder: $0, names: nil, root: prefix) } + } + } + var unreal = Self.sortedLogs(logs(at: inAppData)) + // Keep the successful read that decides whether the fallback is needed. + var newestAppData: (file: GameLogFile, log: Log)? + while let file = unreal.popLast() { + if let log = read(file) { + newestAppData = (file, log) + unreal.append(file) + break + } + } + if newestAppData == nil { + unreal = logs(at: projects.compactMap { project in + SteamDirectLaunch.existingItem( + "\(project.name)/Saved/Logs", in: project.gameFolder, directory: true, fileManager: fileManager) + .map { Location(engine: .unreal, folder: $0, names: nil, root: project.gameFolder) } + }) + } + var selected = [Log]() + for file in Self.sortedLogs(unity + unreal).reversed() { + let log = file == newestAppData?.file ? newestAppData?.log : read(file) + if let log { selected.append(log) } + if selected.count == limit { break } + } + return Array(selected.reversed()) + } + + private static func sortedLogs(_ files: [GameLogFile]) -> [GameLogFile] { + var seen = Set() + return files.filter { seen.insert($0.url.path).inserted } + .sorted { ($0.modified, $0.url.path) < ($1.modified, $1.url.path) } + } + + /// A folder that may hold the game's logs. + private struct Location { + let engine: GameLogFile.Engine + let folder: URL + /// The logs' names; nil for every `.log` file. + let names: [String]? + /// Where the logs must stay once links are resolved. + let root: URL + } + + /// The Windows users' folders in `drive_c/users`. `Public` belongs to + /// no one, and Wine names the user's own folder after the Mac account. + static func userFolders(in prefix: URL, fileManager: FileManager) -> [URL] { + let users = prefix.appendingPathComponent("drive_c/users", isDirectory: true) + return folders(in: users, fileManager: fileManager) + .filter { $0.lastPathComponent.caseInsensitiveCompare("Public") != .orderedSame } + } + + /// The folders in `folder`, not links to one, by name. They keep the + /// path they were found under, as the files in them do. + private static func folders(in folder: URL, fileManager: FileManager) -> [URL] { + ((try? fileManager.contentsOfDirectory(atPath: folder.path)) ?? []).sorted() + .filter { !$0.hasPrefix(".") } + .map { folder.appendingPathComponent($0, isDirectory: true) } + .filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true } + } + + // MARK: Unity + + /// The logs of a Unity player in the Windows users' `AppData/LocalLow`, + /// where `app.info` says, and the oldest versions' in its data folder. + private func unityLocations(users: [URL], fileManager: FileManager) -> [Location] { + let gameFolder = executable.deletingLastPathComponent() + let stem = executable.deletingPathExtension().lastPathComponent + let own = stem.isEmpty ? nil : SteamDirectLaunch.existingItem( + "\(stem)_Data", in: gameFolder, directory: true, fileManager: fileManager) + // A launcher's own name has no data folder; the player beside it does. + let info = own.flatMap { + SteamDirectLaunch.existingItem("app.info", in: $0, directory: false, fileManager: fileManager) + } ?? Self.onlyOther(in: gameFolder, besides: own, fileManager: fileManager) + var locations = Set([own, info?.deletingLastPathComponent()].compactMap { $0?.standardizedFileURL }) + .sorted { $0.path < $1.path } + .map { Location(engine: .unity, folder: $0, names: ["output_log.txt"], root: gameFolder) } + if let info, let names = Self.companyAndProduct(in: info, inside: gameFolder) { + locations += users.compactMap { user in + SteamDirectLaunch.existingItem( + "AppData/LocalLow/\(names.company)/\(names.product)", in: user, + directory: true, fileManager: fileManager) + .map { Location(engine: .unity, folder: $0, + names: ["Player.log", "Player-prev.log", "output_log.txt"], root: prefix) } + } + } + return locations + } + + /// The `app.info` of the only other `*_Data` folder beside the + /// executable that has one; nil when there are none or several. + private static func onlyOther(in gameFolder: URL, besides own: URL?, + fileManager: FileManager) -> URL? { + let others = folders(in: gameFolder, fileManager: fileManager).filter { + $0.lastPathComponent.lowercased().hasSuffix("_data") + && $0.standardizedFileURL.path != own?.standardizedFileURL.path + } + let infos = others.compactMap { + SteamDirectLaunch.existingItem("app.info", in: $0, directory: false, fileManager: fileManager) + } + return infos.count == 1 ? infos[0] : nil + } + + /// The first two lines of a Unity player's `app.info`. + static func companyAndProduct(in info: URL, inside gameFolder: URL) -> (company: String, product: String)? { + guard let root = GameLogFile.realPath(ofFolder: gameFolder), + let opened = GameLogFile.openRegularFile(info, inside: root) else { return nil } + let handle = FileHandle(fileDescriptor: opened.fd, closeOnDealloc: true) + guard opened.info.st_size <= maximumAppInfoBytes, + let data = try? handle.read(upToCount: maximumAppInfoBytes) else { return nil } + let lines = String(decoding: data, as: UTF8.self) + .replacingOccurrences(of: "\r\n", with: "\n") + .components(separatedBy: "\n") + .map { $0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(["\u{FEFF}"])) } + guard lines.count >= 2, SteamDirectLaunch.isPlainName(lines[0]), + SteamDirectLaunch.isPlainName(lines[1]) else { return nil } + return (lines[0], lines[1]) + } + + // MARK: Unreal + + /// The Unreal project: the folder above the executable's + /// `Binaries/Win64`, or, for a launcher, the folder beside it that holds + /// `Binaries/Win64`; of several, the one named like the launcher when + /// there is one. The engine's own `Engine` folder is no game. + private func unrealProjects(fileManager: FileManager) -> [(name: String, gameFolder: URL)] { + let folder = executable.deletingLastPathComponent() + let binaries = folder.deletingLastPathComponent() + var projects = [(name: String, gameFolder: URL)]() + if folder.lastPathComponent.caseInsensitiveCompare("Win64") == .orderedSame, + binaries.lastPathComponent.caseInsensitiveCompare("Binaries") == .orderedSame { + let project = binaries.deletingLastPathComponent() + projects.append((project.lastPathComponent, project.deletingLastPathComponent())) + } else { + for entry in Self.folders(in: folder, fileManager: fileManager) + where SteamDirectLaunch.existingItem( + "Binaries/Win64", in: entry, directory: true, fileManager: fileManager) != nil { + projects.append((entry.lastPathComponent, folder)) + } + } + projects = projects.filter { + SteamDirectLaunch.isPlainName($0.name) && $0.name.caseInsensitiveCompare("Engine") != .orderedSame + } + let launcher = SteamDirectLaunch.comparableName(executable.deletingPathExtension().lastPathComponent) + let named = projects.filter { SteamDirectLaunch.comparableName($0.name) == launcher } + return named.count == 1 ? named : projects + } + + // MARK: Opening the logs + + /// The logs in `locations` written at or after `earliest`, each opened + /// and checked as `GameLogFile.openRegularFile` does; the time is the + /// opened file's. + private static func logs(at locations: [Location], since earliest: Date, + fileManager: FileManager, roots: inout [URL: String?]) -> [GameLogFile] { + locations.flatMap { location -> [GameLogFile] in + let resolved = roots[location.root] ?? GameLogFile.realPath(ofFolder: location.root) + roots[location.root] = .some(resolved) + guard let root = resolved else { return [] } + let entries = (try? fileManager.contentsOfDirectory(atPath: location.folder.path)) ?? [] + return entries.sorted().compactMap { name in + let wanted = location.names.map { logs in + logs.contains { $0.caseInsensitiveCompare(name) == .orderedSame } + } ?? (!name.hasPrefix(".") && (name as NSString).pathExtension.caseInsensitiveCompare("log") == .orderedSame) + let url = location.folder.appendingPathComponent(name, isDirectory: false) + guard wanted, let opened = GameLogFile.openRegularFile(url, inside: root) else { return nil } + close(opened.fd) + let modified = GameLogFile.modificationDate(opened.info) + guard modified >= earliest else { return nil } + return GameLogFile(engine: location.engine, url: url, modified: modified, root: location.root, + resolvedRoot: root, device: opened.info.st_dev, inode: opened.info.st_ino, + earliest: earliest) + } + } + } +} diff --git a/streamer/Sources/BasaltManager/AppModel.swift b/streamer/Sources/BasaltManager/AppModel.swift index 8b6f5be..1f1f0fa 100644 --- a/streamer/Sources/BasaltManager/AppModel.swift +++ b/streamer/Sources/BasaltManager/AppModel.swift @@ -307,9 +307,27 @@ final class BasaltAppModel: ObservableObject { /// left running there, and the cleanup after it. private var leftoverCleanup: (root: URL, task: Task)? /// The session `launch` started; `finishSession` records it to history. - private var openSession: SessionRecord? + private var openSession: (record: SessionRecord, dataRoot: URL)? + /// The game of the running session, whose own log a diagnostic report + /// reads anew; nil once the session has stopped. + private var runningGame: GameLogRun? + /// The latest capture queued, even if it finishes while a report is reading. + private var latestGameLogCaptureID: UUID? + /// Kept until the excerpt and its history entry have been saved. At + /// quit, only captures the background shutdown has yet to claim are read here. + private var pendingGameLogs = [UUID: (run: GameLogRun, claimed: Bool)]() { + didSet { + let pending = !pendingGameLogs.isEmpty + if gameLogCapturePending != pending { gameLogCapturePending = pending } + } + } + @Published private(set) var gameLogCapturePending = false + var hasClaimedGameLogCapture: Bool { pendingGameLogs.values.contains(where: \.claimed) } + /// The session whose output the log shows. A game log read after + /// another launch or a utility has taken the log over is not named there. + private var loggedSessionID: UUID? /// When the current session started streaming; nil before that. - var streamingStartedAt: Date? { openSession?.streamingStartedAt } + var streamingStartedAt: Date? { openSession?.record.streamingStartedAt } private var hasChosenInitialSection = false /// Learning's say in the section the app opens on; nil leaves the choice as it is. var initialSection: (() -> ManagerSection?)? @@ -1026,7 +1044,7 @@ final class BasaltAppModel: ObservableObject { } func deleteRecording(_ recording: DiagnosticRecording) async { - guard !isRecordingInProgress(recording) else { return } + guard !gameLogCapturePending, !isRecordingInProgress(recording) else { return } let store = DiagnosticRecordingStore(dataRoot: dataRoot) do { try await Task.detached { try store.delete(recording) }.value @@ -1038,6 +1056,7 @@ final class BasaltAppModel: ObservableObject { /// Deletes every finished recording; a session still running keeps its files. func deleteAllRecordings() async { + guard !gameLogCapturePending else { return } let store = DiagnosticRecordingStore(dataRoot: dataRoot) var keeping = Set() if sessionState.isActive, let activeRecordingID { keeping.insert(activeRecordingID) } @@ -1364,6 +1383,7 @@ final class BasaltAppModel: ObservableObject { sessionState = .starting(profile: profileName) selection = .stream let traceManager = manager + let sessionRoot = dataRoot let recording = recordingChoice(for: profileName) // The app's setting or the profile's developer variables turn a // recording on. Too little free space withholds only the video. @@ -1378,6 +1398,9 @@ final class BasaltAppModel: ObservableObject { return (session, plan.videoSkippedForLowSpace) }.value try ensureCurrent() + // Keep the previous transcript open until it can name its game log. + await waitForGameLogCapture(latestGameLogCaptureID) + try ensureCurrent() activeRecordingID = frameTrace.map { $0.csv.deletingPathExtension().lastPathComponent } console.restart( with: L10n.string(.modelPreparingProfile, profileName), transcriptURL: frameTrace?.transcript, @@ -1387,7 +1410,8 @@ final class BasaltAppModel: ObservableObject { .modelRecordingVideoSkipped, DiagnosticRecordingPlan.minimumFreeBytesForVideo >> 30)) } - openSession = SessionRecord(profileName: profileName, settings: launchSettings) + openSession = (SessionRecord(profileName: profileName, settings: launchSettings), sessionRoot) + loggedSessionID = openSession?.record.id if let wineShutdown { appendLog(L10n.string(.modelWaitingWineStop)) @@ -1622,6 +1646,15 @@ final class BasaltAppModel: ObservableObject { game.environment = environment attachOutput(of: game, prefix: "game: ") let gameStartedAt = Date() + // Read after Wine shutdown (`stop`), and + // for a diagnostic report while the game runs. + let gameLog = command.gameLog.flatMap { search in + openSession.map { + GameLogRun(search: search, gameStartedAt: gameStartedAt, profileName: profileName, + sessionID: $0.record.id, sessionStartedAt: $0.record.startedAt, recording: frameTrace, + dataRoot: sessionRoot) + } + } game.terminationHandler = { [weak self] game in Task { @MainActor in guard let self, self.gameProcess === game else { return } @@ -1646,13 +1679,14 @@ final class BasaltAppModel: ObservableObject { appendLog(warning) } gameProcess = game + runningGame = gameLog gameFocusKeeper.start( gamePID: game.processIdentifier, headsetConnected: { [weak self] in self?.console.headsetDisconnected == false }, log: { [weak self] in self?.appendLog($0) }) activeWineCommand = command activeLaunchID = nil - openSession?.streamingStartedAt = Date() + openSession?.record.streamingStartedAt = Date() sessionState = .streaming(profile: profileName) selection = .stream } catch { @@ -1698,7 +1732,13 @@ final class BasaltAppModel: ObservableObject { let steam = steamProcess let streamer = streamerProcess let wineCommand = activeWineCommand + let gameLog = runningGame + if let gameLog { + latestGameLogCaptureID = gameLog.sessionID + pendingGameLogs[gameLog.sessionID] = (gameLog, false) + } gameProcess = nil + runningGame = nil steamProcess = nil streamerProcess = nil activeWineCommand = nil @@ -1721,7 +1761,16 @@ final class BasaltAppModel: ObservableObject { if waitingForWine { // An earlier background shutdown may not finish before exit. let commands = (wineShutdown?.commands ?? []) + [wineCommand].compactMap { $0 } - let wineStopped = !shutDown(commands).failed && !wineShutdownFailed + let result = shutDown(commands) + let wineStopped = !result.failed && !wineShutdownFailed + // Quitting waits for Wine anyway; the games' logs are read then + // too, also one a shutdown still under way has not read yet. + let unclaimed = pendingGameLogs.values.filter { !$0.claimed }.map(\.run) + for run in unclaimed.sorted(by: { $0.sessionStartedAt < $1.sessionStartedAt }) { + let saved = run.save(redactedWith: gameLogRedactor(for: run), + wineMayBeRunning: result.failedPrefixes.contains(run.search.prefix.path)) + noteGameLog(run, saved: saved) + } for pending in wineShutdown?.streamers ?? [] where pending.isRunning { pending.terminate() } @@ -1739,18 +1788,21 @@ final class BasaltAppModel: ObservableObject { } guard let wineCommand else { _ = shutDown([]) + if let gameLog { captureGameLog(gameLog, wineMayBeRunning: true) } // An earlier shutdown still running closes it when it finishes. - if wineShutdown == nil { console.closeTranscript() } + if wineShutdown == nil, !gameLogCapturePending { console.closeTranscript() } return } - queueWineShutdown(wineCommand, streamer: streamer) + queueWineShutdown(wineCommand, streamer: streamer, gameLog: gameLog) } /// Stops Wine for `command` off the main actor, after any stop already /// under way, and lists it in `wineShutdown`: a launch waits for it, and /// a later stop runs after it. Every stop goes through here, so that a - /// late forced sweep can never meet processes started after it. - private func queueWineShutdown(_ command: BottleLaunchCommand, streamer: Process? = nil) { + /// late forced sweep can never meet processes started after it. With + /// `gameLog`, the game's log is read after the shutdown attempt. + private func queueWineShutdown(_ command: BottleLaunchCommand, streamer: Process? = nil, + gameLog: GameLogRun? = nil) { if wineShutdown == nil { wineShutdownFailed = false wineShutdownError = nil @@ -1761,7 +1813,8 @@ final class BasaltAppModel: ObservableObject { await previous?.task.value let result = Self.shutDownWine([command], manager: manager, streamer: streamer) await self?.finishWineShutdown(message: result.message, failed: result.failed, - stopped: result.stopped, failedPrefixes: result.failedPrefixes) + stopped: result.stopped, failedPrefixes: result.failedPrefixes, + gameLog: gameLog) } wineShutdown = (task, (previous?.commands ?? []) + [command], (previous?.streamers ?? []) + [streamer].compactMap { $0 }) @@ -1794,7 +1847,8 @@ final class BasaltAppModel: ObservableObject { return (message, failed, stopped, failedPrefixes) } - private func finishWineShutdown(message: String?, failed: Bool, stopped: [String], failedPrefixes: [String]) { + private func finishWineShutdown(message: String?, failed: Bool, stopped: [String], failedPrefixes: [String], + gameLog: GameLogRun?) { wineShutdownFailed = wineShutdownFailed || failed if failed { wineShutdownError = message } // What Steam's panel says about this environment's last stop. @@ -1811,8 +1865,8 @@ final class BasaltAppModel: ObservableObject { pending.commands.removeFirst() pending.streamers.removeAll { !$0.isRunning } wineShutdown = pending.commands.isEmpty ? nil : pending - // A launch started meanwhile has already opened its own transcript. - if wineShutdown == nil, !sessionState.isActive { console.closeTranscript() } + if let gameLog { captureGameLog(gameLog, wineMayBeRunning: failed) } + if wineShutdown == nil, !sessionState.isActive, !gameLogCapturePending { console.closeTranscript() } // A launch waits for this shutdown before it writes its own marker. // Wine that could not be stopped keeps it, for the next start. if wineShutdown == nil { endSessionMarker(stopped: !wineShutdownFailed) } @@ -2118,6 +2172,7 @@ final class BasaltAppModel: ObservableObject { activeWineCommand = command sessionState = .utility(label) console.restart(with: L10n.string(.modelLaunchingUtility, label), clearingSamples: false) + loggedSessionID = nil if !steamWizardPresented { selection = .stream } if let steamInstaller { steamSetupBottleID = steamInstaller.id @@ -2575,22 +2630,25 @@ final class BasaltAppModel: ObservableObject { func clearLog() { guard !sessionState.isActive else { return } console.restart() + loggedSessionID = nil } /// Records the open session to history. The first outcome wins: the /// `stop()` that follows a game exit or failure finds nothing open. private func finishSession(_ outcome: SessionRecord.Outcome, reason: String? = nil) { - guard var record = openSession else { return } + guard let session = openSession else { return } openSession = nil + var record = session.record // A launch stopped before the game started is not a session. guard record.streamingStartedAt != nil || outcome == .failed else { return } record.endedAt = Date() record.outcome = outcome record.failureReason = reason do { - sessionHistory = try SessionHistoryStore(dataRoot: dataRoot).append(record) { moved in + let history = try SessionHistoryStore(dataRoot: session.dataRoot).append(record) { moved in self.appendLog(L10n.string(.modelHistorySetAside, moved.lastPathComponent)) } + if session.dataRoot == dataRoot { sessionHistory = history } } catch { // One line either way; the history file is as it was. let message = error.localizedDescription @@ -2611,10 +2669,88 @@ final class BasaltAppModel: ObservableObject { } } + /// Names the game's log in the session log, as the excerpt's header + /// names it, unless another launch or a utility has taken the log over; + /// and notes the saved excerpt in the session's history record. + private func noteGameLog(_ run: GameLogRun, saved: (excerpt: GameLogExcerpt, file: URL?)?) { + defer { + pendingGameLogs[run.sessionID] = nil + if loggedSessionID == run.sessionID, wineShutdown == nil, !sessionState.isActive { + console.closeTranscript() + } + } + if loggedSessionID == run.sessionID { + appendLog(saved?.excerpt.sources.last.map { L10n.string(.modelGameLog, $0.path) } + ?? L10n.string(.modelGameLogNone)) + } + // The session was recorded when it stopped; a history that has lost + // it since stays as it is. + guard let file = saved?.file, + let history = try? SessionHistoryStore(dataRoot: run.dataRoot).update( + run.sessionID, { $0.gameLog = file.lastPathComponent }), + history.contains(where: { $0.id == run.sessionID }), run.dataRoot == dataRoot else { return } + sessionHistory = history + Task { await refreshRecordings() } + } + + private func captureGameLog(_ run: GameLogRun, wineMayBeRunning: Bool) { + guard pendingGameLogs[run.sessionID]?.claimed == false else { return } + pendingGameLogs[run.sessionID]?.claimed = true + let redactor = gameLogRedactor(for: run) + Task.detached { [weak self] in + let saved = run.save(redactedWith: redactor, wineMayBeRunning: wineMayBeRunning) + await self?.noteGameLog(run, saved: saved) + } + } + + nonisolated private static let gameLogCaptureWaitLimit = Duration.seconds(5) + + private func waitForGameLogCapture(_ sessionID: UUID?, upTo timeout: Duration = gameLogCaptureWaitLimit) async { + guard let sessionID else { return } + await SessionTeardown.wait(upTo: timeout) { pendingGameLogs[sessionID] == nil } + } + + func waitForClaimedGameLogCaptures() async { + await SessionTeardown.wait(upTo: .seconds(3)) { !hasClaimedGameLogCapture } + } + + /// The session's data folder is named as such in its game's excerpt. + private func gameLogRedactor(for run: GameLogRun) -> DiagnosticRedactor { + DiagnosticRedactor(dataFolder: run.dataRoot.path, appFolder: repoRoot.path) + } + + /// The excerpt of the game's own log saved with a session; nil when it is gone. + func gameLogText(for record: SessionRecord) async -> String? { + guard let name = record.gameLog else { return nil } + let store = DiagnosticRecordingStore(dataRoot: dataRoot) + return await Task.detached { store.gameLogText(named: name) }.value + } + + /// Where that excerpt is, for Show in Finder. + func gameLogFile(for record: SessionRecord) -> URL? { + record.gameLog.flatMap { DiagnosticRecordingStore(dataRoot: dataRoot).gameLogFile(named: $0) } + } + /// A snapshot for bug reports. Callers render it through a - /// `DiagnosticRedactor`; nothing here leaves the Mac by itself. - func makeDiagnosticReport(includeLog: Bool) -> DiagnosticReport { - DiagnosticReport( + /// `DiagnosticRedactor`; nothing here leaves the Mac by itself. The + /// game's own log is read off the main thread: that of the running + /// game, else the excerpt saved with the latest session, which a session + /// that has just stopped is given first. + func makeDiagnosticReport(includeLog: Bool, includeGameLog: Bool) async -> DiagnosticReport { + let captureID = latestGameLogCaptureID + let waitStarted = ContinuousClock.now + await waitForGameLogCapture(captureID) + let waitRemaining = Self.gameLogCaptureWaitLimit - waitStarted.duration(to: .now) + var gameLog: DiagnosticReport.GameLog? + if includeGameLog { + gameLog = await readDiagnosticGameLog() + let latest = latestGameLogCaptureID + if latest != captureID { + await waitForGameLogCapture(latest, upTo: waitRemaining) + gameLog = await readDiagnosticGameLog() + } + } + return DiagnosticReport( application: .current(repoRoot: repoRoot), system: .current(), setupChecks: setupChecks, @@ -2625,10 +2761,20 @@ final class BasaltAppModel: ObservableObject { profileStreamSettings: profileSettings, currentSession: .init( state: sessionState.label, - profileName: openSession?.profileName, - metrics: openSession?.metrics), + profileName: openSession?.record.profileName, + metrics: openSession?.record.metrics), recentSessions: sessionHistory, - log: includeLog ? console.diagnosticLog : nil) + log: includeLog ? console.diagnosticLog : nil, + gameLog: gameLog) + } + + private func readDiagnosticGameLog() async -> DiagnosticReport.GameLog { + let (running, history, root) = (runningGame, sessionHistory, dataRoot) + let redactor = DiagnosticRedactor(dataFolder: (running?.dataRoot ?? root).path, appFolder: repoRoot.path) + return await Task.detached { + DiagnosticReport.GameLog.current( + running: running, history: history, dataRoot: root, redactedWith: redactor) + }.value } func export(_ text: String, to url: URL) { @@ -2661,8 +2807,8 @@ final class BasaltAppModel: ObservableObject { } if let metric = StreamLogMetricsParser.parse(line: line) { console.record(metric) - if let target = openSession?.settings.fps { - openSession?.metrics.add(metric, targetFPS: target) + if let target = openSession?.record.settings.fps { + openSession?.record.metrics.add(metric, targetFPS: target) } } else if let refusal = RuntimeConnectionRefusal.message(in: line) { alertMessage = refusal diff --git a/streamer/Sources/BasaltManager/BasaltManagerApp.swift b/streamer/Sources/BasaltManager/BasaltManagerApp.swift index 7e41153..ff6b65f 100644 --- a/streamer/Sources/BasaltManager/BasaltManagerApp.swift +++ b/streamer/Sources/BasaltManager/BasaltManagerApp.swift @@ -125,6 +125,15 @@ private final class BasaltApplicationDelegate: NSObject, NSApplicationDelegate, return true } + func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + guard model.hasClaimedGameLogCapture else { return .terminateNow } + Task { + await model.waitForClaimedGameLogCaptures() + sender.reply(toApplicationShouldTerminate: true) + } + return .terminateLater + } + func applicationWillTerminate(_ notification: Notification) { // First, and at once: a chapter under way is written to disk before // the wait for Wine, which can outlast the time the app is given. diff --git a/streamer/Sources/BasaltManager/DiagnosticsView.swift b/streamer/Sources/BasaltManager/DiagnosticsView.swift index fc56974..041c6af 100644 --- a/streamer/Sources/BasaltManager/DiagnosticsView.swift +++ b/streamer/Sources/BasaltManager/DiagnosticsView.swift @@ -30,6 +30,7 @@ struct DiagnosticsView: View { Button(L(.recordingDeleteAll), role: .destructive) { Task { await model.deleteAllRecordings() } } + .disabled(model.gameLogCapturePending) } message: { Text(L(.recordingDeleteAllDetail, RecordingFormat.size(finished.reduce(0) { $0 + $1.totalBytes }))) @@ -42,6 +43,7 @@ struct DiagnosticsView: View { Button(L(.recordingDelete), role: .destructive) { Task { await model.deleteRecording(recording) } } + .disabled(model.gameLogCapturePending) } message: { recording in Text(L(.recordingDeleteDetail, model.gameTitle(forProfile: recording.profileName), RecordingFormat.date(recording.startedAt), RecordingFormat.size(recording.totalBytes))) @@ -92,7 +94,7 @@ struct DiagnosticsView: View { SectionTitle(title: L(.recordingList), count: model.recordings.count) { Button(L(.recordingDeleteAll)) { confirmingDeleteAll = true } .buttonStyle(TBQuietButtonStyle(compact: true)) - .disabled(finished.isEmpty) + .disabled(finished.isEmpty || model.gameLogCapturePending) } HStack(spacing: 10) { VStack(alignment: .leading, spacing: 2) { @@ -113,6 +115,10 @@ struct DiagnosticsView: View { .buttonStyle(TBIconButtonStyle(accessibilityLabel: L(.libraryShowInFinder), compact: true)) .help(L(.libraryShowInFinder)) } + // Saved without a recording being turned on, so the list says why they are there. + Text(L(.recordingGameLogNote, Int64(GameLogExcerpt.keptExcerpts))) + .font(TB.Typography.meta).foregroundStyle(TB.textSecondary) + .fixedSize(horizontal: false, vertical: true) if model.recordings.isEmpty { Text(L(.recordingListEmpty)).foregroundStyle(TB.textSecondary) .frame(maxWidth: .infinity, alignment: .leading) @@ -126,6 +132,7 @@ struct DiagnosticsView: View { title: model.gameTitle(forProfile: recording.profileName), summary: model.recordingSummaries[recording.id], inProgress: model.isRecordingInProgress(recording), + deleteDisabled: model.gameLogCapturePending, delete: { deleting = recording }) } } @@ -203,6 +210,7 @@ private struct RecordingRow: View { let title: String let summary: RecordingSummaryState? let inProgress: Bool + let deleteDisabled: Bool let delete: () -> Void private var date: String { RecordingFormat.date(recording.startedAt) } @@ -237,7 +245,7 @@ private struct RecordingRow: View { .accessibilityLabel(L(.recordingShowLabel, title, date)) Button(L(.recordingDelete), role: .destructive, action: delete) .accessibilityLabel(L(.recordingDeleteLabel, title, date)) - .disabled(inProgress) + .disabled(inProgress || deleteDisabled) } .buttonStyle(TBQuietButtonStyle(compact: true)) } @@ -304,6 +312,7 @@ private enum RecordingFormat { switch kind { case .frames: L(.recordingFileFrames) case .sessionLog: L(.recordingFileLog) + case .gameLog: L(.recordingFileGameLog) case .video: L(.recordingFileVideo) case .videoIndex: L(.recordingFileVideoIndex) } diff --git a/streamer/Sources/BasaltManager/Sheets.swift b/streamer/Sources/BasaltManager/Sheets.swift index bf927a3..0f8b0d6 100644 --- a/streamer/Sources/BasaltManager/Sheets.swift +++ b/streamer/Sources/BasaltManager/Sheets.swift @@ -545,11 +545,19 @@ struct DiagnosticReportSheet: View { let model: BasaltAppModel @Environment(\.dismiss) private var dismiss @State private var includeLog = true + @State private var includeGameLog = true @State private var report: DiagnosticReport? + /// The choices `report` was made with: while it is remade for others, + /// nothing is copied or saved, so a log left out never leaves in an + /// older report. + @State private var reportChoices: [Bool]? @State private var markdown = "" @State private var copied = false @State private var errorMessage: String? + private var choices: [Bool] { [includeLog, includeGameLog] } + private var reportIsCurrent: Bool { report != nil && reportChoices == choices } + /// The folders this app run uses, which may not be the ones it was /// started with when the person chose another data folder. private var redactor: DiagnosticRedactor { @@ -567,6 +575,7 @@ struct DiagnosticReportSheet: View { if copied { Chip(text: L(.diagnosticsCopied), kind: .success) } if errorMessage != nil { Chip(text: L(.commonError), kind: .failed) } Toggle(L(.diagnosticsIncludeLog), isOn: $includeLog) + Toggle(L(.diagnosticsIncludeGameLog), isOn: $includeGameLog) SessionLogView(text: markdown, followsTail: false) .accessibilityLabel(L(.diagnosticsReportPreview)) .frame(maxWidth: .infinity, maxHeight: .infinity) @@ -593,19 +602,21 @@ struct DiagnosticReportSheet: View { .overlay(RoundedRectangle(cornerRadius: TB.Radius.quietButton).strokeBorder(TB.quietBorder)) } .menuStyle(.button).buttonStyle(.plain).fixedSize() - .disabled(report == nil) + .disabled(!reportIsCurrent) Button(copied ? L(.diagnosticsCopied) : L(.diagnosticsCopy)) { + guard reportIsCurrent else { return } NSPasteboard.general.clearContents() copied = NSPasteboard.general.setString(markdown, forType: .string) } - .disabled(report == nil) + .disabled(!reportIsCurrent) Button(L(.sheetDone)) { dismiss() } .keyboardShortcut(.defaultAction) .buttonStyle(TBPrimaryButtonStyle()) } .frame(width: 800, height: 560) - .onAppear(perform: rebuild) - .onChange(of: includeLog) { rebuild() } + // Reading the game's log can take a moment; a newer choice replaces + // a report still being made. + .task(id: choices) { await rebuild() } .alert(L(.appName), isPresented: Binding( get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } } @@ -616,15 +627,18 @@ struct DiagnosticReportSheet: View { } } - private func rebuild() { - let snapshot = model.makeDiagnosticReport(includeLog: includeLog) + @MainActor private func rebuild() async { + let made = choices + let snapshot = await model.makeDiagnosticReport(includeLog: made[0], includeGameLog: made[1]) + guard !Task.isCancelled else { return } report = snapshot + reportChoices = made markdown = snapshot.markdown(redactedWith: redactor) copied = false } private func save(asJSON: Bool) { - guard let report, let url = FilePanels.saveFile( + guard reportIsCurrent, let report, let url = FilePanels.saveFile( title: L(.diagnosticsSaveTitle), baseName: "BasaltVR-diagnostics", fileExtension: asJSON ? "json" : "md") else { return } do { diff --git a/streamer/Sources/BasaltManager/StreamView.swift b/streamer/Sources/BasaltManager/StreamView.swift index 418b1b4..681d717 100644 --- a/streamer/Sources/BasaltManager/StreamView.swift +++ b/streamer/Sources/BasaltManager/StreamView.swift @@ -922,6 +922,7 @@ private extension StreamHealthIssue.Kind { private struct RecentSessionsCard: View { @ObservedObject var model: BasaltAppModel @State private var confirmingClear = false + @State private var shownGameLog: SessionRecord? private static let visibleCount = 6 @@ -955,7 +956,7 @@ private struct RecentSessionsCard: View { } else { let visible = Array(model.sessionHistory.prefix(Self.visibleCount)) ForEach(visible) { record in - SessionHistoryRow(record: record, model: model) + SessionHistoryRow(record: record, model: model) { shownGameLog = record } if record.id != visible.last?.id { Rectangle().fill(TB.hairline).frame(height: 1).accessibilityHidden(true) } @@ -964,6 +965,7 @@ private struct RecentSessionsCard: View { } .cardStyle(padding: 0) .clearSessionHistoryDialog(isPresented: $confirmingClear, model: model) + .sheet(item: $shownGameLog) { GameLogSheet(record: $0, model: model) } .tourTarget(.chapter(.streamRecentSessions)) } } @@ -971,6 +973,7 @@ private struct RecentSessionsCard: View { private struct SessionHistoryRow: View { let record: SessionRecord @ObservedObject var model: BasaltAppModel + let showGameLog: () -> Void var body: some View { HStack(spacing: 10) { @@ -1001,8 +1004,17 @@ private struct SessionHistoryRow: View { .font(TB.Typography.caption) } .frame(maxWidth: .infinity, alignment: .leading) - // Name, outcome, chips, date and stats read as one row; Replay stays separate. + // Name, outcome, chips, date and stats read as one row; the buttons stay separate. .accessibilityElement(children: .combine) + if record.gameLog != nil { + Button(action: showGameLog) { + Label(L(.streamGameLog), systemImage: "doc.text") + } + .buttonStyle(TBIconButtonStyle( + accessibilityLabel: L(.streamGameLogHelp, title), compact: true, + foreground: TB.textSecondary)) + .help(L(.streamGameLogHelp, title)) + } Button { Task { await model.launch(profileName: record.profileName) } } label: { @@ -1104,3 +1116,65 @@ private struct SessionHistoryRow: View { return parts.isEmpty ? nil : parts.joined(separator: " · ") } } + +/// The excerpt of the game's own log saved with a session. +private struct GameLogSheet: View { + let record: SessionRecord + @ObservedObject var model: BasaltAppModel + @Environment(\.dismiss) private var dismiss + /// nil while it is read, and when it is gone. + @State private var text: String? + @State private var read = false + @State private var copied = false + + var body: some View { + SheetScaffold(symbol: "doc.text.magnifyingglass", title: L(.streamGameLog), subtitle: subtitle) { + VStack(alignment: .leading, spacing: 10) { + if read, text == nil { + Text(L(.streamGameLogMissing)) + .foregroundStyle(TB.textSecondary) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } else { + SessionLogView(text: text ?? "", followsTail: false) + .accessibilityLabel(L(.streamGameLog)) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(TB.sunkenBackground, in: RoundedRectangle(cornerRadius: 8)) + .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(TB.hairline)) + } + Text(L(.streamGameLogNote)).tbFormFooterStyle() + } + .padding(20) + } actions: { + Button(L(.libraryShowInFinder)) { + if let file = model.gameLogFile(for: record) { + NSWorkspace.shared.activateFileViewerSelecting([file]) + } + } + .disabled(text == nil) + Spacer() + Button(copied ? L(.diagnosticsCopied) : L(.menuCopy)) { + NSPasteboard.general.clearContents() + copied = NSPasteboard.general.setString(text ?? "", forType: .string) + } + .disabled(text == nil) + Button(L(.sheetDone)) { dismiss() } + .keyboardShortcut(.defaultAction) + .buttonStyle(TBPrimaryButtonStyle()) + } + .frame(width: 800, height: 560) + .task { + text = await model.gameLogText(for: record) + read = true + } + } + + /// The game's Library name and when the session started. + private var subtitle: String { + let date = DateFormatter() + date.locale = L10n.language.locale + date.dateFormat = L(.streamHistoryDateFormat) + date.shortMonthSymbols = L(.streamHistoryMonths).components(separatedBy: "|") + return [model.gameTitle(forProfile: record.profileName), date.string(from: record.startedAt)] + .joined(separator: " · ") + } +} diff --git a/streamer/Sources/BasaltManagerKit/DiagnosticRecording.swift b/streamer/Sources/BasaltManagerKit/DiagnosticRecording.swift index bf2bf39..43a75b5 100644 --- a/streamer/Sources/BasaltManagerKit/DiagnosticRecording.swift +++ b/streamer/Sources/BasaltManagerKit/DiagnosticRecording.swift @@ -72,10 +72,11 @@ public struct DiagnosticRecordingPlan: Equatable, Sendable { } /// One recorded launch: the files in the `Diagnostics` folder that share a -/// `-` name. +/// `-` name. A launch that recorded nothing has only the +/// excerpt of the game's own log, which the app saves after every session. public struct DiagnosticRecording: Identifiable, Equatable, Sendable { public enum FileKind: String, CaseIterable, Sendable { - case frames, sessionLog, video, videoIndex + case frames, sessionLog, gameLog, video, videoIndex } public struct File: Identifiable, Equatable, Sendable { @@ -133,22 +134,64 @@ public struct DiagnosticRecordingStore: Sendable { /// Removes every file of one recording, including any written since it was listed. public func delete(_ recording: DiagnosticRecording) throws { - _ = try remove { $0 == recording.id } + _ = try remove { stem, _ in stem == recording.id } } /// Removes every recording except `keeping` (a session still being /// written) and returns how many files went. Other files stay. @discardableResult public func deleteAll(keeping: Set = []) throws -> Int { - try remove { !keeping.contains($0) } + try remove { stem, _ in !keeping.contains(stem) } } - private func remove(where matches: (String) -> Bool) throws -> Int { + /// The largest saved game log `gameLogText(named:)` reads: many times + /// the size of an excerpt. + static let maximumGameLogBytes = 1 << 20 + + /// Where a saved excerpt of a game's own log is, by file name; nil when + /// the name is not that of one in this folder. + public func gameLogFile(named name: String) -> URL? { + guard !name.contains("/"), let parsed = Self.parse(fileName: name), parsed.kind == .gameLog, + Self.parse(stem: parsed.stem) != nil else { return nil } + return directory.appendingPathComponent(name) + } + + /// A saved excerpt of a game's own log, by file name; nil when it is + /// gone or the name is not that of one in this folder. + public func gameLogText(named name: String) -> String? { + guard gameLogFile(named: name) != nil else { return nil } + let folder = DiagnosticsStorage.open(dataRoot: dataRoot, create: false) + guard folder >= 0 else { return nil } + defer { close(folder) } + let fd = openat(folder, name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { return nil } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, + info.st_size <= Self.maximumGameLogBytes, + let data = try? handle.read(upToCount: Self.maximumGameLogBytes + 1) ?? Data(), + data.count <= Self.maximumGameLogBytes else { return nil } + return String(decoding: data, as: UTF8.self) + } + + /// Removes the oldest excerpts of a game's own log that are all a + /// launch left, keeping the newest `limit`, and returns how many went. + /// The app saves one after every session; recordings the person turned + /// on keep theirs until they are deleted. + @discardableResult + public func removeGameLogs(keeping limit: Int) throws -> Int { + let old = Set(list().filter { $0.files.allSatisfy { $0.kind == .gameLog } } + .dropFirst(max(0, limit)).map(\.id)) + guard !old.isEmpty else { return 0 } + return try remove { stem, kind in kind == .gameLog && old.contains(stem) } + } + + private func remove(where matches: (_ stem: String, _ kind: DiagnosticRecording.FileKind) -> Bool) throws -> Int { let fd = DiagnosticsStorage.open(dataRoot: dataRoot, create: false) guard fd >= 0 else { return 0 } defer { close(fd) } var removed = 0 - for entry in Self.recordingFiles(in: fd) where matches(entry.stem) { + for entry in Self.recordingFiles(in: fd) where matches(entry.stem, entry.kind) { if unlinkat(fd, entry.name, 0) == 0 { removed += 1 } else if errno != ENOENT { @@ -199,7 +242,7 @@ public struct DiagnosticRecordingStore: Sendable { let codecs = VideoCodec.allCases.map(\.rawValue) let endings: [(String, DiagnosticRecording.FileKind)] = codecs.map { (".\($0).index.csv", .videoIndex) } - + [(".console.log", .sessionLog), (".csv", .frames)] + + [(".console.log", .sessionLog), (".game.log", .gameLog), (".csv", .frames)] + codecs.map { (".\($0)", .video) } for (ending, kind) in endings where fileName.hasSuffix(ending) { let stem = String(fileName.dropLast(ending.count)) diff --git a/streamer/Sources/BasaltManagerKit/Diagnostics.swift b/streamer/Sources/BasaltManagerKit/Diagnostics.swift index b9a9fb0..8c5bc89 100644 --- a/streamer/Sources/BasaltManagerKit/Diagnostics.swift +++ b/streamer/Sources/BasaltManagerKit/Diagnostics.swift @@ -39,13 +39,16 @@ public struct DiagnosticRedactor: Sendable { /// Plain text: a log, or one value of a report before it is rendered. public func redact(_ text: String) -> String { - redactIdentifiers(in: Self.redactStreamerLines(in: text)) + // Copy and Save can also receive a log that is itself JSON. + let first = text.first { !$0.isWhitespace } + let isJSON = (first == "\"" || first == "[" || first == "{") + && (try? JSONSerialization.jsonObject(with: Data(text.utf8), options: .fragmentsAllowed)) != nil + return redactIdentifiers(in: Self.redactStreamerLines(in: text), preservingJSON: isJSON) } - /// Every rule except the streamer's own lines. Replacements contain no - /// quotes or backslashes, and any quote a rule matches is put back, so - /// redacting rendered JSON keeps it valid. - func redactIdentifiers(in text: String) -> String { + /// Every rule except the streamer's own lines. When redacting rendered + /// JSON, keep the enclosing string delimiters and escaped line breaks. + func redactIdentifiers(in text: String, preservingJSON: Bool = false) -> String { var value = text for (expression, placeholder) in folderRules() { value = Self.replace(expression, in: value, with: placeholder) @@ -83,7 +86,8 @@ public struct DiagnosticRedactor: Sendable { value = Self.replaceMatches(Self.uuidOrSerial, in: value) { match in match.contains("-") || Self.isTimeStamp(match) ? nil : "[serial]" } - value = Self.replace(Self.account, in: value, with: "$1$2$3[redacted]$4") + value = Self.replace(preservingJSON ? Self.jsonAccount : Self.account, + in: value, with: "$1$2$3$4$5[redacted]$5") return value } @@ -91,7 +95,8 @@ public struct DiagnosticRedactor: Sendable { /// Lines of basalt-streamer that print a name with no diagnostic use: a /// CoreAudio device ("Ada's AirPods"), the headset's own name, a USB - /// serial of any shape. Such a name can hold any character and may run + /// serial of any shape; and the Windows user and computer an Unreal + /// game's log names. Such a name can hold any character and may run /// to the end of its line, so these rules read plain log lines only, /// never rendered JSON or a Markdown table. static func redactStreamerLines(in text: String) -> String { @@ -106,6 +111,8 @@ public struct DiagnosticRedactor: Sendable { } } value = replace(headsetNameLine, in: value, with: "$1[headset]$2") + value = replace(unrealUserLine, in: value, with: "$1[user]") + value = replace(unrealComputerLine, in: value, with: "$1[host]") return replace(usbSerialLine, in: value, with: "$1[serial]$2") } @@ -142,6 +149,11 @@ public struct DiagnosticRedactor: Sendable { private static let usbSerialLine = regex(#"(USB Quest )\S+( is authorized)"#) + /// Unreal names them as Wine reports them, which takes both from the + /// Mac: the rest of the line is the name, quoted or not. + private static let unrealUserLine = regex(#"(?m)(LogInit: User: ).*$"#) + private static let unrealComputerLine = regex(#"(?m)(LogInit: Computer: ).*$"#) + // MARK: Folders, disks and this Mac's names /// Where a file or host name starts and ends: `/Users/adam` is not the @@ -188,7 +200,8 @@ public struct DiagnosticRedactor: Sendable { + Self.nameEnd, placeholder)) } if homeDirectory.count > 1 { - rules.append((homeDirectory.count, homeDirectory + // Wine's `Z:/Users/ada` is left to the user rule, as `Z:\Users\ada` is. + rules.append((homeDirectory.count, "(? NSRegularExpression? { + let names = path.split(separator: "/") + guard !names.isEmpty else { return nil } + return try? NSRegularExpression(pattern: "(?i)" + nameStart + #"(?:Z:)?[/\\]+"# + + names.map { spellings(of: String($0)) }.joined(separator: #"[/\\]+"#) + nameEnd) + } + /// `/Volumes/` keeps the rest of the path. Connected disks and /// the disks of the app's own folders are known by name, spaces /// included; any other name runs to the next separator. @@ -233,7 +254,11 @@ public struct DiagnosticRedactor: Sendable { + #"(?:(?:[^/\\\r\n"';,:=()<>|]|'(?=\p{L}))+?(?|]|'(?=\p{L}))+)"#) - private static let anyUser = regex(#"(?i)([/\\]users[/\\]+)([^/\\\s"'<>|:*?,;()\[\]{}]+)"#) + /// The whole folder name after `users`, up to the next separator: a + /// Windows user's may hold spaces, apostrophes and brackets ("Jane Doe"). + /// Only what no Windows name holds ends it early, a quote among them, + /// so that rendered JSON stays valid; a space before the end is kept. + private static let anyUser = regex(#"(?i)([/\\]users[/\\]+)([^/\\"<>|:*?\r\n\t]*[^/\\"<>|:*?\s])"#) /// The per-user temporary and cache root, `/var/folders/xx/<28 characters>`, /// is the same for a user on every start. @@ -283,7 +308,8 @@ public struct DiagnosticRedactor: Sendable { /// mistaken for (or hide) an address. private static let fixedRules: [(NSRegularExpression, String)] = [ (regex(#"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b"#), "[email]"), - (regex(#"\b7656119\d{10}\b"#), "[steamid]"), + (regex(#"(?. (regex(#"(?i)(userdata[/\\]+)\d+"#), "$1[steamid]"), @@ -320,13 +346,22 @@ public struct DiagnosticRedactor: Sendable { && parts.allSatisfy { $0.allSatisfy(\.isASCII) && $0.allSatisfy(\.isNumber) } } - /// The value's quotes, plain or JSON-escaped, are captured and put back: - /// a closing quote can also end the enclosing JSON string. Values stop at - /// a lone backslash so JSON escapes such as `\n` stay intact. - private static let account = regex( - #"(?i)\b(account(?:_?name)?|user_?name|login|persona(?:_?name)?|steam_?id(?:64)?|serial(?:_?number)?|computer_?name|host_?name)(\s*[:=]\s*)((?:\\?")?)(?:[^\s"',;\\]|\\\\)+((?:\\?")?)"#) + private static let accountField = + #"(?i)\b(account(?:[ _]?name)?|user[ _]?name|login|persona(?:[ _]?name)?|steam[ _]?id(?:64)?|serial(?:[ _]?number)?|computer[ _]?name|host[ _]?name)"# + + /// Identity fields take the rest of their line. For assignments, keep + /// explicit value quotes or the next variable in an environment dump. + private static let account = regex(accountField + + #"([ \t]*)(?:(:[ \t]*)[^\r\n]+|(=[ \t]*)(?:(")(?:\\.|[^"\\\r\n])*""# + + #"|(?:(?![ \t]+(?-i:[A-Z_][A-Z_0-9]*)=)[^\r\n])+))"#) - private static func replace( + /// Keep the enclosing string delimiters and escaped line breaks in JSON. + private static let jsonAccountValue = #"(?:(?!\\[nr])(?:\\[\\"]|[^"\\\r\n]|\\(?!")))+"# + private static let jsonAccount = regex(accountField + + #"([ \t]*)(?:(:[ \t]*)"# + jsonAccountValue + + #"|(=[ \t]*)(?:(\\")(?:(?!\5|\\[nr])[^\r\n])*\5|"# + jsonAccountValue + "))") + + static func replace( _ expression: NSRegularExpression, in text: String, with template: String ) -> String { expression.stringByReplacingMatches( @@ -366,8 +401,9 @@ extension SessionConsole { } /// A structured snapshot of the Mac, setup, bottles, profiles, stream -/// settings, and recent sessions for bug reports. Build it from live state, -/// then render it with a redactor; the unredacted renderings stay internal. +/// settings, recent sessions, and the session's and the game's own logs for +/// bug reports. Build it from live state, then render it with a redactor; +/// the unredacted renderings stay internal. public struct DiagnosticReport: Codable, Equatable, Sendable { public static let currentFormatVersion = 1 public static let maximumLogLines = 300 @@ -501,6 +537,22 @@ public struct DiagnosticReport: Codable, Equatable, Sendable { } } + /// An excerpt of the game's own log (`GameLogExcerpt`), its personal + /// data already replaced. + public struct GameLog: Codable, Equatable, Sendable { + /// The game profile it comes from; nil when no game has run. + public var profileName: String? + /// Empty when no log of the game was found. + public var lines: [String] + + public init(profileName: String?, excerpt: String?) { + self.profileName = profileName + var lines = excerpt?.components(separatedBy: "\n") ?? [] + if lines.last?.isEmpty == true { lines.removeLast() } + self.lines = lines + } + } + public var formatVersion: Int public var generatedAt: Date public var application: Application @@ -515,6 +567,8 @@ public struct DiagnosticReport: Codable, Equatable, Sendable { public var recentSessions: [SessionRecord] /// The end of the session log, or nil when the user left it out. public var logTail: [String]? + /// The game's own log, or nil when the user left it out. + public var gameLog: GameLog? public init( generatedAt: Date = Date(), @@ -528,7 +582,8 @@ public struct DiagnosticReport: Codable, Equatable, Sendable { profileStreamSettings: [String: StreamLaunchSettings], currentSession: Session, recentSessions: [SessionRecord], - log: String? + log: String?, + gameLog: GameLog? = nil ) { formatVersion = Self.currentFormatVersion self.generatedAt = generatedAt @@ -577,6 +632,10 @@ public struct DiagnosticReport: Codable, Equatable, Sendable { $1.isEmpty ? $0 : $0.replacingOccurrences(of: $1, with: Self.audioCategory($1)) })) } + self.gameLog = gameLog.map { + GameLog(profileName: $0.profileName, + excerpt: DiagnosticRedactor.redactStreamerLines(in: $0.lines.joined(separator: "\n"))) + } } /// A launch argument may be an account name or a password @@ -609,7 +668,7 @@ public struct DiagnosticReport: Codable, Equatable, Sendable { /// Pretty-printed JSON with every string passed through `redactor`. public func json(redactedWith redactor: DiagnosticRedactor) throws -> String { - redactor.redactIdentifiers(in: try renderJSON()) + redactor.redactIdentifiers(in: try renderJSON(), preservingJSON: true) } /// GitHub-flavored Markdown, ready to paste into an issue, with every @@ -725,6 +784,18 @@ public struct DiagnosticReport: Codable, Equatable, Sendable { } else { lines.append(logTail == nil ? "Not included." : "Empty.") } + + lines += ["", "### Game log", ""] + if let gameLog, !gameLog.lines.isEmpty { + let fence = Self.fence(for: gameLog.lines) + let source = gameLog.profileName.map { " from \($0)" } ?? "" + lines += ["
Excerpt\(source): \(gameLog.lines.count) lines", "", + fence + "text"] + lines += gameLog.lines + lines += [fence, "", "
"] + } else { + lines.append(gameLog == nil ? "Not included." : "No log of the game was found.") + } return lines.joined(separator: "\n") + "\n" } diff --git a/streamer/Sources/BasaltManagerKit/GameLogExcerpt.swift b/streamer/Sources/BasaltManagerKit/GameLogExcerpt.swift new file mode 100644 index 0000000..c0b78a3 --- /dev/null +++ b/streamer/Sources/BasaltManagerKit/GameLogExcerpt.swift @@ -0,0 +1,420 @@ +// SPDX-License-Identifier: MIT +import Foundation +import BasaltBottleKit + +/// What a game wrote in its own log, cut to what explains a session: the +/// last lines and every line that reports an error, in the order they were +/// written, with personal data replaced as in a copied session log. It is +/// made after Wine shutdown and for a diagnostic report; code that looks +/// for known problems reads `text`. +public struct GameLogExcerpt: Equatable, Sendable { + /// A log the excerpt is taken from. + public struct Source: Equatable, Sendable { + public var engine: GameLogFile.Engine + /// As the game names it (`C:\users\[user]\AppData\LocalLow\…\Player.log`), + /// with personal data replaced; never the path on this Mac. + public var path: String + + public init(engine: GameLogFile.Engine, path: String) { + self.engine = engine + self.path = path + } + } + + /// Lines kept from the end of the logs. + public static let tailLines = 200 + /// The most the whole text takes, in bytes of UTF-8: headers, notes and + /// line breaks included. + public static let maximumBytes = 64 * 1024 + /// A longer line is cut and ends with "…". + public static let maximumLineBytes = 1_000 + /// A longer line is left out whole, for a note: personal data is only + /// replaced in whole lines, and part of a name or number that a cut + /// leaves would no longer be recognised. + public static let maximumReadLineBytes = 16 * 1024 + /// Of a larger log only its end is kept for line selection. + public static let maximumReadBytes = 8 << 20 + /// The newest logs of one game that are read; older ones stay out. + public static let maximumFiles = 3 + /// Excerpts kept for launches that recorded nothing else: as many as + /// the session history keeps sessions. + public static let keptExcerpts = SessionHistoryStore.defaultLimit + + /// Oldest first. + public var sources: [Source] + /// Each log starts with a `==> <==` line, `[… N lines skipped …]` + /// stands for lines left out, and the text ends with a line break. + public var text: String + + public init(sources: [Source], text: String) { + self.sources = sources + self.text = text + } + + /// The excerpt of the logs `search` finds for a game started at `start`; + /// nil when it wrote none that TrailBridge knows of and can read. + public static func collect(_ search: GameLogSearch, since start: Date, + redactedWith redactor: DiagnosticRedactor, wineMayBeRunning: Bool = false, + fileManager: FileManager = .default) -> GameLogExcerpt? { + let logs = search.readLogs(since: start, limit: maximumFiles, fileManager: fileManager) { file -> Log? in + guard let opened = file.open(), let read = Self.read(opened.handle, size: opened.size) else { + return nil + } + let winePath = BottleManager.winePath(for: file.url, prefix: search.prefix) + guard winePath.hasPrefix("Z:") else { + return Log(engine: file.engine, label: winePath, text: read.text, unreadBytes: read.unreadBytes) + } + let root = file.root.path + let base = root == "/" ? root : root + "/" + let relative = file.url.path.hasPrefix(base) + ? String(file.url.path.dropFirst(base.count)) : file.url.lastPathComponent + let label = gameFolderLabel + #"\"# + relative.replacingOccurrences(of: "/", with: #"\"#) + let standardizedRoot = URL(fileURLWithPath: file.resolvedRoot, isDirectory: true).standardizedFileURL.path + return Log(engine: file.engine, label: label, text: read.text, unreadBytes: read.unreadBytes, + gameFolders: [root, file.resolvedRoot, standardizedRoot]) + } + return logs.isEmpty ? nil : GameLogExcerpt( + logs: logs, redactedWith: redactor, wineMayBeRunning: wineMayBeRunning) + } + + private static let gameFolderLabel = L10n.string(.recordingGameLogFolder, language: .en) + + // MARK: Reading + + /// A log as read, before its lines are chosen. + struct Log { + var engine: GameLogFile.Engine + /// The Windows path its header names, before personal data is replaced. + var label: String + var lines: [Substring] + /// The bytes at its start that were not read. + var unreadBytes: Int64 + var gameFolders: [String] + + init(engine: GameLogFile.Engine, label: String, text: String, unreadBytes: Int64 = 0, + gameFolders: [String] = []) { + self.engine = engine + self.label = label + self.unreadBytes = unreadBytes + self.gameFolders = gameFolders + var lines = text.utf8.split(separator: UInt8(ascii: "\n"), omittingEmptySubsequences: false) + .map { Substring($0) } + // The line break that ends the last line starts no other. + if lines.last?.isEmpty == true { lines.removeLast() } + self.lines = lines.map { $0.utf8.last == UInt8(ascii: "\r") ? $0.dropLast() : $0 } + } + } + + enum Encoding: Equatable { + case utf8, utf16LittleEndian, utf16BigEndian + + init(start: Data) { + if start.starts(with: [0xFF, 0xFE]) { + self = .utf16LittleEndian + } else if start.starts(with: [0xFE, 0xFF]) { + self = .utf16BigEndian + } else { + self = .utf8 + } + } + } + + /// The text of an open log: all of it, or its last `maximumBytes` without + /// the line that start falls in. UTF-16 when the log starts with its byte + /// order mark, as Unreal can write it; else UTF-8 with what is not valid + /// replaced. nil for a log that looks binary. + static func read(_ handle: FileHandle, size: Int64, + maximumBytes: Int = maximumReadBytes) -> (text: String, unreadBytes: Int64)? { + let start: Data + do { start = try handle.read(upToCount: 4096) ?? Data() } catch { return nil } + let encoding = Encoding(start: start) + let first: Int64 = encoding == .utf8 ? 0 : 2 + var offset = max(first, size - Int64(maximumBytes)) + // UTF-16 is read in whole code units. + if encoding != .utf8, (offset - first) % 2 != 0 { offset += 1 } + if offset > first, decode(start.dropFirst(Int(first)), as: encoding) == nil { return nil } + guard (try? handle.seek(toOffset: UInt64(offset))) != nil, + let data = try? handle.read(upToCount: Int(max(0, size - offset))) ?? Data(), + var text = decode(data, as: encoding) else { return nil } + let unread = offset > first ? offset : 0 + if unread > 0 { + text = text.utf8.firstIndex(of: UInt8(ascii: "\n")) + .map { String(text[text.utf8.index(after: $0)...]) } ?? "" + } + return (text, unread) + } + + /// NULs anywhere or a sample dominated by controls indicate binary data. + static func decode(_ data: Data, as encoding: Encoding) -> String? { + let text: String + switch encoding { + case .utf8: + guard !data.contains(0) else { return nil } + text = String(decoding: data.starts(with: [0xEF, 0xBB, 0xBF]) ? data.dropFirst(3) : data[...], + as: UTF8.self) + case .utf16LittleEndian, .utf16BigEndian: + let bytes = [UInt8](data) + let units = stride(from: 0, to: bytes.count - 1, by: 2).map { index -> UInt16 in + encoding == .utf16LittleEndian + ? UInt16(bytes[index]) | UInt16(bytes[index + 1]) << 8 + : UInt16(bytes[index]) << 8 | UInt16(bytes[index + 1]) + } + guard !units.contains(0) else { return nil } + text = String(decoding: units, as: UTF16.self) + } + let sample = text.unicodeScalars.prefix(4096) + let controls = sample.filter { + $0.properties.generalCategory == .control && $0 != "\t" && $0 != "\n" && $0 != "\r" + }.count + return controls > sample.count / 2 ? nil : text + } + + // MARK: Choosing the lines + + /// The last `tailLines` lines and every line before them that reports + /// an error, as many as `maximumBytes` holds. The last lines get what the + /// errors leave and at least half when they need it; errors are kept from + /// the first, which usually names the cause. + init(logs: [Log], redactedWith redactor: DiagnosticRedactor, wineMayBeRunning: Bool = false) { + let folders = Set(logs.flatMap(\.gameFolders)).sorted { $0.count > $1.count } + .compactMap(DiagnosticRedactor.gameFolderRule(for:)) + func redact(_ text: String) -> String { + let withoutFolders = folders.reduce(text) { + DiagnosticRedactor.replace($1, in: $0, with: Self.gameFolderLabel) + } + return redactor.redact(withoutFolders) + } + var firsts = [Int]() + var count = 0 + for log in logs { + firsts.append(count) + count += log.lines.count + } + func line(_ number: Int) -> Substring { + let index = firsts.lastIndex { $0 <= number }! + return logs[index].lines[number - firsts[index]] + } + let tail = Array(max(0, count - Self.tailLines)..= Self.maximumBytes { break } + } + } + + let remainingTail = tail.filter { rendered[$0] == nil } + for (number, text) in zip(remainingTail, Self.render(remainingTail.map(line), redacting: redact)) { + rendered[number] = text + } + let headers = logs.map { redact("==> \($0.label) <==") } + let incomplete = wineMayBeRunning ? L10n.string(.recordingGameLogPossiblyIncomplete, language: .en) : nil + + // The longest note a gap can need is reserved for each gap the + // choice may open, so the whole text never passes `maximumBytes`. + let note = Self.skipped(count).utf8.count + 1 + var fixed = incomplete.map { $0.utf8.count + 1 } ?? 0 + for (index, log) in logs.enumerated() { + fixed += headers[index].utf8.count + 1 + note + if log.unreadBytes > 0 { fixed += Self.unread(log.unreadBytes).utf8.count + 1 } + } + let room = max(0, Self.maximumBytes - fixed) + func cost(_ number: Int) -> Int { rendered[number, default: ""].utf8.count + 1 } + func gap(before number: Int, after previous: Int?) -> Int { + firsts.contains(number) || previous == number - 1 ? 0 : note + } + + let tailCost = tail.reduce(note) { $0 + cost($1) } + var errorCost = 0 + var previous: Int? + for number in errors where number < tail.first ?? count { + errorCost += cost(number) + gap(before: number, after: previous) + previous = number + } + let tailRoom = room - min(errorCost, max(room / 2, room - tailCost)) + var newest = [Int]() + var used = 0 + for number in tail.reversed() { + let added = cost(number) + (newest.isEmpty ? note : 0) + guard used + added <= tailRoom else { break } + newest.append(number) + used += added + } + var kept = [Int]() + previous = nil + for number in errors where number < newest.last ?? count { + let added = cost(number) + gap(before: number, after: previous) + guard used + added <= room else { break } + kept.append(number) + used += added + previous = number + } + kept += newest.reversed() + + var output = incomplete.map { [$0] } ?? [] + var index = 0 + for (position, log) in logs.enumerated() { + let end = firsts[position] + log.lines.count + var next = firsts[position] + output.append(headers[position]) + if log.unreadBytes > 0 { output.append(Self.unread(log.unreadBytes)) } + while index < kept.count, kept[index] < end { + let number = kept[index] + if number > next { output.append(Self.skipped(number - next)) } + output.append(rendered[number, default: ""]) + next = number + 1 + index += 1 + } + if end > next { output.append(Self.skipped(end - next)) } + } + self.init(sources: logs.map { Source(engine: $0.engine, path: redact($0.label)) }, + text: output.joined(separator: "\n") + "\n") + } + + /// Each line with personal data replaced in the whole line, then cut + /// after `maximumLineBytes`; a line too long to be read whole becomes + /// a note. + private static func render(_ lines: [Substring], redacting redact: (String) -> String) -> [String] { + guard !lines.isEmpty else { return [] } + let readable = lines.filter { $0.utf8.count <= maximumReadLineBytes } + var redacted = redact(readable.joined(separator: "\n")).components(separatedBy: "\n") + // No rule adds or removes a line break; should one ever do so, each + // line is redacted on its own. + if redacted.count != readable.count { redacted = readable.map { redact(String($0)) } } + var next = redacted.makeIterator() + return lines.map { line in + line.utf8.count > maximumReadLineBytes ? omitted(line.utf8.count) : shortened(next.next() ?? "") + } + } + + static func shortened(_ line: String) -> String { + guard line.utf8.count > maximumLineBytes else { return line } + var kept = "" + for character in line { + guard kept.utf8.count + character.utf8.count <= maximumLineBytes else { break } + kept.append(character) + } + return kept + "…" + } + + static func skipped(_ lines: Int) -> String { + lines == 1 ? "[… 1 line skipped …]" : "[… \(lines) lines skipped …]" + } + + static func omitted(_ bytes: Int) -> String { "[long line omitted: \(bytes) bytes]" } + + static func unread(_ bytes: Int64) -> String { "[… earlier lines not read: \(bytes) bytes …]" } + + // MARK: Error lines + + private static let errorWords: [[UInt8]] = ["error", "exception", "fail", "fatal"].map { Array($0.utf8) } + + /// Whether a line reports an error: it has a word that starts with + /// "error", "exception", "fail" or "fatal" in any case, also as a part + /// of a CamelCase or snake_case name (`NullReferenceException`, + /// `XR_ERROR_…`). "Terror" has none. The whole line is looked at, even + /// one too long to be kept. + static func reportsError(_ line: Substring) -> Bool { + line.utf8.withContiguousStorageIfAvailable { reportsError($0) } ?? reportsError(Array(line.utf8)) + } + + private static func reportsError(_ line: Bytes) -> Bool + where Bytes.Element == UInt8, Bytes.Index == Int { + func isLower(_ byte: UInt8) -> Bool { byte >= 0x61 && byte <= 0x7A } + func isUpper(_ byte: UInt8) -> Bool { byte >= 0x41 && byte <= 0x5A } + var previous: UInt8 = 0x20 + for index in line.indices { + let byte = line[index] + defer { previous = byte } + // A word starts after anything but a letter, and a CamelCase + // part at a capital after a small letter. + let startsWord = !(isLower(previous) || isUpper(previous)) || (isUpper(byte) && isLower(previous)) + guard isLower(byte) || isUpper(byte), startsWord else { continue } + for word in errorWords where index + word.count <= line.endIndex { + // Setting 0x20 makes an ASCII capital lower case. + if word.indices.allSatisfy({ line[index + $0] | 0x20 == word[$0] }) { return true } + } + } + return false + } +} + +/// A game the app started, as reading the game's own log needs it: where +/// the game runs and since when, the session and recording it belongs to, +/// and the data folder the session started in. +public struct GameLogRun: Sendable { + public var search: GameLogSearch + public var gameStartedAt: Date + public var profileName: String + /// The session's `SessionRecord`. + public var sessionID: UUID + public var sessionStartedAt: Date + /// The launch's recording, which lends the saved excerpt its name; nil + /// when the launch records nothing. + public var recording: FrameTraceSession? + /// Where the excerpt is saved and the session recorded, as it was at launch. + public var dataRoot: URL + + public init(search: GameLogSearch, gameStartedAt: Date, profileName: String, sessionID: UUID, + sessionStartedAt: Date, recording: FrameTraceSession?, dataRoot: URL) { + self.search = search + self.gameStartedAt = gameStartedAt + self.profileName = profileName + self.sessionID = sessionID + self.sessionStartedAt = sessionStartedAt + self.recording = recording + self.dataRoot = dataRoot + } + + /// What the game has written so far. + public func excerpt(redactedWith redactor: DiagnosticRedactor, + wineMayBeRunning: Bool = false, + fileManager: FileManager = .default) -> GameLogExcerpt? { + GameLogExcerpt.collect(search, since: gameStartedAt, redactedWith: redactor, + wineMayBeRunning: wineMayBeRunning, fileManager: fileManager) + } + + /// After trying to stop the session's Wine processes, saves the excerpt + /// in `Diagnostics` beside the session's other files (`file` is nil when + /// it could not be saved). Of the excerpts that are all a launch left, + /// the newest `GameLogExcerpt.keptExcerpts` stay. + public func save(redactedWith redactor: DiagnosticRedactor, + wineMayBeRunning: Bool = false, + fileManager: FileManager = .default) -> (excerpt: GameLogExcerpt, file: URL?)? { + guard let excerpt = excerpt(redactedWith: redactor, wineMayBeRunning: wineMayBeRunning, + fileManager: fileManager) else { return nil } + let file = DiagnosticsStorage.saveGameLog( + Data(excerpt.text.utf8), dataRoot: dataRoot, recording: recording, + profile: profileName, startedAt: sessionStartedAt) + if file != nil { + _ = try? DiagnosticRecordingStore(dataRoot: dataRoot) + .removeGameLogs(keeping: GameLogExcerpt.keptExcerpts) + } + return (excerpt, file) + } +} + +extension DiagnosticReport.GameLog { + /// The running game's log, read now; else the excerpt saved with the + /// latest session, which is empty when that session saved none. + public static func current(running: GameLogRun?, history: [SessionRecord], dataRoot: URL, + redactedWith redactor: DiagnosticRedactor, + fileManager: FileManager = .default) -> Self { + if let running { + return Self(profileName: running.profileName, + excerpt: running.excerpt(redactedWith: redactor, fileManager: fileManager)?.text) + } + guard let latest = history.first else { return Self(profileName: nil, excerpt: nil) } + return Self(profileName: latest.profileName, excerpt: latest.gameLog.flatMap { + DiagnosticRecordingStore(dataRoot: dataRoot).gameLogText(named: $0) + }) + } +} diff --git a/streamer/Sources/BasaltManagerKit/Localization/L10n.swift b/streamer/Sources/BasaltManagerKit/Localization/L10n.swift index bb9dee7..fca6edc 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/L10n.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/L10n.swift @@ -55,7 +55,10 @@ public enum L10n { /// Array overload for forwarding arguments from an app's short helper. public static func string(_ key: L10nKey, arguments: [CVarArg]) -> String { - let language = language + string(key, language: language, arguments: arguments) + } + + static func string(_ key: L10nKey, language: AppLanguage, arguments: [CVarArg] = []) -> String { let value = LocalizationTables.table(for: language)?.strings[key] #if DEBUG if value == nil { assertionFailure("Missing localization: \(language.rawValue).\(key.rawValue)") } diff --git a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift index 01f1349..d77ce2c 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift @@ -70,6 +70,8 @@ public enum L10nKey: String, CaseIterable, Sendable { case modelGamePriority case modelGameExited case modelGameExitedQuickly + case modelGameLog + case modelGameLogNone case modelSteamDirectLaunch case modelGameBroughtForward case modelGameBringForwardFailed @@ -339,6 +341,10 @@ public enum L10nKey: String, CaseIterable, Sendable { case streamReplay case streamReplayHelp case streamCannotReplay + case streamGameLog + case streamGameLogHelp + case streamGameLogNote + case streamGameLogMissing case streamUnknownError case streamHistoryFPS case streamHistoryLatency @@ -789,6 +795,7 @@ public enum L10nKey: String, CaseIterable, Sendable { case diagnosticsTitle case diagnosticsSubtitle case diagnosticsIncludeLog + case diagnosticsIncludeGameLog case diagnosticsRedaction case diagnosticsBugForm case diagnosticsBugFormHelp @@ -853,6 +860,9 @@ public enum L10nKey: String, CaseIterable, Sendable { case recordingVideoFor case recordingList case recordingListEmpty + case recordingGameLogNote + case recordingGameLogFolder + case recordingGameLogPossiblyIncomplete case recordingFolder case recordingTotal case recordingDeleteAll @@ -866,6 +876,7 @@ public enum L10nKey: String, CaseIterable, Sendable { case recordingInProgress case recordingFileFrames case recordingFileLog + case recordingFileGameLog case recordingFileVideo case recordingFileVideoIndex case recordingFileSize diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift index f79fbc8..3644308 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift @@ -73,6 +73,8 @@ final class StringsDE: LocalizationTable { .modelGamePriority: "Priorität des Spielprozesses: hoch (user-interactive QoS)\n", .modelGameExited: "Spiel mit Status %1$@ beendet\n", .modelGameExitedQuickly: "Das Spiel endete %1$@ s nach dem Start. Erschien nichts im Headset, ist die gestartete Datei vielleicht ein Launcher, der das Spiel als eigenen Prozess öffnet, oder das Spiel hat beim Laden aufgehört (siehe die „game:“-Zeilen oben). Um die .exe des Spiels selbst zu starten, diese unter Bibliothek → Spielkarte → ⋯ → %2$@ auswählen.\n", + .modelGameLog: "Eigenes Protokoll des Spiels: %1$@\n", + .modelGameLogNone: "Kein Protokoll gefunden, das das Spiel selbst schreibt. TrailBridge liest die Protokolle von Unity- und Unreal-Spielen.\n", .modelSteamDirectLaunch: "Das Spiel wird direkt gestartet, nicht über Steam: %1$@\n", .modelGameBroughtForward: "Das Spielfenster ist wieder vorne: Viele Spiele geben nur Ton aus, solange ihr Fenster auf dem Mac vorne ist.\n", .modelGameBringForwardFailed: "Das Spielfenster ließ sich nicht nach vorne holen. Wird das Headset stumm, auf dem Mac auf das Spielfenster klicken.\n", @@ -335,6 +337,10 @@ final class StringsDE: LocalizationTable { .streamReplay: "Erneut spielen", .streamReplayHelp: "%1$@ erneut spielen", .streamCannotReplay: "Dieses Spiel ist nicht startbereit", + .streamGameLog: "Spielprotokoll", + .streamGameLogHelp: "Spielprotokoll von %1$@ anzeigen", + .streamGameLogNote: "Ein Auszug aus dem Protokoll, das das Spiel selbst geschrieben hat: die letzten Zeilen und jede Zeile, die einen Fehler meldet, mit Platzhaltern statt persönlicher Daten. Er bleibt auf diesem Mac.", + .streamGameLogMissing: "Dieser Auszug ist nicht mehr auf diesem Mac.", .streamUnknownError: "Unbekannter Fehler", .streamHistoryFPS: "%1$.1f fps", .streamHistoryLatency: "%1$.0f ms", @@ -776,6 +782,7 @@ final class StringsDE: LocalizationTable { .diagnosticsTitle: "Diagnosebericht", .diagnosticsSubtitle: "Den Bericht vor dem Teilen prüfen. TrailBridge lädt ihn nie hoch.", .diagnosticsIncludeLog: "Sitzungsprotokoll einschließen", + .diagnosticsIncludeGameLog: "Spielprotokoll einschließen", .diagnosticsRedaction: "Benutzerordner und Benutzername, E-Mail-Adressen, Steam-IDs, Headset-Seriennummern und -Namen, Mac-Netzwerknamen, IP- und MAC-Adressen sowie Tokens werden durch Platzhalter ersetzt. Werte der Umgebungsvariablen aus Startprofilen werden nie aufgenommen.", .diagnosticsBugForm: "Fehler melden", .diagnosticsBugFormHelp: "Öffnet GitHub im Browser; den kopierten Bericht ins Protokollfeld einfügen.", @@ -819,7 +826,7 @@ final class StringsDE: LocalizationTable { .sidebarDiagnostics: "Diagnose", .sidebarRecordingOn: "Aufzeichnung ist aktiv für %1$@", .recordingTitle: "Diagnoseaufzeichnung", - .recordingIntro: "Eine Sitzung aufzeichnen, um herauszufinden, was sie gebremst hat. Die Aufzeichnung ist für jedes Spiel aus, bis sie hier eingeschaltet wird. Die Dateien bleiben auf diesem Mac; TrailBridge lädt sie nie hoch.", + .recordingIntro: "Eine Sitzung aufzeichnen, um herauszufinden, was sie gebremst hat. Frames, Sitzungsprotokoll und Video werden nur für Spiele aufgezeichnet, für die die Aufzeichnung hier eingeschaltet ist; ein Auszug aus dem Protokoll des Spiels wird nach jeder Sitzung aufbewahrt. Die Dateien bleiben auf diesem Mac; TrailBridge lädt sie nie hoch.", .recordingReminder: "Diagnoseaufzeichnung ist aktiv für %1$@", .recordingOpen: "Diagnose öffnen", .recordingGames: "Spiele", @@ -833,6 +840,9 @@ final class StringsDE: LocalizationTable { .recordingVideoFor: "Video für %1$@ aufzeichnen", .recordingList: "Aufzeichnungen", .recordingListEmpty: "Noch keine Aufzeichnungen. Die Aufzeichnung für ein Spiel einschalten und eine Sitzung spielen.", + .recordingGameLogNote: "In Auszügen aus Spielprotokollen sind persönliche Daten durch Platzhalter ersetzt. Von denen ohne Aufzeichnung bleiben die letzten %1$lld erhalten.", + .recordingGameLogFolder: "[Spielordner]", + .recordingGameLogPossiblyIncomplete: "[… das Spiel lief möglicherweise noch, daher kann dieser Auszug unvollständig sein …]", .recordingFolder: "Ordner der Aufzeichnungen", .recordingTotal: "Gesamtgröße: %1$@", .recordingDeleteAll: "Alle löschen", @@ -846,6 +856,7 @@ final class StringsDE: LocalizationTable { .recordingInProgress: "Wird aufgezeichnet", .recordingFileFrames: "Frames (CSV)", .recordingFileLog: "Sitzungsprotokoll", + .recordingFileGameLog: "Spielprotokoll", .recordingFileVideo: "Video", .recordingFileVideoIndex: "Videoindex", .recordingFileSize: "%1$@: %2$@", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift index bd1826d..e154449 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift @@ -73,6 +73,8 @@ final class StringsEN: LocalizationTable { .modelGamePriority: "Game process priority: high (user-interactive QoS)\n", .modelGameExited: "Game exited with status %1$@\n", .modelGameExitedQuickly: "The game ended %1$@ s after it started. If nothing appeared in the headset, the file started may be a launcher that opens the game as a separate process, or the game stopped while loading (see the “game:” lines above). To start the game's own .exe, choose it in Library → game card → ⋯ → %2$@\n", + .modelGameLog: "The game's own log: %1$@\n", + .modelGameLogNone: "No log written by the game itself was found. TrailBridge reads the logs of Unity and Unreal games.\n", .modelSteamDirectLaunch: "Starting the game itself rather than through Steam: %1$@\n", .modelGameBroughtForward: "Brought the game's window back to the front: many games play sound only while their window on the Mac is in front.\n", .modelGameBringForwardFailed: "Could not bring the game's window back to the front. If the headset goes silent, click the game's window on the Mac.\n", @@ -335,6 +337,10 @@ final class StringsEN: LocalizationTable { .streamReplay: "Play again", .streamReplayHelp: "Play %1$@ again", .streamCannotReplay: "This game is not ready to launch", + .streamGameLog: "Game log", + .streamGameLogHelp: "Show the game log of %1$@", + .streamGameLogNote: "An excerpt of the log the game wrote itself: its last lines and every line that reports an error, with personal data replaced by placeholders. It stays on this Mac.", + .streamGameLogMissing: "This excerpt is no longer on this Mac.", .streamUnknownError: "Unknown error", .streamHistoryFPS: "%1$.1f fps", .streamHistoryLatency: "%1$.0f ms", @@ -776,6 +782,7 @@ final class StringsEN: LocalizationTable { .diagnosticsTitle: "Diagnostic report", .diagnosticsSubtitle: "Review the report before sharing. TrailBridge never uploads it.", .diagnosticsIncludeLog: "Include the session log", + .diagnosticsIncludeGameLog: "Include the game's own log", .diagnosticsRedaction: "Your home folder and user name, email addresses, Steam IDs, headset serials and names, Mac host names, IP and MAC addresses, and tokens are replaced with placeholders. Launch-profile environment values are never included.", .diagnosticsBugForm: "Report a bug", .diagnosticsBugFormHelp: "Opens GitHub in your browser; paste the copied report into the logs field.", @@ -819,7 +826,7 @@ final class StringsEN: LocalizationTable { .sidebarDiagnostics: "Diagnostics", .sidebarRecordingOn: "Recording is on for %1$@", .recordingTitle: "Diagnostic recording", - .recordingIntro: "Record a session to find out what limited it. Recording is off for every game until you turn it on here. The files stay on this Mac; TrailBridge never uploads them.", + .recordingIntro: "Record a session to find out what limited it. Frames, the session log and video are recorded only for games you turn recording on for here; an excerpt of the game's own log is kept after every session. The files stay on this Mac; TrailBridge never uploads them.", .recordingReminder: "Diagnostics recording is on for %1$@", .recordingOpen: "Open Diagnostics", .recordingGames: "Games", @@ -833,6 +840,9 @@ final class StringsEN: LocalizationTable { .recordingVideoFor: "Record video for %1$@", .recordingList: "Recordings", .recordingListEmpty: "No recordings yet. Turn recording on for a game and play a session.", + .recordingGameLogNote: "Game log excerpts have personal data replaced by placeholders. Of those saved without a recording, the latest %1$lld are kept.", + .recordingGameLogFolder: "[game folder]", + .recordingGameLogPossiblyIncomplete: "[… the game may still have been running; this excerpt can be incomplete …]", .recordingFolder: "Recordings folder", .recordingTotal: "Total size: %1$@", .recordingDeleteAll: "Delete All", @@ -846,6 +856,7 @@ final class StringsEN: LocalizationTable { .recordingInProgress: "Recording now", .recordingFileFrames: "Frames (CSV)", .recordingFileLog: "Session log", + .recordingFileGameLog: "Game log", .recordingFileVideo: "Video", .recordingFileVideoIndex: "Video index", .recordingFileSize: "%1$@: %2$@", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift index 886d572..6a8a0fd 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift @@ -73,6 +73,8 @@ final class StringsES: LocalizationTable { .modelGamePriority: "Prioridad del proceso del juego: alta (user-interactive QoS)\n", .modelGameExited: "El juego terminó con el código %1$@\n", .modelGameExitedQuickly: "El juego terminó %1$@ s después de iniciarse. Si no apareció nada en el visor, el archivo iniciado puede ser un lanzador que abre el juego en otro proceso, o el juego se detuvo al cargar (consulta las líneas «game:» de arriba). Para iniciar el .exe del propio juego, elígelo en Biblioteca → tarjeta del juego → ⋯ → %2$@\n", + .modelGameLog: "Registro del propio juego: %1$@\n", + .modelGameLogNone: "No se encontró ningún registro escrito por el propio juego. TrailBridge lee los registros de los juegos de Unity y Unreal.\n", .modelSteamDirectLaunch: "Iniciando el juego directamente, no a través de Steam: %1$@\n", .modelGameBroughtForward: "La ventana del juego vuelve a estar al frente: muchos juegos solo suenan mientras su ventana está al frente en el Mac.\n", .modelGameBringForwardFailed: "No se pudo traer al frente la ventana del juego. Si el visor se queda sin sonido, haz clic en la ventana del juego en el Mac.\n", @@ -335,6 +337,10 @@ final class StringsES: LocalizationTable { .streamReplay: "Volver a jugar", .streamReplayHelp: "Volver a jugar a %1$@", .streamCannotReplay: "Este juego no está listo para iniciarse", + .streamGameLog: "Registro del juego", + .streamGameLogHelp: "Mostrar el registro de %1$@", + .streamGameLogNote: "Un extracto del registro que escribió el propio juego: sus últimas líneas y cada línea que informa de un error, con los datos personales sustituidos por marcadores. Se queda en este Mac.", + .streamGameLogMissing: "Este extracto ya no está en este Mac.", .streamUnknownError: "Error desconocido", .streamHistoryFPS: "%1$.1f fps", .streamHistoryLatency: "%1$.0f ms", @@ -776,6 +782,7 @@ final class StringsES: LocalizationTable { .diagnosticsTitle: "Informe de diagnóstico", .diagnosticsSubtitle: "Revisa el informe antes de compartirlo. TrailBridge nunca lo sube.", .diagnosticsIncludeLog: "Incluir el registro de sesión", + .diagnosticsIncludeGameLog: "Incluir el registro del juego", .diagnosticsRedaction: "Tu carpeta de inicio y nombre de usuario, correos, ID de Steam, números de serie y nombres de visores, nombres de red del Mac, direcciones IP y MAC y tokens se sustituyen por marcadores. Nunca se incluyen los valores de las variables de entorno de los perfiles de inicio.", .diagnosticsBugForm: "Informar de un error", .diagnosticsBugFormHelp: "Abre GitHub en el navegador; pega el informe copiado en el campo de registros.", @@ -819,7 +826,7 @@ final class StringsES: LocalizationTable { .sidebarDiagnostics: "Diagnóstico", .sidebarRecordingOn: "La grabación está activada para %1$@", .recordingTitle: "Grabación de diagnóstico", - .recordingIntro: "Graba una sesión para averiguar qué la limitó. La grabación está desactivada para todos los juegos hasta que la actives aquí. Los archivos se quedan en este Mac; TrailBridge nunca los sube.", + .recordingIntro: "Graba una sesión para averiguar qué la limitó. Los fotogramas, el registro de sesión y el vídeo solo se graban en los juegos para los que actives la grabación aquí; después de cada sesión se guarda un extracto del registro del propio juego. Los archivos se quedan en este Mac; TrailBridge nunca los sube.", .recordingReminder: "La grabación de diagnóstico está activada para %1$@", .recordingOpen: "Abrir Diagnóstico", .recordingGames: "Juegos", @@ -833,6 +840,9 @@ final class StringsES: LocalizationTable { .recordingVideoFor: "Grabar vídeo de %1$@", .recordingList: "Grabaciones", .recordingListEmpty: "Aún no hay grabaciones. Activa la grabación para un juego y juega una sesión.", + .recordingGameLogNote: "En los extractos de los registros de juego, los datos personales se sustituyen por marcadores. De los guardados sin grabación se conservan los últimos %1$lld.", + .recordingGameLogFolder: "[carpeta del juego]", + .recordingGameLogPossiblyIncomplete: "[… es posible que el juego siguiera en ejecución y que este extracto esté incompleto …]", .recordingFolder: "Carpeta de grabaciones", .recordingTotal: "Tamaño total: %1$@", .recordingDeleteAll: "Eliminar todo", @@ -846,6 +856,7 @@ final class StringsES: LocalizationTable { .recordingInProgress: "Grabando ahora", .recordingFileFrames: "Fotogramas (CSV)", .recordingFileLog: "Registro de sesión", + .recordingFileGameLog: "Registro del juego", .recordingFileVideo: "Vídeo", .recordingFileVideoIndex: "Índice de vídeo", .recordingFileSize: "%1$@: %2$@", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift index cebbcd9..a410724 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift @@ -73,6 +73,8 @@ final class StringsFR: LocalizationTable { .modelGamePriority: "Priorité du processus du jeu : élevée (user-interactive QoS)\n", .modelGameExited: "Le jeu s’est arrêté avec le code %1$@\n", .modelGameExitedQuickly: "Le jeu s’est arrêté %1$@ s après son lancement. Si rien n’est apparu dans le casque, le fichier lancé est peut-être un lanceur qui ouvre le jeu dans un processus séparé, ou le jeu s’est arrêté pendant le chargement (voir les lignes « game: » ci-dessus). Pour lancer le .exe du jeu lui-même, choisissez-le dans Bibliothèque → fiche du jeu → ⋯ → %2$@\n", + .modelGameLog: "Journal du jeu lui-même : %1$@\n", + .modelGameLogNone: "Aucun journal écrit par le jeu lui-même n’a été trouvé. TrailBridge lit les journaux des jeux Unity et Unreal.\n", .modelSteamDirectLaunch: "Lancement direct du jeu, sans passer par Steam : %1$@\n", .modelGameBroughtForward: "La fenêtre du jeu est de nouveau au premier plan : beaucoup de jeux n’émettent du son que si leur fenêtre est au premier plan sur le Mac.\n", .modelGameBringForwardFailed: "Impossible de ramener la fenêtre du jeu au premier plan. Si le casque devient muet, cliquez sur la fenêtre du jeu sur le Mac.\n", @@ -335,6 +337,10 @@ final class StringsFR: LocalizationTable { .streamReplay: "Rejouer", .streamReplayHelp: "Rejouer à %1$@", .streamCannotReplay: "Ce jeu n’est pas prêt à démarrer", + .streamGameLog: "Journal du jeu", + .streamGameLogHelp: "Afficher le journal de %1$@", + .streamGameLogNote: "Un extrait du journal écrit par le jeu lui-même : ses dernières lignes et chaque ligne qui signale une erreur, les données personnelles étant remplacées par des marqueurs. Il reste sur ce Mac.", + .streamGameLogMissing: "Cet extrait n’est plus sur ce Mac.", .streamUnknownError: "Erreur inconnue", .streamHistoryFPS: "%1$.1f i/s", .streamHistoryLatency: "%1$.0f ms", @@ -776,6 +782,7 @@ final class StringsFR: LocalizationTable { .diagnosticsTitle: "Rapport de diagnostic", .diagnosticsSubtitle: "Vérifiez le rapport avant de le partager. TrailBridge ne l’envoie jamais.", .diagnosticsIncludeLog: "Inclure le journal de session", + .diagnosticsIncludeGameLog: "Inclure le journal du jeu", .diagnosticsRedaction: "Le dossier de départ et le nom d’utilisateur, les adresses e-mail, identifiants Steam, numéros de série et noms des casques, noms réseau du Mac, adresses IP et MAC et jetons sont remplacés par des marqueurs. Les valeurs des variables d’environnement des profils de lancement ne sont jamais incluses.", .diagnosticsBugForm: "Signaler un bug", .diagnosticsBugFormHelp: "Ouvre GitHub dans le navigateur ; collez le rapport copié dans le champ des journaux.", @@ -819,7 +826,7 @@ final class StringsFR: LocalizationTable { .sidebarDiagnostics: "Diagnostic", .sidebarRecordingOn: "L’enregistrement est activé pour %1$@", .recordingTitle: "Enregistrement de diagnostic", - .recordingIntro: "Enregistrez une session pour savoir ce qui l’a limitée. L’enregistrement est désactivé pour chaque jeu tant que vous ne l’activez pas ici. Les fichiers restent sur ce Mac ; TrailBridge ne les envoie jamais.", + .recordingIntro: "Enregistrez une session pour savoir ce qui l’a limitée. Les images, le journal de session et la vidéo ne sont enregistrés que pour les jeux dont vous activez l’enregistrement ici ; un extrait du journal du jeu est conservé après chaque session. Les fichiers restent sur ce Mac ; TrailBridge ne les envoie jamais.", .recordingReminder: "L’enregistrement de diagnostic est activé pour %1$@", .recordingOpen: "Ouvrir Diagnostic", .recordingGames: "Jeux", @@ -833,6 +840,9 @@ final class StringsFR: LocalizationTable { .recordingVideoFor: "Enregistrer la vidéo pour %1$@", .recordingList: "Enregistrements", .recordingListEmpty: "Aucun enregistrement pour l’instant. Activez l’enregistrement pour un jeu et jouez une session.", + .recordingGameLogNote: "Dans les extraits des journaux de jeu, les données personnelles sont remplacées par des marqueurs. Parmi ceux conservés sans enregistrement, les %1$lld derniers sont gardés.", + .recordingGameLogFolder: "[dossier du jeu]", + .recordingGameLogPossiblyIncomplete: "[… le jeu était peut-être encore en cours d’exécution et cet extrait peut être incomplet …]", .recordingFolder: "Dossier des enregistrements", .recordingTotal: "Taille totale : %1$@", .recordingDeleteAll: "Tout supprimer", @@ -846,6 +856,7 @@ final class StringsFR: LocalizationTable { .recordingInProgress: "Enregistrement en cours", .recordingFileFrames: "Images (CSV)", .recordingFileLog: "Journal de session", + .recordingFileGameLog: "Journal du jeu", .recordingFileVideo: "Vidéo", .recordingFileVideoIndex: "Index vidéo", .recordingFileSize: "%1$@ : %2$@", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift index 50b241d..7b747d0 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift @@ -73,6 +73,8 @@ final class StringsIT: LocalizationTable { .modelGamePriority: "Priorità del processo di gioco: alta (user-interactive QoS)\n", .modelGameExited: "Gioco terminato con codice %1$@\n", .modelGameExitedQuickly: "Il gioco è terminato %1$@ s dopo l’avvio. Se nel visore non è apparso nulla, il file avviato può essere un launcher che apre il gioco in un processo separato, oppure il gioco si è fermato durante il caricamento (vedi le righe «game:» sopra). Per avviare l’.exe del gioco stesso, sceglilo in Libreria → scheda del gioco → ⋯ → %2$@\n", + .modelGameLog: "Registro del gioco stesso: %1$@\n", + .modelGameLogNone: "Non è stato trovato alcun registro scritto dal gioco stesso. TrailBridge legge i registri dei giochi Unity e Unreal.\n", .modelSteamDirectLaunch: "Avvio diretto del gioco, senza passare da Steam: %1$@\n", .modelGameBroughtForward: "La finestra del gioco è di nuovo in primo piano: molti giochi riproducono l’audio solo quando la loro finestra sul Mac è in primo piano.\n", .modelGameBringForwardFailed: "Impossibile riportare in primo piano la finestra del gioco. Se il visore resta senza audio, fai clic sulla finestra del gioco sul Mac.\n", @@ -335,6 +337,10 @@ final class StringsIT: LocalizationTable { .streamReplay: "Gioca di nuovo", .streamReplayHelp: "Gioca di nuovo a %1$@", .streamCannotReplay: "Questo gioco non è pronto per l’avvio", + .streamGameLog: "Registro del gioco", + .streamGameLogHelp: "Mostra il registro di %1$@", + .streamGameLogNote: "Un estratto del registro scritto dal gioco stesso: le ultime righe e ogni riga che segnala un errore, con i dati personali sostituiti da segnaposto. Resta su questo Mac.", + .streamGameLogMissing: "Questo estratto non è più su questo Mac.", .streamUnknownError: "Errore sconosciuto", .streamHistoryFPS: "%1$.1f fps", .streamHistoryLatency: "%1$.0f ms", @@ -776,6 +782,7 @@ final class StringsIT: LocalizationTable { .diagnosticsTitle: "Resoconto diagnostico", .diagnosticsSubtitle: "Controlla il resoconto prima di condividerlo. TrailBridge non lo carica mai.", .diagnosticsIncludeLog: "Includi il registro della sessione", + .diagnosticsIncludeGameLog: "Includi il registro del gioco", .diagnosticsRedaction: "Cartella Inizio e nome utente, email, ID Steam, nomi e numeri di serie dei visori, nomi di rete del Mac, indirizzi IP e MAC e token vengono sostituiti con segnaposto. I valori delle variabili d’ambiente dei profili di avvio non sono mai inclusi.", .diagnosticsBugForm: "Segnala un problema", .diagnosticsBugFormHelp: "Apre GitHub nel browser; incolla il resoconto copiato nel campo dei registri.", @@ -819,7 +826,7 @@ final class StringsIT: LocalizationTable { .sidebarDiagnostics: "Diagnostica", .sidebarRecordingOn: "La registrazione è attiva per %1$@", .recordingTitle: "Registrazione diagnostica", - .recordingIntro: "Registra una sessione per capire che cosa l’ha limitata. La registrazione è disattivata per ogni gioco finché non la attivi qui. I file restano su questo Mac; TrailBridge non li carica mai.", + .recordingIntro: "Registra una sessione per capire che cosa l’ha limitata. Fotogrammi, registro della sessione e video vengono registrati solo per i giochi per cui attivi qui la registrazione; dopo ogni sessione viene conservato un estratto del registro del gioco. I file restano su questo Mac; TrailBridge non li carica mai.", .recordingReminder: "La registrazione diagnostica è attiva per %1$@", .recordingOpen: "Apri Diagnostica", .recordingGames: "Giochi", @@ -833,6 +840,9 @@ final class StringsIT: LocalizationTable { .recordingVideoFor: "Registra video per %1$@", .recordingList: "Registrazioni", .recordingListEmpty: "Ancora nessuna registrazione. Attiva la registrazione per un gioco e gioca una sessione.", + .recordingGameLogNote: "Negli estratti dei registri di gioco i dati personali sono sostituiti da segnaposto. Di quelli salvati senza registrazione vengono tenuti gli ultimi %1$lld.", + .recordingGameLogFolder: "[cartella del gioco]", + .recordingGameLogPossiblyIncomplete: "[… il gioco potrebbe essere stato ancora in esecuzione e questo estratto potrebbe essere incompleto …]", .recordingFolder: "Cartella delle registrazioni", .recordingTotal: "Dimensione totale: %1$@", .recordingDeleteAll: "Elimina tutto", @@ -846,6 +856,7 @@ final class StringsIT: LocalizationTable { .recordingInProgress: "Registrazione in corso", .recordingFileFrames: "Fotogrammi (CSV)", .recordingFileLog: "Registro sessione", + .recordingFileGameLog: "Registro del gioco", .recordingFileVideo: "Video", .recordingFileVideoIndex: "Indice video", .recordingFileSize: "%1$@: %2$@", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift index eab6d24..a49dc64 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift @@ -73,6 +73,8 @@ final class StringsJA: LocalizationTable { .modelGamePriority: "ゲームプロセスの優先度:高(user-interactive QoS)\n", .modelGameExited: "ゲームがコード%1$@で終了しました\n", .modelGameExitedQuickly: "ゲームは起動から%1$@秒後に終了しました。ヘッドセットに何も表示されなかった場合、起動したファイルがゲームを別のプロセスで開くランチャーであるか、読み込み中にゲームが停止した可能性があります(上の「game:」の行を確認してください)。ゲーム本体の.exeを起動するには、ライブラリ → ゲームカード → ⋯ → %2$@ で選択してください。\n", + .modelGameLog: "ゲーム自身のログ:%1$@\n", + .modelGameLogNone: "ゲーム自身が書いたログは見つかりませんでした。TrailBridgeが読むのはUnityとUnrealのゲームのログです。\n", .modelSteamDirectLaunch: "Steam経由ではなくゲーム本体を起動します:%1$@\n", .modelGameBroughtForward: "ゲームのウインドウを最前面に戻しました。多くのゲームは、Mac でウインドウが最前面にあるときだけ音を出します。\n", .modelGameBringForwardFailed: "ゲームのウインドウを最前面に戻せませんでした。ヘッドセットの音が消えたら、Mac でゲームのウインドウをクリックしてください。\n", @@ -335,6 +337,10 @@ final class StringsJA: LocalizationTable { .streamReplay: "もう一度プレイ", .streamReplayHelp: "%1$@をもう一度プレイ", .streamCannotReplay: "このゲームは起動の準備ができていません", + .streamGameLog: "ゲームのログ", + .streamGameLogHelp: "%1$@のログを表示", + .streamGameLogNote: "ゲーム自身が書いたログの抜粋です。最後の行と、エラーを報告するすべての行を含み、個人情報は伏せ字に置き換えています。このMacから外には出ません。", + .streamGameLogMissing: "この抜粋はもうこのMacにありません。", .streamUnknownError: "不明なエラー", .streamHistoryFPS: "%1$.1f fps", .streamHistoryLatency: "%1$.0f ms", @@ -776,6 +782,7 @@ final class StringsJA: LocalizationTable { .diagnosticsTitle: "診断レポート", .diagnosticsSubtitle: "共有する前にレポートを確認してください。TrailBridgeがアップロードすることはありません。", .diagnosticsIncludeLog: "セッションログを含める", + .diagnosticsIncludeGameLog: "ゲームのログを含める", .diagnosticsRedaction: "ホームフォルダ、ユーザ名、メールアドレス、Steam ID、ヘッドセットのシリアル番号と名前、Macのホスト名、IPアドレスとMACアドレス、トークンは伏せ字に置き換えます。起動プロファイルの環境変数の値は含めません。", .diagnosticsBugForm: "バグを報告", .diagnosticsBugFormHelp: "ブラウザでGitHubを開きます。コピーしたレポートをログ欄に貼り付けてください。", @@ -819,7 +826,7 @@ final class StringsJA: LocalizationTable { .sidebarDiagnostics: "診断", .sidebarRecordingOn: "%1$@の記録がオンです", .recordingTitle: "診断記録", - .recordingIntro: "セッションを記録して、何が性能を制限したかを確認できます。ここでオンにするまで、すべてのゲームで記録はオフです。ファイルはこのMacに保存され、TrailBridgeがアップロードすることはありません。", + .recordingIntro: "セッションを記録して、何が性能を制限したかを確認できます。フレーム、セッションログ、ビデオは、ここで記録をオンにしたゲームでのみ記録されます。ゲーム自身のログの抜粋は、セッションのたびに保存されます。ファイルはこのMacに保存され、TrailBridgeがアップロードすることはありません。", .recordingReminder: "%1$@の診断記録がオンです", .recordingOpen: "診断を開く", .recordingGames: "ゲーム", @@ -833,6 +840,9 @@ final class StringsJA: LocalizationTable { .recordingVideoFor: "%1$@のビデオを記録", .recordingList: "記録", .recordingListEmpty: "まだ記録がありません。ゲームの記録をオンにして、セッションをプレイしてください。", + .recordingGameLogNote: "ゲームのログの抜粋では、個人情報を伏せ字に置き換えています。記録なしで保存された抜粋は、最新の%1$lld件を残します。", + .recordingGameLogFolder: "[ゲームフォルダ]", + .recordingGameLogPossiblyIncomplete: "[… ゲームがまだ実行中だった可能性があるため、この抜粋は不完全な場合があります …]", .recordingFolder: "記録フォルダ", .recordingTotal: "合計サイズ: %1$@", .recordingDeleteAll: "すべて削除", @@ -846,6 +856,7 @@ final class StringsJA: LocalizationTable { .recordingInProgress: "記録中", .recordingFileFrames: "フレーム(CSV)", .recordingFileLog: "セッションログ", + .recordingFileGameLog: "ゲームのログ", .recordingFileVideo: "ビデオ", .recordingFileVideoIndex: "ビデオインデックス", .recordingFileSize: "%1$@: %2$@", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift index 364087c..afc3505 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift @@ -73,6 +73,8 @@ final class StringsKO: LocalizationTable { .modelGamePriority: "게임 프로세스 우선순위: 높음(user-interactive QoS)\n", .modelGameExited: "게임 종료 코드: %1$@\n", .modelGameExitedQuickly: "게임이 시작 후 %1$@초 만에 종료되었습니다. 헤드셋에 아무것도 나타나지 않았다면, 실행한 파일이 게임을 별도 프로세스로 여는 런처이거나 게임이 로딩 중에 멈췄을 수 있습니다(위의 “game:” 줄 참고). 게임 본체의 .exe를 실행하려면 라이브러리 → 게임 카드 → ⋯ → %2$@에서 선택하세요.\n", + .modelGameLog: "게임 자체 로그: %1$@\n", + .modelGameLogNone: "게임이 직접 남긴 로그를 찾지 못했습니다. TrailBridge는 Unity와 Unreal 게임의 로그를 읽습니다.\n", .modelSteamDirectLaunch: "Steam을 거치지 않고 게임을 직접 실행합니다: %1$@\n", .modelGameBroughtForward: "게임 창을 다시 맨 앞으로 가져왔습니다. 많은 게임은 Mac에서 창이 맨 앞에 있을 때만 소리를 냅니다.\n", .modelGameBringForwardFailed: "게임 창을 맨 앞으로 가져오지 못했습니다. 헤드셋에서 소리가 사라지면 Mac에서 게임 창을 클릭하세요.\n", @@ -335,6 +337,10 @@ final class StringsKO: LocalizationTable { .streamReplay: "다시 플레이", .streamReplayHelp: "%1$@ 다시 플레이", .streamCannotReplay: "이 게임은 아직 실행 준비가 되지 않았어요", + .streamGameLog: "게임 로그", + .streamGameLogHelp: "%1$@ 게임 로그 보기", + .streamGameLogNote: "게임이 직접 남긴 로그의 발췌본이에요. 마지막 줄들과 오류를 알리는 모든 줄이 들어 있고, 개인 정보는 대체 표시로 가렸어요. 이 Mac 밖으로 나가지 않아요.", + .streamGameLogMissing: "이 발췌본은 더 이상 이 Mac에 없어요.", .streamUnknownError: "알 수 없는 오류", .streamHistoryFPS: "%1$.1f fps", .streamHistoryLatency: "%1$.0f ms", @@ -776,6 +782,7 @@ final class StringsKO: LocalizationTable { .diagnosticsTitle: "진단 보고서", .diagnosticsSubtitle: "공유하기 전에 보고서를 확인하세요. TrailBridge는 보고서를 업로드하지 않아요.", .diagnosticsIncludeLog: "세션 로그 포함", + .diagnosticsIncludeGameLog: "게임 로그 포함", .diagnosticsRedaction: "홈 폴더와 사용자 이름, 이메일 주소, Steam ID, 헤드셋 일련번호와 이름, Mac 호스트 이름, IP 및 MAC 주소, 토큰은 대체 표시로 가려요. 실행 프로필의 환경 변수 값은 포함하지 않아요.", .diagnosticsBugForm: "버그 신고", .diagnosticsBugFormHelp: "브라우저에서 GitHub를 열어요. 복사한 보고서를 로그 입력란에 붙여 넣으세요.", @@ -819,7 +826,7 @@ final class StringsKO: LocalizationTable { .sidebarDiagnostics: "진단", .sidebarRecordingOn: "%1$@ 기록이 켜져 있어요", .recordingTitle: "진단 기록", - .recordingIntro: "세션을 기록해 무엇이 성능을 제한했는지 확인하세요. 여기에서 켜기 전에는 모든 게임의 기록이 꺼져 있어요. 파일은 이 Mac에만 저장되며, TrailBridge는 파일을 업로드하지 않아요.", + .recordingIntro: "세션을 기록해 무엇이 성능을 제한했는지 확인하세요. 프레임, 세션 로그, 비디오는 여기에서 기록을 켠 게임만 기록해요. 게임 자체 로그의 발췌본은 세션이 끝날 때마다 보관해요. 파일은 이 Mac에만 저장되며, TrailBridge는 파일을 업로드하지 않아요.", .recordingReminder: "%1$@의 진단 기록이 켜져 있어요", .recordingOpen: "진단 열기", .recordingGames: "게임", @@ -833,6 +840,9 @@ final class StringsKO: LocalizationTable { .recordingVideoFor: "%1$@의 비디오 기록", .recordingList: "기록", .recordingListEmpty: "아직 기록이 없어요. 게임의 기록을 켜고 세션을 플레이하세요.", + .recordingGameLogNote: "게임 로그 발췌본의 개인 정보는 대체 표시로 가려요. 기록 없이 저장된 발췌본은 최근 %1$lld개를 보관해요.", + .recordingGameLogFolder: "[게임 폴더]", + .recordingGameLogPossiblyIncomplete: "[… 게임이 계속 실행 중이었을 수 있어 이 발췌본이 불완전할 수 있습니다 …]", .recordingFolder: "기록 폴더", .recordingTotal: "전체 크기: %1$@", .recordingDeleteAll: "모두 삭제", @@ -846,6 +856,7 @@ final class StringsKO: LocalizationTable { .recordingInProgress: "기록 중", .recordingFileFrames: "프레임(CSV)", .recordingFileLog: "세션 로그", + .recordingFileGameLog: "게임 로그", .recordingFileVideo: "비디오", .recordingFileVideoIndex: "비디오 색인", .recordingFileSize: "%1$@: %2$@", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift index 3e1c080..48284cf 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift @@ -73,6 +73,8 @@ final class StringsPL: LocalizationTable { .modelGamePriority: "Priorytet procesu gry: wysoki (user-interactive QoS)\n", .modelGameExited: "Gra zakończyła się z kodem %1$@\n", .modelGameExitedQuickly: "Gra zakończyła się %1$@ s po uruchomieniu. Jeśli w goglach nic się nie pojawiło, uruchomiony plik może być launcherem, który otwiera grę jako osobny proces, albo gra zatrzymała się podczas ładowania (zobacz wiersze „game:” powyżej). Aby uruchamiać sam plik .exe gry, wybierz go w: Biblioteka → karta gry → ⋯ → %2$@\n", + .modelGameLog: "Dziennik samej gry: %1$@\n", + .modelGameLogNone: "Nie znaleziono dziennika zapisywanego przez samą grę. TrailBridge czyta dzienniki gier na Unity i Unreal.\n", .modelSteamDirectLaunch: "Uruchamianie samej gry, nie przez Steam: %1$@\n", .modelGameBroughtForward: "Okno gry znów jest na pierwszym planie: wiele gier gra dźwięk tylko wtedy, gdy ich okno na Macu jest na wierzchu.\n", .modelGameBringForwardFailed: "Nie udało się przywrócić okna gry na pierwszy plan. Jeśli w goglach zniknie dźwięk, kliknij okno gry na Macu.\n", @@ -335,6 +337,10 @@ final class StringsPL: LocalizationTable { .streamReplay: "Zagraj ponownie", .streamReplayHelp: "Zagraj ponownie w %1$@", .streamCannotReplay: "Ta gra nie jest gotowa do uruchomienia", + .streamGameLog: "Dziennik gry", + .streamGameLogHelp: "Pokaż dziennik gry %1$@", + .streamGameLogNote: "Fragment dziennika zapisanego przez samą grę: ostatnie wiersze i każdy wiersz zgłaszający błąd, z danymi osobowymi zastąpionymi symbolami. Zostaje na tym Macu.", + .streamGameLogMissing: "Tego fragmentu nie ma już na tym Macu.", .streamUnknownError: "Nieznany błąd", .streamHistoryFPS: "%1$.1f kl./s", .streamHistoryLatency: "%1$.0f ms", @@ -776,6 +782,7 @@ final class StringsPL: LocalizationTable { .diagnosticsTitle: "Raport diagnostyczny", .diagnosticsSubtitle: "Przejrzyj raport przed udostępnieniem. TrailBridge nigdy go nie wysyła.", .diagnosticsIncludeLog: "Dołącz dziennik sesji", + .diagnosticsIncludeGameLog: "Dołącz dziennik gry", .diagnosticsRedaction: "Folder domowy i nazwa użytkownika, adresy e-mail, identyfikatory Steam, numery seryjne i nazwy gogli, nazwy sieciowe Maca, adresy IP i MAC oraz tokeny są zastępowane symbolami. Wartości zmiennych środowiskowych profili uruchamiania nigdy nie są dołączane.", .diagnosticsBugForm: "Zgłoś błąd", .diagnosticsBugFormHelp: "Otwiera GitHub w przeglądarce; wklej skopiowany raport w polu dzienników.", @@ -819,7 +826,7 @@ final class StringsPL: LocalizationTable { .sidebarDiagnostics: "Diagnostyka", .sidebarRecordingOn: "Nagrywanie jest włączone dla: %1$@", .recordingTitle: "Nagrywanie diagnostyczne", - .recordingIntro: "Nagraj sesję, aby sprawdzić, co ją ograniczało. Nagrywanie jest wyłączone dla każdej gry, dopóki nie włączysz go tutaj. Pliki zostają na tym Macu; TrailBridge nigdy ich nie wysyła.", + .recordingIntro: "Nagraj sesję, aby sprawdzić, co ją ograniczało. Klatki, dziennik sesji i wideo są nagrywane tylko dla gier, dla których włączysz tu nagrywanie; po każdej sesji zachowywany jest fragment dziennika samej gry. Pliki zostają na tym Macu; TrailBridge nigdy ich nie wysyła.", .recordingReminder: "Nagrywanie diagnostyczne jest włączone dla: %1$@", .recordingOpen: "Otwórz Diagnostykę", .recordingGames: "Gry", @@ -833,6 +840,9 @@ final class StringsPL: LocalizationTable { .recordingVideoFor: "Nagrywaj wideo dla: %1$@", .recordingList: "Nagrania", .recordingListEmpty: "Nie ma jeszcze nagrań. Włącz nagrywanie dla gry i rozegraj sesję.", + .recordingGameLogNote: "We fragmentach dzienników gier dane osobowe są zastąpione symbolami. Z zapisanych bez nagrania TrailBridge przechowuje do %1$lld ostatnich.", + .recordingGameLogFolder: "[folder gry]", + .recordingGameLogPossiblyIncomplete: "[… gra mogła nadal działać, więc ten fragment może być niepełny …]", .recordingFolder: "Folder nagrań", .recordingTotal: "Łączny rozmiar: %1$@", .recordingDeleteAll: "Usuń wszystkie", @@ -846,6 +856,7 @@ final class StringsPL: LocalizationTable { .recordingInProgress: "Trwa nagrywanie", .recordingFileFrames: "Klatki (CSV)", .recordingFileLog: "Dziennik sesji", + .recordingFileGameLog: "Dziennik gry", .recordingFileVideo: "Wideo", .recordingFileVideoIndex: "Indeks wideo", .recordingFileSize: "%1$@: %2$@", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift index f530217..06aeb82 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift @@ -73,6 +73,8 @@ final class StringsRU: LocalizationTable { .modelGamePriority: "Приоритет процесса игры: высокий (user-interactive QoS)\n", .modelGameExited: "Игра завершилась с кодом %1$@\n", .modelGameExitedQuickly: "Игра завершилась через %1$@ с после запуска. Если в шлеме ничего не появилось, запущенный файл может быть лаунчером, который открывает игру отдельным процессом, или игра остановилась при загрузке (см. строки «game:» выше). Чтобы запускать сам .exe игры, выберите его: «Библиотека» → карточка игры → ⋯ → «%2$@».\n", + .modelGameLog: "Журнал самой игры: %1$@\n", + .modelGameLogNone: "Журнал, который ведёт сама игра, не найден. TrailBridge читает журналы игр на Unity и Unreal.\n", .modelSteamDirectLaunch: "Запускаем саму игру, а не через Steam: %1$@\n", .modelGameBroughtForward: "Окно игры снова впереди: многие игры звучат, только пока их окно на Mac впереди.\n", .modelGameBringForwardFailed: "Не удалось вернуть окно игры вперёд. Если в шлеме пропал звук, щёлкните окно игры на Mac.\n", @@ -335,6 +337,10 @@ final class StringsRU: LocalizationTable { .streamReplay: "Запустить снова", .streamReplayHelp: "Запустить %1$@ снова", .streamCannotReplay: "Эта игра сейчас не готова к запуску", + .streamGameLog: "Журнал игры", + .streamGameLogHelp: "Показать журнал игры %1$@", + .streamGameLogNote: "Выдержка из журнала, который вела сама игра: последние строки и каждая строка с сообщением об ошибке, личные данные заменены заглушками. Она хранится только на этом Mac.", + .streamGameLogMissing: "Этой выдержки больше нет на этом Mac.", .streamUnknownError: "Неизвестная ошибка", .streamHistoryFPS: "%1$.1f к/с", .streamHistoryLatency: "%1$.0f мс", @@ -776,6 +782,7 @@ final class StringsRU: LocalizationTable { .diagnosticsTitle: "Диагностический отчёт", .diagnosticsSubtitle: "Просмотрите отчёт перед отправкой. TrailBridge не отправляет его.", .diagnosticsIncludeLog: "Включить журнал сеанса", + .diagnosticsIncludeGameLog: "Включить журнал игры", .diagnosticsRedaction: "Домашняя папка и имя пользователя, адреса почты, Steam ID, серийные номера и имена шлемов, сетевые имена Mac, IP- и MAC-адреса и токены заменяются заглушками. Значения переменных среды профиля запуска не включаются в отчёт.", .diagnosticsBugForm: "Сообщить об ошибке", .diagnosticsBugFormHelp: "Откроет GitHub в браузере; вставьте скопированный отчёт в поле для журналов.", @@ -819,7 +826,7 @@ final class StringsRU: LocalizationTable { .sidebarDiagnostics: "Диагностика", .sidebarRecordingOn: "Запись включена: %1$@", .recordingTitle: "Диагностическая запись", - .recordingIntro: "Запишите сеанс, чтобы понять, что его ограничивало. Запись выключена для каждой игры, пока вы не включите её здесь. Файлы остаются на этом Mac; TrailBridge никуда их не отправляет.", + .recordingIntro: "Запишите сеанс, чтобы понять, что его ограничивало. Кадры, журнал сеанса и видео записываются только для игр, для которых вы включили запись здесь; выдержка из журнала самой игры сохраняется после каждого сеанса. Файлы остаются на этом Mac; TrailBridge никуда их не отправляет.", .recordingReminder: "Диагностическая запись включена: %1$@", .recordingOpen: "Открыть «Диагностику»", .recordingGames: "Игры", @@ -833,6 +840,9 @@ final class StringsRU: LocalizationTable { .recordingVideoFor: "Записывать видео: %1$@", .recordingList: "Записи", .recordingListEmpty: "Записей пока нет. Включите запись для игры и проведите сеанс.", + .recordingGameLogNote: "В выдержках из журналов игр личные данные заменены заглушками. Из сохранённых без записи хранятся последние %1$lld.", + .recordingGameLogFolder: "[папка игры]", + .recordingGameLogPossiblyIncomplete: "[… возможно, игра ещё работала, поэтому эта выдержка может быть неполной …]", .recordingFolder: "Папка записей", .recordingTotal: "Общий размер: %1$@", .recordingDeleteAll: "Удалить все", @@ -846,6 +856,7 @@ final class StringsRU: LocalizationTable { .recordingInProgress: "Идёт запись", .recordingFileFrames: "Кадры (CSV)", .recordingFileLog: "Журнал сеанса", + .recordingFileGameLog: "Журнал игры", .recordingFileVideo: "Видео", .recordingFileVideoIndex: "Индекс видео", .recordingFileSize: "%1$@: %2$@", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift index 6a335fe..fb5d59f 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift @@ -73,6 +73,8 @@ final class StringsUK: LocalizationTable { .modelGamePriority: "Пріоритет процесу гри: високий (user-interactive QoS)\n", .modelGameExited: "Гра завершилася з кодом %1$@\n", .modelGameExitedQuickly: "Гра завершилася через %1$@ с після запуску. Якщо в шоломі нічого не з’явилося, запущений файл може бути лаунчером, що відкриває гру окремим процесом, або гра зупинилася під час завантаження (див. рядки «game:» вище). Щоб запускати сам .exe гри, виберіть його: Бібліотека → картка гри → ⋯ → %2$@\n", + .modelGameLog: "Журнал самої гри: %1$@\n", + .modelGameLogNone: "Журнал, який веде сама гра, не знайдено. TrailBridge читає журнали ігор на Unity та Unreal.\n", .modelSteamDirectLaunch: "Запускаємо саму гру, а не через Steam: %1$@\n", .modelGameBroughtForward: "Вікно гри знову попереду: багато ігор звучать, лише поки їхнє вікно на Mac попереду.\n", .modelGameBringForwardFailed: "Не вдалося повернути вікно гри наперед. Якщо в шоломі зник звук, клацніть вікно гри на Mac.\n", @@ -335,6 +337,10 @@ final class StringsUK: LocalizationTable { .streamReplay: "Грати знову", .streamReplayHelp: "Грати в %1$@ знову", .streamCannotReplay: "Ця гра не готова до запуску", + .streamGameLog: "Журнал гри", + .streamGameLogHelp: "Показати журнал гри %1$@", + .streamGameLogNote: "Уривок із журналу, який вела сама гра: останні рядки та кожен рядок із повідомленням про помилку, особисті дані замінено заглушками. Він зберігається лише на цьому Mac.", + .streamGameLogMissing: "Цього уривка більше немає на цьому Mac.", .streamUnknownError: "Невідома помилка", .streamHistoryFPS: "%1$.1f к/с", .streamHistoryLatency: "%1$.0f мс", @@ -776,6 +782,7 @@ final class StringsUK: LocalizationTable { .diagnosticsTitle: "Діагностичний звіт", .diagnosticsSubtitle: "Перегляньте звіт, перш ніж ним поділитися. TrailBridge ніколи не надсилає його.", .diagnosticsIncludeLog: "Додати журнал сеансу", + .diagnosticsIncludeGameLog: "Додати журнал гри", .diagnosticsRedaction: "Домашня тека та ім’я користувача, адреси пошти, ідентифікатори Steam, серійні номери й назви шоломів, мережеві назви Mac, IP- і MAC-адреси та токени замінюються заглушками. Значення змінних середовища профілю запуску не включаються до звіту.", .diagnosticsBugForm: "Повідомити про помилку", .diagnosticsBugFormHelp: "Відкриє GitHub у браузері; вставте скопійований звіт у поле журналів.", @@ -819,7 +826,7 @@ final class StringsUK: LocalizationTable { .sidebarDiagnostics: "Діагностика", .sidebarRecordingOn: "Запис увімкнено для %1$@", .recordingTitle: "Діагностичний запис", - .recordingIntro: "Запишіть сеанс, щоб з’ясувати, що його обмежувало. Запис вимкнено для кожної гри, доки ви не ввімкнете його тут. Файли залишаються на цьому Mac; TrailBridge ніколи їх не надсилає.", + .recordingIntro: "Запишіть сеанс, щоб з’ясувати, що його обмежувало. Кадри, журнал сеансу та відео записуються лише для ігор, для яких ви ввімкнули запис тут; уривок із журналу самої гри зберігається після кожного сеансу. Файли залишаються на цьому Mac; TrailBridge ніколи їх не надсилає.", .recordingReminder: "Діагностичний запис увімкнено для %1$@", .recordingOpen: "Відкрити «Діагностику»", .recordingGames: "Ігри", @@ -833,6 +840,9 @@ final class StringsUK: LocalizationTable { .recordingVideoFor: "Записувати відео для %1$@", .recordingList: "Записи", .recordingListEmpty: "Записів ще немає. Увімкніть запис для гри та зіграйте сеанс.", + .recordingGameLogNote: "В уривках із журналів ігор особисті дані замінено заглушками. Зі збережених без запису зберігаються останні %1$lld.", + .recordingGameLogFolder: "[тека гри]", + .recordingGameLogPossiblyIncomplete: "[… можливо, гра ще працювала, тому цей уривок може бути неповним …]", .recordingFolder: "Тека записів", .recordingTotal: "Загальний розмір: %1$@", .recordingDeleteAll: "Видалити всі", @@ -846,6 +856,7 @@ final class StringsUK: LocalizationTable { .recordingInProgress: "Триває запис", .recordingFileFrames: "Кадри (CSV)", .recordingFileLog: "Журнал сеансу", + .recordingFileGameLog: "Журнал гри", .recordingFileVideo: "Відео", .recordingFileVideoIndex: "Індекс відео", .recordingFileSize: "%1$@: %2$@", diff --git a/streamer/Sources/BasaltManagerKit/SessionHistory.swift b/streamer/Sources/BasaltManagerKit/SessionHistory.swift index d617490..6a04b2a 100644 --- a/streamer/Sources/BasaltManagerKit/SessionHistory.swift +++ b/streamer/Sources/BasaltManagerKit/SessionHistory.swift @@ -87,6 +87,10 @@ public struct SessionRecord: Codable, Equatable, Identifiable, Sendable { public var outcome: Outcome? public var failureReason: String? public var metrics: StreamMetricSummary + /// The excerpt of the game's own log saved for this session: a file name + /// in the data folder's `Diagnostics` folder, set once the game has + /// ended; nil when none was saved. + public var gameLog: String? public init(id: UUID = UUID(), profileName: String, settings: StreamLaunchSettings, startedAt: Date = Date()) { @@ -178,6 +182,24 @@ public struct SessionHistoryStore: Sendable { return try write(records) } + /// Changes the saved record with `id` where it stands and returns the + /// saved history. A history without that record, a missing or damaged + /// file included, is left as it is; one of a newer format throws, as in + /// `append`. + @discardableResult + public func update(_ id: UUID, _ change: (inout SessionRecord) -> Void) throws -> [SessionRecord] { + guard case .document(let document) = try contents() else { return [] } + guard document.formatVersion <= Document.currentFormatVersion else { + throw Failure.newerFormat(document.formatVersion) + } + var records = document.sessions.compactMap(\.value) + guard let index = records.firstIndex(where: { $0.id == id }) else { + return Array(records.prefix(limit)) + } + change(&records[index]) + return try write(records) + } + private enum Contents { /// No file: no session was recorded yet. case missing diff --git a/streamer/Sources/BasaltManagerKit/SessionMarker.swift b/streamer/Sources/BasaltManagerKit/SessionMarker.swift index b62b672..56d1777 100644 --- a/streamer/Sources/BasaltManagerKit/SessionMarker.swift +++ b/streamer/Sources/BasaltManagerKit/SessionMarker.swift @@ -342,6 +342,20 @@ public enum LeftoverSession { } public enum SessionTeardown { + /// Gives a pending operation time to finish while the main actor can + /// still publish its result. + @MainActor + public static func wait(upTo timeout: Duration, until done: () -> Bool) async { + let clock = ContinuousClock() + let deadline = clock.now + timeout + while !done() { + let now = clock.now + guard now < deadline else { return } + do { try await clock.sleep(until: min(deadline, now + .milliseconds(20))) } + catch { return } + } + } + /// Blocks until `done` answers true or `seconds` have passed; returns the /// last answer. For quitting, where the app waits for the streamer to /// restore the Mac's audio output, but never for long. diff --git a/streamer/Tests/BasaltBottleKitTests/FrameTraceSessionTests.swift b/streamer/Tests/BasaltBottleKitTests/FrameTraceSessionTests.swift index 6c67dbe..8d59dd7 100644 --- a/streamer/Tests/BasaltBottleKitTests/FrameTraceSessionTests.swift +++ b/streamer/Tests/BasaltBottleKitTests/FrameTraceSessionTests.swift @@ -98,6 +98,54 @@ final class FrameTraceSessionTests: XCTestCase { } } + func testTheGameLogTakesTheRecordingsNameOrOneOfItsOwn() throws { + let root = try temporaryDirectory() + let date = Date(timeIntervalSince1970: 1_735_689_600) + let excerpt = Data("==> C:\\users\\[user]\\Player.log <==\nline\n".utf8) + var env = ["BASALT_FRAME_TRACE": "1"] + let recording = try XCTUnwrap(FrameTraceSession.rewrite( + environment: &env, dataRoot: root, prefix: root.appendingPathComponent("prefix"), + profile: "game", now: date)) + + // A launch that records lends its name, so the excerpt is listed with it. + let saved = try XCTUnwrap(DiagnosticsStorage.saveGameLog( + excerpt, dataRoot: root, recording: recording, profile: "game", startedAt: Date())) + XCTAssertEqual(saved, recording.gameLog) + XCTAssertEqual(saved.lastPathComponent, "20250101T000000.000000Z-game.game.log") + XCTAssertEqual(try Data(contentsOf: saved), excerpt) + let mode = try FileManager.default.attributesOfItem(atPath: saved.path)[.posixPermissions] as? Int + XCTAssertEqual(mode, 0o600) + // An excerpt is never written over. + XCTAssertNil(DiagnosticsStorage.saveGameLog( + Data("other".utf8), dataRoot: root, recording: recording, profile: "game", startedAt: Date())) + XCTAssertEqual(try Data(contentsOf: saved), excerpt) + + // Any other launch gets a name from its start, never one already in use. + let own = try XCTUnwrap(DiagnosticsStorage.saveGameLog( + excerpt, dataRoot: root, recording: nil, profile: "game", startedAt: date)) + XCTAssertEqual(own.lastPathComponent, "20250101T000000.000001Z-game.game.log") + XCTAssertEqual(own.deletingLastPathComponent(), DiagnosticsStorage.directory(dataRoot: root)) + let next = try XCTUnwrap(DiagnosticsStorage.saveGameLog( + excerpt, dataRoot: root, recording: nil, profile: "game", startedAt: date)) + XCTAssertEqual(next.lastPathComponent, "20250101T000000.000002Z-game.game.log") + + XCTAssertNil(DiagnosticsStorage.saveGameLog( + excerpt, dataRoot: root, recording: nil, profile: "../game", startedAt: date)) + let missing = root.appendingPathComponent("missing") + XCTAssertNil(DiagnosticsStorage.saveGameLog( + excerpt, dataRoot: missing, recording: nil, profile: "game", startedAt: date)) + XCTAssertFalse(FileManager.default.fileExists(atPath: missing.path)) + + // Written whole under another name and renamed: nothing else is left, + // not even after a save that found its name taken. + XCTAssertEqual(try FileManager.default.contentsOfDirectory( + atPath: DiagnosticsStorage.directory(dataRoot: root).path).sorted(), [ + "20250101T000000.000000Z-game.console.log", "20250101T000000.000000Z-game.csv", + "20250101T000000.000000Z-game.game.log", "20250101T000000.000001Z-game.game.log", + "20250101T000000.000002Z-game.game.log", + ]) + } + func testStorageNeverCreatesTheDataRootAndOnlyCreatesTheFolderOnRequest() throws { let root = try temporaryDirectory() let missing = root.appendingPathComponent("missing") diff --git a/streamer/Tests/BasaltBottleKitTests/GameLogSearchTests.swift b/streamer/Tests/BasaltBottleKitTests/GameLogSearchTests.swift new file mode 100644 index 0000000..277eca7 --- /dev/null +++ b/streamer/Tests/BasaltBottleKitTests/GameLogSearchTests.swift @@ -0,0 +1,312 @@ +// SPDX-License-Identifier: MIT +import XCTest +@testable import BasaltBottleKit + +final class GameLogSearchTests: XCTestCase { + // MARK: - Unity + + func testFindsTheUnityPlayerLogOfTheWineUserButNotOfPublic() throws { + let prefix = try FakePrefix(test: self) + let exe = try prefix.unityGame(company: "Example Studio", product: "Electrician VR") + let start = Date() + let log = try prefix.write("users/steamuser/AppData/LocalLow/Example Studio/Electrician VR/Player.log") + // Public belongs to no one; a file there is not the game's. + try prefix.write("users/Public/AppData/LocalLow/Example Studio/Electrician VR/Player.log") + // Another game's folder beside it. + try prefix.write("users/steamuser/AppData/LocalLow/Example Studio/Other Game/Player.log") + + let files = GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start) + + XCTAssertEqual(files.map(\.url.path), [log.path]) + XCTAssertEqual(files.map(\.engine), [.unity]) + } + + func testOnlyLogsWrittenSinceTheGameStartedCountAndTheRunBeforeComesFirst() throws { + let prefix = try FakePrefix(test: self) + let exe = try prefix.unityGame(company: "Example Studio", product: "Electrician VR") + let folder = "users/steamuser/AppData/LocalLow/Example Studio/Electrician VR/" + let start = Date(timeIntervalSinceNow: -60) + let current = try prefix.write(folder + "Player.log", modified: start.addingTimeInterval(30)) + // The last session's log, which the player moved aside when it started. + let previous = try prefix.write(folder + "Player-prev.log", modified: start.addingTimeInterval(-600)) + let search = GameLogSearch(prefix: prefix.prefix, executable: exe) + + XCTAssertEqual(search.files(since: start).map(\.url.path), [current.path]) + // A player that ran twice in one session: both runs, the first one first. + try prefix.touch(previous, modified: start.addingTimeInterval(10)) + XCTAssertEqual(search.files(since: start).map(\.url.path), [previous.path, current.path]) + // A disk that keeps whole seconds may date a log just before the start. + try prefix.touch(previous, modified: start.addingTimeInterval(-1)) + XCTAssertEqual(search.files(since: start).map(\.url.path), [previous.path, current.path]) + try prefix.touch(previous, modified: start.addingTimeInterval(-GameLogSearch.timeSlack - 1)) + XCTAssertEqual(search.files(since: start).map(\.url.path), [current.path]) + XCTAssertEqual(search.files(since: start.addingTimeInterval(60)), []) + } + + func testOlderUnityVersionsWroteOutputLogInLocalLowOrBesideTheGame() throws { + let prefix = try FakePrefix(test: self) + let exe = try prefix.unityGame(company: "Example Studio", product: "Electrician VR") + let start = Date(timeIntervalSinceNow: -60) + // Unity 2017.2 to 2018. + let localLow = try prefix.write( + "users/steamuser/AppData/LocalLow/Example Studio/Electrician VR/output_log.txt", + modified: start.addingTimeInterval(10)) + // Unity 5 to 2017.1, which needs no app.info. + let beside = try prefix.write("Games/Electrician VR/ElectricianVR_Data/output_log.txt", + modified: start.addingTimeInterval(20)) + let search = GameLogSearch(prefix: prefix.prefix, executable: exe) + XCTAssertEqual(search.files(since: start).map(\.url.path), [localLow.path, beside.path]) + XCTAssertEqual(search.files(since: start).map(\.engine), [.unity, .unity]) + + try FileManager.default.removeItem(at: beside.deletingLastPathComponent().appendingPathComponent("app.info")) + try prefix.touch(localLow, modified: start.addingTimeInterval(-600)) + XCTAssertEqual(search.files(since: start).map(\.url.path), [beside.path]) + } + + func testALauncherUsesTheOnlyUnityPlayerBesideIt() throws { + let prefix = try FakePrefix(test: self) + let player = try prefix.unityGame(company: "Example Studio", product: "Electrician VR") + let launcher = try prefix.write("Games/Electrician VR/Launcher.exe") + let start = Date() + let log = try prefix.write("users/steamuser/AppData/LocalLow/Example Studio/Electrician VR/Player.log") + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: launcher).files(since: start) + .map(\.url.path), [log.path]) + + // Two players beside the launcher: neither is taken for it. + let second = player.deletingLastPathComponent().appendingPathComponent("Benchmark_Data/app.info") + try FileManager.default.createDirectory( + at: second.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("Example Studio\nElectrician VR".utf8).write(to: second) + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: launcher).files(since: start), []) + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: player).files(since: start) + .map(\.url.path), [log.path]) + } + + func testAppInfoNamesTheFolderAndNothingElse() throws { + let prefix = try FakePrefix(test: self) + let start = Date() + try prefix.write("users/steamuser/AppData/LocalLow/Example Studio/Electrician VR/Player.log") + // Windows line ends, a byte order mark and the case of the executable. + let exe = try prefix.unityGame(company: "Example Studio", product: "Electrician VR", + info: "\u{FEFF}Example Studio\r\nElectrician VR\r\n", + executable: "ElectricianVR.EXE", dataFolder: "ElectricianVR_Data") + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start).count, 1) + + let info = exe.deletingLastPathComponent().appendingPathComponent("ElectricianVR_Data/app.info") + let tooLarge = "Example Studio\nElectrician VR\n" + String(repeating: " ", count: GameLogSearch.maximumAppInfoBytes) + for text in ["Example Studio", "../..\nElectrician VR", "Example Studio\nElectrician VR/../x", "", tooLarge] { + try Data(text.utf8).write(to: info) + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start), [], + String(text.prefix(40))) + } + // Nor is an app.info that is a link read. + try FileManager.default.removeItem(at: info) + let elsewhere = prefix.root.appendingPathComponent("app.info") + try Data("Example Studio\nElectrician VR".utf8).write(to: elsewhere) + try FileManager.default.createSymbolicLink(at: info, withDestinationURL: elsewhere) + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start), []) + } + + // MARK: - Unreal + + func testFindsUnrealLogsInAppDataAndOnlyThenInTheGameFolder() throws { + let prefix = try FakePrefix(test: self) + let game = "Games/Blood Trail" + let shipping = try prefix.write(game + "/BTVR/Binaries/Win64/BTVR-Win64-Shipping.exe") + let launcher = try prefix.write(game + "/BloodTrail.exe") + try prefix.write(game + "/Engine/Binaries/Win64/CrashReportClient.exe") + let start = Date(timeIntervalSinceNow: -60) + let log = try prefix.write("users/steamuser/AppData/Local/BTVR/Saved/Logs/BTVR.log", + modified: start.addingTimeInterval(20)) + // The last run's log, renamed when this one started. + try prefix.write("users/steamuser/AppData/Local/BTVR/Saved/Logs/BTVR-backup-2026.11.20-10.00.00.log", + modified: start.addingTimeInterval(-3600)) + try prefix.write("users/steamuser/AppData/Local/BTVR/Saved/Logs/notes.txt") + try prefix.write("users/steamuser/AppData/Local/Engine/Saved/Logs/Engine.log") + // Beside the game, and older here than the log in AppData. + let beside = try prefix.write(game + "/BTVR/Saved/Logs/BTVR.log", modified: start.addingTimeInterval(10)) + + for exe in [shipping, launcher] { + let files = GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start) + XCTAssertEqual(files.map(\.url.path), [log.path], exe.lastPathComponent) + XCTAssertEqual(files.map(\.engine), [.unreal], exe.lastPathComponent) + } + + // A game that keeps its logs beside itself. + try prefix.touch(log, modified: start.addingTimeInterval(-600)) + for exe in [shipping, launcher] { + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start) + .map(\.url.path), [beside.path], exe.lastPathComponent) + } + } + + func testALauncherBesideSeveralProjectsTakesTheOneNamedLikeIt() throws { + let prefix = try FakePrefix(test: self) + let game = "Games/Blood Trail" + let launcher = try prefix.write(game + "/BTVR.exe") + try prefix.write(game + "/BTVR/Binaries/Win64/BTVR-Win64-Shipping.exe") + try prefix.write(game + "/Benchmark/Binaries/Win64/Benchmark-Win64-Shipping.exe") + let start = Date() + let log = try prefix.write("users/steamuser/AppData/Local/BTVR/Saved/Logs/BTVR.log") + try prefix.write("users/steamuser/AppData/Local/Benchmark/Saved/Logs/Benchmark.log") + + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: launcher).files(since: start) + .map(\.url.path), [log.path]) + // Named like neither: both are read. + let other = try prefix.write(game + "/Play.exe") + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: other).files(since: start).count, 2) + } + + // MARK: - Neither, and what is never read + + func testOtherGamesLinksAndPipesGiveNothing() throws { + let prefix = try FakePrefix(test: self) + let start = Date() + let other = try prefix.write("Games/Custom/Custom.exe") + try prefix.write("Games/Custom/custom.log") + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: other).files(since: start), []) + + // A log that is a link to a file elsewhere on the Mac is not read. + let exe = try prefix.unityGame(company: "Example Studio", product: "Electrician VR") + let outside = prefix.root.appendingPathComponent("outside.log") + try Data("private\n".utf8).write(to: outside) + let folder = prefix.driveC.appendingPathComponent( + "users/steamuser/AppData/LocalLow/Example Studio/Electrician VR", isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: folder.appendingPathComponent("Player.log"), withDestinationURL: outside) + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start), []) + + // Nor is a pipe, which would wait for a writer forever. + try FileManager.default.removeItem(at: folder.appendingPathComponent("Player.log")) + XCTAssertEqual(mkfifo(folder.appendingPathComponent("Player.log").path, 0o600), 0) + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start), []) + + // Nor a log folder that is a link out of the prefix. + let elsewhere = prefix.root.appendingPathComponent("elsewhere", isDirectory: true) + try FileManager.default.createDirectory(at: elsewhere, withIntermediateDirectories: true) + try Data("private\n".utf8).write(to: elsewhere.appendingPathComponent("Player.log")) + try FileManager.default.removeItem(at: folder) + try FileManager.default.createSymbolicLink(at: folder, withDestinationURL: elsewhere) + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start), []) + + // A prefix without users has no logs to read. + try FileManager.default.removeItem(at: prefix.driveC.appendingPathComponent("users")) + XCTAssertEqual(GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start), []) + } + + func testALogIsCheckedAgainWhenItIsOpened() throws { + let prefix = try FakePrefix(test: self) + let exe = try prefix.unityGame(company: "Example Studio", product: "Electrician VR") + let start = Date() + let log = try prefix.write("users/steamuser/AppData/LocalLow/Example Studio/Electrician VR/Player.log") + let file = try XCTUnwrap(GameLogSearch(prefix: prefix.prefix, executable: exe).files(since: start).first) + + let opened = try XCTUnwrap(file.open()) + XCTAssertEqual(opened.size, 5) + XCTAssertEqual(try opened.handle.readToEnd(), Data("line\n".utf8)) + + // The same file must still have been written during this session. + try prefix.touch(log, modified: start.addingTimeInterval(-60)) + XCTAssertNil(file.open()) + try prefix.touch(log, modified: start) + XCTAssertNotNil(file.open()) + + // A fresh regular file at the same path belongs to a different run. + let moved = log.deletingLastPathComponent().appendingPathComponent("moved.log") + try FileManager.default.moveItem(at: log, to: moved) + try Data("new run\n".utf8).write(to: log) + XCTAssertNil(file.open()) + + // Swapped for a link after it was found. + let outside = prefix.root.appendingPathComponent("outside.log") + try Data("private\n".utf8).write(to: outside) + try FileManager.default.removeItem(at: log) + try FileManager.default.createSymbolicLink(at: log, withDestinationURL: outside) + XCTAssertNil(file.open()) + + // Moving the original file with its root cannot change the allowed root. + try FileManager.default.removeItem(at: log) + try FileManager.default.moveItem(at: moved, to: log) + let movedRoot = prefix.root.appendingPathComponent("moved-prefix", isDirectory: true) + try FileManager.default.moveItem(at: prefix.prefix, to: movedRoot) + try FileManager.default.createSymbolicLink(at: prefix.prefix, withDestinationURL: movedRoot) + XCTAssertNil(file.open()) + } + + // MARK: - A profile's launch + + func testTheLaunchCommandSaysWhereTheGameWritesItsLog() throws { + let steam = try SteamPrefix(test: self) + let install = try steam.install(appID: "3256020", folder: "Electrician Simulator VR", files: [ + "Electrician Simulator VR.exe", "Electrician Simulator VR_Data/", + ]) + let manager = try steam.manager(bottleName: "Steam") + let control = steam.root.appendingPathComponent("control") + try Data("123 token".utf8).write(to: control) + try manager.saveProfile(LaunchProfile( + name: "steam", bottleName: "Steam", source: .steam, + executable: #"C:\Program Files (x86)\Steam\steam.exe"#, arguments: ["-applaunch", "3256020"])) + try manager.saveProfile(LaunchProfile( + name: "direct", bottleName: "Steam", source: .direct, + executable: #"C:\Program Files (x86)\Steam\steamapps\common\Electrician Simulator VR\Electrician Simulator VR.exe"#)) + let expected = install.appendingPathComponent("Electrician Simulator VR.exe").standardizedFileURL.path + + for name in ["steam", "direct"] { + let search = try XCTUnwrap(manager.profileLaunchCommand(name, controlFile: control).gameLog, name) + XCTAssertEqual(search.executable.path, expected, name) + XCTAssertEqual(search.prefix.path, steam.prefix.standardizedFileURL.path, name) + } + // A drive the prefix does not map is no path on this Mac. + try manager.saveProfile(LaunchProfile( + name: "elsewhere", bottleName: "Steam", source: .direct, executable: #"D:\Games\Game.exe"#)) + XCTAssertNil(try manager.profileLaunchCommand("elsewhere", controlFile: control).gameLog) + } +} + +/// A prefix with a Windows user, `steamuser`, and `Public`. +private struct FakePrefix { + let root: URL + let prefix: URL + var driveC: URL { prefix.appendingPathComponent("drive_c", isDirectory: true) } + + init(test: XCTestCase) throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + "BasaltGameLogSearch-\(UUID().uuidString)", isDirectory: true) + test.addTeardownBlock { try? FileManager.default.removeItem(at: directory) } + root = directory + prefix = directory.appendingPathComponent("Bottles/game/prefix", isDirectory: true) + for user in ["Public", "steamuser"] { + try FileManager.default.createDirectory( + at: driveC.appendingPathComponent("users/\(user)/AppData", isDirectory: true), + withIntermediateDirectories: true) + } + } + + /// A file in drive_c, written now unless `modified` says otherwise. + @discardableResult + func write(_ path: String, modified: Date? = nil) throws -> URL { + let url = driveC.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("line\n".utf8).write(to: url) + if let modified { try touch(url, modified: modified) } + return url + } + + func touch(_ url: URL, modified: Date) throws { + try FileManager.default.setAttributes([.modificationDate: modified], ofItemAtPath: url.path) + } + + /// A Unity player: `Game.exe` beside `Game_Data/app.info`. + func unityGame(company: String, product: String, info: String? = nil, + executable: String = "ElectricianVR.exe", + dataFolder: String = "ElectricianVR_Data") throws -> URL { + let exe = try write("Games/Electrician VR/" + executable) + let appInfo = exe.deletingLastPathComponent().appendingPathComponent(dataFolder + "/app.info") + try FileManager.default.createDirectory( + at: appInfo.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data((info ?? "\(company)\n\(product)").utf8).write(to: appInfo) + return exe + } +} diff --git a/streamer/Tests/BasaltManagerKitTests/DiagnosticRecordingTests.swift b/streamer/Tests/BasaltManagerKitTests/DiagnosticRecordingTests.swift index 4321eb6..110dc18 100644 --- a/streamer/Tests/BasaltManagerKitTests/DiagnosticRecordingTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/DiagnosticRecordingTests.swift @@ -260,6 +260,12 @@ final class DiagnosticRecordingTests: XCTestCase { XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".csv")?.stem, stem) XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".csv")?.kind, .frames) XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".console.log")?.kind, .sessionLog) + XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".game.log")?.kind, .gameLog) + XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".game.log")?.stem, stem) + // A profile may end in ".game" or ".console" itself. + XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".game.console.log")?.stem, stem + ".game") + XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".console.game.log")?.stem, stem + ".console") + XCTAssertNil(DiagnosticRecordingStore.parse(fileName: stem + ".log")) XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".hevc")?.kind, .video) XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".h264")?.kind, .video) XCTAssertEqual(DiagnosticRecordingStore.parse(fileName: stem + ".hevc.index.csv")?.kind, .videoIndex) diff --git a/streamer/Tests/BasaltManagerKitTests/DiagnosticRedactionTests.swift b/streamer/Tests/BasaltManagerKitTests/DiagnosticRedactionTests.swift index f3bfcf7..4b4b35f 100644 --- a/streamer/Tests/BasaltManagerKitTests/DiagnosticRedactionTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/DiagnosticRedactionTests.swift @@ -114,6 +114,48 @@ final class DiagnosticRedactionTests: XCTestCase { #"C:\users\[user]\Saved Games\Blood Trail"#) } + /// A game's own log, written inside its Wine prefix: Unity prints + /// Windows paths with forward slashes, Unreal names the Windows user and + /// computer, which Wine takes from the Mac. + func testRedactsWindowsPathsAndNamesInAGamesOwnLog() { + let redactor = makeRedactor(hostNames: ["Adas-Mac-mini"]) + let expected = [ + "Logging to C:/users/ada/AppData/LocalLow/Example Studio/Game/Player.log": + "Logging to C:/users/[user]/AppData/LocalLow/Example Studio/Game/Player.log", + // A bottle made on another Mac or by another app. + "C:/users/steamuser/AppData/Local/BTVR/Saved/Logs/BTVR.log": + "C:/users/[user]/AppData/Local/BTVR/Saved/Logs/BTVR.log", + #"C:\Users\crossover\AppData\LocalLow\Game"#: #"C:\Users\[user]\AppData\LocalLow\Game"#, + // The Mac's own folders through Wine's Z: drive, either way round. + #"Z:\Users\ada\Games\Game.exe"#: #"Z:\Users\[user]\Games\Game.exe"#, + "Z:/Users/ada/Games/Game.exe": "Z:/Users/[user]/Games/Game.exe", + "Z:/Users/bob/Games/Game.exe": "Z:/Users/[user]/Games/Game.exe", + #"Z:\\Users\\ada\\Games"#: #"Z:\\Users\\[user]\\Games"#, + "C:/users/Public/Documents/Game": "C:/users/Public/Documents/Game", + "[2026.11.25-10.00.00:000][ 0]LogInit: Computer: ADAS-MAC-MINI": + "[2026.11.25-10.00.00:000][ 0]LogInit: Computer: [host]", + // Windows keeps 15 characters of a longer name. + "[2026.11.25-10.00.00:000][ 0]LogInit: Computer: IVANS-MACBOOK-P": + "[2026.11.25-10.00.00:000][ 0]LogInit: Computer: [host]", + "[2026.11.25-10.00.00:000][ 0]LogInit: User: ada": + "[2026.11.25-10.00.00:000][ 0]LogInit: User: [user]", + "LogInit: User: steamuser": "LogInit: User: [user]", + // A name with a space or in quotes is replaced whole. + #"C:\users\Jane Doe\AppData\Local\BTVR"#: #"C:\users\[user]\AppData\Local\BTVR"#, + "C:/Users/Jane Doe/AppData/Local/BTVR": "C:/Users/[user]/AppData/Local/BTVR", + #"Z:\Users\Jane O'Brien (Work)\Games"#: #"Z:\Users\[user]\Games"#, + #"L"C:\\users\\Jane Doe\\Saved""#: #"L"C:\\users\\[user]\\Saved""#, + "| C:\\users\\Jane Doe | ok |": "| C:\\users\\[user] | ok |", + #"LogInit: User: "Jane Doe""#: "LogInit: User: [user]", + "LogInit: User: Jane Doe": "LogInit: User: [user]", + "LogInit: Computer: 'Jane Doe's Mac'\nLogInit: CPU Page size=4096": + "LogInit: Computer: [host]\nLogInit: CPU Page size=4096", + ] + for (text, redacted) in expected { + XCTAssertEqual(redactor.redact(text), redacted) + } + } + /// The exact lines of BasaltStreamer/App.swift and /// BasaltCore/GameAudioCapture.swift that print a CoreAudio device name. func testRedactsAudioDeviceNamesInStreamerLines() { @@ -212,6 +254,36 @@ final class DiagnosticRedactionTests: XCTestCase { } } + func testRedactsSteamIDsAndCompleteIdentityValues() { + let redactor = makeRedactor() + let log = #""" + Steam owner 76561190000000000, 76561200000000000, STEAM_0:0:0, STEAM_5:1:42, [U:1:0] + Username: Jane Doe + User name: Jane "JJ" Doe + Account: Jane O'Brien; personal + Login: CORP\Robert Example + Nickname and Username: "Jane" Doe + Persona name=Jane Doe + Serial number: Example 42 + Next line + """# + XCTAssertEqual(redactor.redact(log), """ + Steam owner [steamid], [steamid], [steamid], [steamid], [steamid] + Username: [redacted] + User name: [redacted] + Account: [redacted] + Login: [redacted] + Nickname and Username: [redacted] + Persona name=[redacted] + Serial number: [redacted] + Next line + """) + let otherNumbers = "AppID 3256020, counters 7656120000000000 and 765612000000000000" + XCTAssertEqual(redactor.redact(otherNumbers), otherNumbers) + XCTAssertEqual(redactor.redact(#""Account: \"Jane\" Doe\nNext line""#), + #""Account: [redacted]\nNext line""#) + } + func testKeepsUsefulDiagnosticContent() { let redactor = makeRedactor( dataFolder: Self.dataFolder, appFolder: Self.appFolder, diff --git a/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift b/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift index 6c1fff4..68334bf 100644 --- a/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift @@ -223,6 +223,43 @@ final class DiagnosticsTests: XCTestCase { func testReportCanLeaveOutTheLog() { let markdown = makeReport(log: nil).markdown(redactedWith: redactor) XCTAssertTrue(markdown.contains("### Session log\n\nNot included.")) + XCTAssertTrue(markdown.contains("### Game log\n\nNot included.")) + } + + func testReportShowsTheGamesOwnLog() throws { + let excerpt = #""" + ==> C:\users\[user]\AppData\LocalLow\Example Studio\Electrician VR\Player.log <== + [… 812 lines skipped …] + WindowsVideoMedia error 0xc00d36bb while reading C:/Games/sharedassets0.resource + ``` + + """# + var report = makeReport(log: nil) + report.gameLog = DiagnosticReport.GameLog(profileName: "electrician", excerpt: excerpt) + let markdown = report.markdown(redactedWith: redactor) + XCTAssertTrue(markdown.contains(""" + ### Game log + +
Excerpt from electrician: 4 lines + + ````text + ==> C:\\users\\[user]\\AppData\\LocalLow\\Example Studio\\Electrician VR\\Player.log <== + [… 812 lines skipped …] + WindowsVideoMedia error 0xc00d36bb while reading C:/Games/sharedassets0.resource + ``` + ```` + +
+ """), markdown) + let object = try XCTUnwrap(JSONSerialization.jsonObject( + with: Data(try report.json(redactedWith: redactor).utf8)) as? [String: Any]) + let gameLog = try XCTUnwrap(object["gameLog"] as? [String: Any]) + XCTAssertEqual(gameLog["profileName"] as? String, "electrician") + XCTAssertEqual((gameLog["lines"] as? [String])?.count, 4) + + report.gameLog = DiagnosticReport.GameLog(profileName: "electrician", excerpt: nil) + XCTAssertTrue(report.markdown(redactedWith: redactor) + .contains("### Game log\n\nNo log of the game was found.")) } func testReportSaysWhenSetupHasNotRun() { diff --git a/streamer/Tests/BasaltManagerKitTests/GameLogExcerptTests.swift b/streamer/Tests/BasaltManagerKitTests/GameLogExcerptTests.swift new file mode 100644 index 0000000..b12b5cb --- /dev/null +++ b/streamer/Tests/BasaltManagerKitTests/GameLogExcerptTests.swift @@ -0,0 +1,604 @@ +// SPDX-License-Identifier: MIT +import XCTest +import BasaltBottleKit +@testable import BasaltManagerKit + +final class GameLogExcerptTests: XCTestCase { + /// Nothing is read from the Mac the tests run on. + private let redactor = DiagnosticRedactor( + homeDirectory: "/Users/ada", userName: "ada", dataFolder: nil, appFolder: nil, + hostNames: [], volumeNames: []) + + // MARK: - Choosing the lines + + func testAShortLogIsKeptWhole() { + XCTAssertEqual(excerpt([("Player.log", "first\nsecond\r\nthird")]).text, + "==> Player.log <==\nfirst\nsecond\nthird\n") + XCTAssertEqual(excerpt([("Player.log", "")]).text, "==> Player.log <==\n") + } + + func testKeepsTheLastLinesAndEveryErrorInTheirOrder() { + var lines = (0..<1000).map { "line \($0)" } + lines[10] = "line 10 NullReferenceException: Object reference not set to an instance of an object" + lines[500] = "line 500 WindowsVideoMedia error 0xc00d36bb while reading sharedassets0.resource" + lines[799] = "line 799 LogD3D11RHI: Error: device removed" + lines[850] = "line 850 Failed to load 'aqProf.dll'" + + let text = excerpt([("Player.log", lines.joined(separator: "\n") + "\n")]).text + XCTAssertEqual(text, (["==> Player.log <==", "[… 10 lines skipped …]", lines[10], + "[… 489 lines skipped …]", lines[500], "[… 298 lines skipped …]", lines[799]] + + lines[800...]).joined(separator: "\n") + "\n") + // A gap of one line says so. + lines[798] = "line 798 error" + lines[799] = "line 799" + XCTAssertTrue(excerpt([("Player.log", lines.joined(separator: "\n"))]).text + .contains("\nline 798 error\n[… 1 line skipped …]\nline 800\n")) + } + + func testLinesThatReportErrors() { + let errors = [ + "WindowsVideoMedia error 0xc00d36bb while reading C:/Games/data.resource", + "Error details: Unexpected error.", + "NullReferenceException: Object reference not set to an instance of an object", + "[XR] xrCreateSession: XR_ERROR_RUNTIME_FAILURE", + "[2026.11.25-10.00.00:000][ 0]LogWindows: Error: Fatal error!", + "Failed to load 'aqProf.dll' (GetLastError=126)", + "D3D11: FAILED to create the device", + "Assertion failed on expression: 'IsMatrixValid(matrix)'", + "FATAL: out of memory", + "DllNotFoundException: GfxPluginNativeRenderer", + ] + let others = [ + "Terror of the deep: chapter 2", + "Fallback handler could not load library", + "Initialize engine version: 6000.0.58f2", + // The runtime refuses the first API version Unity asks for; Unity + // then asks for 1.0 and the session works. + "Basalt OpenXR: unsupported application API version 1.1.45 (runtime supports OpenXR 1.0)", + "Errands are done", + "", + ] + for line in errors { XCTAssertTrue(GameLogExcerpt.reportsError(Substring(line)), line) } + for line in others { XCTAssertFalse(GameLogExcerpt.reportsError(Substring(line)), line) } + } + + func testTheWholeTextStaysWithinItsSize() { + // An error every frame, then long lines at the end. + let flood = (0..<5000).map { "NullReferenceException at frame \($0) " + String(repeating: "x", count: 60) } + let tail = (0.. Player.log <==\nerror 0\n[… 1 line skipped …]\nerror 2\n")) + XCTAssertTrue(gaps.hasSuffix("\nok 39999\n")) + + // Names a placeholder makes longer, in several logs that were not read whole. + let wide = (0..<3000).map { "error at C:/users/x/\($0)" }.joined(separator: "\n") + let several = GameLogExcerpt(logs: (0..<3).map { + GameLogExcerpt.Log(engine: .unity, label: "Player-\($0).log", text: wide, unreadBytes: 1 << 30) + }, redactedWith: redactor).text + XCTAssertLessThanOrEqual(several.utf8.count, GameLogExcerpt.maximumBytes) + XCTAssertTrue(several.contains("error at C:/users/[user]/0\n")) + XCTAssertEqual(several.components(separatedBy: "[… earlier lines not read: 1073741824 bytes …]").count, 4) + } + + func testLongLinesAreRedactedWholeOrLeftOutWhole() { + // A name that a cut at 4 KB would have split, after a disk name the + // redactor makes much shorter. + let crossing = "/Volumes/" + String(repeating: "x", count: 3978) + "/ owner 76561190000000042 " + + String(repeating: "y", count: 3000) + // One byte more than is read of a line, with the same name in it. + let tooLong = "owner 76561190000000042 " + + String(repeating: "z", count: GameLogExcerpt.maximumReadLineBytes - 24 + 1) + let longest = String(repeating: "w", count: GameLogExcerpt.maximumReadLineBytes) + let wide = String(repeating: "\u{E9}", count: 1200) + XCTAssertEqual(tooLong.utf8.count, GameLogExcerpt.maximumReadLineBytes + 1) + let text = excerpt([("Player.log", [crossing, tooLong, longest, wide, "short"].joined(separator: "\n"))]).text + let lines = text.split(separator: "\n").map(String.init) + + XCTAssertEqual(lines.count, 6) + XCTAssertFalse(text.contains("76561"), text) + let head = "/Volumes/[disk]/ owner [steamid] " + XCTAssertEqual(lines[1], head + String(repeating: "y", count: GameLogExcerpt.maximumLineBytes - head.utf8.count) + "…") + XCTAssertEqual(lines[2], "[long line omitted: \(GameLogExcerpt.maximumReadLineBytes + 1) bytes]") + XCTAssertEqual(lines[3], String(repeating: "w", count: GameLogExcerpt.maximumLineBytes) + "…") + // Cut between characters, never inside one. + XCTAssertEqual(lines[4], String(repeating: "\u{E9}", count: GameLogExcerpt.maximumLineBytes / 2) + "…") + XCTAssertEqual(lines[5], "short") + + // Whether a line reports an error is judged on all of it, also when + // it is too long to keep. + let late = String(repeating: "v", count: GameLogExcerpt.maximumReadLineBytes) + " Fatal error" + let early = ([late] + (0.. Player.log <==\n[long line omitted: \(late.utf8.count) bytes]\nline 0\n")) + } + + func testReadsSeveralLogsOldestFirst() { + var previous = (0..<150).map { "prev \($0)" } + previous[10] = "prev 10 error" + let current = (0..<100).map { "now \($0)" } + let text = excerpt([ + ("Player-prev.log", previous.joined(separator: "\n") + "\n"), + // The last line of the newer log has no line break yet. + ("Player.log", current.joined(separator: "\n")), + ]).text + XCTAssertEqual(text, (["==> Player-prev.log <==", "[… 10 lines skipped …]", previous[10], + "[… 39 lines skipped …]"] + previous[50...] + ["==> Player.log <=="] + current) + .joined(separator: "\n") + "\n") + + // A log whose lines are all left out still has its header. + let quiet = excerpt([("old.log", "one\ntwo\n"), ("new.log", (0..<300).map { "n\($0)" }.joined(separator: "\n"))]) + XCTAssertTrue(quiet.text.hasPrefix( + "==> old.log <==\n[… 2 lines skipped …]\n==> new.log <==\n[… 100 lines skipped …]\nn100\n")) + } + + func testOmittedLongErrorsLeaveRoomForLaterErrors() { + let longError = "Fatal error " + String(repeating: "x", count: GameLogExcerpt.maximumReadLineBytes) + let early = Array(repeating: longError, count: 80) + ["Error: later cause", "ok"] + let tail = (0.. Player.log <==\n[… earlier lines not read: \(read.unreadBytes) bytes …]\nline ")) + } + + // MARK: - Reading a game's logs + + func testCollectsTheUnityPlayerLogWithPersonalDataReplaced() throws { + let game = try UnityPrefix(test: self) + let start = Date() + try game.writeLog("Player.log", """ + Mono path[0] = 'C:/Program Files (x86)/Steam/steamapps/common/Electrician VR/ElectricianVR_Data/Managed' + Logging to C:/users/steamuser/AppData/LocalLow/Example Studio/Electrician VR/Player.log + Data folder: Z:\\Users\\ada\\TrailBridge\\data and Z:/Users/ada/Games + Steam user 76561190000000042 signed in + Basalt OpenXR: unsupported application API version 1.1.45 (runtime supports OpenXR 1.0) + WindowsVideoMedia error 0xc00d36bb while reading C:/Program Files (x86)/Steam/steamapps/common/Electrician VR/ElectricianVR_Data/sharedassets0.resource + + Context: CreateObjectFromByteStream + Error details: Unexpected error. + + """) + + let excerpt = try XCTUnwrap(GameLogExcerpt.collect(game.search, since: start, redactedWith: redactor)) + + // The header and the source name the log as the game does, never by its path on this Mac. + let path = #"C:\users\[user]\AppData\LocalLow\Example Studio\Electrician VR\Player.log"# + XCTAssertEqual(excerpt.sources, [GameLogExcerpt.Source(engine: .unity, path: path)]) + XCTAssertTrue(excerpt.text.hasPrefix("==> \(path) <==\nMono path[0] = 'C:/Program Files (x86)/")) + for kept in [ + "WindowsVideoMedia error 0xc00d36bb while reading C:/Program Files (x86)/Steam/steamapps/common/" + + "Electrician VR/ElectricianVR_Data/sharedassets0.resource\n\nContext: CreateObjectFromByteStream\n", + "\nLogging to C:/users/[user]/AppData/LocalLow/Example Studio/Electrician VR/Player.log\n", + "\nData folder: Z:\\Users\\[user]\\TrailBridge\\data and Z:/Users/[user]/Games\n", + "\nSteam user [steamid] signed in\n", + ] { + XCTAssertTrue(excerpt.text.contains(kept), kept) + } + for leaked in ["steamuser", "/ada", "\\ada", "7656119", game.prefix.path] { + XCTAssertFalse(excerpt.text.contains(leaked), leaked) + } + + // A game that wrote nothing since it started has no excerpt. + XCTAssertNil(GameLogExcerpt.collect(game.search, since: Date(timeIntervalSinceNow: 60), + redactedWith: redactor)) + } + + /// A Windows user whose name has a space, and the names Unreal prints + /// with or without quotes: none of it reaches the saved excerpt or a + /// report made from it. + func testNamesWithSpacesAndQuotesReachNeitherTheExcerptNorTheReport() throws { + let root = try temporaryDirectory() + let prefix = root.appendingPathComponent("prefix", isDirectory: true) + let driveC = prefix.appendingPathComponent("drive_c", isDirectory: true) + let exe = driveC.appendingPathComponent("Games/Blood Trail/BTVR/Binaries/Win64/BTVR-Win64-Shipping.exe") + let logs = driveC.appendingPathComponent("users/Jane Doe/AppData/Local/BTVR/Saved/Logs", isDirectory: true) + for folder in [exe.deletingLastPathComponent(), logs, driveC.appendingPathComponent("users/Public")] { + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + } + try Data().write(to: exe) + let start = Date() + try Data(""" + [2026.11.25-10.00.00:000][ 0]LogInit: Computer: "JANE-DOE-MAC" + [2026.11.25-10.00.00:000][ 0]LogInit: User: "Jane Doe" + LogInit: User: Jane Doe + LogInit: Computer: 'Jane Doe's Mac' + Username: Jane Doe + User name: Jane "JJ" Doe + Account: Jane O'Brien; personal + Steam IDs 76561190000000000 76561200000000000 STEAM_0:1:0 [U:1:0] + LogPlatformFile: Using C:/Users/Jane Doe/AppData/Local/BTVR/Saved/Config + LogWindows: Error: Could not open C:\\users\\Jane Doe\\AppData\\Local\\BTVR\\Saved\\x.sav + + """.utf8).write(to: logs.appendingPathComponent("BTVR.log")) + let run = GameLogRun( + search: GameLogSearch(prefix: prefix, executable: exe), gameStartedAt: start, + profileName: "blood-trail", sessionID: UUID(), sessionStartedAt: start, recording: nil, + dataRoot: try symlinkFreeDirectory()) + + let saved = try XCTUnwrap(run.save(redactedWith: redactor)) + let file = try XCTUnwrap(saved.file) + let text = try String(contentsOf: file, encoding: .utf8) + XCTAssertEqual(text, saved.excerpt.text) + XCTAssertEqual(saved.excerpt.sources.map(\.path), [#"C:\users\[user]\AppData\Local\BTVR\Saved\Logs\BTVR.log"#]) + for kept in ["LogInit: Computer: [host]\n", "LogInit: User: [user]\n", + "Username: [redacted]\n", "User name: [redacted]\n", "Account: [redacted]\n", + "Steam IDs [steamid] [steamid] [steamid] [steamid]\n", + "Using C:/Users/[user]/AppData/Local/BTVR/Saved/Config\n", + #"Could not open C:\users\[user]\AppData\Local\BTVR\Saved\x.sav"#] { + XCTAssertTrue(text.contains(kept), kept) + } + + var record = SessionRecord(profileName: "blood-trail", settings: StreamLaunchSettings()) + record.gameLog = file.lastPathComponent + let report = DiagnosticReport( + application: .init(version: "0.2.1", build: nil, sourceRevision: nil), + system: .init(operatingSystem: "macOS 26.0", hardwareModel: nil, chip: nil, architecture: "arm64", + memoryGigabytes: 16, processorCount: 8, thermalState: "nominal", lowPowerMode: false), + setupChecks: [], engines: [], bottles: [], profiles: [], + defaultStreamSettings: StreamLaunchSettings(), profileStreamSettings: [:], + currentSession: .init(state: "stopped"), recentSessions: [record], log: nil, + gameLog: .current(running: nil, history: [record], dataRoot: run.dataRoot, redactedWith: redactor)) + let markdown = report.markdown(redactedWith: redactor) + let json = try report.json(redactedWith: redactor) + XCTAssertTrue(markdown.contains("LogInit: User: [user]")) + XCTAssertNotNil(try JSONSerialization.jsonObject(with: Data(json.utf8))) + for output in [text, markdown, json] { + for leaked in ["Jane", "Doe", "JANE", "76561190000000000", "76561200000000000", "STEAM_0:1:0", "[U:1:0]"] { + XCTAssertFalse(output.contains(leaked), "\(leaked) in \(output)") + } + } + } + + // MARK: - Saving + + @MainActor + func testCaptureWaitYieldsToCompletionAndHasATimeout() async { + var finished = false + Task { finished = true } + await SessionTeardown.wait(upTo: .seconds(1)) { finished } + XCTAssertTrue(finished) + + let clock = ContinuousClock() + let start = clock.now + await SessionTeardown.wait(upTo: .milliseconds(25)) { false } + XCTAssertGreaterThanOrEqual(start.duration(to: clock.now), .milliseconds(25)) + } + + func testExternalUnrealLogUsesTheGameFolderLabelInTheExcerptAndReport() throws { + let root = try temporaryDirectory() + let prefix = root.appendingPathComponent("prefix", isDirectory: true) + let game = root.appendingPathComponent("Example Library/Private Install", isDirectory: true) + let executablePath = "Example/Binaries/Win64/Example.exe" + let exe = game.appendingPathComponent(executablePath) + let log = game.appendingPathComponent("Example/Saved/Logs/Example.log") + for folder in [exe.deletingLastPathComponent(), log.deletingLastPathComponent()] { + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + } + try Data().write(to: exe) + let alias = root.appendingPathComponent("Launch Alias", isDirectory: true) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: game) + let start = Date() + let windowsPath = "Z:" + game.path.replacingOccurrences(of: "/", with: #"\"#) + try Data(""" + Loading \(game.path)/Example/Content + Error: \(windowsPath)\\Example\\Content + Loading Z:\(game.path)/Example/Content + Loading \(alias.standardizedFileURL.path)/Example/Content + + """.utf8).write(to: log) + let run = GameLogRun( + search: GameLogSearch(prefix: prefix, executable: alias.appendingPathComponent(executablePath)), + gameStartedAt: start, + profileName: "example", sessionID: UUID(), sessionStartedAt: start, recording: nil, + dataRoot: try symlinkFreeDirectory()) + let saved = try XCTUnwrap(run.save(redactedWith: redactor, wineMayBeRunning: true)) + let file = try XCTUnwrap(saved.file) + let label = #"[game folder]\Example\Saved\Logs\Example.log"# + XCTAssertEqual(saved.excerpt.sources.map(\.path), [label]) + XCTAssertEqual(try String(contentsOf: file, encoding: .utf8), """ + [… the game may still have been running; this excerpt can be incomplete …] + ==> \(label) <== + Loading [game folder]/Example/Content + Error: [game folder]\\Example\\Content + Loading [game folder]/Example/Content + Loading [game folder]/Example/Content + + """) + var record = SessionRecord(profileName: "example", settings: StreamLaunchSettings()) + record.gameLog = file.lastPathComponent + let report = DiagnosticReport.GameLog.current( + running: nil, history: [record], dataRoot: run.dataRoot, redactedWith: redactor) + XCTAssertTrue(report.lines.contains("==> \(label) <==")) + XCTAssertFalse(report.lines.joined().contains("Private Install")) + } + + func testUnrealFallbackAndFileLimitCountOnlyReadableTextLogs() throws { + let root = try temporaryDirectory() + let prefix = root.appendingPathComponent("prefix", isDirectory: true) + let exe = prefix.appendingPathComponent("drive_c/Games/Example/Example/Binaries/Win64/Example.exe") + let appData = prefix.appendingPathComponent("drive_c/users/steamuser/AppData/Local/Example/Saved/Logs") + let install = prefix.appendingPathComponent("drive_c/Games/Example/Example/Saved/Logs") + for folder in [exe.deletingLastPathComponent(), appData, install] { + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + } + try Data().write(to: exe) + let search = GameLogSearch(prefix: prefix, executable: exe) + let start = Date() + func write(_ data: Data, named name: String, in folder: URL, at seconds: TimeInterval) throws { + let file = folder.appendingPathComponent(name) + try data.write(to: file) + try FileManager.default.setAttributes( + [.modificationDate: start.addingTimeInterval(seconds)], ofItemAtPath: file.path) + } + let binary = Data(repeating: 0x01, count: 32) + try write(binary, named: "binary.log", in: appData, at: 20) + for number in 0..<4 { + try write(Data("install \(number)\n".utf8), named: "install-\(number).log", in: install, at: Double(number)) + try write(binary, named: "binary-\(number).log", in: install, at: Double(number + 10)) + } + let fallback = try XCTUnwrap(GameLogExcerpt.collect(search, since: start, redactedWith: redactor)) + XCTAssertEqual(fallback.sources.map { $0.path.components(separatedBy: "\\").last }, + ["install-1.log", "install-2.log", "install-3.log"]) + + try write(Data("app data\n".utf8), named: "app-data.log", in: appData, at: 5) + let preferred = try XCTUnwrap(GameLogExcerpt.collect(search, since: start, redactedWith: redactor)) + XCTAssertEqual(preferred.sources.map { $0.path.components(separatedBy: "\\").last }, ["app-data.log"]) + XCTAssertTrue(preferred.text.hasSuffix("\napp data\n")) + } + + func testSavesTheExcerptBesideTheRecordingOrUnderItsOwnName() throws { + let game = try UnityPrefix(test: self) + let root = try symlinkFreeDirectory() + let start = Date() + try game.writeLog("Player.log", "Fatal error in the game\n") + var environment = ["BASALT_FRAME_TRACE": "1"] + let recording = try XCTUnwrap(FrameTraceSession.rewrite( + environment: &environment, dataRoot: root, prefix: game.prefix, profile: "electrician", + now: Date(timeIntervalSince1970: 1_735_689_600))) + + let recorded = try XCTUnwrap(game.run(dataRoot: root, recording: recording, sessionStartedAt: start) + .save(redactedWith: redactor)) + XCTAssertEqual(recorded.file, recording.gameLog) + let plain = try XCTUnwrap(game.run(dataRoot: root, sessionStartedAt: Date(timeIntervalSince1970: 1_735_693_200)) + .save(redactedWith: redactor)) + let file = try XCTUnwrap(plain.file) + XCTAssertEqual(file.lastPathComponent, "20250101T010000.000000Z-electrician.game.log") + XCTAssertEqual(plain.excerpt.text, recorded.excerpt.text) + + let store = DiagnosticRecordingStore(dataRoot: root) + XCTAssertEqual(store.list().map { $0.files.map(\.kind) }, [[.gameLog], [.frames, .sessionLog, .gameLog]]) + XCTAssertEqual(store.gameLogText(named: file.lastPathComponent), plain.excerpt.text) + XCTAssertEqual(store.gameLogFile(named: file.lastPathComponent), file) + + // A game without a log saves nothing. + XCTAssertNil(game.run(dataRoot: root, sessionStartedAt: start, gameStartedAt: Date(timeIntervalSinceNow: 60)) + .save(redactedWith: redactor)) + XCTAssertEqual(store.list().count, 2) + } + + func testReadsOnlySavedGameLogsByTheirOwnNames() throws { + let root = try symlinkFreeDirectory() + let store = DiagnosticRecordingStore(dataRoot: root) + let saved = try XCTUnwrap(DiagnosticsStorage.saveGameLog( + Data("excerpt\n".utf8), dataRoot: root, recording: nil, profile: "game", + startedAt: Date(timeIntervalSince1970: 1_735_689_600))) + XCTAssertEqual(store.gameLogText(named: saved.lastPathComponent), "excerpt\n") + try Data(repeating: 0x61, count: DiagnosticRecordingStore.maximumGameLogBytes).write(to: saved) + XCTAssertEqual(store.gameLogText(named: saved.lastPathComponent)?.utf8.count, + DiagnosticRecordingStore.maximumGameLogBytes) + try Data(repeating: 0x61, count: DiagnosticRecordingStore.maximumGameLogBytes + 1).write(to: saved) + XCTAssertNil(store.gameLogText(named: saved.lastPathComponent)) + + let outside = root.appendingPathComponent("outside.log") + try Data("private\n".utf8).write(to: outside) + let link = store.directory.appendingPathComponent("20250101T000000.000000Z-link.game.log") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outside) + let stem = "20250101T000000.000000Z-game" + let pipe = store.directory.appendingPathComponent("20250101T000000.000000Z-pipe.game.log") + XCTAssertEqual(mkfifo(pipe.path, 0o600), 0) + XCTAssertNil(store.gameLogText(named: pipe.lastPathComponent)) + for name in [link.lastPathComponent, "../outside.log", stem + ".console.log", stem + ".csv", + "notes.game.log", "20250101T000000.000000Z-other.game.log", "x/" + saved.lastPathComponent] { + XCTAssertNil(store.gameLogText(named: name), name) + } + XCTAssertNil(store.gameLogFile(named: "../outside.game.log")) + } + + func testKeepsOnlyTheNewestGameLogsThatAreAllALaunchLeft() throws { + let root = try symlinkFreeDirectory() + let store = DiagnosticRecordingStore(dataRoot: root) + var environment = ["BASALT_FRAME_TRACE": "1"] + let recording = try XCTUnwrap(FrameTraceSession.rewrite( + environment: &environment, dataRoot: root, prefix: root, profile: "recorded", + now: Date(timeIntervalSince1970: 1_000))) + XCTAssertNotNil(DiagnosticsStorage.saveGameLog( + Data("x\n".utf8), dataRoot: root, recording: recording, profile: "recorded", + startedAt: Date(timeIntervalSince1970: 1_000))) + for hour in 1...3 { + XCTAssertNotNil(DiagnosticsStorage.saveGameLog( + Data("x\n".utf8), dataRoot: root, recording: nil, profile: "game-\(hour)", + startedAt: Date(timeIntervalSince1970: TimeInterval(hour * 3600)))) + } + + XCTAssertEqual(try store.removeGameLogs(keeping: 1), 2) + XCTAssertEqual(store.list().map(\.profileName), ["game-3", "recorded"]) + XCTAssertEqual(store.list().last?.files.map(\.kind), [.frames, .sessionLog, .gameLog]) + XCTAssertEqual(try store.removeGameLogs(keeping: 1), 0) + + // Saving after a session keeps as many as the history keeps sessions. + let game = try UnityPrefix(test: self) + try game.writeLog("Player.log", "line\n") + for minute in 0.. GameLogExcerpt { + GameLogExcerpt(logs: logs.map { GameLogExcerpt.Log(engine: .unity, label: $0.label, text: $0.text) }, + redactedWith: redactor) + } + + /// `data` as a log file read for an excerpt. + private func read(_ data: Data, maximumBytes: Int = GameLogExcerpt.maximumReadBytes) + -> (text: String, unreadBytes: Int64)? { + guard let url = try? temporaryDirectory().appendingPathComponent("game.log"), + (try? data.write(to: url)) != nil, + let handle = try? FileHandle(forReadingFrom: url) else { return nil } + defer { try? handle.close() } + return GameLogExcerpt.read(handle, size: Int64(data.count), maximumBytes: maximumBytes) + } + + /// The storage walk refuses symlinks, and the system temporary folder is + /// reached through one, so these tests use the project's own. + private func symlinkFreeDirectory() throws -> URL { + let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + let root = repo.appendingPathComponent(".local/tmp/game-log-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: root) } + return root + } +} + +/// A prefix with a Unity player, `Electrician VR`, whose Windows user is `steamuser`. +private struct UnityPrefix { + let prefix: URL + let executable: URL + var logFolder: URL { + prefix.appendingPathComponent( + "drive_c/users/steamuser/AppData/LocalLow/Example Studio/Electrician VR", isDirectory: true) + } + var search: GameLogSearch { GameLogSearch(prefix: prefix, executable: executable) } + + init(test: XCTestCase) throws { + prefix = try test.temporaryDirectory().appendingPathComponent("prefix", isDirectory: true) + let game = prefix.appendingPathComponent("drive_c/Games/Electrician VR", isDirectory: true) + try FileManager.default.createDirectory( + at: game.appendingPathComponent("ElectricianVR_Data"), withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: prefix.appendingPathComponent("drive_c/users/Public"), withIntermediateDirectories: true) + executable = game.appendingPathComponent("ElectricianVR.exe") + try Data().write(to: executable) + try Data("Example Studio\nElectrician VR".utf8) + .write(to: game.appendingPathComponent("ElectricianVR_Data/app.info")) + } + + func writeLog(_ name: String, _ text: String) throws { + try FileManager.default.createDirectory(at: logFolder, withIntermediateDirectories: true) + try Data(text.utf8).write(to: logFolder.appendingPathComponent(name)) + } + + func run(dataRoot: URL, recording: FrameTraceSession? = nil, sessionStartedAt: Date, + gameStartedAt: Date? = nil) -> GameLogRun { + GameLogRun(search: search, gameStartedAt: gameStartedAt ?? sessionStartedAt, profileName: "electrician", + sessionID: UUID(), sessionStartedAt: sessionStartedAt, recording: recording, dataRoot: dataRoot) + } +} diff --git a/streamer/Tests/BasaltManagerKitTests/SessionHistoryTests.swift b/streamer/Tests/BasaltManagerKitTests/SessionHistoryTests.swift index f9214a6..8a741fb 100644 --- a/streamer/Tests/BasaltManagerKitTests/SessionHistoryTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/SessionHistoryTests.swift @@ -69,6 +69,36 @@ final class SessionHistoryTests: XCTestCase { try store.clear() } + func testUpdateChangesOneRecordWhereItStands() throws { + let file = try temporaryDirectory().appendingPathComponent("history.json") + let store = SessionHistoryStore(file: file) + // Nothing to change in a history that is not there, and none is made. + XCTAssertEqual(try store.update(UUID()) { $0.outcome = .ended }, []) + XCTAssertFalse(FileManager.default.fileExists(atPath: file.path)) + + let older = SessionRecord(profileName: "older", settings: StreamLaunchSettings(), + startedAt: Date(timeIntervalSince1970: 1_800_000_000)) + let newer = SessionRecord(profileName: "newer", settings: StreamLaunchSettings(), + startedAt: Date(timeIntervalSince1970: 1_800_000_100)) + try store.append(older) + try store.append(newer) + + // The game log of the older session is saved after the newer one started. + let updated = try store.update(older.id) { $0.gameLog = "20270115T080000.000000Z-older.game.log" } + XCTAssertEqual(updated.map(\.profileName), ["newer", "older"]) + XCTAssertEqual(store.load().last?.gameLog, "20270115T080000.000000Z-older.game.log") + XCTAssertNil(store.load().first?.gameLog) + // A session the history no longer has stays out of it. + XCTAssertEqual(try store.update(UUID()) { $0.gameLog = "x" }.map(\.profileName), ["newer", "older"]) + XCTAssertEqual(store.load(), updated) + + // Written by a newer app: left alone. + try Data(#"{"formatVersion": 99, "sessions": []}"#.utf8).write(to: file) + XCTAssertThrowsError(try store.update(older.id) { $0.outcome = .ended }) { + XCTAssertEqual($0 as? SessionHistoryStore.Failure, .newerFormat(99)) + } + } + func testStoreSkipsUnreadableRecordsAndToleratesCorruptFiles() throws { let file = try temporaryDirectory().appendingPathComponent("history.json") let store = SessionHistoryStore(file: file) From 57072e71353391565fbc933054007111ce3ccb65 Mon Sep 17 00:00:00 2001 From: abgitdev <266600699+abgitdev@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:35:53 +0000 Subject: [PATCH 5/7] Hint at known causes when a session ends The session log now ends a session with a short hint for each error whose cause is known, found in the game's own log or in the session's process output: - a WindowsVideoMedia error: GStreamer is missing (see Setup), or, when it is installed, the video failed through Media Foundation in Wine; - a missing openvr_api DLL or a failed OpenVR initialisation: set up OpenComposite through the game card's OpenVR Support; - an xrCreateInstance failure in a session whose runtime never connected: the game could not start OpenXR; - "wineserver crashed": restart the game, and attach the diagnostic report if it happens again. The rules are data in KnownErrorHint and are matched as lines arrive, so a trimmed console or Clear loses nothing. One finalizer per session gives each hint once, after the game's own log has been read. The app's own lines, excerpt headers and GStreamer's harmless warnings never match, and Unity's refused request for OpenXR 1.1 gives no hint once the runtime connects. The hints are kept with the session's history record and listed in the diagnostic report. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + docs/MANAGEMENT.md | 26 +- streamer/Sources/BasaltCore/RuntimeLink.swift | 3 + streamer/Sources/BasaltManager/AppModel.swift | 88 +++- .../BasaltManagerKit/Diagnostics.swift | 9 + .../BasaltManagerKit/KnownErrorHint.swift | 256 ++++++++++++ .../Localization/L10nKey.swift | 5 + .../Localization/Strings+de.swift | 5 + .../Localization/Strings+en.swift | 5 + .../Localization/Strings+es.swift | 5 + .../Localization/Strings+fr.swift | 5 + .../Localization/Strings+it.swift | 5 + .../Localization/Strings+ja.swift | 5 + .../Localization/Strings+ko.swift | 5 + .../Localization/Strings+pl.swift | 5 + .../Localization/Strings+ru.swift | 5 + .../Localization/Strings+uk.swift | 5 + .../BasaltManagerKit/SessionHistory.swift | 4 + streamer/Sources/BasaltStreamer/App.swift | 2 +- .../DiagnosticsTests.swift | 25 ++ .../KnownErrorHintTests.swift | 381 ++++++++++++++++++ 21 files changed, 843 insertions(+), 13 deletions(-) create mode 100644 streamer/Sources/BasaltManagerKit/KnownErrorHint.swift create mode 100644 streamer/Tests/BasaltManagerKitTests/KnownErrorHintTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ec6b51..462dcb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,13 @@ All notable changes to TrailBridge VR are documented here. diagnostic report; it stays on the Mac. - Diagnostic redaction covers more Steam ID formats, hides full names in account fields and shows a game folder outside the Wine C: drive as `[game folder]`. +- When a session ends, the session log gives a short hint for errors whose cause is known, found + in the game's own log or output or in Wine's output: a video the game could not play, pointing + to Setup when GStreamer is missing; OpenVR that could not start, pointing to the game's OpenVR + Support for OpenComposite; OpenXR the game could not start; and a Wine crash. Each hint is given + once, and the diagnostic report lists the hints of recent sessions. GStreamer's harmless + warnings never give one, nor does Unity's refused first request for OpenXR 1.1 when the game's + runtime connects after it. ## 0.2.1 — 2026-11-15 diff --git a/docs/MANAGEMENT.md b/docs/MANAGEMENT.md index 2d9ead0..b80107a 100644 --- a/docs/MANAGEMENT.md +++ b/docs/MANAGEMENT.md @@ -104,11 +104,30 @@ shows the session state with a Stop button. recording when there is one; of the others the latest 50 are kept. The session log names the game's log as the game does (`C:\users\[user]\…`), the session's row in Recent Sessions shows the excerpt, and the next launch and a diagnostic report wait until it is saved. + Every session, with a game log or without, then gives a hint, once, for each error with a known + cause (`KnownErrorHint.rules`), after the line that names the game's log. What its processes + print is read as it arrives, so a trimmed or cleared session log loses nothing; the app's own + lines, which quote paths, and the excerpt's headers and notes are never read. The hints wait + for the game's log to be read, at most as long as a launch waits for it. A + `WindowsVideoMedia error` in the game's log or output sends to Setup when GStreamer was missing + as the game started, and otherwise says that Media Foundation in Wine could not play the video. + A `DllNotFoundException` for `openvr_api` or a failed OpenVR initialisation sends to the game + card's **OpenVR Support…**, for OpenComposite, and says to restore the game's own + `openvr_api.dll` first, by verifying its files in Steam, when none is found. A failed + `xrCreateInstance`, or the runtime's own reason for refusing one, says that the game could not + start OpenXR, but only when no runtime connected in the session (the streamer's + `OpenXR runtime connected` line, read also when it comes late), so Unity's refused first + request for OpenXR 1.1 gives none. A line of the game's or Steam's output that starts with + `wineserver crashed` asks to start the game again and to attach a diagnostic report if it + happens again. GStreamer's known harmless warnings never give a hint. When another launch or a + utility has taken the log over, the hints are not shown there; the session's record keeps them + either way. 8. **Settings** persists global stream defaults and per-profile overrides, selects audio and USB/Wi-Fi transport, and allows the managed Basalt data directory to be changed from the UI. 9. **Diagnostic Report** (Settings, or **Help › Diagnostic Report…**) previews a bug-report snapshot: app version, commit, and control protocol; Mac model, macOS, and power state; setup - checks; engines, bottles, and profiles; stream settings; the current and recent sessions; and, + checks; engines, bottles, and profiles; stream settings; the current and recent sessions, with + the hints the session log gave for each; and, optionally, the end of the session log and the excerpt of the game's own log: read anew from the running game, else the one saved with the latest session. It can be copied as Markdown for a GitHub issue or saved as Markdown or JSON. The home folder and user name (also in Wine's @@ -146,8 +165,9 @@ swift test --package-path streamer default/configured/explicit-location and managed-bottle launcher/instance discovery, Windows/host path mapping, Beat Saber scanning and source inference, duplicate resolution, stream argument generation, live-stat parsing, session history persistence and summaries, stream-health rules, -metric CSV export, diagnostic redaction, report rendering, and the game log excerpt, its storage -and its place in the report. `BasaltBottleKitTests` verifies repository/support-root +metric CSV export, diagnostic redaction, report rendering, the game log excerpt, its storage +and its place in the report, and the hints for known errors in both logs. `BasaltBottleKitTests` +verifies repository/support-root discovery, maintenance and VR launch commands, the BSManager Steam prerequisite, profile deletion, where Unity and Unreal games write their logs inside a prefix, and a real isolated import whose source remains unchanged. diff --git a/streamer/Sources/BasaltCore/RuntimeLink.swift b/streamer/Sources/BasaltCore/RuntimeLink.swift index e451601..d8ef28a 100644 --- a/streamer/Sources/BasaltCore/RuntimeLink.swift +++ b/streamer/Sources/BasaltCore/RuntimeLink.swift @@ -127,6 +127,9 @@ public final class RuntimeLink: @unchecked Sendable { /// The streamer prefixes refusal reasons with this on stderr so the /// manager can surface them; the game itself only sees a headless session. public static let connectionRefusedLogPrefix = "OpenXR runtime connection refused: " + /// The streamer starts its line for an accepted Hello with this on + /// stdout: the one sign the manager gets that the game's runtime connected. + public static let connectedLogPrefix = "OpenXR runtime connected " private var hapticHandler: ((_ hand: AlvrHand, _ durationNanoseconds: UInt64, _ frequency: Float, _ amplitude: Float) -> Void)? diff --git a/streamer/Sources/BasaltManager/AppModel.swift b/streamer/Sources/BasaltManager/AppModel.swift index 1f1f0fa..1354f37 100644 --- a/streamer/Sources/BasaltManager/AppModel.swift +++ b/streamer/Sources/BasaltManager/AppModel.swift @@ -326,6 +326,12 @@ final class BasaltAppModel: ObservableObject { /// The session whose output the log shows. A game log read after /// another launch or a utility has taken the log over is not named there. private var loggedSessionID: UUID? + /// Each session's output and game log, read for known errors until its + /// hints are given (`finishKnownErrors`). + private var knownErrors = KnownErrorScanner() + /// The session whose processes are being started: their output is read + /// for its hints, also once it has stopped. From launch to `stop()`. + private var scannedSessionID: UUID? /// When the current session started streaming; nil before that. var streamingStartedAt: Date? { openSession?.record.streamingStartedAt } private var hasChosenInitialSection = false @@ -1412,6 +1418,10 @@ final class BasaltAppModel: ObservableObject { } openSession = (SessionRecord(profileName: profileName, settings: launchSettings), sessionRoot) loggedSessionID = openSession?.record.id + if let id = loggedSessionID { + knownErrors.begin(id, dataRoot: sessionRoot) + scannedSessionID = id + } if let wineShutdown { appendLog(L10n.string(.modelWaitingWineStop)) @@ -1675,11 +1685,15 @@ final class BasaltAppModel: ObservableObject { } // Replaces attachOutput's /dev/null stdin: hello_xr quits at its EOF. try HeldOpenStandardInput.run(game) - if let warning = console.gStreamerWarning(for: GStreamerInstallation.detect()) { + let gStreamer = GStreamerInstallation.detect() + if let warning = console.gStreamerWarning(for: gStreamer) { appendLog(warning) } gameProcess = game runningGame = gameLog + // The hints go by GStreamer as the game found it, even when it is + // installed while the game runs. + if let id = openSession?.record.id { knownErrors.gameStarted(in: id, gStreamer: gStreamer) } gameFocusKeeper.start( gamePID: game.processIdentifier, headsetConnected: { [weak self] in self?.console.headsetDisconnected == false }, @@ -1737,6 +1751,9 @@ final class BasaltAppModel: ObservableObject { latestGameLogCaptureID = gameLog.sessionID pendingGameLogs[gameLog.sessionID] = (gameLog, false) } + // Its processes' output still counts for its hints until they are given. + let scannedSession = scannedSessionID + scannedSessionID = nil gameProcess = nil runningGame = nil steamProcess = nil @@ -1771,6 +1788,10 @@ final class BasaltAppModel: ObservableObject { wineMayBeRunning: result.failedPrefixes.contains(run.search.prefix.path)) noteGameLog(run, saved: saved) } + // Every session yet to give its hints gives them now, with or + // without its game's log, before the transcript closes. + // Lines still queued while this teardown blocks may not be read. + knownErrors.unfinished.forEach(finishKnownErrors(of:)) for pending in wineShutdown?.streamers ?? [] where pending.isRunning { pending.terminate() } @@ -1789,20 +1810,23 @@ final class BasaltAppModel: ObservableObject { guard let wineCommand else { _ = shutDown([]) if let gameLog { captureGameLog(gameLog, wineMayBeRunning: true) } + // A launch sets its Wine command before it starts any process: no pipe to wait for. + if let scannedSession { finishKnownErrorsAfterGameLog(of: scannedSession) } // An earlier shutdown still running closes it when it finishes. if wineShutdown == nil, !gameLogCapturePending { console.closeTranscript() } return } - queueWineShutdown(wineCommand, streamer: streamer, gameLog: gameLog) + queueWineShutdown(wineCommand, streamer: streamer, gameLog: gameLog, session: scannedSession) } /// Stops Wine for `command` off the main actor, after any stop already /// under way, and lists it in `wineShutdown`: a launch waits for it, and /// a later stop runs after it. Every stop goes through here, so that a /// late forced sweep can never meet processes started after it. With - /// `gameLog`, the game's log is read after the shutdown attempt. + /// `gameLog`, the game's log is read after the shutdown attempt; with + /// `session`, that session's hints are given after it. private func queueWineShutdown(_ command: BottleLaunchCommand, streamer: Process? = nil, - gameLog: GameLogRun? = nil) { + gameLog: GameLogRun? = nil, session: UUID? = nil) { if wineShutdown == nil { wineShutdownFailed = false wineShutdownError = nil @@ -1812,9 +1836,10 @@ final class BasaltAppModel: ObservableObject { let task = Task.detached { [weak self] in await previous?.task.value let result = Self.shutDownWine([command], manager: manager, streamer: streamer) + if let session { await self?.waitForOutputToEnd(of: session) } await self?.finishWineShutdown(message: result.message, failed: result.failed, stopped: result.stopped, failedPrefixes: result.failedPrefixes, - gameLog: gameLog) + gameLog: gameLog, session: session) } wineShutdown = (task, (previous?.commands ?? []) + [command], (previous?.streamers ?? []) + [streamer].compactMap { $0 }) @@ -1848,7 +1873,7 @@ final class BasaltAppModel: ObservableObject { } private func finishWineShutdown(message: String?, failed: Bool, stopped: [String], failedPrefixes: [String], - gameLog: GameLogRun?) { + gameLog: GameLogRun?, session: UUID?) { wineShutdownFailed = wineShutdownFailed || failed if failed { wineShutdownError = message } // What Steam's panel says about this environment's last stop. @@ -1866,6 +1891,7 @@ final class BasaltAppModel: ObservableObject { pending.streamers.removeAll { !$0.isRunning } wineShutdown = pending.commands.isEmpty ? nil : pending if let gameLog { captureGameLog(gameLog, wineMayBeRunning: failed) } + if let session { finishKnownErrorsAfterGameLog(of: session) } if wineShutdown == nil, !sessionState.isActive, !gameLogCapturePending { console.closeTranscript() } // A launch waits for this shutdown before it writes its own marker. // Wine that could not be stopped keeps it, for the next start. @@ -2098,6 +2124,9 @@ final class BasaltAppModel: ObservableObject { // order; a Task per chunk could run them out of order. let source = ObjectIdentifier(pipe) console.registerOutputSource(source) + if let session = scannedSessionID, let printer = KnownErrorScanner.Printer(rawValue: prefix) { + knownErrors.attach(source, printer: printer, to: session) + } let (chunks, continuation) = AsyncStream.makeStream(of: Data.self) pipe.fileHandleForReading.readabilityHandler = { handle in let data = handle.availableData @@ -2671,7 +2700,8 @@ final class BasaltAppModel: ObservableObject { /// Names the game's log in the session log, as the excerpt's header /// names it, unless another launch or a utility has taken the log over; - /// and notes the saved excerpt in the session's history record. + /// gives the session's hints after it; and notes the saved excerpt in + /// the session's history record. private func noteGameLog(_ run: GameLogRun, saved: (excerpt: GameLogExcerpt, file: URL?)?) { defer { pendingGameLogs[run.sessionID] = nil @@ -2683,6 +2713,8 @@ final class BasaltAppModel: ObservableObject { appendLog(saved?.excerpt.sources.last.map { L10n.string(.modelGameLog, $0.path) } ?? L10n.string(.modelGameLogNone)) } + knownErrors.read(gameLog: saved?.excerpt, of: run.sessionID) + finishKnownErrors(of: run.sessionID) // The session was recorded when it stopped; a history that has lost // it since stays as it is. guard let file = saved?.file, @@ -2693,6 +2725,39 @@ final class BasaltAppModel: ObservableObject { Task { await refreshRecordings() } } + /// Once a stopped session's processes are gone, the last lines of its + /// pipes, a crashed wineserver's among them, may still be on their way + /// to the scanner: they are read until every pipe has closed, for a + /// moment at most, and then no more. + private func waitForOutputToEnd(of sessionID: UUID) async { + await SessionTeardown.wait(upTo: .seconds(2)) { !knownErrors.isReading(sessionID) } + knownErrors.stopReading(sessionID) + } + + /// Gives the hints of a session that has stopped once its game's log has + /// been read: `noteGameLog` gives them then. When that takes longer than + /// a launch waits for it, they are given without the game's log. + private func finishKnownErrorsAfterGameLog(of sessionID: UUID) { + guard pendingGameLogs[sessionID] != nil else { return finishKnownErrors(of: sessionID) } + Task { [weak self] in + await self?.waitForGameLogCapture(sessionID) + self?.finishKnownErrors(of: sessionID) + } + } + + /// The hints of a session that has stopped, each once: in the session + /// log while it still shows the session, and in its history record. + private func finishKnownErrors(of sessionID: UUID) { + guard let finished = knownErrors.finish(sessionID), !finished.hints.isEmpty else { return } + let hints = finished.hints.map(\.text) + if loggedSessionID == sessionID { hints.forEach { appendLog($0 + "\n") } } + // As the excerpt is: a history that has lost the session stays as it is. + guard let history = try? SessionHistoryStore(dataRoot: finished.dataRoot).update( + sessionID, { $0.hints = hints }), + history.contains(where: { $0.id == sessionID }), finished.dataRoot == dataRoot else { return } + sessionHistory = history + } + private func captureGameLog(_ run: GameLogRun, wineMayBeRunning: Bool) { guard pendingGameLogs[run.sessionID]?.claimed == false else { return } pendingGameLogs[run.sessionID]?.claimed = true @@ -2787,11 +2852,16 @@ final class BasaltAppModel: ObservableObject { private func appendLog(_ value: String, from source: ObjectIdentifier? = nil, prefix: String = "") { - recordLines(console.append(value, from: source, prefix: prefix)) + let lines = console.append(value, from: source, prefix: prefix) + recordLines(lines) + knownErrors.read(lines, from: source) } private func finishLog(from source: ObjectIdentifier, prefix: String) { - recordLines(console.finish(source, prefix: prefix)) + let lines = console.finish(source, prefix: prefix) + recordLines(lines) + knownErrors.read(lines, from: source) + knownErrors.close(source) } private func recordLines(_ lines: [String]) { diff --git a/streamer/Sources/BasaltManagerKit/Diagnostics.swift b/streamer/Sources/BasaltManagerKit/Diagnostics.swift index 8c5bc89..b940a05 100644 --- a/streamer/Sources/BasaltManagerKit/Diagnostics.swift +++ b/streamer/Sources/BasaltManagerKit/Diagnostics.swift @@ -774,6 +774,15 @@ public struct DiagnosticReport: Codable, Equatable, Sendable { } } + // Each with the session it belongs to. + lines += ["", "### Hints", ""] + let hints = recentSessions.flatMap { record in + (record.hints ?? []).map { + "- \(dates.string(from: record.startedAt)) · \(flat(record.profileName)): \(flat($0))" + } + } + lines += hints.isEmpty ? ["None."] : hints + lines += ["", "### Session log", ""] if let logTail, !logTail.isEmpty { let fence = Self.fence(for: logTail) diff --git a/streamer/Sources/BasaltManagerKit/KnownErrorHint.swift b/streamer/Sources/BasaltManagerKit/KnownErrorHint.swift new file mode 100644 index 0000000..ae21c0d --- /dev/null +++ b/streamer/Sources/BasaltManagerKit/KnownErrorHint.swift @@ -0,0 +1,256 @@ +// SPDX-License-Identifier: MIT +import Foundation +import BasaltCore + +/// An error whose cause TrailBridge knows, as the game's own log or a +/// session's output shows it, and the hint the session log gives for it. A +/// game that runs with a black headset often says why only in a line that +/// means nothing to the person playing it. Each rule is one entry of +/// `rules`; `KnownErrorScanner` reads a session's lines with them. +public struct KnownErrorHint: Sendable { + /// What a rule reads. + public enum Reads: Sendable { + /// What the game wrote itself: the content lines of the excerpt of + /// its own log, and its output in the session log, where a Unity + /// player started with `-logFile -` writes its log too. + case game + /// What the session's Wine processes printed, the game and Steam: + /// Wine's own messages go to the process that started its server. + case wine + } + + /// What a rule needs besides its line. + public enum Condition: Sendable { + /// As the game found it when it started. + case gStreamerMissing + case gStreamerInstalled + /// The game's OpenXR runtime did not connect at any time in the session. + case runtimeNeverConnected + } + + /// Matched against one line, without the prefix of the process that + /// printed it. + public let pattern: NSRegularExpression + public let reads: Reads + public let condition: Condition? + /// The hint, also what makes it one: a hint is given once however many + /// rules for it match. + public let key: L10nKey + /// The places in the app the hint sends the person to, by the names the + /// app shows for them, in the order of the hint's placeholders. + public let places: [L10nKey] + + /// The patterns are literals that the tests read, so they are compiled + /// once and a mistake in one shows there. + init(_ pattern: String, reads: Reads, when condition: Condition? = nil, key: L10nKey, + places: [L10nKey] = []) { + self.pattern = try! NSRegularExpression(pattern: pattern) + self.reads = reads + self.condition = condition + self.key = key + self.places = places + } + + /// The hint in the app's language, without a line break. + public var text: String { + L10n.string(key, arguments: places.map { L10n.string($0) as CVarArg }) + } + + public static let rules: [KnownErrorHint] = [ + // Unity plays video through Media Foundation, which Wine implements + // with GStreamer. Electrician Simulator VR waited forever for an + // intro video it could not open, and only its Player.log said so. + KnownErrorHint("WindowsVideoMedia error", reads: .game, when: .gStreamerMissing, + key: .modelHintVideoWithoutGStreamer, places: [.sidebarSetup, .setupGStreamerPackage]), + KnownErrorHint("WindowsVideoMedia error", reads: .game, when: .gStreamerInstalled, + key: .modelHintVideoMediaFoundation), + // OpenVR's DLL that Unity could not load, or OpenVR that found no + // SteamVR, as Unity's built-in VR support and the SteamVR plugin + // say it. OpenComposite stands in for SteamVR; the hint names the + // game card's menu item, which is there even when the game folder + // has no openvr_api.dll left to replace. + KnownErrorHint( + #"DllNotFoundException.*openvr_api|OpenVR failed initialization"# + + #"|\[SteamVR\](?:)? Initialization (?i:failed)"#, + reads: .game, key: .modelHintOpenVR, places: [.sidebarLibrary, .libraryOpenVRSupport]), + // A line naming xrCreateInstance with a failure, an XR_ERROR_ result + // or a negative XrResult after it, or after a "FAIL:" that starts + // the line, as TrailBridge's own smoke clients in runtime/tests + // print it, however an engine words the rest; or the reason the + // runtime prints to the game's output as it refuses one + // (runtime/pe/runtime.cpp). Unity asks for OpenXR 1.1 first and + // falls back to 1.0, so a refusal is an error only when no runtime + // connected in the session. + KnownErrorHint( + #"xrCreateInstance\b.*(?:(?i:fail)|XR_ERROR_|\breturned XrResult -[0-9]+)"# + + #"|^FAIL: .*\bxrCreateInstance\b"# + + #"|Basalt OpenXR: (?:xrCreateInstance rejected|unsupported application API version"# + + #"|null enabled extension name|unsupported enabled extension"# + + #"|D3D11 runtime support is unavailable)"#, + reads: .game, when: .runtimeNeverConnected, key: .modelHintOpenXR), + // Wine's server prints this as it dies (server/signal.c), as a line + // of its own in the output of the Wine process that started it. + KnownErrorHint("^wineserver crashed", reads: .wine, key: .modelHintWineCrashed, + places: [.menuHelp, .menuDiagnostics]), + ] +} + +/// Reads each session's output for known errors as it arrives, and its +/// game's own log once that has been read, so that neither the session +/// log's trimmed tail nor Clear loses a line; a session's hints are given +/// once, when it has ended. A process's output belongs to the session that +/// started it, also when it arrives after the session has stopped or +/// another launch has taken the log over. The app's own lines are never +/// read: they quote paths and names that can hold anything. +public struct KnownErrorScanner: Sendable { + /// Who printed a session's output, by the prefix its lines carry in the + /// session log. + public enum Printer: String, Sendable { + case streamer = "" + case steam = "steam: " + case game = "game: " + } + + private struct Session: Sendable { + let order: Int + /// The data folder whose history has the session's record. + let dataRoot: URL + var gStreamer: GStreamerInstallation? + var runtimeConnected = false + /// The rules a line has matched, by their index in `rules`; their + /// conditions are read when the hints are given. + var matched = Set() + } + + private let rules: [KnownErrorHint] + private var sessions = [UUID: Session]() + private var sources = [ObjectIdentifier: (session: UUID, printer: Printer)]() + private var begun = 0 + + public init() { + self.init(rules: KnownErrorHint.rules) + } + + init(rules: [KnownErrorHint]) { + self.rules = rules + } + + /// Sessions whose hints have yet to be given, oldest first. + public var unfinished: [UUID] { + sessions.sorted { $0.value.order < $1.value.order }.map(\.key) + } + + /// A session the app starts, recorded in the history in `dataRoot`. + public mutating func begin(_ session: UUID, dataRoot: URL) { + begun += 1 + sessions[session] = Session(order: begun, dataRoot: dataRoot) + } + + /// What `source`, a pipe, carries from now on is `printer`'s output in `session`. + public mutating func attach(_ source: ObjectIdentifier, printer: Printer, to session: UUID) { + sources[source] = (session, printer) + } + + /// `source` has closed: a pipe opened later may have its identity. + public mutating func close(_ source: ObjectIdentifier) { + sources[source] = nil + } + + /// Whether a pipe attached to `session` has yet to close. + public func isReading(_ session: UUID) -> Bool { + sources.values.contains { $0.session == session } + } + + /// Nothing more of `session`'s pipes is read, closed or not. + public mutating func stopReading(_ session: UUID) { + sources = sources.filter { $0.value.session != session } + } + + public mutating func gameStarted(in session: UUID, gStreamer: GStreamerInstallation) { + sessions[session]?.gStreamer = gStreamer + } + + /// Reads lines as the session log got them (`SessionConsole.append`), + /// with `source` the pipe they came from: nil, or one no session + /// attached, for the app's own lines. + public mutating func read(_ lines: [String], from source: ObjectIdentifier?) { + guard let source, let (session, printer) = sources[source], var state = sessions[session] else { return } + for line in lines { + let message = line.hasPrefix(printer.rawValue) ? line.dropFirst(printer.rawValue.count) : Substring(line) + switch printer { + // The streamer's report of an accepted Hello; no game can print a + // line of the streamer's. + case .streamer: + if message.hasPrefix(RuntimeLink.connectedLogPrefix) { state.runtimeConnected = true } + case .steam: + match(message, reading: [.wine], into: &state) + case .game: + match(message, reading: [.game, .wine], into: &state) + } + } + sessions[session] = state + } + + /// Reads the excerpt of the session's game's own log, once read. + public mutating func read(gameLog excerpt: GameLogExcerpt?, of session: UUID) { + guard let excerpt, var state = sessions[session] else { return } + for line in Self.contentLines(of: excerpt) { + match(line, reading: [.game], into: &state) + } + sessions[session] = state + } + + /// The hints of a session that has ended, each once, in the order of + /// `rules`, with the data folder of its history; nil when they have + /// been given already. + public mutating func finish(_ session: UUID) -> (hints: [KnownErrorHint], dataRoot: URL)? { + guard let state = sessions.removeValue(forKey: session) else { return nil } + stopReading(session) + var given = Set() + let hints = rules.indices.filter { index in + let rule = rules[index] + guard state.matched.contains(index), !given.contains(rule.key) else { return false } + switch rule.condition { + case nil: break + case .gStreamerMissing?: guard state.gStreamer == .missing else { return false } + case .gStreamerInstalled?: guard case .installed = state.gStreamer else { return false } + case .runtimeNeverConnected?: guard !state.runtimeConnected else { return false } + } + given.insert(rule.key) + return true + }.map { rules[$0] } + return (hints, state.dataRoot) + } + + /// GStreamer's known harmless warnings never match, whatever they say: + /// once it is installed, Wine prints them in every session. + private func match(_ line: Substring, reading reads: Set, into state: inout Session) { + let text = String(line) + let range = NSRange(text.startIndex..., in: text) + for (index, rule) in rules.enumerated() + where reads.contains(rule.reads) && !state.matched.contains(index) + && rule.pattern.firstMatch(in: text, range: range) != nil + && !SessionConsole.isKnownHarmlessNoise(text) { + state.matched.insert(index) + } + } + + // MARK: The excerpt's own lines + + /// The lines the game wrote, without the excerpt's headers, which name a + /// folder of the game's own choosing, and its notes. + static func contentLines(of excerpt: GameLogExcerpt) -> [Substring] { + excerpt.text.split(whereSeparator: \.isNewline).filter { line in + guard !(line.hasPrefix("==> ") && line.hasSuffix(" <==")), line != possiblyIncomplete else { return false } + let text = String(line) + return excerptNote.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) == nil + } + } + + /// As `GameLogExcerpt` writes its notes: `skipped`, `unread` and `omitted`. + private static let excerptNote = try! NSRegularExpression( + pattern: #"^\[(?:… [0-9]+ lines? skipped …|… earlier lines not read: [0-9]+ bytes …"# + + #"|long line omitted: [0-9]+ bytes)\]$"#) + + private static let possiblyIncomplete = L10n.string(.recordingGameLogPossiblyIncomplete, language: .en) +} diff --git a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift index d77ce2c..ba33733 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/L10nKey.swift @@ -72,6 +72,11 @@ public enum L10nKey: String, CaseIterable, Sendable { case modelGameExitedQuickly case modelGameLog case modelGameLogNone + case modelHintVideoWithoutGStreamer + case modelHintVideoMediaFoundation + case modelHintOpenVR + case modelHintOpenXR + case modelHintWineCrashed case modelSteamDirectLaunch case modelGameBroughtForward case modelGameBringForwardFailed diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift index 3644308..a26d682 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+de.swift @@ -75,6 +75,11 @@ final class StringsDE: LocalizationTable { .modelGameExitedQuickly: "Das Spiel endete %1$@ s nach dem Start. Erschien nichts im Headset, ist die gestartete Datei vielleicht ein Launcher, der das Spiel als eigenen Prozess öffnet, oder das Spiel hat beim Laden aufgehört (siehe die „game:“-Zeilen oben). Um die .exe des Spiels selbst zu starten, diese unter Bibliothek → Spielkarte → ⋯ → %2$@ auswählen.\n", .modelGameLog: "Eigenes Protokoll des Spiels: %1$@\n", .modelGameLogNone: "Kein Protokoll gefunden, das das Spiel selbst schreibt. TrailBridge liest die Protokolle von Unity- und Unreal-Spielen.\n", + .modelHintVideoWithoutGStreamer: "Das Spiel konnte ein Video nicht abspielen, weil GStreamer nicht installiert ist. „%1$@“ öffnen und auf „%2$@“ klicken.", + .modelHintVideoMediaFoundation: "Das Spiel konnte ein Video über Media Foundation in Wine nicht abspielen. Bleibt das Headset schwarz, wartet das Spiel vielleicht auf dieses Video.", + .modelHintOpenVR: "Das Spiel konnte OpenVR nicht starten. SteamVR-Spiele brauchen OpenComposite: in „%1$@“ das Menü ⋯ der Spielkarte öffnen und „%2$@“ wählen. Wird dort keine openvr_api.dll gefunden, zuerst die des Spiels wiederherstellen, etwa durch Überprüfen der Spieldateien in Steam.", + .modelHintOpenXR: "Das Spiel konnte OpenXR nicht starten, daher kam im Headset nichts an.", + .modelHintWineCrashed: "Wine ist abgestürzt. Das Spiel erneut starten; passiert es wieder, einen Diagnosebericht („%1$@“ → „%2$@“) an die Fehlermeldung anhängen.", .modelSteamDirectLaunch: "Das Spiel wird direkt gestartet, nicht über Steam: %1$@\n", .modelGameBroughtForward: "Das Spielfenster ist wieder vorne: Viele Spiele geben nur Ton aus, solange ihr Fenster auf dem Mac vorne ist.\n", .modelGameBringForwardFailed: "Das Spielfenster ließ sich nicht nach vorne holen. Wird das Headset stumm, auf dem Mac auf das Spielfenster klicken.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift index e154449..40d6669 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+en.swift @@ -75,6 +75,11 @@ final class StringsEN: LocalizationTable { .modelGameExitedQuickly: "The game ended %1$@ s after it started. If nothing appeared in the headset, the file started may be a launcher that opens the game as a separate process, or the game stopped while loading (see the “game:” lines above). To start the game's own .exe, choose it in Library → game card → ⋯ → %2$@\n", .modelGameLog: "The game's own log: %1$@\n", .modelGameLogNone: "No log written by the game itself was found. TrailBridge reads the logs of Unity and Unreal games.\n", + .modelHintVideoWithoutGStreamer: "The game could not play a video because GStreamer is not installed. Open “%1$@” and click “%2$@”.", + .modelHintVideoMediaFoundation: "The game could not play a video through Media Foundation in Wine. If the headset stays black, the game may be waiting for that video.", + .modelHintOpenVR: "The game could not start OpenVR. SteamVR games need OpenComposite: in “%1$@”, open the game card's ⋯ menu and choose “%2$@”. If no openvr_api.dll is found there, first restore the game's own copy, for example by verifying the game's files in Steam.", + .modelHintOpenXR: "The game could not start OpenXR, so nothing reached the headset.", + .modelHintWineCrashed: "Wine crashed. Start the game again; if it happens again, attach a diagnostic report (“%1$@” → “%2$@”) to your bug report.", .modelSteamDirectLaunch: "Starting the game itself rather than through Steam: %1$@\n", .modelGameBroughtForward: "Brought the game's window back to the front: many games play sound only while their window on the Mac is in front.\n", .modelGameBringForwardFailed: "Could not bring the game's window back to the front. If the headset goes silent, click the game's window on the Mac.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift index 6a8a0fd..b5118f4 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+es.swift @@ -75,6 +75,11 @@ final class StringsES: LocalizationTable { .modelGameExitedQuickly: "El juego terminó %1$@ s después de iniciarse. Si no apareció nada en el visor, el archivo iniciado puede ser un lanzador que abre el juego en otro proceso, o el juego se detuvo al cargar (consulta las líneas «game:» de arriba). Para iniciar el .exe del propio juego, elígelo en Biblioteca → tarjeta del juego → ⋯ → %2$@\n", .modelGameLog: "Registro del propio juego: %1$@\n", .modelGameLogNone: "No se encontró ningún registro escrito por el propio juego. TrailBridge lee los registros de los juegos de Unity y Unreal.\n", + .modelHintVideoWithoutGStreamer: "El juego no pudo reproducir un vídeo porque GStreamer no está instalado. Abre «%1$@» y haz clic en «%2$@».", + .modelHintVideoMediaFoundation: "El juego no pudo reproducir un vídeo mediante Media Foundation en Wine. Si el visor se queda en negro, puede que el juego esté esperando ese vídeo.", + .modelHintOpenVR: "El juego no pudo iniciar OpenVR. Los juegos de SteamVR necesitan OpenComposite: en «%1$@», abre el menú ⋯ de la tarjeta del juego y elige «%2$@». Si no se encuentra ningún openvr_api.dll, restaura primero el del propio juego, por ejemplo verificando la integridad de los archivos del juego en Steam.", + .modelHintOpenXR: "El juego no pudo iniciar OpenXR, así que no llegó nada al visor.", + .modelHintWineCrashed: "Wine se ha cerrado inesperadamente. Vuelve a iniciar el juego; si vuelve a ocurrir, adjunta un informe de diagnóstico («%1$@» → «%2$@») al notificar el error.", .modelSteamDirectLaunch: "Iniciando el juego directamente, no a través de Steam: %1$@\n", .modelGameBroughtForward: "La ventana del juego vuelve a estar al frente: muchos juegos solo suenan mientras su ventana está al frente en el Mac.\n", .modelGameBringForwardFailed: "No se pudo traer al frente la ventana del juego. Si el visor se queda sin sonido, haz clic en la ventana del juego en el Mac.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift index a410724..c242f5f 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+fr.swift @@ -75,6 +75,11 @@ final class StringsFR: LocalizationTable { .modelGameExitedQuickly: "Le jeu s’est arrêté %1$@ s après son lancement. Si rien n’est apparu dans le casque, le fichier lancé est peut-être un lanceur qui ouvre le jeu dans un processus séparé, ou le jeu s’est arrêté pendant le chargement (voir les lignes « game: » ci-dessus). Pour lancer le .exe du jeu lui-même, choisissez-le dans Bibliothèque → fiche du jeu → ⋯ → %2$@\n", .modelGameLog: "Journal du jeu lui-même : %1$@\n", .modelGameLogNone: "Aucun journal écrit par le jeu lui-même n’a été trouvé. TrailBridge lit les journaux des jeux Unity et Unreal.\n", + .modelHintVideoWithoutGStreamer: "Le jeu n’a pas pu lire une vidéo, car GStreamer n’est pas installé. Ouvrez « %1$@ » et cliquez sur « %2$@ ».", + .modelHintVideoMediaFoundation: "Le jeu n’a pas pu lire une vidéo avec Media Foundation dans Wine. Si le casque reste noir, le jeu attend peut-être cette vidéo.", + .modelHintOpenVR: "Le jeu n’a pas pu démarrer OpenVR. Les jeux SteamVR ont besoin d’OpenComposite : dans « %1$@ », ouvrez le menu ⋯ de la fiche du jeu et choisissez « %2$@ ». Si aucun openvr_api.dll n’y est trouvé, restaurez d’abord celui du jeu, par exemple en vérifiant l’intégrité des fichiers du jeu dans Steam.", + .modelHintOpenXR: "Le jeu n’a pas pu démarrer OpenXR, rien n’est donc parvenu au casque.", + .modelHintWineCrashed: "Wine s’est arrêté de manière inattendue. Relancez le jeu ; si cela se reproduit, joignez un rapport de diagnostic (« %1$@ » → « %2$@ ») à votre signalement.", .modelSteamDirectLaunch: "Lancement direct du jeu, sans passer par Steam : %1$@\n", .modelGameBroughtForward: "La fenêtre du jeu est de nouveau au premier plan : beaucoup de jeux n’émettent du son que si leur fenêtre est au premier plan sur le Mac.\n", .modelGameBringForwardFailed: "Impossible de ramener la fenêtre du jeu au premier plan. Si le casque devient muet, cliquez sur la fenêtre du jeu sur le Mac.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift index 7b747d0..a237a88 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+it.swift @@ -75,6 +75,11 @@ final class StringsIT: LocalizationTable { .modelGameExitedQuickly: "Il gioco è terminato %1$@ s dopo l’avvio. Se nel visore non è apparso nulla, il file avviato può essere un launcher che apre il gioco in un processo separato, oppure il gioco si è fermato durante il caricamento (vedi le righe «game:» sopra). Per avviare l’.exe del gioco stesso, sceglilo in Libreria → scheda del gioco → ⋯ → %2$@\n", .modelGameLog: "Registro del gioco stesso: %1$@\n", .modelGameLogNone: "Non è stato trovato alcun registro scritto dal gioco stesso. TrailBridge legge i registri dei giochi Unity e Unreal.\n", + .modelHintVideoWithoutGStreamer: "Il gioco non è riuscito a riprodurre un video perché GStreamer non è installato. Apri “%1$@” e fai clic su “%2$@”.", + .modelHintVideoMediaFoundation: "Il gioco non è riuscito a riprodurre un video tramite Media Foundation in Wine. Se il visore resta nero, il gioco potrebbe essere in attesa di quel video.", + .modelHintOpenVR: "Il gioco non è riuscito ad avviare OpenVR. I giochi per SteamVR richiedono OpenComposite: in “%1$@” apri il menu ⋯ della scheda del gioco e scegli “%2$@”. Se lì non viene trovato alcun openvr_api.dll, ripristina prima quello del gioco, ad esempio verificando l’integrità dei file di gioco in Steam.", + .modelHintOpenXR: "Il gioco non è riuscito ad avviare OpenXR, quindi nel visore non è arrivato nulla.", + .modelHintWineCrashed: "Wine si è arrestato in modo anomalo. Avvia di nuovo il gioco; se succede ancora, allega un resoconto diagnostico (“%1$@” → “%2$@”) alla segnalazione del problema.", .modelSteamDirectLaunch: "Avvio diretto del gioco, senza passare da Steam: %1$@\n", .modelGameBroughtForward: "La finestra del gioco è di nuovo in primo piano: molti giochi riproducono l’audio solo quando la loro finestra sul Mac è in primo piano.\n", .modelGameBringForwardFailed: "Impossibile riportare in primo piano la finestra del gioco. Se il visore resta senza audio, fai clic sulla finestra del gioco sul Mac.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift index a49dc64..651c493 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ja.swift @@ -75,6 +75,11 @@ final class StringsJA: LocalizationTable { .modelGameExitedQuickly: "ゲームは起動から%1$@秒後に終了しました。ヘッドセットに何も表示されなかった場合、起動したファイルがゲームを別のプロセスで開くランチャーであるか、読み込み中にゲームが停止した可能性があります(上の「game:」の行を確認してください)。ゲーム本体の.exeを起動するには、ライブラリ → ゲームカード → ⋯ → %2$@ で選択してください。\n", .modelGameLog: "ゲーム自身のログ:%1$@\n", .modelGameLogNone: "ゲーム自身が書いたログは見つかりませんでした。TrailBridgeが読むのはUnityとUnrealのゲームのログです。\n", + .modelHintVideoWithoutGStreamer: "GStreamerがインストールされていないため、ゲームが動画を再生できませんでした。「%1$@」を開いて「%2$@」をクリックしてください。", + .modelHintVideoMediaFoundation: "ゲームがWineのMedia Foundationで動画を再生できませんでした。ヘッドセットが黒いままの場合、ゲームはその動画を待っている可能性があります。", + .modelHintOpenVR: "ゲームがOpenVRを開始できませんでした。SteamVRのゲームにはOpenCompositeが必要です。「%1$@」でゲームカードの⋯メニューを開き、「%2$@」を選んでください。そこでopenvr_api.dllが見つからない場合は、まずゲーム本来のファイルを復元してください(例:Steamでゲームファイルの整合性を確認)。", + .modelHintOpenXR: "ゲームがOpenXRを開始できなかったため、ヘッドセットには何も届きませんでした。", + .modelHintWineCrashed: "Wineがクラッシュしました。ゲームをもう一度起動してください。再び起きた場合は、バグ報告に診断レポート(「%1$@」→「%2$@」)を添付してください。", .modelSteamDirectLaunch: "Steam経由ではなくゲーム本体を起動します:%1$@\n", .modelGameBroughtForward: "ゲームのウインドウを最前面に戻しました。多くのゲームは、Mac でウインドウが最前面にあるときだけ音を出します。\n", .modelGameBringForwardFailed: "ゲームのウインドウを最前面に戻せませんでした。ヘッドセットの音が消えたら、Mac でゲームのウインドウをクリックしてください。\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift index afc3505..e4d3fa5 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ko.swift @@ -75,6 +75,11 @@ final class StringsKO: LocalizationTable { .modelGameExitedQuickly: "게임이 시작 후 %1$@초 만에 종료되었습니다. 헤드셋에 아무것도 나타나지 않았다면, 실행한 파일이 게임을 별도 프로세스로 여는 런처이거나 게임이 로딩 중에 멈췄을 수 있습니다(위의 “game:” 줄 참고). 게임 본체의 .exe를 실행하려면 라이브러리 → 게임 카드 → ⋯ → %2$@에서 선택하세요.\n", .modelGameLog: "게임 자체 로그: %1$@\n", .modelGameLogNone: "게임이 직접 남긴 로그를 찾지 못했습니다. TrailBridge는 Unity와 Unreal 게임의 로그를 읽습니다.\n", + .modelHintVideoWithoutGStreamer: "GStreamer가 설치되어 있지 않아 게임이 동영상을 재생하지 못했습니다. “%1$@”을(를) 열고 “%2$@”을(를) 클릭하세요.", + .modelHintVideoMediaFoundation: "게임이 Wine의 Media Foundation으로 동영상을 재생하지 못했습니다. 헤드셋 화면이 계속 검다면 게임이 그 동영상을 기다리고 있을 수 있습니다.", + .modelHintOpenVR: "게임이 OpenVR을 시작하지 못했습니다. SteamVR 게임에는 OpenComposite가 필요합니다. “%1$@”에서 게임 카드의 ⋯ 메뉴를 열고 “%2$@”을(를) 선택하세요. 그곳에서 openvr_api.dll을 찾지 못하면 먼저 게임 원래의 파일을 복원하세요(예: Steam에서 게임 파일 무결성 확인).", + .modelHintOpenXR: "게임이 OpenXR을 시작하지 못해 헤드셋에 아무것도 전달되지 않았습니다.", + .modelHintWineCrashed: "Wine이 비정상 종료되었습니다. 게임을 다시 시작하세요. 다시 발생하면 버그 신고에 진단 보고서(“%1$@” → “%2$@”)를 첨부하세요.", .modelSteamDirectLaunch: "Steam을 거치지 않고 게임을 직접 실행합니다: %1$@\n", .modelGameBroughtForward: "게임 창을 다시 맨 앞으로 가져왔습니다. 많은 게임은 Mac에서 창이 맨 앞에 있을 때만 소리를 냅니다.\n", .modelGameBringForwardFailed: "게임 창을 맨 앞으로 가져오지 못했습니다. 헤드셋에서 소리가 사라지면 Mac에서 게임 창을 클릭하세요.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift index 48284cf..1b84772 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+pl.swift @@ -75,6 +75,11 @@ final class StringsPL: LocalizationTable { .modelGameExitedQuickly: "Gra zakończyła się %1$@ s po uruchomieniu. Jeśli w goglach nic się nie pojawiło, uruchomiony plik może być launcherem, który otwiera grę jako osobny proces, albo gra zatrzymała się podczas ładowania (zobacz wiersze „game:” powyżej). Aby uruchamiać sam plik .exe gry, wybierz go w: Biblioteka → karta gry → ⋯ → %2$@\n", .modelGameLog: "Dziennik samej gry: %1$@\n", .modelGameLogNone: "Nie znaleziono dziennika zapisywanego przez samą grę. TrailBridge czyta dzienniki gier na Unity i Unreal.\n", + .modelHintVideoWithoutGStreamer: "Gra nie mogła odtworzyć filmu, ponieważ GStreamer nie jest zainstalowany. Otwórz „%1$@” i kliknij „%2$@”.", + .modelHintVideoMediaFoundation: "Gra nie mogła odtworzyć filmu przez Media Foundation w Wine. Jeśli w goglach jest czarny obraz, gra może czekać na ten film.", + .modelHintOpenVR: "Gra nie mogła uruchomić OpenVR. Gry SteamVR potrzebują OpenComposite: w sekcji „%1$@” otwórz menu ⋯ na karcie gry i wybierz „%2$@”. Jeśli nie zostanie tam znaleziony plik openvr_api.dll, najpierw przywróć plik samej gry, na przykład weryfikując spójność plików gry w Steam.", + .modelHintOpenXR: "Gra nie mogła uruchomić OpenXR, więc nic nie dotarło do gogli.", + .modelHintWineCrashed: "Wine uległ awarii. Uruchom grę ponownie; jeśli to się powtórzy, dołącz raport diagnostyczny („%1$@” → „%2$@”) do zgłoszenia błędu.", .modelSteamDirectLaunch: "Uruchamianie samej gry, nie przez Steam: %1$@\n", .modelGameBroughtForward: "Okno gry znów jest na pierwszym planie: wiele gier gra dźwięk tylko wtedy, gdy ich okno na Macu jest na wierzchu.\n", .modelGameBringForwardFailed: "Nie udało się przywrócić okna gry na pierwszy plan. Jeśli w goglach zniknie dźwięk, kliknij okno gry na Macu.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift index 06aeb82..0398d31 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+ru.swift @@ -75,6 +75,11 @@ final class StringsRU: LocalizationTable { .modelGameExitedQuickly: "Игра завершилась через %1$@ с после запуска. Если в шлеме ничего не появилось, запущенный файл может быть лаунчером, который открывает игру отдельным процессом, или игра остановилась при загрузке (см. строки «game:» выше). Чтобы запускать сам .exe игры, выберите его: «Библиотека» → карточка игры → ⋯ → «%2$@».\n", .modelGameLog: "Журнал самой игры: %1$@\n", .modelGameLogNone: "Журнал, который ведёт сама игра, не найден. TrailBridge читает журналы игр на Unity и Unreal.\n", + .modelHintVideoWithoutGStreamer: "Игра не смогла воспроизвести видео: GStreamer не установлен. Откройте «%1$@» и нажмите «%2$@».", + .modelHintVideoMediaFoundation: "Игра не смогла воспроизвести видео через Media Foundation в Wine. Если в шлеме чёрный экран, игра, возможно, ждёт это видео.", + .modelHintOpenVR: "Игра не смогла запустить OpenVR. Играм для SteamVR нужен OpenComposite: в разделе «%1$@» откройте меню ⋯ на карточке игры и выберите «%2$@». Если openvr_api.dll там не найдётся, сначала восстановите собственный файл игры, например проверив целостность файлов игры в Steam.", + .modelHintOpenXR: "Игра не смогла запустить OpenXR, поэтому в шлеме ничего не появилось.", + .modelHintWineCrashed: "Wine аварийно завершил работу. Запустите игру снова; если это повторится, приложите диагностический отчёт («%1$@» → «%2$@») к сообщению об ошибке.", .modelSteamDirectLaunch: "Запускаем саму игру, а не через Steam: %1$@\n", .modelGameBroughtForward: "Окно игры снова впереди: многие игры звучат, только пока их окно на Mac впереди.\n", .modelGameBringForwardFailed: "Не удалось вернуть окно игры вперёд. Если в шлеме пропал звук, щёлкните окно игры на Mac.\n", diff --git a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift index fb5d59f..5fb64f2 100644 --- a/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift +++ b/streamer/Sources/BasaltManagerKit/Localization/Strings+uk.swift @@ -75,6 +75,11 @@ final class StringsUK: LocalizationTable { .modelGameExitedQuickly: "Гра завершилася через %1$@ с після запуску. Якщо в шоломі нічого не з’явилося, запущений файл може бути лаунчером, що відкриває гру окремим процесом, або гра зупинилася під час завантаження (див. рядки «game:» вище). Щоб запускати сам .exe гри, виберіть його: Бібліотека → картка гри → ⋯ → %2$@\n", .modelGameLog: "Журнал самої гри: %1$@\n", .modelGameLogNone: "Журнал, який веде сама гра, не знайдено. TrailBridge читає журнали ігор на Unity та Unreal.\n", + .modelHintVideoWithoutGStreamer: "Гра не змогла відтворити відео: GStreamer не встановлено. Відкрийте «%1$@» і натисніть «%2$@».", + .modelHintVideoMediaFoundation: "Гра не змогла відтворити відео через Media Foundation у Wine. Якщо в шоломі чорний екран, гра, можливо, чекає на це відео.", + .modelHintOpenVR: "Гра не змогла запустити OpenVR. Іграм для SteamVR потрібен OpenComposite: у розділі «%1$@» відкрийте меню ⋯ на картці гри й виберіть «%2$@». Якщо openvr_api.dll там не знайдеться, спершу відновіть власний файл гри, наприклад перевіривши цілісність файлів гри в Steam.", + .modelHintOpenXR: "Гра не змогла запустити OpenXR, тому в шоломі нічого не з’явилося.", + .modelHintWineCrashed: "Wine аварійно завершив роботу. Запустіть гру знову; якщо це повториться, додайте діагностичний звіт («%1$@» → «%2$@») до повідомлення про помилку.", .modelSteamDirectLaunch: "Запускаємо саму гру, а не через Steam: %1$@\n", .modelGameBroughtForward: "Вікно гри знову попереду: багато ігор звучать, лише поки їхнє вікно на Mac попереду.\n", .modelGameBringForwardFailed: "Не вдалося повернути вікно гри наперед. Якщо в шоломі зник звук, клацніть вікно гри на Mac.\n", diff --git a/streamer/Sources/BasaltManagerKit/SessionHistory.swift b/streamer/Sources/BasaltManagerKit/SessionHistory.swift index 6a04b2a..1c21619 100644 --- a/streamer/Sources/BasaltManagerKit/SessionHistory.swift +++ b/streamer/Sources/BasaltManagerKit/SessionHistory.swift @@ -91,6 +91,10 @@ public struct SessionRecord: Codable, Equatable, Identifiable, Sendable { /// in the data folder's `Diagnostics` folder, set once the game has /// ended; nil when none was saved. public var gameLog: String? + /// The hints for known errors in the session's logs (`KnownErrorHint`), + /// as the session log gives them, set once the game's log has been + /// read; nil when there were none. + public var hints: [String]? public init(id: UUID = UUID(), profileName: String, settings: StreamLaunchSettings, startedAt: Date = Date()) { diff --git a/streamer/Sources/BasaltStreamer/App.swift b/streamer/Sources/BasaltStreamer/App.swift index f4c6abc..a9aa347 100644 --- a/streamer/Sources/BasaltStreamer/App.swift +++ b/streamer/Sources/BasaltStreamer/App.swift @@ -272,7 +272,7 @@ struct BasaltStreamerApp { keepAliveWithoutTracking: true) link.onHello = { sessionId, renderer in progress?.runtimeConnected() - print("OpenXR runtime connected (session \(sessionId), \(renderer))") + print(RuntimeLink.connectedLogPrefix + "(session \(sessionId), \(renderer))") encoder.forceKeyframe() } link.onTeardown = { diff --git a/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift b/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift index 68334bf..8928487 100644 --- a/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/DiagnosticsTests.swift @@ -262,6 +262,31 @@ final class DiagnosticsTests: XCTestCase { .contains("### Game log\n\nNo log of the game was found.")) } + func testReportShowsTheHintsOfEachRecentSession() throws { + var report = makeReport(log: nil) + XCTAssertTrue(report.markdown(redactedWith: redactor).contains("### Hints\n\nNone.\n\n### Session log")) + + let hints = [ + "The game could not start OpenXR, so nothing reached the headset.", + "Wine crashed. Start the game again; if it happens again, attach a diagnostic report " + + "(“Help” → “Diagnostic Report…”) to your bug report.", + ] + report.recentSessions[0].hints = hints + let markdown = report.markdown(redactedWith: redactor) + XCTAssertTrue(markdown.contains(""" + ### Hints + + - 2027-01-15T08:00:00Z · beat-saber-vr: \(hints[0]) + - 2027-01-15T08:00:00Z · beat-saber-vr: \(hints[1]) + + ### Session log + """), markdown) + let object = try XCTUnwrap(JSONSerialization.jsonObject( + with: Data(try report.json(redactedWith: redactor).utf8)) as? [String: Any]) + let sessions = try XCTUnwrap(object["recentSessions"] as? [[String: Any]]) + XCTAssertEqual(sessions.first?["hints"] as? [String], hints) + } + func testReportSaysWhenSetupHasNotRun() { let report = makeReport(log: nil, setupChecks: []) XCTAssertTrue(report.setupChecks.isEmpty) diff --git a/streamer/Tests/BasaltManagerKitTests/KnownErrorHintTests.swift b/streamer/Tests/BasaltManagerKitTests/KnownErrorHintTests.swift new file mode 100644 index 0000000..258bc07 --- /dev/null +++ b/streamer/Tests/BasaltManagerKitTests/KnownErrorHintTests.swift @@ -0,0 +1,381 @@ +// SPDX-License-Identifier: MIT +import XCTest +import BasaltCore +@testable import BasaltManagerKit + +@MainActor +final class KnownErrorHintTests: XCTestCase { + /// Nothing is read from the Mac the tests run on. + private let redactor = DiagnosticRedactor( + homeDirectory: "/Users/example", userName: "example", dataFolder: nil, appFolder: nil, + hostNames: [], volumeNames: []) + + /// Electrician Simulator VR's Player.log when it could not open its intro video. + private let videoError = """ + WindowsVideoMedia error 0xc00d36bb while reading C:/Program Files (x86)/Steam/steamapps/common/Electrician Simulator VR/ElectricianVR_Data/sharedassets0.resource + + Context: CreateObjectFromByteStream + Error details: Unexpected error. + """ + /// Unity's Mono when P/Invoke cannot load the plugin. + private let openVRNotLoaded = "DllNotFoundException: openvr_api assembly: type: member:(null)" + /// The runtime refuses the API version Unity asks for first + /// (runtime/pe/runtime.cpp); Unity then asks for 1.0. + private let apiVersionRefused = "Basalt OpenXR: unsupported application API version 1.1.45 (runtime supports OpenXR 1.0)" + /// The streamer's line for the runtime's accepted Hello. + private let runtimeConnected = "OpenXR runtime connected (session 1, Apple M4 Pro (DXMT v0.61-basalt))" + /// Wine's server prints this on a segmentation fault (server/signal.c). + private let wineserverCrash = "wineserver crashed, please enable coredumps (ulimit -c unlimited) and restart." + + // MARK: - The rules + + func testAVideoTheGameCouldNotPlaySendsToSetupOnlyWithoutGStreamer() { + let gameLog = excerpt("Initialize engine version: 6000.0.58f2\n" + videoError) + XCTAssertEqual(Recording(gStreamer: .missing).hints(gameLog: gameLog), [.modelHintVideoWithoutGStreamer]) + XCTAssertEqual(Recording().hints(gameLog: gameLog), [.modelHintVideoMediaFoundation]) + XCTAssertEqual(Recording(gStreamer: .installed(version: nil)).hints(gameLog: gameLog), + [.modelHintVideoMediaFoundation]) + // A Unity player started with `-logFile -` writes its log to its output. + let output = Recording(gStreamer: .missing) + output.print(videoError + "\n", by: .game) + XCTAssertEqual(output.hints(), [.modelHintVideoWithoutGStreamer]) + // Steam's output is not the game's, and a game that never started played no video. + let steam = Recording(gStreamer: .missing) + steam.print(videoError + "\n", by: .steam) + XCTAssertEqual(steam.hints(), []) + XCTAssertEqual(Recording(gStreamer: nil).hints(gameLog: gameLog), []) + } + + func testOpenVRThatCouldNotStartSuggestsOpenComposite() { + let lines = [ + openVRNotLoaded, + // Unity's built-in VR support when OpenVR finds no SteamVR. + #"VR: OpenVR Error! OpenVR failed initialization with error code VRInitError_Init_PathRegistryNotFound: "Installation path could not be located (110)"!"#, + // The SteamVR Unity plugin; the log keeps its rich-text tags. + "[SteamVR] Initialization failed. Please verify that you have SteamVR installed, " + + "your hmd is functioning, and OpenVR Loader is checked in the XR Plugin Management " + + "section of Project Settings.", + ] + for line in lines { + XCTAssertEqual(Recording().hints(gameLog: excerpt(line)), [.modelHintOpenVR], line) + } + // In the game's own output too, the app's own line about OpenVR + // support aside. + let output = Recording() + output.appLine(L10n.string(.modelOpenVRReinstalled)) + XCTAssertEqual(output.hints(), []) + let game = Recording() + game.appLine(L10n.string(.modelOpenVRReinstalled)) + game.print(openVRNotLoaded + "\n", by: .game) + XCTAssertEqual(game.hints(), [.modelHintOpenVR]) + // Another plugin that Unity could not load is not this. + XCTAssertEqual(Recording().hints(gameLog: excerpt("DllNotFoundException: GfxPluginNativeRenderer")), []) + } + + func testAnOpenXRStartTheRuntimeRefusedIsHintedOnlyWhenNoRuntimeConnected() { + // What the runtime prints to the game's output as it refuses + // xrCreateInstance (runtime/pe/runtime.cpp). + let refusals = [ + "Basalt OpenXR: xrCreateInstance rejected an invalid application or engine name", + "Basalt OpenXR: unsupported enabled extension 'XR_KHR_vulkan_enable2'", + "Basalt OpenXR: null enabled extension name at index 1", + "Basalt OpenXR: D3D11 runtime support is unavailable", + ] + for line in refusals { + let output = Recording() + output.print(line + "\n", by: .game) + XCTAssertEqual(output.hints(), [.modelHintOpenXR], line) + XCTAssertEqual(Recording().hints(gameLog: excerpt(line)), [.modelHintOpenXR], line) + let connected = Recording() + connected.print(line + "\n", by: .game) + connected.print(runtimeConnected + "\n", by: .streamer) + XCTAssertEqual(connected.hints(gameLog: excerpt(line)), [], line) + } + // The words the rule is named for, with a result. Engines word such a + // line differently, and no engine's wording is pinned here. + XCTAssertEqual(Recording().hints(gameLog: excerpt("[XR] xrCreateInstance failed: XR_ERROR_RUNTIME_UNAVAILABLE")), + [.modelHintOpenXR]) + // Other lines of the runtime are not a failed start. + let other = Recording() + other.print("Basalt OpenXR: right system button pressed\n", by: .game) + XCTAssertEqual(other.hints(), []) + } + + func testTrailBridgesOwnSmokeClientsThatCouldNotStartOpenXRAreHinted() { + let lines = [ + // fail() in runtime/tests/d3d11_runtime_smoke.cpp, after xrCreateInstance. + "FAIL: xrCreateInstance(D3D11) returned XrResult -2", + // runtime/tests/loader_smoke.cpp. + "FAIL: loader xrCreateInstance returned -2", + ] + for line in lines { + let never = Recording() + never.print(line + "\n", by: .game) + XCTAssertEqual(never.hints(), [.modelHintOpenXR], line) + let connected = Recording() + connected.print(line + "\n", by: .game) + connected.print(runtimeConnected + "\n", by: .streamer) + XCTAssertEqual(connected.hints(), [], line) + } + // A result that is no failure is not one. + let succeeded = Recording() + succeeded.print("xrCreateInstance(D3D11) returned XrResult 0\n", by: .game) + XCTAssertEqual(succeeded.hints(), []) + } + + func testAnUnsupportedAPIVersionIsNoErrorWhenTheSessionCameUpAfterIt() { + // Electrician Simulator VR ran after Unity fell back to OpenXR 1.0. + let cameUp = Recording() + cameUp.print(apiVersionRefused + "\n", by: .game) + cameUp.print(runtimeConnected + "\n", by: .streamer) + XCTAssertEqual(cameUp.hints(gameLog: excerpt("Initialize engine version: 6000.0.58f2\n" + apiVersionRefused)), []) + // Nothing came up after it. + let never = Recording() + never.print(apiVersionRefused + "\n", by: .game) + XCTAssertEqual(never.hints(), [.modelHintOpenXR]) + } + + func testTheRuntimeConnectingAfterTheGameEndedStillCounts() { + // The game's output closes and the session stops before the + // streamer's line about the Hello is read; it still counts. + let late = Recording() + late.print(apiVersionRefused + "\n", by: .game) + late.close(.game) + late.print(runtimeConnected + "\n", by: .streamer) + late.close(.streamer) + XCTAssertEqual(late.hints(gameLog: excerpt(apiVersionRefused)), []) + // Only the streamer can say it: the game's output cannot. + let claimed = Recording() + claimed.print(apiVersionRefused + "\n" + runtimeConnected + "\n", by: .game) + XCTAssertEqual(claimed.hints(), [.modelHintOpenXR]) + } + + func testACrashedWineserverIsHintedFromWineOutput() { + for printer in [KnownErrorScanner.Printer.game, .steam] { + let recording = Recording() + recording.print("\(wineserverCrash)\n", by: printer) + recording.appLine(L10n.string(.modelGameExited, "0")) + XCTAssertEqual(recording.hints(), [.modelHintWineCrashed], "\(printer)") + } + // Only at the start of a line of Wine's own; never from the game's log. + let quoted = Recording() + quoted.print(#"Loading C:\Games\wineserver crashed\data.pak"# + "\n", by: .game) + quoted.print(wineserverCrash + "\n", by: .streamer) + XCTAssertEqual(quoted.hints(gameLog: excerpt(wineserverCrash)), []) + } + + // MARK: - What is read + + func testTheAppsOwnLinesAreNeverRead() { + // The manager's launch line quotes an executable path, which can hold anything. + let path = #"C:\Games\wineserver crashed\DllNotFoundException openvr_api\WindowsVideoMedia error.exe"# + let recording = Recording(gStreamer: .missing) + recording.appLine(L10n.string(.modelSteamDirectLaunch, path)) + recording.appLine(wineserverCrash + "\n" + openVRNotLoaded + "\n" + apiVersionRefused) + XCTAssertTrue(recording.console.log.contains(path), recording.console.log) + XCTAssertEqual(recording.hints(), []) + } + + func testOnlyTheExcerptsContentLinesAreRead() throws { + // A header names a folder of the game's own choosing; the notes are + // the excerpt's own. + let label = #"C:\users\steamuser\AppData\LocalLow\DllNotFoundException openvr_api\WindowsVideoMedia error\Player.log"# + let lines = (0..<400).map { "frame \($0)" }.joined(separator: "\n") + let text = GameLogExcerpt(logs: [GameLogExcerpt.Log(engine: .unity, label: label, text: lines, unreadBytes: 4096)], + redactedWith: redactor, wineMayBeRunning: true).text + for marker in ["DllNotFoundException openvr_api", "[… earlier lines not read: 4096 bytes …]", + "[… 200 lines skipped …]", "may still have been running"] { + XCTAssertTrue(text.contains(marker), "\(marker) in \(text)") + } + let marked = GameLogExcerpt(sources: [], text: text) + XCTAssertEqual(KnownErrorScanner.contentLines(of: marked).first, "frame 200") + XCTAssertEqual(KnownErrorScanner.contentLines(of: marked).count, 200) + XCTAssertEqual(Recording(gStreamer: .missing).hints(gameLog: marked), []) + // Every note the excerpt writes is left out, and nothing else. + let notes = [GameLogExcerpt.skipped(1), GameLogExcerpt.skipped(12), GameLogExcerpt.unread(1 << 30), + GameLogExcerpt.omitted(20_000), L10n.string(.recordingGameLogPossiblyIncomplete, language: .en)] + let content = ["[1 line skipped]", "==> not a header", "WindowsVideoMedia error 0xc00d36bb"] + XCTAssertEqual(KnownErrorScanner.contentLines(of: GameLogExcerpt( + sources: [], text: (notes + content).joined(separator: "\n") + "\n")).map(String.init), content) + XCTAssertEqual(Recording(gStreamer: .missing).hints(gameLog: excerpt(videoError)), + [.modelHintVideoWithoutGStreamer]) + } + + func testHarmlessGStreamerNoiseGivesNoHint() { + let pygobject = #"** (wine:39619): CRITICAL **: 11:21:56.465: pygobject initialization failed: could not import gobject (error was: ModuleNotFoundError("No module named 'gi'"))"# + let videoCaps = "(wine:40051): GStreamer-Video-CRITICAL **: 11:22:28.693: " + + "gst_video_info_from_caps: assertion 'gst_caps_is_fixed (caps)' failed" + // As the session log gets them once GStreamer is installed: the first + // between empty "steam:" and "game:" lines, and the repeat total the + // console adds when the game's output closes. A game's own log can + // have them too. + func record(_ recording: Recording) { + recording.print("\n" + pygobject + "\n", by: .steam) + recording.print("\n" + videoCaps + "\n\n" + videoCaps + "\n", by: .game) + recording.close(.game) + } + let gameLog = excerpt([pygobject, videoCaps, videoCaps].joined(separator: "\n")) + let recording = Recording(gStreamer: .missing) + record(recording) + let total = "game: " + L10n.string(.modelGStreamerWarningRepeats, "gst_video_info_from_caps", Int64(1)) + XCTAssertTrue(recording.console.log.hasSuffix(total + "\n"), recording.console.log) + XCTAssertEqual(recording.hints(gameLog: gameLog), []) + + // Rules that would take every one of these lines pass over them, and + // still take a line that is not one. + let rules = [KnownErrorHint("CRITICAL|failed|repeats", reads: .wine, key: .modelHintWineCrashed), + KnownErrorHint("CRITICAL|failed", reads: .game, key: .modelHintOpenVR)] + let wide = Recording(rules: rules) + record(wide) + XCTAssertEqual(wide.hints(gameLog: gameLog), []) + let other = Recording(rules: rules) + record(other) + other.print("(wine:40051): GLib-CRITICAL **: a source failed\n", by: .steam) + XCTAssertEqual(other.hints(), [.modelHintWineCrashed]) + } + + func testEachHintOnceInTheOrderOfTheRules() { + let recording = Recording(gStreamer: .missing) + recording.print([wineserverCrash, "Basalt OpenXR: D3D11 runtime support is unavailable", wineserverCrash, + openVRNotLoaded].joined(separator: "\n") + "\n", by: .game) + XCTAssertEqual(recording.hints(gameLog: excerpt([openVRNotLoaded, videoError, videoError].joined(separator: "\n"))), + [.modelHintVideoWithoutGStreamer, .modelHintOpenVR, .modelHintOpenXR, .modelHintWineCrashed]) + // Given once: the session is done with. + XCTAssertNil(recording.scanner.finish(recording.session)) + recording.print(wineserverCrash + "\n", by: .game) + XCTAssertNil(recording.scanner.finish(recording.session)) + // Two rules for one hint give it once. + let twice = Recording(rules: [KnownErrorHint("^wineserver crashed", reads: .wine, key: .modelHintWineCrashed), + KnownErrorHint("restart", reads: .wine, key: .modelHintWineCrashed)]) + twice.print(wineserverCrash + "\n", by: .steam) + XCTAssertEqual(twice.hints(), [.modelHintWineCrashed]) + } + + func testEachSessionKeepsItsOwnOutput() throws { + var scanner = KnownErrorScanner() + let root = URL(fileURLWithPath: "/Users/example/TrailBridge", isDirectory: true) + let first = UUID(), second = UUID() + let firstGame = NSObject(), secondGame = NSObject(), utility = NSObject() + scanner.begin(first, dataRoot: root) + scanner.attach(ObjectIdentifier(firstGame), printer: .game, to: first) + scanner.begin(second, dataRoot: root.appendingPathComponent("other")) + scanner.attach(ObjectIdentifier(secondGame), printer: .game, to: second) + XCTAssertEqual(scanner.unfinished, [first, second]) + + // The first session's game still prints after the second has taken the log over. + scanner.read(["game: " + wineserverCrash], from: ObjectIdentifier(firstGame)) + scanner.read([wineserverCrash], from: ObjectIdentifier(utility)) + let secondHints = try XCTUnwrap(scanner.finish(second)) + XCTAssertEqual(secondHints.hints.map(\.key), []) + XCTAssertEqual(secondHints.dataRoot, root.appendingPathComponent("other")) + // A closed pipe's identity may come back for one no session attached. + XCTAssertTrue(scanner.isReading(first)) + scanner.close(ObjectIdentifier(firstGame)) + XCTAssertFalse(scanner.isReading(first)) + scanner.read(["game: " + openVRNotLoaded], from: ObjectIdentifier(firstGame)) + XCTAssertEqual(scanner.unfinished, [first]) + XCTAssertEqual(scanner.finish(first)?.hints.map(\.key), [.modelHintWineCrashed]) + XCTAssertEqual(scanner.unfinished, []) + + // A pipe that does not close in time is not read once the session stops reading. + let third = UUID(), thirdGame = NSObject() + scanner.begin(third, dataRoot: root) + scanner.attach(ObjectIdentifier(thirdGame), printer: .game, to: third) + scanner.stopReading(third) + XCTAssertFalse(scanner.isReading(third)) + scanner.read(["game: " + wineserverCrash], from: ObjectIdentifier(thirdGame)) + XCTAssertEqual(scanner.finish(third)?.hints.map(\.key), []) + withExtendedLifetime((firstGame, secondGame, utility, thirdGame)) {} + } + + // MARK: - The hints + + func testHintsNameThePlacesAsTheAppNamesThem() throws { + let previous = L10n.language + defer { L10n.language = previous } + for language in AppLanguage.allCases { + L10n.language = language + for rule in KnownErrorHint.rules { + let text = rule.text + XCTAssertFalse(text.contains("%") || text.contains("\n"), "\(language).\(rule.key): \(text)") + for place in rule.places { + XCTAssertTrue(text.contains(L10n.string(place)), "\(language).\(rule.key): \(place)") + } + } + } + let gStreamer = try XCTUnwrap(KnownErrorHint.rules.first { $0.key == .modelHintVideoWithoutGStreamer }) + let openVR = try XCTUnwrap(KnownErrorHint.rules.first { $0.key == .modelHintOpenVR }) + L10n.language = .en + XCTAssertEqual(gStreamer.text, "The game could not play a video because GStreamer is not installed. " + + "Open “Setup” and click “Get GStreamer…”.") + // The game card's menu item is there even when no openvr_api.dll is + // left for “SET UP OPENVR” to point at. + XCTAssertEqual(openVR.text, "The game could not start OpenVR. SteamVR games need OpenComposite: " + + "in “Library”, open the game card's ⋯ menu and choose “OpenVR Support…”. " + + "If no openvr_api.dll is found there, first restore the game's own copy, " + + "for example by verifying the game's files in Steam.") + L10n.language = .ru + XCTAssertEqual(gStreamer.text, "Игра не смогла воспроизвести видео: GStreamer не установлен. " + + "Откройте «Подготовка» и нажмите «Скачать GStreamer…».") + } + + func testTheSessionRecordKeepsItsHints() throws { + let store = SessionHistoryStore(file: try temporaryDirectory().appendingPathComponent("history.json")) + let record = SessionRecord(profileName: "electrician", settings: StreamLaunchSettings()) + try store.append(record) + XCTAssertNil(store.load().first?.hints) + + let hints = KnownErrorHint.rules.prefix(2).map(\.text) + try store.update(record.id) { $0.hints = hints } + XCTAssertEqual(store.load().first?.hints, hints) + } + + // MARK: - Helpers + + /// The excerpt of a Unity player's log as the app keeps it. + private func excerpt(_ playerLog: String) -> GameLogExcerpt { + GameLogExcerpt(logs: [GameLogExcerpt.Log( + engine: .unity, label: #"C:\users\steamuser\AppData\LocalLow\Example Studio\Electrician VR\Player.log"#, + text: playerLog)], redactedWith: redactor) + } +} + +/// One session as the app records it: what its processes print reaches the +/// session console and then the scanner, as `appendLog` and `finishLog` +/// pass it on; the app's own lines come without a pipe. +@MainActor +private final class Recording { + let console = SessionConsole() + var scanner: KnownErrorScanner + let session = UUID() + private let pipes: [KnownErrorScanner.Printer: NSObject] = [.streamer: NSObject(), .steam: NSObject(), .game: NSObject()] + + /// `gStreamer` as the game found it when it started; nil when it never did. + init(gStreamer: GStreamerInstallation? = .installed(version: "1.28.1"), rules: [KnownErrorHint]? = nil) { + scanner = rules.map(KnownErrorScanner.init(rules:)) ?? KnownErrorScanner() + scanner.begin(session, dataRoot: URL(fileURLWithPath: "/Users/example/TrailBridge", isDirectory: true)) + for (printer, pipe) in pipes { scanner.attach(ObjectIdentifier(pipe), printer: printer, to: session) } + if let gStreamer { scanner.gameStarted(in: session, gStreamer: gStreamer) } + } + + func print(_ output: String, by printer: KnownErrorScanner.Printer) { + let source = ObjectIdentifier(pipes[printer]!) + scanner.read(console.append(output, from: source, prefix: printer.rawValue), from: source) + } + + func close(_ printer: KnownErrorScanner.Printer) { + let source = ObjectIdentifier(pipes[printer]!) + scanner.read(console.finish(source, prefix: printer.rawValue), from: source) + scanner.close(source) + } + + func appLine(_ line: String) { + scanner.read(console.append(line.hasSuffix("\n") ? line : line + "\n"), from: nil) + } + + /// The session's hints once its game's own log has been read. + func hints(gameLog: GameLogExcerpt? = nil) -> [L10nKey] { + scanner.read(gameLog: gameLog, of: session) + return scanner.finish(session)?.hints.map(\.key) ?? [] + } +} From b6fb57a7da5bc28dce4517246f516d9a9a700e3a Mon Sep 17 00:00:00 2001 From: abgitdev <266600699+abgitdev@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:21:59 +0000 Subject: [PATCH 6/7] Test the translated hint without Russian text in the source The test compared the Russian GStreamer hint with a Russian sentence. It now checks that the Russian hint is not the English sentence and does not use the English place names. The loop above already checks that every language names its own places. Co-Authored-By: Claude Opus 5.5 --- .../BasaltManagerKitTests/KnownErrorHintTests.swift | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/streamer/Tests/BasaltManagerKitTests/KnownErrorHintTests.swift b/streamer/Tests/BasaltManagerKitTests/KnownErrorHintTests.swift index 258bc07..879ce97 100644 --- a/streamer/Tests/BasaltManagerKitTests/KnownErrorHintTests.swift +++ b/streamer/Tests/BasaltManagerKitTests/KnownErrorHintTests.swift @@ -306,7 +306,8 @@ final class KnownErrorHintTests: XCTestCase { let gStreamer = try XCTUnwrap(KnownErrorHint.rules.first { $0.key == .modelHintVideoWithoutGStreamer }) let openVR = try XCTUnwrap(KnownErrorHint.rules.first { $0.key == .modelHintOpenVR }) L10n.language = .en - XCTAssertEqual(gStreamer.text, "The game could not play a video because GStreamer is not installed. " + let english = gStreamer.text + XCTAssertEqual(english, "The game could not play a video because GStreamer is not installed. " + "Open “Setup” and click “Get GStreamer…”.") // The game card's menu item is there even when no openvr_api.dll is // left for “SET UP OPENVR” to point at. @@ -314,9 +315,11 @@ final class KnownErrorHintTests: XCTestCase { + "in “Library”, open the game card's ⋯ menu and choose “OpenVR Support…”. " + "If no openvr_api.dll is found there, first restore the game's own copy, " + "for example by verifying the game's files in Steam.") + // Another language has its own sentence and names the places in that + // language; the loop above checks the names themselves. L10n.language = .ru - XCTAssertEqual(gStreamer.text, "Игра не смогла воспроизвести видео: GStreamer не установлен. " - + "Откройте «Подготовка» и нажмите «Скачать GStreamer…».") + XCTAssertNotEqual(gStreamer.text, english) + XCTAssertFalse(gStreamer.text.contains("Setup"), gStreamer.text) } func testTheSessionRecordKeepsItsHints() throws { From 0d36cdb29fa3a80fc6ed71f74655e85c0253c7cf Mon Sep 17 00:00:00 2001 From: abgitdev <266600699+abgitdev@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:23:43 +0000 Subject: [PATCH 7/7] TrailBridge VR 0.2.2: every Steam game starts in the headset Version 0.2.2 starts every Steam game itself instead of through steam.exe -applaunch, checks for GStreamer, keeps a redacted excerpt of the game's own log with each session and hints at known causes when a session ends. The README lists Electrician Simulator VR among the tested games and the diagnostics among the features. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +++- README.md | 3 +++ VERSION | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 462dcb6..21c6c71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ All notable changes to TrailBridge VR are documented here. -## Unreleased +## 0.2.2 — 2026-11-25 - Every Steam game starts in the headset, not only the verified ones. A profile made by Add Steam Game for any other game used to run `steam.exe -applaunch APP_ID`: Steam then started the game @@ -36,6 +36,8 @@ All notable changes to TrailBridge VR are documented here. once, and the diagnostic report lists the hints of recent sessions. GStreamer's harmless warnings never give one, nor does Unity's refused first request for OpenXR 1.1 when the game's runtime connects after it. +- The README lists Electrician Simulator VR among the tested games and the diagnostics among the + features. ## 0.2.1 — 2026-11-15 diff --git a/README.md b/README.md index a6ae267..08bcf8e 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,8 @@ on [BasaltVR](https://github.com/frenchbaguetteman/BasaltVR). - **Game audio** from the Mac itself (macOS 14.2 or newer) or through BlackHole. - **Guided setup**: a Learning guide from a new Mac to the first game, and a Setup page that downloads Wine, the ALVR client and Android platform tools with checksums. +- **Diagnostics that stay on the Mac**: each session keeps an excerpt of the game's own log with + personal data replaced, and the session log hints at known causes, such as a missing GStreamer. - **Clean removal**: one button deletes everything the app stored on the Mac. - **10 languages**: English, Russian, Ukrainian, German, Spanish, French, Italian, Polish, Japanese and Korean. English and Russian are reviewed; the others are machine translations. @@ -97,6 +99,7 @@ on [BasaltVR](https://github.com/frenchbaguetteman/BasaltVR). | VTOL VR | OpenComposite (OpenVR) | TrailBridge VR switches the game to one render pass per eye; without it the right eye stays black. | | BONELAB | The game's own OpenXR | | | Blade & Sorcery | OpenComposite (OpenVR) | | +| Electrician Simulator VR | The game's own OpenXR | Its intro video needs GStreamer, which the Setup page checks for. | Not tested: Macs with 8 GB or 16 GB of memory, other Mac models and other headsets. TrailBridge VR does not promise stable operation on them. Other games may work but are not verified. diff --git a/VERSION b/VERSION index 0c62199..ee1372d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.2.1 +0.2.2