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
Library Phase 2, session 1: unified data layer in HighballKit
Gauthier Piarrette94b0bb735f93
diff --git a/Sources/HighballApp/BottleView.swift b/Sources/HighballApp/BottleView.swiftindex 10feb0e..d530304 100644--- a/Sources/HighballApp/BottleView.swift+++ b/Sources/HighballApp/BottleView.swift@@ -50,9 +50,9 @@ struct BottleView: View {}}/// Pins that aren't one of the known launchers (dropped .exe files, custom programs).+ /// The filter itself lives in the Kit so the unified library shares one definition.private var customPins: [Pin] {- let launcherNames = ["steam", "epic games", "battle.net", "gog galaxy", "ea app", "ubisoft connect", "rockstar launcher", "rockstar"]- return bottle.settings.pins.filter { !launcherNames.contains($0.name.lowercased()) }+ bottle.settings.pins.filter { !LibraryIndex.isLauncherPin($0) }}var body: some View {diff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swiftnew file mode 100644index 0000000..ce46c1f--- /dev/null+++ b/Sources/HighballKit/Library.swift@@ -0,0 +1,168 @@+import Foundation++// The unified library (One Library, Phase 2): every playable thing across all bottles and+// sources as one flat, source-neutral list. The store is a badge and a filter, never a+// section; the bottle is a per-game property, never the navigation.++public enum LibrarySource: String, Sendable, Codable {+ case steam, epic, pin+}++/// A playable item in the unified library. Pure value: no Bottle, no GameDBEntry — the app+/// resolves `bottleName` to a Bottle at action time and joins the db at render time, which+/// keeps this type constructible (and the aggregator testable) without a filesystem.+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>".+ public let id: String+ public let title: String+ /// Where it lives. nil only for an Epic title owned but not installed in any bottle.+ public let bottleName: String?+ public let installed: Bool+ public let steamAppID: Int?+ public let epicAppName: String?+ public let pinID: UUID?+ public let artworkTall: URL?+ public let artworkWide: URL?+ /// Dedup leftovers: other bottles holding the same Steam game (detail view only).+ public let otherBottles: [String]+ public let sizeOnDisk: Int64+ public let lastPlayed: Date?++ public init(source: LibrarySource, id: String, title: String, bottleName: String?,+ installed: Bool, steamAppID: Int? = nil, epicAppName: 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 = bottleName+ self.installed = installed; self.steamAppID = steamAppID; self.epicAppName = epicAppName+ self.pinID = pinID; self.artworkTall = artworkTall; self.artworkWide = artworkWide+ self.otherBottles = otherBottles; self.sizeOnDisk = sizeOnDisk; self.lastPlayed = lastPlayed+ }+}++public enum LibraryIndex {+ /// Launcher pins are infrastructure, not games — they never appear in the library, and+ /// launching one is not "playing" for the Continue shelf. Single source of truth for the+ /// filter BottleView's Programs section shares.+ public static func isLauncherPin(_ pin: Pin) -> Bool {+ let launcherNames = ["steam", "epic games", "battle.net", "gog galaxy", "ea app",+ "ubisoft connect", "rockstar launcher", "rockstar"]+ return launcherNames.contains(pin.name.lowercased())+ }++ /// 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.+ public static func build(bottles: [Bottle],+ steamByBottle: [String: [SteamGame]],+ epicOwned: [EpicStore.Game],+ epicInstalls: [String: String],+ plays: [String: LibraryStore.PlayRecord] = [:]) -> [LibraryItem] {+ var items: [LibraryItem] = []++ // Steam: group by appid, pick a primary copy, remember the others.+ var byAppID: [Int: [(bottle: String, game: SteamGame)]] = [:]+ for bottle in bottles {+ for game in steamByBottle[bottle.name] ?? [] {+ byAppID[game.appid, default: []].append((bottle.name, game))+ }+ }+ for (appid, copies) in byAppID {+ let id = "steam:\(appid)"+ 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 }+ if a.game.isReady != b.game.isReady { return a.game.isReady }+ return a.bottle.localizedCaseInsensitiveCompare(b.bottle) == .orderedAscending+ }!+ let acfPlayed = copies.compactMap(\.game.lastPlayed).max()+ let recorded = plays[id]?.lastPlayedAt+ 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,+ otherBottles: copies.map(\.bottle).filter { $0 != primary.bottle }.sorted(),+ sizeOnDisk: primary.game.sizeOnDisk,+ lastPlayed: [acfPlayed, recorded].compactMap { $0 }.max()))+ }++ // Epic: legendary installs one copy; the owning bottle is whichever drive_c+ // prefixes the install path (see EpicStore.isInstalled).+ for game in epicOwned {+ let id = "epic:\(game.app_name)"+ let home = epicInstalls[game.app_name].flatMap { path in+ bottles.first { EpicStore.isInstalled(path: path, inDriveC: $0.driveC) }?.name+ }+ items.append(LibraryItem(+ source: .epic, id: id, title: game.app_title, bottleName: home,+ installed: home != nil, epicAppName: game.app_name,+ artworkTall: game.artworkTall, artworkWide: game.artworkWide,+ lastPlayed: plays[id]?.lastPlayedAt))+ }++ // Custom pins (dropped exes, preinstalled games) — always installed, no artwork.+ for bottle in bottles {+ for pin in bottle.settings.pins where !isLauncherPin(pin) {+ let id = "pin:\(bottle.name):\(pin.id.uuidString)"+ items.append(LibraryItem(+ source: .pin, id: id, title: pin.name, bottleName: bottle.name,+ installed: true, pinID: pin.id,+ lastPlayed: plays[id]?.lastPlayedAt))+ }+ }++ return items.sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == .orderedAscending }+ }+}++/// Last-played persistence for the Continue shelf. Lives in its own library.json at the+/// Highball home — NOT in bottle.json: an Epic item's bottle is derived, dedup makes the+/// timestamp belong to the game identity, and a duplicated bottle must not duplicate play+/// history. Steam items additionally seed from the ACF's own LastPlayed, so the shelf is+/// meaningful on first run and stays right when Steam launches games without us.+public struct LibraryStore: Sendable {+ public struct PlayRecord: Codable, Sendable, Equatable {+ public var lastPlayedAt: Date+ public var bottle: String?+ public init(lastPlayedAt: Date, bottle: String?) {+ self.lastPlayedAt = lastPlayedAt; self.bottle = bottle+ }+ }+ private struct FileShape: Codable {+ var formatVersion: Int = 1+ var items: [String: PlayRecord] = [:]+ }++ public let paths: HighballPaths+ public init(paths: HighballPaths = HighballPaths()) { self.paths = paths }++ var fileURL: URL { paths.home.appending(path: "library.json") }++ /// Tolerant load: missing or corrupt file is an empty history, never an error.+ public func load() -> [String: PlayRecord] {+ guard let data = try? Data(contentsOf: fileURL),+ let shape = try? JSONDecoder.highball.decode(FileShape.self, from: data) else { return [:] }+ return shape.items+ }++ public func recordPlay(id: String, bottle: String?, date: Date = Date()) {+ var shape = FileShape(items: load())+ shape.items[id] = PlayRecord(lastPlayedAt: date, bottle: bottle)+ try? paths.ensure()+ if let data = try? JSONEncoder.highball.encode(shape) {+ try? data.write(to: fileURL, options: .atomic)+ }+ }++ /// Drops records whose items no longer exist (uninstalled games, deleted pins).+ public func prune(validIDs: Set<String>) {+ let current = load()+ let kept = current.filter { validIDs.contains($0.key) }+ guard kept.count != current.count else { return }+ let shape = FileShape(items: kept)+ if let data = try? JSONEncoder.highball.encode(shape) {+ try? data.write(to: fileURL, options: .atomic)+ }+ }+}diff --git a/Sources/HighballKit/SteamLibrary.swift b/Sources/HighballKit/SteamLibrary.swiftindex 6e7f360..58b6bfd 100644--- a/Sources/HighballKit/SteamLibrary.swift+++ b/Sources/HighballKit/SteamLibrary.swift@@ -8,6 +8,9 @@ public struct SteamGame: Identifiable, Sendable, Hashable {public let installdir: Stringpublic let sizeOnDisk: Int64public let stateFlags: Int+ /// Steam's own LastPlayed from the ACF (unix seconds; 0 = never). Seeds the library's+ /// Continue shelf so it works on first run and tracks plays Steam started without us.+ public let lastPlayed: Date?public var id: Int { appid }/// StateFlags 4 = fully installed; anything else is updating/downloading/broken.@@ -46,12 +49,14 @@ public enum SteamLibrary {fields[String(match.1)] = String(match.2)}guard let appidText = fields["appid"], let appid = Int(appidText), let name = fields["name"] else { return nil }+ let played = TimeInterval(fields["LastPlayed"] ?? "") ?? 0return SteamGame(appid: appid,name: name,installdir: fields["installdir"] ?? "",sizeOnDisk: Int64(fields["SizeOnDisk"] ?? "") ?? 0,- stateFlags: Int(fields["StateFlags"] ?? "") ?? 0+ stateFlags: Int(fields["StateFlags"] ?? "") ?? 0,+ lastPlayed: played > 0 ? Date(timeIntervalSince1970: played) : nil)}}diff --git a/Tests/HighballKitTests/LibraryTests.swift b/Tests/HighballKitTests/LibraryTests.swiftnew file mode 100644index 0000000..fd0d457--- /dev/null+++ b/Tests/HighballKitTests/LibraryTests.swift@@ -0,0 +1,98 @@+import XCTest+@testable import HighballKit++/// The unified library's data layer (One Library Phase 2): aggregation, dedup, per-bottle+/// Epic resolution, launcher-pin filtering, and last-played persistence.+final class LibraryTests: XCTestCase {+ private func bottle(_ name: String) -> Bottle {+ Bottle(url: URL(fileURLWithPath: "/tmp/hb-lib-tests/bottles/\(name)"),+ settings: BottleSettings(name: name, engineID: "e"))+ }+ private func steam(_ appid: Int, _ name: String, ready: Bool = true, played: Date? = nil) -> SteamGame {+ SteamGame(appid: appid, name: name, installdir: name, sizeOnDisk: 1,+ stateFlags: ready ? 4 : 2, lastPlayed: played)+ }++ func testAggregationAcrossSourcesAndBottles() {+ var a = bottle("a"); let b = bottle("b")+ a.settings.pins = [Pin(name: "Steam", path: "s/steam.exe"), // launcher: excluded+ Pin(name: "MyGame", path: "Games/my.exe")] // custom: included+ let items = LibraryIndex.build(+ bottles: [a, b],+ steamByBottle: ["a": [steam(620, "Portal 2")], "b": [steam(730, "CS2")]],+ epicOwned: [EpicStore.Game(app_name: "Duck", app_title: "Cardpocalypse")],+ epicInstalls: [:])+ XCTAssertEqual(items.count, 4, "2 steam + 1 epic + 1 custom pin (launcher pin excluded)")+ XCTAssertEqual(items.map(\.id).sorted(),+ ["epic:Duck", "pin:a:\(a.settings.pins[1].id.uuidString)", "steam:620", "steam:730"].sorted())+ XCTAssertTrue(items.first { $0.id == "epic:Duck" }!.installed == false)+ }++ func testSteamDedupPrimarySelection() {+ let a = bottle("a"), b = bottle("b"), c = bottle("c")+ let both = ["a": [steam(620, "Portal 2", ready: false)],+ "b": [steam(620, "Portal 2", ready: true)],+ "c": [steam(620, "Portal 2", ready: true)]]+ // No play history: a ready copy wins, name order tiebreaks (b before c).+ var items = LibraryIndex.build(bottles: [a, b, c], steamByBottle: both,+ epicOwned: [], epicInstalls: [:])+ XCTAssertEqual(items.count, 1, "one tile per game, never per install")+ XCTAssertEqual(items[0].bottleName, "b")+ XCTAssertEqual(items[0].otherBottles, ["a", "c"])+ // Play history wins over readiness order.+ items = LibraryIndex.build(bottles: [a, b, c], steamByBottle: both,+ epicOwned: [], epicInstalls: [:],+ plays: ["steam:620": .init(lastPlayedAt: Date(), bottle: "c")])+ XCTAssertEqual(items[0].bottleName, "c", "last-played bottle is the primary")+ }++ func testEpicBottleResolutionByInstallPath() {+ let a = bottle("a"), b = bottle("b")+ let game = EpicStore.Game(app_name: "Duck", app_title: "Cardpocalypse")+ let inA = LibraryIndex.build(bottles: [a, b], steamByBottle: [:], epicOwned: [game],+ epicInstalls: ["Duck": a.driveC.appending(path: "Games/Cardpocalypse").path])+ XCTAssertEqual(inA[0].bottleName, "a")+ XCTAssertTrue(inA[0].installed)+ let orphan = LibraryIndex.build(bottles: [a, b], steamByBottle: [:], epicOwned: [game],+ epicInstalls: ["Duck": "/tmp/somewhere/else"])+ XCTAssertNil(orphan[0].bottleName, "an install outside every bottle is not installed here")+ XCTAssertFalse(orphan[0].installed)+ }++ func testLauncherPinFilter() {+ XCTAssertTrue(LibraryIndex.isLauncherPin(Pin(name: "Steam", path: "x")))+ XCTAssertTrue(LibraryIndex.isLauncherPin(Pin(name: "Battle.net", path: "x")))+ XCTAssertFalse(LibraryIndex.isLauncherPin(Pin(name: "MyGame", path: "x")))+ }++ func testLibraryStoreRoundTripAndPrune() throws {+ let tmp = FileManager.default.temporaryDirectory.appending(path: "hb-lib-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: tmp) }+ let store = LibraryStore(paths: HighballPaths(home: tmp))+ XCTAssertEqual(store.load(), [:], "missing file is an empty history")+ store.recordPlay(id: "steam:620", bottle: "a", date: Date(timeIntervalSince1970: 1000))+ store.recordPlay(id: "epic:Duck", bottle: "b", date: Date(timeIntervalSince1970: 2000))+ let loaded = store.load()+ XCTAssertEqual(loaded.count, 2)+ XCTAssertEqual(loaded["steam:620"]?.bottle, "a")+ store.prune(validIDs: ["epic:Duck"])+ XCTAssertEqual(store.load().keys.sorted(), ["epic:Duck"])+ // Corrupt file tolerated.+ try Data("not json".utf8).write(to: tmp.appending(path: "library.json"))+ XCTAssertEqual(store.load(), [:])+ }++ func testACFLastPlayedSeedsShelf() {+ let acf = """+ "AppState" { "appid" "620" "name" "Portal 2" "StateFlags" "4" "LastPlayed" "1756300000" }+ """+ let tmp = FileManager.default.temporaryDirectory.appending(path: "hb-acf-\(UUID().uuidString).acf")+ defer { try? FileManager.default.removeItem(at: tmp) }+ try? Data(acf.utf8).write(to: tmp)+ let game = SteamLibrary.parseManifest(tmp)+ XCTAssertEqual(game?.lastPlayed, Date(timeIntervalSince1970: 1756300000))+ // LastPlayed 0 (never played) must stay nil.+ try? Data(acf.replacingOccurrences(of: "1756300000", with: "0").utf8).write(to: tmp)+ XCTAssertNil(SteamLibrary.parseManifest(tmp)?.lastPlayed)+ }+}