Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.
Swift apple-silicond3dmetaldxmtdxvkfexgame-porting-toolkitgamingmac-gamingmacosmetalmoltenvksteamswiftuivkd3d-protonwhisky-alternativewindows-gameswinewine-wrapper
Battle.net games in the library (highball#417)
Gauthier Piarrette556d6e8fdb2b
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 07dd3f0..6b937a2 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -23,6 +23,8 @@ final class AppState {/// before opening the window; the TabView binds its selection to it.var settingsTab: SettingsTab = .environmentsvar gamesByBottle: [String: [SteamGame]] = [:]+ /// What Battle.net installed in each bottle, from its own records (BattleNetLibrary, highball#417).+ var battleNetByBottle: [String: [BattleNetGame]] = [:]/// The Steam account's games per bottle, installed or not (SteamOwnedLibrary, highball#199).var steamOwnedByBottle: [String: [OwnedSteamGame]] = [:]/// What Steam's app data says about each owned game's Mac build (MacAppInfoBuild), by appid.@@ -280,6 +282,7 @@ final class AppState {libraryItems = LibraryIndex.build(bottles: bottles, steamByBottle: gamesByBottle,steamOwnedByBottle: steamOwnedByBottle, macInstalled: macSteamGames,epicOwned: epicOwned, epicInstalls: epicInstalls,+ battleNetByBottle: battleNetByBottle,plays: libraryPlays, defaultBottle: defaultBottle?.name,pinExists: { bottle, pin in// follows links, so a link to a file that is gone counts as missing@@ -662,6 +665,9 @@ final class AppState {case .pin:guard let pin = bottle.settings.pins.first(where: { $0.id == item.pinID }) else { return }launch(pin: pin.launching(with: renderer), in: bottle)+ case .battlenet:+ guard let game = battleNetGame(for: item, in: bottle.name) else { return }+ launchBattleNetGame(game, item: item, in: bottle, renderer: renderer)}}@@ -984,6 +990,7 @@ final class AppState {/// directories it watches.func refreshInstalledGames() {refreshSteamInstalls()+ refreshBattleNetInstalls()let mac = MacSteam.installedGames()if mac != macSteamGames { macSteamGames = mac; rebuildLibrary() }refreshEpicInstalls()@@ -1000,6 +1007,31 @@ final class AppState {if games != gamesByBottle { gamesByBottle = games; forgetProgramExecutables(); rebuildLibrary() }}+ /// Re-reads what Battle.net installed in each bottle. Its own watcher calls this when the update+ /// agent rewrites its records, which it does often during a download, so it reads two small+ /// files per bottle and nothing else.+ @ObservationIgnored private var battleNetWatcher: DirectoryWatcher?++ func refreshBattleNetInstalls() {+ if readBattleNetInstalls() { forgetProgramExecutables(); rebuildLibrary() }+ }++ /// The reading part, for `refresh` too, which rebuilds the library itself. True on a change.+ @discardableResult private func readBattleNetInstalls() -> Bool {+ if battleNetWatcher == nil { battleNetWatcher = DirectoryWatcher { [weak self] in self?.refreshBattleNetInstalls() } }+ battleNetWatcher?.watch(bottles.map(BattleNetLibrary.agentDirectory(of:)))+ let games = Dictionary(bottles.map { ($0.name, BattleNetLibrary.games(in: $0)) }, uniquingKeysWith: { a, _ in a })+ guard games != battleNetByBottle else { return false }+ battleNetByBottle = games+ return true+ }++ /// The Battle.net game a library item stands for, in the environment the item is homed in.+ func battleNetGame(for item: LibraryItem, in bottleName: String? = nil) -> BattleNetGame? {+ guard let code = item.battleNetProduct, let name = bottleName ?? item.bottleName else { return nil }+ return battleNetByBottle[name]?.first { $0.productCode == code }+ }+private func refreshEpicInstalls() {guard epicSignedIn, !epicFetchInFlight else { return }epicFetchInFlight = true@@ -1048,6 +1080,7 @@ final class AppState {if installWatcher == nil { installWatcher = DirectoryWatcher { [weak self] in self?.refreshInstalledGames() } }installWatcher?.watch(bottles.flatMap(installDirectories) + MacSteam.steamappsDirectories())macSteamGames = MacSteam.installedGames()+ readBattleNetInstalls()startSteamClientWatch()startDiscordWatch()libraryPlays = libraryStore.load()@@ -1993,7 +2026,7 @@ final class AppState {private func findProgramExecutable(for item: LibraryItem) -> URL? {guard let bottleName = item.bottleName, let bottle = bottles.first(where: { $0.name == bottleName }) else { return nil }switch item.source {- case .steam, .epic:+ case .steam, .epic, .battlenet:return programFolder(for: item).flatMap { PEIcon.bestExecutable(in: $0) }case .pin:return item.pinID.flatMap { id in bottle.settings.pins.first { $0.id == id } }.map { $0.executableURL(driveC: bottle.driveC) }@@ -2015,6 +2048,8 @@ final class AppState {folder = item.epicAppName.flatMap { epicInstalls[$0] }.map { URL(fileURLWithPath: $0, isDirectory: true) }case .pin:folder = item.pinID.flatMap { id in bottle.settings.pins.first { $0.id == id } }.map { $0.executableURL(driveC: bottle.driveC).deletingLastPathComponent() }+ case .battlenet:+ folder = battleNetGame(for: item, in: bottleName)?.folder}guard let folder else { return nil }var isDir: ObjCBool = false@@ -2420,6 +2455,11 @@ final class AppState {case .pin:guard let pin = bottles.first(where: { $0.name == bottleName })?.settings.pins.first(where: { $0.id == item.pinID }) else { return nil }executable = URL(fileURLWithPath: pin.path.replacingOccurrences(of: "\\", with: "/")).lastPathComponent+ case .battlenet:+ // The game runs under Battle.net, so its log is that of the launcher Play started.+ guard let game = battleNetGame(for: item, in: bottleName),+ let start = BattleNetLibrary.launch(game, client: bottles.first(where: { $0.name == bottleName }).flatMap(BattleNetLibrary.client(in:))) else { return nil }+ executable = start.executable.lastPathComponentdefault: return nil}let names = (try? FileManager.default.contentsOfDirectory(atPath: paths.logs.path)) ?? []@@ -2452,7 +2492,7 @@ final class AppState {while !Task.isCancelled {try? await Task.sleep(for: .seconds(5))let processes = SessionWatch.currentProcessList()- if SessionWatch.isAlive(markers: session.markers, ps: processes) {+ if SessionWatch.isAlive(session, ps: processes) {misses = 0if let prefix = await self?.discordEnvironmentPrefix(for: session),let env = DiscordSessions.environment(for: session, prefix: prefix, processList: processes) {@@ -2481,7 +2521,7 @@ final class AppState {for _ in 0..<60 {try? await Task.sleep(for: .seconds(2))guard let self, self.runningSessions.contains(session), NSApp.isActive else { return }- let pids = await Task.detached { SessionWatch.pids(ofPrefix: prefix, markers: session.markers) }.value+ let pids = await Task.detached { SessionWatch.pids(ofPrefix: prefix, session: session) }.valueguard let pid = pids.first(where: Self.hasWindowOnScreen),let game = NSRunningApplication(processIdentifier: pid) else { continue }let done = game.activate(from: .current, options: [])@@ -2515,7 +2555,7 @@ final class AppState {await self.appendLog("\(session.title): chosen display is not connected, leaving the window where it opened")return}- for pid in SessionWatch.pids(ofPrefix: prefix, markers: session.markers) {+ for pid in SessionWatch.pids(ofPrefix: prefix, session: session) {for _ in 0..<WindowMover.move(pid: pid, to: monitor.bounds, alreadyMoved: &handled) {await self.appendLog("moved \(session.title) to \(monitor.name)")}@@ -2559,10 +2599,10 @@ final class AppState {// The environment was deleted while the game "ran": end the record, no ghost prompt.endSession(session, reason: "stopped"); postPlay = nil; return}- let prefix = bottle.url, markers = session.markers+ let prefix = bottle.url// terminate waits out a grace period: off the main thread, then the record.Task.detached {- _ = ProcessTable.terminate(SessionWatch.pids(ofPrefix: prefix, markers: markers))+ _ = ProcessTable.terminate(SessionWatch.pids(ofPrefix: prefix, session: session))await MainActor.run { self.endSession(session, reason: "stopped") }}}@@ -2905,6 +2945,61 @@ final class AppState {}}+ /// Starts a game Battle.net installed the way Battle.net's own shortcut does+ /// (BattleNetLibrary.launch): the game's launcher hands the request to Battle.net, opening it+ /// when it is not running, and Battle.net starts the game. As for a Steam game, the game's own+ /// processes, found by its folder, decide when "starting" ends, so the launcher exiting once it+ /// has handed over is no crash. Battle.net starts the game with the environment it was itself+ /// started with: a client already running keeps its graphics mode for the game.+ func launchBattleNetGame(_ game: BattleNetGame, item: LibraryItem, in bottle: Bottle, renderer: Renderer? = nil) {+ guard let engine = engine(for: bottle) else { return }+ if runningSessions.contains(where: { $0.libraryID == item.id && $0.bottleName == bottle.name }) {+ fail(HighballError.failed("\(game.title) is already running."))+ return+ }+ guard let start = BattleNetLibrary.launch(game, client: BattleNetLibrary.client(in: bottle)) else {+ fail(HighballError.failed("\(game.title) has no Battle.net launcher in its folder and Battle.net is not installed in \(bottle.name). Install Battle.net there, or open the game from Battle.net."))+ return+ }+ let entry = gameDB.entry(for: item)+ // The variables this game's recipe scoped to it (highball#198), as for the other stores.+ let gameEnvironment = bottle.settings.environment(forGame: entry?.id)+ let marks = BattleNetLibrary.sessionMarkers(for: game)+ runBusy("Starting \(game.title)",+ expected: start.throughClient ? L("Battle.net opens, then press Play there") : L("a cold Battle.net can take a couple of minutes"),+ done: .handedOff,+ stop: .killBottle(bottle, label: L("Stop"))) { [self] in+ let runner = WineRunner(paths: paths, engine: engine, bottle: bottle)+ await adoptRuntimesInstalledByGames(in: bottle, engine: engine)+ await removeMacMetadataFiles(from: game.folder, of: game.title)+ if start.throughClient {+ appendLog("\(game.title): no Battle.net launcher in its folder, so Battle.net opens and its Play button starts the game")+ }+ let box = LaunchOutcome()+ let log = logLine(box)+ watchedLaunch(box) {+ try await runner.start(start.executable, arguments: start.arguments, renderer: renderer,+ extraEnvironment: gameEnvironment,+ workingDirectory: start.executable.deletingLastPathComponent(), onOutput: log)+ }+ let handedOff = try await awaitHandoff(box, program: game.title, timeout: 360, exitEndsWait: false) {+ let processes = await Self.processList()+ box.processList = processes+ return SessionWatch.isAlive(markers: marks.markers, excluding: marks.excluding, ps: processes)+ } crashed: { result in+ let current = renderer ?? bottle.settings.renderer+ self.crashSuggestion = CrashSuggestion(program: game.title, bottleName: bottle.name,+ renderer: Renderer.suggestion(after: current, d3dmetalAvailable: engine.rendererDir("d3dmetal") != nil, vkd3dAvailable: engine.rendererDir("vkd3d") != nil),+ logPath: result.log.path, current: current, seconds: Int(result.duration),+ alternateEngine: self.alternateEngine(for: bottle), itemID: item.id)+ }+ guard handedOff else { return }+ beginSession(GameSession(title: game.title, bottleName: bottle.name, appid: nil, markers: marks.markers, excluding: marks.excluding,+ renderer: (renderer ?? bottle.settings.renderer).rawValue, libraryID: item.id,+ startNotice: entry?.startNotice, startNoticeMinutes: entry?.startNoticeMinutes), processList: box.processList)+ }+ }+/// Where a launch reports back. The busy work polls this instead of awaiting the task:/// `Task.value` is not cancellation-aware, so racing it against a timer blocked until the/// process exited and the hand-off never happened (review, 2026-09-04).diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swiftindex dc3f7af..58c4c5d 100644--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@ -135,7 +135,8 @@ struct GameDetailView: View {private var libraryInfo: some View {VStack(alignment: .leading, spacing: 12) {- row(L("Source"), item.source == .steam ? "Steam" : item.source == .epic ? "Epic Games" : L("Windows program"))+ row(L("Source"), item.source == .steam ? "Steam" : item.source == .epic ? "Epic Games"+ : item.source == .battlenet ? "Battle.net" : L("Windows program"))if item.sizeOnDisk > 0 {row(L("Size on disk"), ByteCountFormatter.string(fromByteCount: item.sizeOnDisk, countStyle: .file))}diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex 41029b8..b8bcbf1 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -359,6 +359,8 @@ enum L10n {"Running": "En cours","Stop": "Arrêter","a cold Steam client can take a couple of minutes": "un client Steam à froid peut prendre quelques minutes",+ "a cold Battle.net can take a couple of minutes": "un Battle.net à froid peut prendre quelques minutes",+ "Battle.net opens, then press Play there": "Battle.net s'ouvre, appuyez ensuite sur Jouer","Try again": "Réessayer","Download again": "Retélécharger","Repair": "Réparer",diff --git a/Sources/HighballApp/LibraryView.swift b/Sources/HighballApp/LibraryView.swiftindex 46bd2da..83d727d 100644--- a/Sources/HighballApp/LibraryView.swift+++ b/Sources/HighballApp/LibraryView.swift@@ -122,6 +122,10 @@ struct LibraryView: View {FilterChip(label: L("All"), on: sourceFilter == nil) { sourceFilter = nil }FilterChip(label: "Steam", on: sourceFilter == .steam) { sourceFilter = .steam }FilterChip(label: "Epic", on: sourceFilter == .epic) { sourceFilter = .epic }+ // Only once Battle.net has installed something: most libraries never have a game from it.+ if sourceFilter == .battlenet || state.libraryItems.contains(where: { $0.source == .battlenet }) {+ FilterChip(label: "Battle.net", on: sourceFilter == .battlenet) { sourceFilter = .battlenet }+ }FilterChip(label: L("Programs"), on: sourceFilter == .pin) { sourceFilter = .pin }Divider().frame(height: 16)FilterChip(label: L("Installed"), on: installedOnly) { installedOnly.toggle() }@@ -426,7 +430,7 @@ struct SourceBadge: View {/// whole badge lit when Steam for Mac has it installed.var mac: MacSteamBuild? = nilprivate var label: String {- switch source { case .steam: "STEAM"; case .epic: "EPIC"; case .pin: "EXE" }+ switch source { case .steam: "STEAM"; case .epic: "EPIC"; case .pin: "EXE"; case .battlenet: "BATTLE.NET" }}private var lit: Bool { mac == .installed }var body: some View {diff --git a/Sources/HighballKit/BattleNetLibrary.swift b/Sources/HighballKit/BattleNetLibrary.swiftnew file mode 100644index 0000000..b6b47cc--- /dev/null+++ b/Sources/HighballKit/BattleNetLibrary.swift@@ -0,0 +1,296 @@+import Foundation++/// A game Battle.net installed in an environment, read from Battle.net's own records in+/// `ProgramData/Battle.net/Agent` (highball#417): `product.db`, where the update agent keeps one+/// install record per product, and `aggregate.json`, the client's list of what it shows as+/// installed. Nothing here names a game: titles, folders and launchers all come from those files.+public struct BattleNetGame: Sendable, Hashable {+ /// Blizzard's product code, the install record's second field ("pro", "wow", "hsb"). The key+ /// everything joins on: the uid beside it varies ("prometheus", "hs_beta") and the client's+ /// own list keys on the code too.+ public let productCode: String+ public let uid: String+ /// The client's own name for the game when its list has it, else the install folder's name,+ /// which Battle.net names after the game.+ public let title: String+ /// The install folder as Battle.net wrote it ("C:/Program Files (x86)/Overwatch").+ public let installPath: String+ /// The same folder on the Mac.+ public let folder: URL+ /// The game's own Battle.net launcher in its folder ("Overwatch Launcher.exe"), what the+ /// desktop and Start menu shortcuts Battle.net creates point at. nil when there is none.+ public let launcher: URL?+ public let version: String+ /// The installed build's size as the agent recorded it when the download completed, 0 unknown.+ public let sizeOnDisk: Int64+ public let lastPlayed: Date?+ /// The client's box art for the game, when its list carries one.+ public let boxArt: URL?++ public init(productCode: String, uid: String, title: String, installPath: String, folder: URL, launcher: URL?,+ version: String = "", sizeOnDisk: Int64 = 0, lastPlayed: Date? = nil, boxArt: URL? = nil) {+ self.productCode = productCode; self.uid = uid; self.title = title; self.installPath = installPath+ self.folder = folder; self.launcher = launcher; self.version = version; self.sizeOnDisk = sizeOnDisk+ self.lastPlayed = lastPlayed; self.boxArt = boxArt+ }++ /// The library id, "battlenet:<product code>": one tile per game, whatever environment holds it.+ public var libraryID: String { "battlenet:\(productCode)" }+}++public enum BattleNetLibrary {+ /// Battle.net's own products, the update agent and the client. Every record that is not one of+ /// them is a game or a game's edition.+ static let clientProducts: Set<String> = ["agent", "bna"]++ /// Where the update agent keeps its records. The install watcher follows this folder: the agent+ /// rewrites product.db when an install, update or removal ends.+ public static func agentDirectory(of bottle: Bottle) -> URL {+ bottle.driveC.appending(path: "ProgramData/Battle.net/Agent", directoryHint: .isDirectory)+ }++ /// The games Battle.net has installed in a bottle: records the agent marks installed and+ /// playable whose folder is there. A game still downloading, or one whose folder was deleted+ /// behind Battle.net's back, is left out. Empty for a bottle without Battle.net.+ public static func games(in bottle: Bottle) -> [BattleNetGame] {+ let agent = agentDirectory(of: bottle)+ guard let db = try? Data(contentsOf: agent.appending(path: "product.db")),+ let installs = try? ProductDB.installs(in: db) else { return [] }+ let aggregate = (try? Data(contentsOf: agent.appending(path: "aggregate.json"))).map(Aggregate.entries) ?? [:]+ return games(installs: installs, aggregate: aggregate, bottle: bottle)+ }++ static func games(installs: [ProductDB.Install], aggregate: [String: Aggregate.Entry], bottle: Bottle) -> [BattleNetGame] {+ let fm = FileManager.default+ var games: [BattleNetGame] = []+ for install in installs {+ let code = install.productCode+ guard !code.isEmpty, !clientProducts.contains(code.lowercased()), install.installed, install.playable,+ !install.installPath.isEmpty, !games.contains(where: { $0.productCode == code }),+ let folder = macURL(forWindowsPath: install.installPath, in: bottle) else { continue }+ var isDir: ObjCBool = false+ guard fm.fileExists(atPath: folder.path, isDirectory: &isDir), isDir.boolValue else { continue }+ let listed = aggregate[code]+ let folderName = folder.lastPathComponent+ let title = listed?.name ?? (folderName.isEmpty ? code : folderName)+ games.append(BattleNetGame(+ productCode: code, uid: install.uid, title: title, installPath: install.installPath, folder: folder,+ launcher: launcher(listed: listed?.iconPath, folder: folder, bottle: bottle),+ version: install.version, sizeOnDisk: install.totalBytes, lastPlayed: listed?.lastPlayed,+ boxArt: listed?.boxArt))+ }+ // Two editions in one folder (World of Warcraft and its Classic share it) would read alike+ // when the client's list does not name them: the product code tells them apart.+ let titles = Dictionary(grouping: games, by: { $0.title.lowercased() })+ return games.map { game in+ guard (titles[game.title.lowercased()]?.count ?? 0) > 1 else { return game }+ return BattleNetGame(productCode: game.productCode, uid: game.uid, title: "\(game.title) (\(game.productCode))",+ installPath: game.installPath, folder: game.folder, launcher: game.launcher,+ version: game.version, sizeOnDisk: game.sizeOnDisk, lastPlayed: game.lastPlayed, boxArt: game.boxArt)+ }.sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == .orderedAscending }+ }++ /// The game's own launcher: the one the client's list names, else the one file in the game's+ /// folder whose name ends in " Launcher.exe", the name Blizzard gives every game's launcher.+ static func launcher(listed: String?, folder: URL, bottle: Bottle) -> URL? {+ let fm = FileManager.default+ if let listed, listed.lowercased().hasSuffix(".exe"), let url = macURL(forWindowsPath: listed, in: bottle),+ fm.fileExists(atPath: url.path) { return url }+ let names = (try? fm.contentsOfDirectory(atPath: folder.path)) ?? []+ let launchers = names.filter { $0.lowercased().hasSuffix(" launcher.exe") }+ return launchers.count == 1 ? folder.appending(path: launchers[0]) : nil+ }++ /// The Battle.net client itself, from the client's own install record, at the default folder+ /// when that record is missing. nil when neither holds the client.+ public static func client(in bottle: Bottle) -> URL? {+ let agent = agentDirectory(of: bottle)+ let recorded = (try? Data(contentsOf: agent.appending(path: "product.db")))+ .flatMap { try? ProductDB.installs(in: $0) }?+ .first { $0.productCode.lowercased() == "bna" }+ .flatMap { macURL(forWindowsPath: $0.installPath, in: bottle) }+ let folders = [recorded, bottle.driveC.appending(path: "Program Files (x86)/Battle.net", directoryHint: .isDirectory)].compactMap { $0 }+ for folder in folders {+ for name in ["Battle.net Launcher.exe", "Battle.net.exe"] where FileManager.default.fileExists(atPath: folder.appending(path: name).path) {+ return folder.appending(path: name)+ }+ }+ return nil+ }++ /// How Play starts a game, the way Battle.net's own shortcut does: the game's launcher with+ /// `--productcode=<code>`, the argument Blizzard's shortcuts pass it to pick the edition (one+ /// launcher serves World of Warcraft and its Classic). The launcher opens Battle.net, or hands+ /// over to a running one, which then starts the game. Without a launcher, Battle.net opens and+ /// its Play button starts the game.+ public struct Launch: Equatable, Sendable {+ public let executable: URL+ public let arguments: [String]+ /// True when this only opens Battle.net, so the player presses Play there.+ public let throughClient: Bool+ }++ public static func launch(_ game: BattleNetGame, client: URL?) -> Launch? {+ if let launcher = game.launcher {+ return Launch(executable: launcher, arguments: ["--productcode=\(game.productCode)"], throughClient: false)+ }+ return client.map { Launch(executable: $0, arguments: [], throughClient: true) }+ }++ /// What tells a running game apart in `ps`: its folder, in the two spellings Wine's command+ /// lines use, as for Steam games. The launcher in that folder exits once Battle.net has the+ /// request, so it is not the game.+ public static func sessionMarkers(for game: BattleNetGame) -> (markers: [String], excluding: [String]) {+ var windows = game.installPath.replacingOccurrences(of: "/", with: "\\")+ if windows.count >= 2, windows.dropFirst().first == ":" { windows = String(windows.dropFirst(2)) }+ if !windows.hasPrefix("\\") { windows = "\\" + windows }+ if !windows.hasSuffix("\\") { windows += "\\" }+ let unix = game.folder.path.hasSuffix("/") ? game.folder.path : game.folder.path + "/"+ return ([windows, unix], game.launcher.map { [$0.lastPathComponent] } ?? [])+ }++ /// A Windows path as Battle.net writes it ("C:/Program Files (x86)/Overwatch", either slash) on+ /// the Mac. C: is the bottle's drive_c; any other letter is the environment's link for it (a+ /// drive the player added, Z: for the Mac's own root). nil for a path without a drive letter.+ static func macURL(forWindowsPath path: String, in bottle: Bottle) -> URL? {+ let p = path.replacingOccurrences(of: "\\", with: "/")+ guard p.count >= 2, p.dropFirst().first == ":", let letter = p.first?.lowercased(), letter.count == 1,+ letter.first!.isLetter else { return nil }+ let rest = String(p.dropFirst(2)).trimmingCharacters(in: CharacterSet(charactersIn: "/"))+ let drive = letter == "c" ? bottle.driveC+ : bottle.url.appending(path: "dosdevices/\(letter):", directoryHint: .isDirectory).resolvingSymlinksInPath()+ return rest.isEmpty ? drive : drive.appending(path: rest)+ }+}++/// The client's list of installed games (`Agent/aggregate.json`): name, launcher, box art and last+/// play per product code. It can list a game before its download ends, so product.db decides what+/// is installed and this only adds what that file lacks.+enum Aggregate {+ struct Entry: Equatable {+ var name: String?+ var iconPath: String?+ var boxArt: URL?+ var lastPlayed: Date?+ }++ static func entries(_ data: Data) -> [String: Entry] {+ guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let installed = root["installed"] as? [[String: Any]] else { return [:] }+ var out: [String: Entry] = [:]+ for item in installed {+ guard let code = item["product_id"] as? String, !code.isEmpty else { continue }+ let name = (item["name"] as? String).flatMap { $0.trimmingCharacters(in: .whitespaces).isEmpty ? nil : $0 }+ let art = (item["box_art_uri"] as? String).flatMap(URL.init(string:)).flatMap { $0.scheme == "https" ? $0 : nil }+ // Milliseconds since 1970; 0 for never played.+ let played = (item["last_played_timestamp"] as? NSNumber).map(\.doubleValue).flatMap { $0 > 0 ? Date(timeIntervalSince1970: $0 / 1000) : nil }+ out[code] = Entry(name: name, iconPath: item["icon_path"] as? String, boxArt: art, lastPlayed: played)+ }+ return out+ }+}++/// The few fields Highball needs from the update agent's `product.db`, a protocol buffer: a list of+/// install records (field 1), each with uid (1), product code (2), settings (3: install path 1)+/// and cached state (4: base state 1 with installed 1, playable 2, version 7; update progress 4+/// with the build's total bytes 4). The layout is the one Battle.net has used for years and the+/// open readers (Lutris, the GOG Galaxy plugin) document. Fields not listed are skipped by wire+/// type, so fields the agent adds later change nothing.+enum ProductDB {+ struct Install: Equatable {+ var uid = ""+ var productCode = ""+ var installPath = ""+ var installed = false+ var playable = false+ var version = ""+ var totalBytes: Int64 = 0+ }++ static func installs(in data: Data) throws -> [Install] {+ try Protobuf.fields(in: [UInt8](data)).compactMap { field, value in+ guard field == 1, case .bytes(let record) = value else { return nil }+ return try install(record)+ }+ }++ private static func install(_ bytes: [UInt8]) throws -> Install {+ var install = Install()+ for (field, value) in try Protobuf.fields(in: bytes) {+ switch (field, value) {+ case (1, .bytes(let b)): install.uid = String(decoding: b, as: UTF8.self)+ case (2, .bytes(let b)): install.productCode = String(decoding: b, as: UTF8.self)+ case (3, .bytes(let settings)):+ for case (1, .bytes(let b)) in try Protobuf.fields(in: settings) { install.installPath = String(decoding: b, as: UTF8.self) }+ case (4, .bytes(let cached)):+ for (f, v) in try Protobuf.fields(in: cached) {+ switch (f, v) {+ case (1, .bytes(let base)):+ for (g, w) in try Protobuf.fields(in: base) {+ switch (g, w) {+ case (1, .varint(let n)): install.installed = n != 0+ case (2, .varint(let n)): install.playable = n != 0+ case (7, .bytes(let b)): install.version = String(decoding: b, as: UTF8.self)+ default: break+ }+ }+ case (4, .bytes(let progress)):+ for case (4, .varint(let n)) in try Protobuf.fields(in: progress) { install.totalBytes = Int64(clamping: n) }+ default: break+ }+ }+ default: break+ }+ }+ return install+ }+}++/// A minimal protocol buffer wire-format reader: the fields of one message, in order, without a+/// schema. Groups (wire types 3 and 4, long deprecated) and anything cut short are an error.+enum Protobuf {+ enum Value: Equatable {+ case varint(UInt64)+ case fixed64(UInt64)+ case bytes([UInt8])+ case fixed32(UInt32)+ }++ struct Malformed: Error {}++ static func fields(in bytes: [UInt8]) throws -> [(Int, Value)] {+ var out: [(Int, Value)] = []+ var i = 0+ func varint() throws -> UInt64 {+ var result: UInt64 = 0, shift: UInt64 = 0+ while true {+ guard i < bytes.count, shift < 64 else { throw Malformed() }+ let b = bytes[i]; i += 1+ result |= UInt64(b & 0x7F) << shift+ if b & 0x80 == 0 { return result }+ shift += 7+ }+ }+ func take(_ n: Int) throws -> [UInt8] {+ guard n >= 0, n <= bytes.count - i else { throw Malformed() }+ defer { i += n }+ return Array(bytes[i..<i + n])+ }+ while i < bytes.count {+ let key = try varint()+ let field = Int(key >> 3)+ guard field > 0 else { throw Malformed() }+ switch key & 7 {+ case 0: out.append((field, .varint(try varint())))+ case 1: out.append((field, .fixed64(try take(8).reversed().reduce(UInt64(0)) { $0 << 8 | UInt64($1) })))+ case 2:+ let n = try varint()+ guard n <= UInt64(Int.max) else { throw Malformed() }+ out.append((field, .bytes(try take(Int(n)))))+ case 5: out.append((field, .fixed32(try take(4).reversed().reduce(UInt32(0)) { $0 << 8 | UInt32($1) })))+ default: throw Malformed()+ }+ }+ return out+ }+}diff --git a/Sources/HighballKit/DiscordSessions.swift b/Sources/HighballKit/DiscordSessions.swiftindex 9b9a960..4293bf7 100644--- a/Sources/HighballKit/DiscordSessions.swift+++ b/Sources/HighballKit/DiscordSessions.swift@@ -15,7 +15,7 @@ public enum DiscordSessions {public static func environment(for session: GameSession, prefix: URL, processList: String) -> [String: String]? {let root = prefix.resolvingSymlinksInPath().pathfor line in processList.split(whereSeparator: \.isNewline) {- guard session.markers.contains(where: { line.contains($0) }),+ guard session.markers.contains(where: { line.contains($0) }), !session.excluding.contains(where: { line.contains($0) }),let first = line.split(whereSeparator: \.isWhitespace).first,let pid = Int32(first),let command = ProcessTable.commandLineAndEnvironment(of: pid),diff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swiftindex 772f99c..de92b45 100644--- a/Sources/HighballKit/Library.swift+++ b/Sources/HighballKit/Library.swift@@ -7,7 +7,7 @@ import ImageIO// section; the bottle is a per-game property, never the navigation.public enum LibrarySource: String, Sendable, Codable {- case steam, epic, pin+ case steam, epic, pin, battlenet}/// A playable item in the unified library. Pure value: no Bottle, no GameDBEntry — the app@@ -16,7 +16,7 @@ public enum LibrarySource: String, Sendable, Codable {public struct LibraryItem: Identifiable, Sendable, Hashable {public let source: LibrarySource/// Stable identity, also the persistence key in library.json — never change its shape:- /// "steam:<appid>" | "epic:<app_name>" | "pin:<bottle>:<uuid>".+ /// "steam:<appid>" | "epic:<app_name>" | "pin:<bottle>:<uuid>" | "battlenet:<product code>".public let id: Stringpublic let title: String/// Where it lives. nil only for an Epic title owned but not installed in any bottle.@@ -26,6 +26,8 @@ public struct LibraryItem: Identifiable, Sendable, Hashable {public let installedOnMac: Boolpublic let steamAppID: Int?public let epicAppName: String?+ /// Blizzard's product code for a game Battle.net installed (BattleNetGame.productCode).+ public let battleNetProduct: String?public let pinID: UUID?public let artworkTall: URL?public let artworkWide: URL?@@ -36,11 +38,11 @@ public struct LibraryItem: Identifiable, Sendable, Hashable {public init(source: LibrarySource, id: String, title: String, bottleName: String?,installed: Bool, installedOnMac: Bool = false, steamAppID: Int? = nil, epicAppName: String? = nil,- pinID: UUID? = nil, artworkTall: URL? = nil, artworkWide: URL? = nil,+ battleNetProduct: String? = nil, pinID: UUID? = nil, artworkTall: URL? = nil, artworkWide: URL? = nil,otherBottles: [String] = [], sizeOnDisk: Int64 = 0, lastPlayed: Date? = nil) {self.source = source; self.id = id; self.title = title; self.bottleName = bottleNameself.installed = installed; self.installedOnMac = installedOnMac- self.steamAppID = steamAppID; self.epicAppName = epicAppName+ self.steamAppID = steamAppID; self.epicAppName = epicAppName; self.battleNetProduct = battleNetProductself.pinID = pinID; self.artworkTall = artworkTall; self.artworkWide = artworkWideself.otherBottles = otherBottles; self.sizeOnDisk = sizeOnDisk; self.lastPlayed = lastPlayed}@@ -58,7 +60,7 @@ public struct LibraryItem: Identifiable, Sendable, Hashable {let others = (otherBottles.filter { $0 != bottle } + (installed ? [bottleName].compactMap { $0 } : [])).sorted()return LibraryItem(source: source, id: id, title: title, bottleName: bottle, installed: holds,installedOnMac: installedOnMac, steamAppID: steamAppID, epicAppName: epicAppName,- pinID: pinID, artworkTall: artworkTall, artworkWide: artworkWide,+ battleNetProduct: battleNetProduct, pinID: pinID, artworkTall: artworkTall, artworkWide: artworkWide,otherBottles: others, sizeOnDisk: holds ? 0 : sizeOnDisk, lastPlayed: lastPlayed)}}@@ -94,13 +96,15 @@ public enum LibraryIndex {/// `steamOwnedByBottle` adds the account's games that aren't installed anywhere/// (SteamOwnedLibrary, highball#199), homed in the first bottle whose Steam owns them./// `macInstalled` is what Steam for Mac has installed (MacSteam): those games count as- /// installed, and one no bottle knows gets a tile of its own.+ /// installed, and one no bottle knows gets a tile of its own. `battleNetByBottle` is what+ /// Battle.net installed in each bottle (BattleNetLibrary, highball#417).public static func build(bottles: [Bottle],steamByBottle: [String: [SteamGame]],steamOwnedByBottle: [String: [OwnedSteamGame]] = [:],macInstalled: [SteamGame] = [],epicOwned: [EpicStore.Game],epicInstalls: [String: String],+ battleNetByBottle: [String: [BattleNetGame]] = [:],plays: [String: LibraryStore.PlayRecord] = [:],defaultBottle: String? = nil,pinExists: (Bottle, Pin) -> Bool = { _, _ in true }) -> [LibraryItem] {@@ -184,6 +188,27 @@ public enum LibraryIndex {lastPlayed: plays[id]?.lastPlayedAt))}+ // Battle.net: one tile per game like Steam's, homed where it was last played, then in the+ // default environment, then by name; the other environments holding it are remembered.+ var byProduct: [String: [(bottle: String, game: BattleNetGame)]] = [:]+ for bottle in bottles {+ for game in battleNetByBottle[bottle.name] ?? [] { byProduct[game.productCode, default: []].append((bottle.name, game)) }+ }+ for (code, copies) in byProduct {+ let id = "battlenet:\(code)"+ let lastPlayedBottle = plays[id]?.bottle+ let primary = copies.min { a, b in+ if let lp = lastPlayedBottle, (a.bottle == lp) != (b.bottle == lp) { return a.bottle == lp }+ return before(a.bottle, b.bottle)+ }!+ items.append(LibraryItem(+ source: .battlenet, id: id, title: primary.game.title, bottleName: primary.bottle,+ installed: true, battleNetProduct: code, artworkTall: primary.game.boxArt,+ otherBottles: copies.map(\.bottle).filter { $0 != primary.bottle }.sorted(),+ sizeOnDisk: primary.game.sizeOnDisk,+ lastPlayed: [primary.game.lastPlayed, plays[id]?.lastPlayedAt].compactMap { $0 }.max()))+ }+// Custom pins (dropped exes, preinstalled games), no artwork. Installed when the program's// file is there: one on a drive that is unplugged, or deleted since, is not (highball#269,// the Installed filter kept listing them). `pinExists` is the app's check of the disk;diff --git a/Sources/HighballKit/Sessions.swift b/Sources/HighballKit/Sessions.swiftindex e186b38..c9bac65 100644--- a/Sources/HighballKit/Sessions.swift+++ b/Sources/HighballKit/Sessions.swift@@ -10,6 +10,9 @@ public struct GameSession: Identifiable, Sendable, Equatable {public let appid: Int?/// Substrings of the game's command line, in both path styles Wine reports.public let markers: [String]+ /// Substrings of processes that carry a marker without being the game: a Battle.net game's+ /// launcher sits in the game's folder and exits once Battle.net has the request.+ public let excluding: [String]public let started: Date/// The renderer the launch used, for the post-play report.public let renderer: String?@@ -17,9 +20,11 @@ public struct GameSession: Identifiable, Sendable, Equatable {public let startNotice: String?public let startNoticeMinutes: Intpublic let libraryID: String?- public init(id: UUID = UUID(), title: String, bottleName: String, appid: Int?, markers: [String], started: Date = Date(), renderer: String? = nil,+ public init(id: UUID = UUID(), title: String, bottleName: String, appid: Int?, markers: [String], excluding: [String] = [],+ started: Date = Date(), renderer: String? = nil,libraryID: String? = nil, startNotice: String? = nil, startNoticeMinutes: Int? = nil) {- self.id = id; self.title = title; self.bottleName = bottleName; self.appid = appid; self.markers = markers; self.started = started+ self.id = id; self.title = title; self.bottleName = bottleName; self.appid = appid; self.markers = markers+ self.excluding = excluding; self.started = startedself.renderer = renderer; self.libraryID = libraryIDself.startNotice = startNotice.flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 }self.startNoticeMinutes = startNoticeMinutes ?? 15@@ -69,20 +74,37 @@ public enum SessionWatch {markers.contains { ps.contains($0) }}+ /// The same, line by line, leaving out lines that carry one of `excluding`. With nothing to+ /// leave out it is `isAlive(markers:ps:)`.+ public static func isAlive(markers: [String], excluding: [String], ps: String) -> Bool {+ guard !excluding.isEmpty else { return isAlive(markers: markers, ps: ps) }+ return ps.split(whereSeparator: \.isNewline).contains { line in+ markers.contains { line.contains($0) } && !excluding.contains { line.contains($0) }+ }+ }++ public static func isAlive(_ session: GameSession, ps: String) -> Bool {+ isAlive(markers: session.markers, excluding: session.excluding, ps: ps)+ }+public static func currentProcessList() -> String {(try? Shell.capture("/bin/ps", ["axww"])) ?? ""}/// Process ids of the game's own processes inside a prefix, by command line. Used by Stop;/// Steam and the wineserver are left alone so a second game can follow without a cold start.- public static func pids(ofPrefix prefix: URL, markers: [String]) -> [pid_t] {+ public static func pids(ofPrefix prefix: URL, markers: [String], excluding: [String] = []) -> [pid_t] {ProcessTable.processes(ofPrefix: prefix).filter { pid inguard let cl = ProcessTable.commandLineAndEnvironment(of: pid) else { return false }let joined = cl.arguments.joined(separator: " ")- return markers.contains { joined.contains($0) }+ return markers.contains { joined.contains($0) } && !excluding.contains { joined.contains($0) }}}+ public static func pids(ofPrefix prefix: URL, session: GameSession) -> [pid_t] {+ pids(ofPrefix: prefix, markers: session.markers, excluding: session.excluding)+ }+public static func append(_ record: SessionRecord, to logs: URL) {let file = logs.appending(path: "sessions.jsonl")let enc = JSONEncoder(); enc.dateEncodingStrategy = .iso8601diff --git a/Sources/HighballKit/Uninstall.swift b/Sources/HighballKit/Uninstall.swiftindex 22d3316..d1a6546 100644--- a/Sources/HighballKit/Uninstall.swift+++ b/Sources/HighballKit/Uninstall.swift@@ -40,6 +40,10 @@ public enum Uninstall {return .epic(appName: name)case .pin:return .windowsUninstaller+ case .battlenet:+ // Battle.net registers each game with Windows' Add or Remove Programs, pointing at its+ // own uninstaller, which also updates the client's records.+ return .windowsUninstaller}}diff --git a/Tests/Fixtures/battlenet/product-client-only.db b/Tests/Fixtures/battlenet/product-client-only.dbnew file mode 100644index 0000000..c524736Binary files /dev/null and b/Tests/Fixtures/battlenet/product-client-only.db differdiff --git a/Tests/HighballKitTests/BattleNetLibraryTests.swift b/Tests/HighballKitTests/BattleNetLibraryTests.swiftnew file mode 100644index 0000000..8de4062--- /dev/null+++ b/Tests/HighballKitTests/BattleNetLibraryTests.swift@@ -0,0 +1,274 @@+import XCTest+@testable import HighballKit++/// Battle.net games in the library (highball#417): the update agent's product.db read without a+/// schema library, the client's aggregate.json, the launch Battle.net's own shortcuts use, and the+/// tile the library builds. product-client-only.db is the file from a real environment on this+/// project's test Mac, with Battle.net installed and no game (2026-10-29). The game records are+/// built here field by field in the same layout, because no game was installed on that Mac.+final class BattleNetLibraryTests: XCTestCase {+ // MARK: A protocol buffer writer for fixtures++ private enum PB {+ static func varint(_ value: UInt64) -> [UInt8] {+ var v = value, out: [UInt8] = []+ repeat {+ var b = UInt8(v & 0x7F); v >>= 7+ if v != 0 { b |= 0x80 }+ out.append(b)+ } while v != 0+ return out+ }+ static func field(_ n: Int, _ v: UInt64) -> [UInt8] { varint(UInt64(n << 3)) + varint(v) }+ static func field(_ n: Int, _ bytes: [UInt8]) -> [UInt8] { varint(UInt64(n << 3 | 2)) + varint(UInt64(bytes.count)) + bytes }+ static func field(_ n: Int, _ s: String) -> [UInt8] { field(n, Array(s.utf8)) }+ }++ /// One install record as the agent writes it: uid, product code, settings (install path,+ /// region), cached state (base state: installed, playable, version; a backfill progress+ /// holding a double; update progress with the build's total bytes), operations.+ private func record(uid: String, code: String, path: String, installed: Bool = true, playable: Bool = true,+ version: String = "1.0.0.1", bytes: UInt64 = 0) -> [UInt8] {+ let settings = PB.field(1, path) + PB.field(2, "us") + PB.field(3, 0) + PB.field(6, "enUS")+ let base = PB.field(1, installed ? 1 : 0) + PB.field(2, playable ? 1 : 0) + PB.field(3, 1) + PB.field(7, version)+ + PB.field(10, "")+ let backfill = [0x09] + [UInt8](repeating: 0, count: 6) + [0xF0, 0x3F] // field 1, double 1.0+ let update = PB.field(4, bytes)+ let cached = PB.field(1, base) + PB.field(2, backfill) + PB.field(4, update)+ return PB.field(1, PB.field(1, uid) + PB.field(2, code) + PB.field(3, settings) + PB.field(4, cached)+ + PB.field(5, PB.field(2, 0x7FFF_FFFF)) + PB.field(6, "") + PB.field(7, 0))+ }++ private var tmp: URL!++ override func setUpWithError() throws {+ tmp = FileManager.default.temporaryDirectory.appending(path: "hb-bnet-\(UUID().uuidString)", directoryHint: .isDirectory)+ try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws { try? FileManager.default.removeItem(at: tmp) }++ private func bottle(_ name: String = "Games") throws -> Bottle {+ let b = Bottle(url: tmp.appending(path: "bottles/\(name)", directoryHint: .isDirectory),+ settings: BottleSettings(name: name, engineID: "e"))+ try FileManager.default.createDirectory(at: BattleNetLibrary.agentDirectory(of: b), withIntermediateDirectories: true)+ return b+ }++ @discardableResult+ private func folder(_ relative: String, in b: Bottle, files: [String] = []) throws -> URL {+ let url = b.driveC.appending(path: relative, directoryHint: .isDirectory)+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ for f in files { try Data("MZ".utf8).write(to: url.appending(path: f)) }+ return url+ }++ private func write(_ bytes: [UInt8], aggregate: String? = nil, to b: Bottle) throws {+ let agent = BattleNetLibrary.agentDirectory(of: b)+ try Data(bytes).write(to: agent.appending(path: "product.db"))+ if let aggregate { try Data(aggregate.utf8).write(to: agent.appending(path: "aggregate.json")) }+ }++ private var clientRecords: [UInt8] {+ record(uid: "agent", code: "agent", path: "C:/ProgramData/Battle.net/Agent", playable: false)+ + record(uid: "battle.net", code: "bna", path: "C:/Program Files (x86)/Battle.net")+ }++ // MARK: product.db++ func testRealProductDBWithOnlyTheClientHasNoGames() throws {+ let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()+ .appending(path: "Fixtures/battlenet/product-client-only.db")+ let installs = try ProductDB.installs(in: Data(contentsOf: fixture))+ XCTAssertEqual(installs.map(\.productCode), ["agent", "bna"])+ let client = try XCTUnwrap(installs.last)+ XCTAssertEqual(client.uid, "battle.net")+ XCTAssertEqual(client.installPath, "C:/Program Files (x86)/Battle.net")+ XCTAssertEqual(client.version, "2.52.11.17778")+ XCTAssertTrue(client.installed)+ XCTAssertTrue(client.playable)+ XCTAssertFalse(installs[0].playable, "the agent is installed but never playable")++ let b = try bottle()+ try folder("Program Files (x86)/Battle.net", in: b, files: ["Battle.net Launcher.exe"])+ try FileManager.default.copyItem(at: fixture, to: BattleNetLibrary.agentDirectory(of: b).appending(path: "product.db"))+ try Data(#"{"installed": []}"#.utf8).write(to: BattleNetLibrary.agentDirectory(of: b).appending(path: "aggregate.json"))+ XCTAssertEqual(BattleNetLibrary.games(in: b), [], "the agent and the client are not games")+ XCTAssertEqual(BattleNetLibrary.client(in: b)?.lastPathComponent, "Battle.net Launcher.exe")+ }++ func testInstalledGamesComeFromProductDBAndTheClientsList() throws {+ let b = try bottle()+ let ow = try folder("Program Files (x86)/Overwatch", in: b, files: ["Overwatch Launcher.exe"])+ try folder("Program Files (x86)/Overwatch/_retail_", in: b, files: ["Overwatch.exe"])+ let hs = try folder("Program Files (x86)/Hearthstone", in: b, files: ["Hearthstone Beta Launcher.exe", "Hearthstone.exe"])+ try folder("Program Files (x86)/Diablo IV", in: b) // still downloading+ let db = clientRecords+ + record(uid: "prometheus", code: "pro", path: "C:/Program Files (x86)/Overwatch", version: "2.19.0.0.143071", bytes: 52_000_000_000)+ + record(uid: "hs_beta", code: "hsb", path: "C:\\Program Files (x86)\\Hearthstone", bytes: 4_000_000_000)+ + record(uid: "fenris", code: "fenris", path: "C:/Program Files (x86)/Diablo IV", playable: false)+ + record(uid: "osi", code: "osi", path: "C:/Program Files (x86)/Diablo II Resurrected") // folder deleted+ // The client's list, in the shape it writes: Hearthstone named, its launcher, art and last play.+ let aggregate = """+ {"installed": [+ {"product_id": "hsb", "name": "Hearthstone", "icon_index": 0,+ "icon_path": "C:/Program Files (x86)/Hearthstone/Hearthstone Beta Launcher.exe",+ "launch_uri": "battlenet://game/hsb", "last_played_timestamp": 1786266760000,+ "box_art_uri": "https://bnetxboxassets.akamaized.net/hsb/box-enUS.webp",+ "logo_art_uri": "https://bnetxboxassets.akamaized.net/hsb/logo-enUS.webp"},+ {"product_id": "fenris", "name": "Diablo IV", "icon_path": "C:/Program Files (x86)/Diablo IV/Diablo IV Launcher.exe"}+ ]}+ """+ try write(db, aggregate: aggregate, to: b)++ let games = BattleNetLibrary.games(in: b)+ XCTAssertEqual(games.map(\.productCode), ["hsb", "pro"], "installed and playable with a folder only, by title")+ let hsb = try XCTUnwrap(games.first { $0.productCode == "hsb" })+ XCTAssertEqual(hsb.title, "Hearthstone")+ XCTAssertEqual(hsb.uid, "hs_beta")+ XCTAssertEqual(hsb.folder.path, hs.path, "backslashes too")+ XCTAssertEqual(hsb.launcher?.lastPathComponent, "Hearthstone Beta Launcher.exe")+ XCTAssertEqual(hsb.lastPlayed, Date(timeIntervalSince1970: 1_786_266_760))+ XCTAssertEqual(hsb.boxArt?.absoluteString, "https://bnetxboxassets.akamaized.net/hsb/box-enUS.webp")+ XCTAssertEqual(hsb.sizeOnDisk, 4_000_000_000)+ let pro = try XCTUnwrap(games.first { $0.productCode == "pro" })+ XCTAssertEqual(pro.title, "Overwatch", "the folder's name when the client's list has none")+ XCTAssertEqual(pro.launcher?.path, ow.appending(path: "Overwatch Launcher.exe").path, "the one launcher in the folder")+ XCTAssertEqual(pro.version, "2.19.0.0.143071")+ XCTAssertNil(pro.lastPlayed)+ XCTAssertNil(pro.boxArt)+ XCTAssertEqual(pro.libraryID, "battlenet:pro")+ }++ func testEditionsSharingAFolderAreToldApart() throws {+ let b = try bottle()+ try folder("Program Files (x86)/World of Warcraft", in: b, files: ["World of Warcraft Launcher.exe"])+ try write(clientRecords+ + record(uid: "wow", code: "wow", path: "C:/Program Files (x86)/World of Warcraft")+ + record(uid: "wow_classic", code: "wow_classic", path: "C:/Program Files (x86)/World of Warcraft"), to: b)+ let games = BattleNetLibrary.games(in: b)+ XCTAssertEqual(Set(games.map(\.title)), ["World of Warcraft (wow)", "World of Warcraft (wow_classic)"])+ XCTAssertEqual(Set(games.compactMap { $0.launcher?.lastPathComponent }), ["World of Warcraft Launcher.exe"])+ XCTAssertEqual(Set(games.compactMap { BattleNetLibrary.launch($0, client: nil)?.arguments }), [["--productcode=wow"], ["--productcode=wow_classic"]],+ "one launcher, the product code picks the edition, as Blizzard's own shortcuts do")+ }++ func testAnyOtherDriveLetterFollowsTheEnvironmentsLink() throws {+ let b = try bottle()+ let external = tmp.appending(path: "External", directoryHint: .isDirectory)+ try FileManager.default.createDirectory(at: external.appending(path: "Games/Diablo IV"), withIntermediateDirectories: true)+ try Data("MZ".utf8).write(to: external.appending(path: "Games/Diablo IV/Diablo IV Launcher.exe"))+ try FileManager.default.createDirectory(at: b.url.appending(path: "dosdevices"), withIntermediateDirectories: true)+ try FileManager.default.createSymbolicLink(at: b.url.appending(path: "dosdevices/d:"), withDestinationURL: external)+ try write(clientRecords + record(uid: "fenris", code: "fenris", path: "D:/Games/Diablo IV"), to: b)+ let game = try XCTUnwrap(BattleNetLibrary.games(in: b).first)+ XCTAssertEqual(game.folder.resolvingSymlinksInPath().path, external.appending(path: "Games/Diablo IV").resolvingSymlinksInPath().path)+ XCTAssertEqual(game.launcher?.lastPathComponent, "Diablo IV Launcher.exe")+ XCTAssertNil(BattleNetLibrary.macURL(forWindowsPath: "Games/Diablo IV", in: b), "no drive letter, no guess")+ }++ func testDamagedOrMissingRecordsAreNoGames() throws {+ let b = try bottle()+ XCTAssertEqual(BattleNetLibrary.games(in: b), [], "no product.db")+ try folder("Program Files (x86)/Overwatch", in: b)+ let whole = clientRecords + record(uid: "prometheus", code: "pro", path: "C:/Program Files (x86)/Overwatch")+ try write(Array(whole.dropLast(3)), to: b)+ XCTAssertThrowsError(try ProductDB.installs(in: Data(whole.dropLast(3))))+ XCTAssertEqual(BattleNetLibrary.games(in: b), [], "a file cut short reads as nothing, never as half a list")+ try write(whole, aggregate: "not json", to: b)+ XCTAssertEqual(BattleNetLibrary.games(in: b).map(\.title), ["Overwatch"], "an unreadable list only loses the extras")+ }++ func testProtobufSkipsEveryWireTypeItDoesNotNeed() throws {+ let bytes = PB.field(1, 150) + [0x11] + [UInt8](repeating: 1, count: 8) + PB.field(3, "x") + [0x25, 1, 0, 0, 0]+ let fields = try Protobuf.fields(in: bytes)+ XCTAssertEqual(fields.map { $0.0 }, [1, 2, 3, 4])+ XCTAssertEqual(fields[0].1, .varint(150))+ XCTAssertEqual(fields[1].1, .fixed64(0x0101_0101_0101_0101))+ XCTAssertEqual(fields[2].1, .bytes(Array("x".utf8)))+ XCTAssertEqual(fields[3].1, .fixed32(1))+ XCTAssertThrowsError(try Protobuf.fields(in: [0x0B]), "a group is not something the agent writes")+ XCTAssertThrowsError(try Protobuf.fields(in: [0x0A, 0x05, 0x61]), "a length past the end")+ }++ // MARK: Play++ func testPlayStartsTheGamesLauncherElseOpensBattleNet() throws {+ let b = try bottle()+ let client = try folder("Program Files (x86)/Battle.net", in: b, files: ["Battle.net Launcher.exe", "Battle.net.exe"])+ try folder("Program Files (x86)/Overwatch", in: b, files: ["Overwatch Launcher.exe"])+ try folder("Program Files (x86)/Some Game", in: b, files: ["Game.exe"])+ try write(clientRecords + record(uid: "prometheus", code: "pro", path: "C:/Program Files (x86)/Overwatch")+ + record(uid: "zzz", code: "zzz", path: "C:/Program Files (x86)/Some Game"), to: b)+ let games = BattleNetLibrary.games(in: b)+ let bnet = BattleNetLibrary.client(in: b)+ XCTAssertEqual(bnet?.path, client.appending(path: "Battle.net Launcher.exe").path, "the client's own record, the launcher the recipe pins")+ let pro = try XCTUnwrap(BattleNetLibrary.launch(try XCTUnwrap(games.first { $0.productCode == "pro" }), client: bnet))+ XCTAssertEqual(pro.executable.lastPathComponent, "Overwatch Launcher.exe")+ XCTAssertEqual(pro.arguments, ["--productcode=pro"])+ XCTAssertFalse(pro.throughClient)+ let other = try XCTUnwrap(games.first { $0.productCode == "zzz" })+ XCTAssertNil(other.launcher)+ XCTAssertEqual(BattleNetLibrary.launch(other, client: bnet), .init(executable: bnet!, arguments: [], throughClient: true),+ "without a launcher of its own, Battle.net opens and its Play starts the game")+ XCTAssertNil(BattleNetLibrary.launch(other, client: nil))+ }++ func testTheRunningGameIsItsFolderButNotItsLauncher() throws {+ let b = try bottle()+ try folder("Program Files (x86)/Overwatch", in: b, files: ["Overwatch Launcher.exe"])+ try write(clientRecords + record(uid: "prometheus", code: "pro", path: "C:/Program Files (x86)/Overwatch"), to: b)+ let game = try XCTUnwrap(BattleNetLibrary.games(in: b).first)+ let marks = BattleNetLibrary.sessionMarkers(for: game)+ XCTAssertEqual(marks.markers.first, "\\Program Files (x86)\\Overwatch\\")+ XCTAssertEqual(marks.excluding, ["Overwatch Launcher.exe"])+ let launcherOnly = """+ 4242 ?? S 0:00.10 C:\\Program Files (x86)\\Overwatch\\Overwatch Launcher.exe --productcode=pro+ 4243 ?? S 0:03.00 C:\\Program Files (x86)\\Battle.net\\Battle.net.exe+ """+ XCTAssertFalse(SessionWatch.isAlive(markers: marks.markers, excluding: marks.excluding, ps: launcherOnly))+ let playing = launcherOnly + "\n4250 ?? R 1:00.00 C:\\Program Files (x86)\\Overwatch\\_retail_\\Overwatch.exe -uid prometheus"+ XCTAssertTrue(SessionWatch.isAlive(markers: marks.markers, excluding: marks.excluding, ps: playing))+ let session = GameSession(title: game.title, bottleName: "Games", appid: nil, markers: marks.markers, excluding: marks.excluding)+ XCTAssertTrue(SessionWatch.isAlive(session, ps: playing))+ XCTAssertFalse(SessionWatch.isAlive(session, ps: launcherOnly))+ XCTAssertTrue(SessionWatch.isAlive(markers: ["x"], excluding: [], ps: "a x b"), "nothing to leave out is the plain check")+ }++ // MARK: The library++ func testOneTilePerGameHomedLikeSteams() {+ func bottle(_ name: String) -> Bottle {+ Bottle(url: URL(fileURLWithPath: "/tmp/hb-lib-tests/bottles/\(name)"), settings: BottleSettings(name: name, engineID: "e"))+ }+ func game(in name: String, played: Date? = nil) -> BattleNetGame {+ BattleNetGame(productCode: "pro", uid: "prometheus", title: "Overwatch", installPath: "C:/Program Files (x86)/Overwatch",+ folder: URL(fileURLWithPath: "/tmp/hb-lib-tests/bottles/\(name)/drive_c/Program Files (x86)/Overwatch"),+ launcher: nil, sizeOnDisk: 7, lastPlayed: played,+ boxArt: URL(string: "https://bnetxboxassets.akamaized.net/pro/box-enUS.webp"))+ }+ let a = bottle("a"), games = bottle("Games")+ let both = ["a": [game(in: "a")], "Games": [game(in: "Games", played: Date(timeIntervalSince1970: 100))]]+ var items = LibraryIndex.build(bottles: [a, games], steamByBottle: [:], epicOwned: [], epicInstalls: [:],+ battleNetByBottle: both, defaultBottle: "Games")+ XCTAssertEqual(items.count, 1, "one tile per game, never per install")+ let item = items[0]+ XCTAssertEqual(item.id, "battlenet:pro")+ XCTAssertEqual(item.source, .battlenet)+ XCTAssertEqual(item.battleNetProduct, "pro")+ XCTAssertEqual(item.bottleName, "Games", "the default environment before name order")+ XCTAssertEqual(item.otherBottles, ["a"])+ XCTAssertTrue(item.installed)+ XCTAssertEqual(item.sizeOnDisk, 7)+ XCTAssertEqual(item.lastPlayed, Date(timeIntervalSince1970: 100))+ XCTAssertEqual(item.artworkTall?.host, "bnetxboxassets.akamaized.net")+ XCTAssertEqual(item.homed(in: "a").battleNetProduct, "pro", "Play in another environment keeps the product")+ items = LibraryIndex.build(bottles: [a, games], steamByBottle: [:], epicOwned: [], epicInstalls: [:],+ battleNetByBottle: both, plays: ["battlenet:pro": .init(lastPlayedAt: Date(timeIntervalSince1970: 200), bottle: "a")],+ defaultBottle: "Games")+ XCTAssertEqual(items[0].bottleName, "a", "where it was last played comes first")+ XCTAssertEqual(items[0].lastPlayed, Date(timeIntervalSince1970: 200))+ XCTAssertEqual(LibraryIndex.installedForHome(items).map(\.id), ["battlenet:pro"], "installed, so on the Home row")+ XCTAssertEqual(Uninstall.route(for: items[0]), .windowsUninstaller, "Battle.net's own uninstaller, through Add or Remove Programs")+ }+}