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
Epic copies match database rows, and a removed Epic game no longer shows as installed (#63)
Gauthier Piarrettec67615d5dba4
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 64fc6b0..3198e2d 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -148,7 +148,7 @@ final class AppState {/// The verified fix recipe for a library item, if the db has one (db entry id == recipe id).func fixRecipe(for item: LibraryItem) -> HighballKit.Recipe? {- guard let appid = item.steamAppID, let entry = gameDB[appid],+ guard let entry = gameDB.entry(for: item),let recipe = Self.recipe(entry.id), recipe.kind == .game else { return nil }return recipe}@@ -172,7 +172,7 @@ final class AppState {// the engine simply lacks degrades to one it has, and the log says so.var renderer = rendererif let engine = engine(for: bottle) {- let rowMode = bottle.settings.rendererExplicit ? nil : item.steamAppID.flatMap { gameDB[$0]?.effectiveRenderer() }+ let rowMode = bottle.settings.rendererExplicit ? nil : gameDB.entry(for: item)?.effectiveRenderer()let pinMode = item.pinID.flatMap { id in bottle.settings.pins.first { $0.id == id }?.renderer }let wanted = renderer ?? rowMode ?? pinMode ?? bottle.settings.rendererswitch wanted.availability(in: engine) {@@ -334,7 +334,7 @@ final class AppState {await MainActor.run { [weak self] inguard let self else { return }self.epicFetchInFlight = false- let installs = Dictionary(uniqueKeysWithValues: installed.compactMap { g in g.install_path.map { (g.app_name, $0) } })+ let installs = EpicStore.installMap(installed)guard installs != self.epicInstalls else { return }self.epicInstalls = installsself.rebuildLibrary()@@ -1390,8 +1390,7 @@ final class AppState {let installed = (try? store.installedGames()) ?? []await MainActor.run { [weak self] inself?.epicOwned = owned.sorted { $0.app_title < $1.app_title }- self?.epicInstalls = Dictionary(uniqueKeysWithValues:- installed.compactMap { g in g.install_path.map { (g.app_name, $0) } })+ self?.epicInstalls = EpicStore.installMap(installed)self?.epicLoading = falseself?.epicFetchInFlight = falseself?.rebuildLibrary() // Epic results arrive after refresh(); fold them indiff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swiftindex e692e28..568735b 100644--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@ -12,7 +12,7 @@ struct GameDetailView: View {@State private var showWhy = false@State private var showAdvanced = false- private var entry: GameDBEntry? { item.steamAppID.flatMap { state.gameDB[$0] } }+ 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 }private var fixRecipe: HighballKit.Recipe? { state.fixRecipe(for: item) }diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex 34fabea..f15ad4f 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -227,9 +227,9 @@ struct ContentView: View {isPresented: .init(get: { state.pendingD3DMetal != nil }, set: { if !$0 { state.pendingD3DMetal = nil } }),presenting: state.pendingD3DMetal) { pending inButton(L("Turn it on and play")) { state.enableD3DMetalAndPlay() }- if let other = GamePageCopy.otherWorkingRenderer(pending.item.steamAppID.flatMap { state.gameDB[$0] }) {+ if let other = GamePageCopy.otherWorkingRenderer(state.gameDB.entry(for: pending.item)) {Button(String(format: L("Play with %@"), GamePageCopy.plainName(other))) { state.playPendingD3DMetal(with: other) }- } else if pending.item.steamAppID.flatMap({ state.gameDB[$0]?.effectiveRenderer() }) != .d3dmetal {+ } else if state.gameDB.entry(for: pending.item)?.effectiveRenderer() != .d3dmetal {// The ask came from the environment's setting, not a row that needs D3DMetal:// the default mode is a real way out (#61 had none short of a new bottle).Button(String(format: L("Play with %@"), GamePageCopy.plainName(.dxmt))) { state.playPendingD3DMetal(with: .dxmt) }@@ -241,8 +241,7 @@ struct ContentView: View {}Button(L("Not now"), role: .cancel) { state.pendingD3DMetal = nil }} message: { pending in- let entry = pending.item.steamAppID.flatMap { state.gameDB[$0] }- Text(GamePageCopy.d3dMetalAsk(title: pending.item.title, entry: entry))+ Text(GamePageCopy.d3dMetalAsk(title: pending.item.title, entry: state.gameDB.entry(for: pending.item)))}.alert(state.pendingEngine.map { String(format: L("%@ needs the %@ engine"), $0.recipe.title, GamePageCopy.shortEngineName($0.manifest)) } ?? "",isPresented: .init(get: { state.pendingEngine != nil }, set: { if !$0 { state.pendingEngine = nil } }),diff --git a/Sources/HighballApp/LibraryView.swift b/Sources/HighballApp/LibraryView.swiftindex e345743..0c85e94 100644--- a/Sources/HighballApp/LibraryView.swift+++ b/Sources/HighballApp/LibraryView.swift@@ -22,8 +22,7 @@ struct LibraryView: View {if let sourceFilter, item.source != sourceFilter { return false }if installedOnly && !item.installed { return false }if verifiedOnly {- guard let appid = item.steamAppID,- state.gameDB[appid]?.status == "verified-local" else { return false }+ guard state.gameDB.entry(for: item)?.status == "verified-local" else { return false }}if !search.isEmpty && !item.title.localizedCaseInsensitiveContains(search) { return false }return true@@ -81,7 +80,7 @@ struct LibraryView: View {}private func entry(for item: LibraryItem) -> GameDBEntry? {- item.steamAppID.flatMap { state.gameDB[$0] }+ state.gameDB.entry(for: item)}private var filterBar: some View {diff --git a/Sources/HighballKit/EpicStore.swift b/Sources/HighballKit/EpicStore.swiftindex bccd18e..5281358 100644--- a/Sources/HighballKit/EpicStore.swift+++ b/Sources/HighballKit/EpicStore.swift@@ -161,6 +161,15 @@ public struct EpicStore: Sendable {return try JSONDecoder().decode([InstalledGame].self, from: Data(out.utf8))}+ /// Legendary's install records, app name to path, keeping only the ones whose folder still+ /// exists. Legendary never notices a removed environment or a deleted game folder, and a+ /// record it keeps showed Guardians of the Galaxy as installed after its bottle was gone (#63).+ public static func installMap(_ games: [InstalledGame]) -> [String: String] {+ Dictionary(uniqueKeysWithValues: games.compactMap { g in+ g.install_path.flatMap { FileManager.default.fileExists(atPath: $0) ? (g.app_name, $0) : nil }+ })+ }+/// True when an install path lies inside the given bottle's drive_c.public static func isInstalled(path: String, inDriveC driveC: URL) -> Bool {let p = URL(fileURLWithPath: path).standardizedFileURL.path + "/"diff --git a/Sources/HighballKit/SteamLibrary.swift b/Sources/HighballKit/SteamLibrary.swiftindex ba0dc9f..1c5a5bc 100644--- a/Sources/HighballKit/SteamLibrary.swift+++ b/Sources/HighballKit/SteamLibrary.swift@@ -73,6 +73,9 @@ public struct GameDBEntry: Codable, Sendable {public var id: Stringpublic var title: Stringpublic var steam_appid: Int?+ /// Legendary's app name for the Epic copy (#63: an Epic copy of a row's game matched nothing,+ /// so Play never asked for D3DMetal and DXMT refused the DirectX 12 game).+ public var epic_app_name: String?public var status: String // verified-local | reported-upstream | community | blocked-anticheatpublic var renderer: Renderer?public var provenance: String?@@ -135,6 +138,10 @@ public struct GameDBEntry: Codable, Sendable {public struct GameDB: Sendable {public let byAppID: [Int: GameDBEntry]+ /// Rows by Legendary app name, for Epic copies.+ public let byEpicAppName: [String: GameDBEntry]+ /// Rows by normalized title, the fallback for a copy from a store the row does not name.+ public let byTitle: [String: GameDBEntry]/// Default lookup locations for a CLI/dev context: a sibling highball-db checkout, or ./db/games.public static func defaultDirectories() -> [URL] {@@ -142,18 +149,40 @@ public struct GameDB: Sendable {}public init(directories: [URL]) {- var index: [Int: GameDBEntry] = [:]+ var index: [Int: GameDBEntry] = [:], epic: [String: GameDBEntry] = [:], titles: [String: GameDBEntry] = [:]for dir in directories {guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) else { continue }for file in files where file.pathExtension == "json" {guard let data = try? Data(contentsOf: file),- let entry = try? JSONDecoder().decode(GameDBEntry.self, from: data),- let appid = entry.steam_appid else { continue }- index[appid] = entry+ let entry = try? JSONDecoder().decode(GameDBEntry.self, from: data) else { continue }+ if let appid = entry.steam_appid { index[appid] = entry }+ if let name = entry.epic_app_name { epic[name] = entry }+ let key = Self.normalizedTitle(entry.title)+ if !key.isEmpty, titles[key] == nil { titles[key] = entry }}}- byAppID = index+ byAppID = index; byEpicAppName = epic; byTitle = titles}public subscript(appid: Int) -> GameDBEntry? { byAppID[appid] }++ /// Lowercased letters, digits and single spaces, apostrophes dropped: "Marvel's Guardians of+ /// the Galaxy™" and "Marvels Guardians Of The Galaxy" are the same title. Exact after that,+ /// never fuzzy.+ public static func normalizedTitle(_ title: String) -> String {+ let apostrophes: Set<Unicode.Scalar> = ["'", "\u{2019}", "\u{2018}"]+ let kept = title.lowercased().unicodeScalars.compactMap { scalar -> Character? in+ if apostrophes.contains(scalar) { return nil }+ return CharacterSet.alphanumerics.contains(scalar) ? Character(scalar) : " "+ }+ return String(kept).split(separator: " ").joined(separator: " ")+ }++ /// The row for a library item, whatever store it came from: the Steam id first, then the+ /// Epic app name, then the normalized title. Nil for a program the database does not know.+ public func entry(for item: LibraryItem) -> GameDBEntry? {+ if let appid = item.steamAppID, let e = byAppID[appid] { return e }+ if let name = item.epicAppName, let e = byEpicAppName[name] { return e }+ return byTitle[Self.normalizedTitle(item.title)]+ }}diff --git a/Tests/HighballKitTests/GameDBMatchTests.swift b/Tests/HighballKitTests/GameDBMatchTests.swiftnew file mode 100644index 0000000..9740f51--- /dev/null+++ b/Tests/HighballKitTests/GameDBMatchTests.swift@@ -0,0 +1,62 @@+import XCTest+@testable import HighballKit++/// A row must be found for a copy from any store (#63: an Epic copy of Guardians of the Galaxy+/// matched nothing, so Play never asked for D3DMetal and DXMT refused the DirectX 12 game), and+/// an Epic install whose folder is gone must not show as installed.+final class GameDBMatchTests: XCTestCase {+ private var dir: URL!++ override func setUpWithError() throws {+ dir = FileManager.default.temporaryDirectory.appending(path: "hb-gamedb-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ try """+ {"id": "marvels-guardians-of-the-galaxy", "title": "Marvel's Guardians of the Galaxy™", "steam_appid": 1088850,+ "epic_app_name": "63a665088eb1480298f1e57943b225d8", "status": "community", "renderer": "d3dmetal"}+ """.write(to: dir.appending(path: "gotg.json"), atomically: true, encoding: .utf8)+ try """+ {"id": "epic-only", "title": "Epic Only Game", "status": "community", "renderer": "dxmt"}+ """.write(to: dir.appending(path: "epic-only.json"), atomically: true, encoding: .utf8)+ }++ override func tearDownWithError() throws { try? FileManager.default.removeItem(at: dir) }++ private func item(source: LibrarySource, title: String, steam: Int? = nil, epic: String? = nil) -> HighballKit.LibraryItem {+ HighballKit.LibraryItem(source: source, id: "t:\(title)", title: title, bottleName: "Games", installed: true, steamAppID: steam, epicAppName: epic)+ }++ func testSteamIDStillWinsAndRowsWithoutOneAreIndexed() {+ let db = GameDB(directories: [dir])+ XCTAssertEqual(db[1088850]?.id, "marvels-guardians-of-the-galaxy")+ XCTAssertEqual(db.entry(for: item(source: .steam, title: "anything", steam: 1088850))?.id, "marvels-guardians-of-the-galaxy")+ XCTAssertEqual(db.byTitle.count, 2, "a row with no Steam id is still a row")+ }++ func testEpicCopyMatchesByAppNameThenByTitle() {+ let db = GameDB(directories: [dir])+ XCTAssertEqual(db.entry(for: item(source: .epic, title: "Whatever Epic Calls It", epic: "63a665088eb1480298f1e57943b225d8"))?.id,+ "marvels-guardians-of-the-galaxy", "the app name is exact")+ XCTAssertEqual(db.entry(for: item(source: .epic, title: "Marvels Guardians Of The Galaxy", epic: "unknown"))?.id,+ "marvels-guardians-of-the-galaxy", "punctuation and case do not separate the same title")+ XCTAssertEqual(db.entry(for: item(source: .epic, title: "Epic Only Game", epic: "x"))?.renderer, .dxmt)+ XCTAssertNil(db.entry(for: item(source: .pin, title: "Notepad++")), "a program the database does not know")+ XCTAssertNil(db.entry(for: item(source: .epic, title: "Guardians of the Galaxy", epic: "y")), "exact after normalizing, never fuzzy")+ }++ func testNormalizedTitle() {+ XCTAssertEqual(GameDB.normalizedTitle("Marvel's Guardians of the Galaxy™"), "marvels guardians of the galaxy")+ XCTAssertEqual(GameDB.normalizedTitle(" Portal 2 "), "portal 2")+ XCTAssertEqual(GameDB.normalizedTitle("Marvel’s Guardians of the Galaxy"), GameDB.normalizedTitle("Marvel's Guardians of the Galaxy"), "straight and curly apostrophes agree")+ }++ func testInstallMapKeepsOnlyFoldersStillOnDisk() throws {+ let present = dir.appending(path: "Games/Present")+ try FileManager.default.createDirectory(at: present, withIntermediateDirectories: true)+ let games = [+ EpicStore.InstalledGame(app_name: "present", install_path: present.path),+ EpicStore.InstalledGame(app_name: "gone", install_path: dir.appending(path: "Games/Gone").path),+ EpicStore.InstalledGame(app_name: "pathless", install_path: nil),+ ]+ XCTAssertEqual(EpicStore.installMap(games), ["present": present.path])+ }+}