Skip to content

Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.

Show the owned Steam library, not only installed games

Kevin993fdb1d6a38
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index a77bca7..4988a05 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -22,6 +22,8 @@ final class AppState {
/// before opening the window; the TabView binds its selection to it.
var settingsTab: SettingsTab = .environments
var gamesByBottle: [String: [SteamGame]] = [:]
+ /// The Steam account's games per bottle, installed or not (SteamOwnedLibrary, highball#199).
+ var steamOwnedByBottle: [String: [OwnedSteamGame]] = [:]
var gameDB = GameDB(directories: [])
// Long-running work
@@ -236,6 +238,7 @@ final class AppState {
func rebuildLibrary() {
libraryItems = LibraryIndex.build(bottles: bottles, steamByBottle: gamesByBottle,
+ steamOwnedByBottle: steamOwnedByBottle,
epicOwned: epicOwned, epicInstalls: epicInstalls,
plays: libraryPlays)
if let deferred = deferredPlayLink { resolvePlayLink(deferred.request) }
@@ -380,9 +383,55 @@ final class AppState {
}
}
- /// Epic-only today: installs into the item's resolved bottle, else the selected one,
- /// else the first — a menu in the detail view refines it, never a modal prerequisite.
+ /// Reads each bottle's owned Steam games off the main thread: appinfo.vdf runs to megabytes
+ /// on a large library. Only a full refresh does this; the library changes rarely.
+ func steamOwnedRefresh() {
+ let bottles = self.bottles
+ Task.detached { [weak self] in
+ let owned = Dictionary(bottles.map { ($0.name, SteamOwnedLibrary.games(in: $0)) }, uniquingKeysWith: { a, _ in a })
+ await MainActor.run {
+ guard let self, owned != self.steamOwnedByBottle else { return }
+ self.steamOwnedByBottle = owned
+ self.rebuildLibrary()
+ }
+ }
+ }
+
+ @ObservationIgnored private var steamLibrarySignatures: [String: String] = [:]
+
+ func steamLibraryMayHaveChanged(_ bottle: String, signature: String) {
+ guard steamLibrarySignatures[bottle] != signature else { return }
+ steamLibrarySignatures[bottle] = signature
+ steamOwnedRefresh()
+ }
+
+ /// Hands an owned Steam game to its bottle's Steam, whose own dialog asks where to put it:
+ /// a running client takes the steam:// URL; otherwise Steam starts as its pin does (with
+ /// the sync its window needs) and receives it as an argument. Nothing is automated.
+ func installSteamGame(_ item: LibraryItem) {
+ guard item.source == .steam, let appid = item.steamAppID,
+ let bottle = item.bottleName.flatMap({ name in bottles.first { $0.name == name } }) ?? defaultBottle,
+ let engine = engine(for: bottle) else { return }
+ let url = "steam://install/\(appid)"
+ appendLog("\(item.title): asking Steam to install it (\(url))")
+ let runner = WineRunner(paths: paths, engine: engine, bottle: bottle)
+ // The recipe's own Steam pin carries the environment Steam's window needs (sync off);
+ // a plain one stands in when the bottle has none.
+ let steam = bottle.driveC.appending(path: "Program Files (x86)/Steam/steam.exe")
+ var pin = bottle.settings.pins.first(where: isSteamUI)
+ ?? Pin(name: "Steam", path: Pin.storagePath(for: steam, driveC: bottle.driveC))
+ pin.arguments.append(url)
+ Task { [weak self] in
+ if (try? await runner.forwardToRunningSteam([url])) == nil {
+ self?.launch(pin: pin, in: bottle)
+ }
+ }
+ }
+
+ /// Epic installs into the item's resolved bottle, else the selected one, else the first — a
+ /// menu in the detail view refines it, never a modal prerequisite. Steam hands off to Steam.
func install(_ item: LibraryItem) {
+ if item.source == .steam { installSteamGame(item); return }
guard item.source == .epic,
let game = epicOwned.first(where: { $0.app_name == item.epicAppName }) else { return }
guard let target = item.bottleName.flatMap({ name in bottles.first { $0.name == name } }) ?? defaultBottle else { return }
@@ -636,6 +685,7 @@ final class AppState {
libraryPlays = libraryStore.load()
libraryOverrides = libraryStore.rendererOverrides()
rebuildLibrary()
+ steamOwnedRefresh()
epicRefresh()
maybeAutoUpdateEngine()
if gameDB.byAppID.isEmpty {
@@ -1416,6 +1466,9 @@ final class AppState {
await MainActor.run { [self] in self.restartHungFirstStart(bottle) }
continue
}
+ // The owned library fills in as the client loads it after sign-in (highball#199).
+ let signature = SteamOwnedLibrary.signature(steamRoot: root)
+ await MainActor.run { [self] in self.steamLibraryMayHaveChanged(bottle.name, signature: signature) }
// Steam can park a launch on a dialog nobody sees (issue #74).
if let waiting = SteamGameAction.pending(steamRoot: root) {
await MainActor.run { [self] in self.steamIsWaitingForAnAnswer(waiting, in: bottle) }
diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swift
index 9e1e1fe..3b101c4 100644
--- a/Sources/HighballApp/GameDetailView.swift
+++ b/Sources/HighballApp/GameDetailView.swift
@@ -16,6 +16,12 @@ struct GameDetailView: View {
private var entry: GameDBEntry? { state.gameDB.entry(for: item) }
private var bottle: Bottle? { item.bottleName.flatMap { name in state.bottles.first { $0.name == name } } }
private var blocked: Bool { entry?.isBlocked == true }
+ /// Steam already has an appmanifest for it (downloading or updating), as opposed to a game
+ /// that is only owned.
+ private var steamHasManifest: Bool {
+ guard let name = item.bottleName, let appid = item.steamAppID else { return false }
+ return state.gamesByBottle[name]?.contains { $0.appid == appid } == true
+ }
private var fixRecipe: HighballKit.Recipe? { state.fixRecipe(for: item) }
private var fixApplied: Bool {
guard let fixRecipe, let bottle else { return false }
@@ -137,6 +143,11 @@ struct GameDetailView: View {
Button(L("Install")) { state.install(item) }.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber)
.disabled(state.busy)
Text(String(format: L("Installs into %@."), state.defaultBottle?.name ?? L("your environment"))).font(.callout).foregroundStyle(.secondary)
+ } else if item.source == .steam, !steamHasManifest {
+ // Owned, never installed here (highball#199): Steam's own dialog takes it from here.
+ Button(L("Install")) { state.install(item) }.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber)
+ .disabled(state.busy)
+ Text(L("Steam asks where to put it.")).font(.callout).foregroundStyle(.secondary)
} else if item.source == .steam {
Text(L("Not downloaded yet. Install it from the Steam window.")).font(.callout).foregroundStyle(.secondary)
if let b = bottle ?? state.defaultBottle { Button(L("Open Steam")) { state.showSteam(in: b) }.controlSize(.large) }
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index 4dd9d7c..8f628c9 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -12,6 +12,7 @@ enum L10n {
"Frame generation (Lossless Scaling, beta)": "Génération d’images (Lossless Scaling, bêta)",
"How frame generation works": "Comment fonctionne la génération d’images",
"Off": "Désactivé",
+ "Steam asks where to put it.": "Steam demande où l’installer.",
"Force vsync": "Forcer la VSync",
"Warning": "Avertissement",
"What this setting does": "Ce que fait ce réglage",
diff --git a/Sources/HighballApp/LibraryView.swift b/Sources/HighballApp/LibraryView.swift
index f44287a..5edffdd 100644
--- a/Sources/HighballApp/LibraryView.swift
+++ b/Sources/HighballApp/LibraryView.swift
@@ -14,7 +14,9 @@ struct LibraryView: View {
@Environment(\.openSettings) private var openSettings
@State private var search = ""
@State private var sourceFilter: LibrarySource?
- @State private var installedOnly = false
+ /// On by default: the owned Steam library (highball#199) must not change what the library
+ /// shows until someone asks for it; switching Installed off reveals owned games.
+ @State private var installedOnly = true
@State private var verifiedOnly = false
private var filtered: [LibraryItem] {
diff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swift
index 84ca893..5a6a107 100644
--- a/Sources/HighballKit/Library.swift
+++ b/Sources/HighballKit/Library.swift
@@ -56,8 +56,11 @@ public enum LibraryIndex {
/// Builds the unified item list. Pure: takes exactly what AppState already holds.
/// Steam games dedup by appid across bottles — one tile per game, never per install;
/// the primary bottle is where it was last played, then a ready copy, then name order.
+ /// `steamOwnedByBottle` adds the account's games that aren't installed anywhere
+ /// (SteamOwnedLibrary, highball#199), homed in the first bottle whose Steam owns them.
public static func build(bottles: [Bottle],
steamByBottle: [String: [SteamGame]],
+ steamOwnedByBottle: [String: [OwnedSteamGame]] = [:],
epicOwned: [EpicStore.Game],
epicInstalls: [String: String],
plays: [String: LibraryStore.PlayRecord] = [:]) -> [LibraryItem] {
@@ -80,15 +83,33 @@ public enum LibraryIndex {
}!
let acfPlayed = copies.compactMap(\.game.lastPlayed).max()
let recorded = plays[id]?.lastPlayedAt
+ // The client's cached art when it has it (see OwnedSteamGame), the CDN otherwise.
+ let owned = steamOwnedByBottle.values.lazy.compactMap { $0.first { $0.appid == appid } }.first
items.append(LibraryItem(
source: .steam, id: id, title: primary.game.name, bottleName: primary.bottle,
installed: primary.game.isReady, steamAppID: appid,
- artworkTall: primary.game.capsuleImage, artworkWide: primary.game.headerImage,
+ artworkTall: owned?.localCapsule ?? primary.game.capsuleImage,
+ artworkWide: owned?.localHeader ?? primary.game.headerImage,
otherBottles: copies.map(\.bottle).filter { $0 != primary.bottle }.sorted(),
sizeOnDisk: primary.game.sizeOnDisk,
lastPlayed: [acfPlayed, recorded].compactMap { $0 }.max()))
}
+ // Steam games owned but not installed: one tile each, like Epic's, in the first bottle
+ // (by name) whose client lists them, where Install will hand them to Steam.
+ var ownedOnly = Set<Int>()
+ for bottle in bottles.sorted(by: { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }) {
+ for game in steamOwnedByBottle[bottle.name] ?? [] where byAppID[game.appid] == nil && !ownedOnly.contains(game.appid) {
+ ownedOnly.insert(game.appid)
+ let id = "steam:\(game.appid)"
+ items.append(LibraryItem(
+ source: .steam, id: id, title: game.name, bottleName: bottle.name,
+ installed: false, steamAppID: game.appid,
+ artworkTall: game.capsuleImage, artworkWide: game.headerImage,
+ lastPlayed: plays[id]?.lastPlayedAt))
+ }
+ }
+
// Epic: legendary installs one copy; the owning bottle is whichever drive_c
// prefixes the install path (see EpicStore.isInstalled).
for game in epicOwned {
diff --git a/Sources/HighballKit/SteamOwnedLibrary.swift b/Sources/HighballKit/SteamOwnedLibrary.swift
new file mode 100644
index 0000000..db7af85
--- /dev/null
+++ b/Sources/HighballKit/SteamOwnedLibrary.swift
@@ -0,0 +1,185 @@
+import Foundation
+
+/// A game the signed-in Steam account owns, installed or not.
+public struct OwnedSteamGame: Sendable, Hashable {
+ public let appid: Int
+ public let name: String
+ /// The client's own copies of the artwork in librarycache, when it has them.
+ public var localCapsule: URL? = nil
+ public var localHeader: URL? = nil
+
+ public init(appid: Int, name: String, localCapsule: URL? = nil, localHeader: URL? = nil) {
+ self.appid = appid; self.name = name; self.localCapsule = localCapsule; self.localHeader = localHeader
+ }
+
+ /// Local art first: newer apps keep theirs at hashed store paths, so the fixed CDN name
+ /// 404s (BALL x PIT, 2062430, checked 2026-09-25) while the client already has the file.
+ public var capsuleImage: URL { localCapsule ?? URL(string: "https://cdn.akamai.steamstatic.com/steam/apps/\(appid)/library_600x900.jpg")! }
+ public var headerImage: URL { localHeader ?? URL(string: "https://cdn.akamai.steamstatic.com/steam/apps/\(appid)/header.jpg")! }
+}
+
+/// The account's library, read from what the environment's own Windows Steam client keeps on
+/// disk: no network, no credentials, no Web API key (highball#199).
+///
+/// - `appcache/librarycache/<appid>/` holds each library app's artwork. The client writes one
+/// folder per app once it has loaded the library, so the folder names are the owned appids
+/// (games, DLC, tools and soundtracks alike).
+/// - `appcache/appinfo.vdf` is Steam's binary app database; its `common.type` keeps the games.
+///
+/// Nothing is there before the first sign-in, which reads as an empty library, not an error.
+public enum SteamOwnedLibrary {
+ public static func games(in bottle: Bottle) -> [OwnedSteamGame] {
+ guard let root = SteamLibrary.steamRoot(of: bottle) else { return [] }
+ return games(steamRoot: root)
+ }
+
+ /// Cheap change check for a running client: the library fills in after sign-in, and
+ /// appinfo.vdf is rewritten as Steam learns about apps. Folder count plus the file's date.
+ public static func signature(steamRoot: URL) -> String {
+ let fm = FileManager.default
+ let count = (try? fm.contentsOfDirectory(atPath: steamRoot.appending(path: "appcache/librarycache").path))?.count ?? 0
+ let date = (try? fm.attributesOfItem(atPath: steamRoot.appending(path: "appcache/appinfo.vdf").path)[.modificationDate] as? Date)?
+ .timeIntervalSince1970 ?? 0
+ return "\(count)|\(date)"
+ }
+
+ static func games(steamRoot: URL) -> [OwnedSteamGame] {
+ let cache = steamRoot.appending(path: "appcache/librarycache")
+ let owned = Set(((try? FileManager.default.contentsOfDirectory(atPath: cache.path)) ?? []).compactMap(Int.init))
+ guard !owned.isEmpty,
+ let apps = try? SteamAppInfo.read(steamRoot.appending(path: "appcache/appinfo.vdf"), only: owned) else { return [] }
+ return owned.compactMap { appid in
+ guard let app = apps[appid], app.type?.lowercased() == "game", let name = app.name else { return nil }
+ let art = artwork(in: cache.appending(path: String(appid)))
+ return OwnedSteamGame(appid: appid, name: name, localCapsule: art["library_600x900.jpg"],
+ localHeader: art["library_header.jpg"] ?? art["header.jpg"])
+ }
+ .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
+ }
+}
+
+extension SteamOwnedLibrary {
+ /// Artwork files in one app's librarycache folder, by name. The client keeps them either at
+ /// the top or one level down in a folder named for the asset's hash.
+ static func artwork(in folder: URL) -> [String: URL] {
+ let fm = FileManager.default
+ var found: [String: URL] = [:]
+ for entry in (try? fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey])) ?? [] {
+ if (try? entry.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true {
+ for file in (try? fm.contentsOfDirectory(at: entry, includingPropertiesForKeys: nil)) ?? [] where found[file.lastPathComponent] == nil {
+ found[file.lastPathComponent] = file
+ }
+ } else {
+ found[entry.lastPathComponent] = entry // top level wins over a hashed copy
+ }
+ }
+ return found
+ }
+}
+
+/// Reader for Steam's binary app database, `appcache/appinfo.vdf` (formats 28 and 29). Only the
+/// fields the library needs are kept.
+///
+/// Layout: magic, universe, (v29) the offset of a key-string table at the end of the file, then
+/// per app: appid, size, info state, last updated, PICS token, text SHA-1, change number,
+/// binary SHA-1, and a binary KeyValues tree whose root is `appinfo`. Type bytes: 0x00 object,
+/// 0x01 string, 0x02 int32, 0x03 float, 0x07 uint64, 0x0A int64, 0x08 end of object. In v29
+/// keys are int32 indexes into the string table; in v28 they're inline C strings.
+public enum SteamAppInfo {
+ public struct App: Sendable, Equatable {
+ public var name: String?
+ public var type: String?
+ public var oslist: String?
+ }
+
+ public struct ParseError: Error, CustomStringConvertible {
+ public let message: String
+ public var description: String { "appinfo.vdf: \(message)" }
+ }
+
+ static let magic28: UInt32 = 0x0756_4428
+ static let magic29: UInt32 = 0x0756_4429
+
+ public static func read(_ url: URL, only wanted: Set<Int>? = nil) throws -> [Int: App] {
+ try parse(Data(contentsOf: url, options: .mappedIfSafe), only: wanted)
+ }
+
+ static func parse(_ data: Data, only wanted: Set<Int>? = nil) throws -> [Int: App] {
+ var r = Reader(bytes: [UInt8](data))
+ let magic = try r.u32()
+ guard magic == magic28 || magic == magic29 else { throw ParseError(message: String(format: "unknown magic %08x", magic)) }
+ _ = try r.u32() // universe
+ var strings: [String]?
+ if magic == magic29 {
+ var t = Reader(bytes: r.bytes, offset: Int(try r.i64()))
+ strings = try (0..<Int(try t.u32())).map { _ in try t.cString() }
+ }
+ var apps: [Int: App] = [:]
+ while true {
+ let appid = Int(try r.u32())
+ if appid == 0 { break }
+ let size = Int(try r.u32())
+ let end = r.offset + size
+ defer { r.offset = end }
+ if let wanted, !wanted.contains(appid) { continue }
+ r.offset += 4 + 4 + 8 + 20 + 4 + 20
+ let root = try r.object(strings)
+ let common = (root["appinfo"]?.object ?? root)["common"]?.object
+ apps[appid] = App(name: common?["name"]?.string, type: common?["type"]?.string, oslist: common?["oslist"]?.string)
+ }
+ return apps
+ }
+
+ enum Node {
+ case string(String)
+ case object([String: Node])
+ var string: String? { if case let .string(s) = self { return s }; return nil }
+ var object: [String: Node]? { if case let .object(o) = self { return o }; return nil }
+ }
+
+ struct Reader {
+ let bytes: [UInt8]
+ var offset = 0
+
+ mutating func take(_ n: Int) throws -> ArraySlice<UInt8> {
+ guard offset + n <= bytes.count else { throw ParseError(message: "truncated at \(offset)") }
+ defer { offset += n }
+ return bytes[offset..<offset + n]
+ }
+ mutating func u8() throws -> UInt8 { try take(1).first! }
+ mutating func u32() throws -> UInt32 { try take(4).reversed().reduce(0) { $0 << 8 | UInt32($1) } }
+ mutating func u64() throws -> UInt64 { try take(8).reversed().reduce(0) { $0 << 8 | UInt64($1) } }
+ mutating func i64() throws -> Int64 { Int64(bitPattern: try u64()) }
+ mutating func cString() throws -> String {
+ let start = offset
+ while offset < bytes.count, bytes[offset] != 0 { offset += 1 }
+ guard offset < bytes.count else { throw ParseError(message: "unterminated string at \(start)") }
+ defer { offset += 1 }
+ return String(decoding: bytes[start..<offset], as: UTF8.self)
+ }
+ mutating func key(_ strings: [String]?) throws -> String {
+ guard let strings else { return try cString() }
+ let i = Int(try u32())
+ guard i < strings.count else { throw ParseError(message: "key index \(i) out of range") }
+ return strings[i]
+ }
+ /// Keys are case-insensitive in Valve's reader; stored lowercased here, so look up lowercase.
+ mutating func object(_ strings: [String]?) throws -> [String: Node] {
+ var out: [String: Node] = [:]
+ while true {
+ let type = try u8()
+ if type == 0x08 { return out }
+ let name = try key(strings).lowercased()
+ switch type {
+ case 0x00: out[name] = .object(try object(strings))
+ case 0x01: out[name] = .string(try cString())
+ case 0x02, 0x04, 0x06: out[name] = .string(String(Int32(bitPattern: try u32())))
+ case 0x03: out[name] = .string(String(Float(bitPattern: try u32())))
+ case 0x07: out[name] = .string(String(try u64()))
+ case 0x0A: out[name] = .string(String(try i64()))
+ default: throw ParseError(message: "unknown value type \(type) at \(offset - 1)")
+ }
+ }
+ }
+ }
+}
diff --git a/Tests/HighballKitTests/SteamOwnedLibraryTests.swift b/Tests/HighballKitTests/SteamOwnedLibraryTests.swift
new file mode 100644
index 0000000..3ff0280
--- /dev/null
+++ b/Tests/HighballKitTests/SteamOwnedLibraryTests.swift
@@ -0,0 +1,151 @@
+import XCTest
+@testable import HighballKit
+
+/// The owned Steam library (highball#199): Steam's binary appinfo.vdf, the librarycache folders
+/// that name the account's apps, and how owned-only games join the library.
+final class SteamOwnedLibraryTests: XCTestCase {
+
+ // MARK: A synthetic appinfo.vdf
+
+ private struct App { var appid: UInt32; var name: String; var type: String; var oslist: String = "windows" }
+
+ private func le<T: FixedWidthInteger>(_ v: T) -> [UInt8] { withUnsafeBytes(of: v.littleEndian) { Array($0) } }
+
+ /// Builds a v29 file (keys as indexes into a trailing string table) or a v28 one (inline keys).
+ private func appinfo(_ apps: [App], v29: Bool = true) -> Data {
+ let keys = ["appinfo", "Common", "name", "type", "oslist", "appid"]
+ func key(_ k: String) -> [UInt8] { v29 ? le(UInt32(keys.firstIndex(of: k)!)) : Array(k.utf8) + [0] }
+ func str(_ k: String, _ v: String) -> [UInt8] { [0x01] + key(k) + Array(v.utf8) + [0] }
+ func int(_ k: String, _ v: UInt32) -> [UInt8] { [0x02] + key(k) + le(v) }
+ func obj(_ k: String, _ body: [UInt8]) -> [UInt8] { [0x00] + key(k) + body + [0x08] }
+
+ var entries: [UInt8] = []
+ for app in apps {
+ // Key case varies in Valve's data; the reader must not care.
+ let kv = obj("appinfo", int("appid", app.appid)
+ + obj("Common", str("name", app.name) + str("type", app.type) + str("oslist", app.oslist))) + [0x08]
+ let header = le(UInt32(2)) + le(UInt32(0)) + le(UInt64(0)) + [UInt8](repeating: 0, count: 20)
+ + le(UInt32(1)) + [UInt8](repeating: 0, count: 20)
+ entries += le(app.appid) + le(UInt32(header.count + kv.count)) + header + kv
+ }
+ var out = le(v29 ? SteamAppInfo.magic29 : SteamAppInfo.magic28) + le(UInt32(1))
+ if v29 {
+ let tableOffset = out.count + 8 + entries.count + 4
+ out += le(Int64(tableOffset)) + entries + le(UInt32(0))
+ out += le(UInt32(keys.count)) + keys.flatMap { Array($0.utf8) + [0] }
+ } else {
+ out += entries + le(UInt32(0))
+ }
+ return Data(out)
+ }
+
+ private let apps = [
+ App(appid: 1145360, name: "Hades", type: "Game", oslist: "windows,macos"),
+ App(appid: 570940, name: "DARK SOULS™: REMASTERED", type: "game"),
+ App(appid: 1145361, name: "Hades Soundtrack", type: "Music"),
+ App(appid: 228980, name: "Steamworks Common Redistributables", type: "Config"),
+ ]
+
+ // MARK: appinfo.vdf
+
+ func testReadsV29() throws {
+ let parsed = try SteamAppInfo.parse(appinfo(apps))
+ XCTAssertEqual(parsed[1145360], SteamAppInfo.App(name: "Hades", type: "Game", oslist: "windows,macos"))
+ XCTAssertEqual(parsed[570940]?.name, "DARK SOULS™: REMASTERED")
+ XCTAssertEqual(parsed.count, 4)
+ }
+
+ func testReadsV28InlineKeys() throws {
+ let parsed = try SteamAppInfo.parse(appinfo(apps, v29: false))
+ XCTAssertEqual(parsed[1145361]?.type, "Music")
+ }
+
+ func testOnlySkipsTheRest() throws {
+ let parsed = try SteamAppInfo.parse(appinfo(apps), only: [570940])
+ XCTAssertEqual(Array(parsed.keys), [570940])
+ }
+
+ func testRejectsUnknownAndTruncatedFiles() throws {
+ XCTAssertThrowsError(try SteamAppInfo.parse(Data([1, 2, 3, 4, 5, 6, 7, 8])))
+ let whole = appinfo(apps)
+ XCTAssertThrowsError(try SteamAppInfo.parse(whole.prefix(whole.count / 2)))
+ }
+
+ // MARK: librarycache + appinfo
+
+ private func steamRoot(owned: [Int], appinfo data: Data?) throws -> URL {
+ let root = FileManager.default.temporaryDirectory.appending(path: "hb-owned-\(UUID())/Steam")
+ for appid in owned {
+ try FileManager.default.createDirectory(at: root.appending(path: "appcache/librarycache/\(appid)"),
+ withIntermediateDirectories: true)
+ }
+ if let data { try data.write(to: root.appending(path: "appcache/appinfo.vdf")) }
+ addTeardownBlock { try? FileManager.default.removeItem(at: root.deletingLastPathComponent()) }
+ return root
+ }
+
+ func testOwnedGamesAreLibraryAppsOfTypeGame() throws {
+ // 999 has artwork but no appinfo row yet: skipped rather than shown nameless.
+ let root = try steamRoot(owned: [1145360, 570940, 1145361, 228980, 999], appinfo: appinfo(apps))
+ let games = SteamOwnedLibrary.games(steamRoot: root)
+ XCTAssertEqual(games.map(\.appid), [570940, 1145360], "games only, by name")
+ XCTAssertEqual(games.first?.capsuleImage.absoluteString,
+ "https://cdn.akamai.steamstatic.com/steam/apps/570940/library_600x900.jpg")
+ }
+
+ func testPrefersTheClientsCachedArtwork() throws {
+ let root = try steamRoot(owned: [2062430, 570940], appinfo: appinfo([
+ App(appid: 2062430, name: "BALL x PIT", type: "game"), App(appid: 570940, name: "DSR", type: "game")]))
+ let cache = root.appending(path: "appcache/librarycache")
+ // BALL x PIT keeps its cover one level down under a hash, as the client writes it.
+ let hashed = cache.appending(path: "2062430/b6cabe1940c55119820eee4ed2d0b604bd5b3af4")
+ try FileManager.default.createDirectory(at: hashed, withIntermediateDirectories: true)
+ try Data([0xFF]).write(to: hashed.appending(path: "library_600x900.jpg"))
+ try Data([0xFF]).write(to: cache.appending(path: "2062430/library_header.jpg"))
+ let games = SteamOwnedLibrary.games(steamRoot: root)
+ let ball = try XCTUnwrap(games.first { $0.appid == 2062430 })
+ XCTAssertEqual(ball.capsuleImage.lastPathComponent, "library_600x900.jpg")
+ XCTAssertTrue(ball.capsuleImage.isFileURL)
+ XCTAssertTrue(ball.headerImage.isFileURL)
+ let dsr = try XCTUnwrap(games.first { $0.appid == 570940 })
+ XCTAssertEqual(dsr.capsuleImage.host, "cdn.akamai.steamstatic.com", "no local art: the CDN")
+ }
+
+ func testNothingBeforeFirstSignIn() throws {
+ XCTAssertEqual(SteamOwnedLibrary.games(steamRoot: try steamRoot(owned: [], appinfo: nil)), [])
+ XCTAssertEqual(SteamOwnedLibrary.games(steamRoot: try steamRoot(owned: [570940], appinfo: nil)), [])
+ }
+
+ func testSignatureChangesAsTheLibraryLoads() throws {
+ let root = try steamRoot(owned: [570940], appinfo: appinfo(apps))
+ let before = SteamOwnedLibrary.signature(steamRoot: root)
+ try FileManager.default.createDirectory(at: root.appending(path: "appcache/librarycache/1145360"), withIntermediateDirectories: true)
+ XCTAssertNotEqual(SteamOwnedLibrary.signature(steamRoot: root), before)
+ XCTAssertEqual(SteamOwnedLibrary.signature(steamRoot: root), SteamOwnedLibrary.signature(steamRoot: root))
+ }
+
+ // MARK: LibraryIndex
+
+ private func bottle(_ name: String) -> Bottle {
+ Bottle(url: URL(fileURLWithPath: "/tmp/hb-lib-tests/bottles/\(name)"), settings: BottleSettings(name: name, engineID: "e"))
+ }
+
+ func testOwnedOnlyGamesJoinTheLibraryOnce() {
+ let a = bottle("a"), b = bottle("b")
+ let installed = SteamGame(appid: 570940, name: "DARK SOULS™: REMASTERED", installdir: "DSR", sizeOnDisk: 1, stateFlags: 4, lastPlayed: nil)
+ let hades = OwnedSteamGame(appid: 1145360, name: "Hades")
+ let dsr = OwnedSteamGame(appid: 570940, name: "DARK SOULS™: REMASTERED")
+ let items = LibraryIndex.build(
+ bottles: [b, a],
+ steamByBottle: ["b": [installed]],
+ steamOwnedByBottle: ["a": [hades, dsr], "b": [hades, dsr]],
+ epicOwned: [], epicInstalls: [:])
+ XCTAssertEqual(items.map(\.id), ["steam:570940", "steam:1145360"], "one tile per game")
+ let dsrItem = items.first { $0.steamAppID == 570940 }!
+ XCTAssertTrue(dsrItem.installed, "the installed copy wins over the owned entry")
+ XCTAssertEqual(dsrItem.bottleName, "b")
+ let hadesItem = items.first { $0.steamAppID == 1145360 }!
+ XCTAssertFalse(hadesItem.installed)
+ XCTAssertEqual(hadesItem.bottleName, "a", "owned-only games live in the first bottle by name")
+ }
+}