Skip to content

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

Steam: which account installed a game, a warning when another is signed in, and an account filter

Gabedf76015df04d
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 1e5ee74..15bf8d2 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -289,6 +289,9 @@ final class AppState {
var libraryStore: LibraryStore { LibraryStore(paths: paths) }
func rebuildLibrary() {
+ steamInstallers = gamesByBottle.mapValues { games in
+ Dictionary(games.compactMap { game in game.lastOwner.map { (game.appid, $0) } }, uniquingKeysWith: { a, _ in a })
+ }
customNames = nameStore.names()
carryOverGOGCoveredPins()
libraryItems = LibraryIndex.build(bottles: bottles, steamByBottle: gamesByBottle,
@@ -306,6 +309,85 @@ final class AppState {
refreshMacFlags()
}
+ // MARK: Whose Steam games
+
+ /// The accounts that have signed in to each environment's Steam, newest sign-in first.
+ var steamAccountsByBottle: [String: [SteamAccount]] = [:]
+ /// Every account across them, once each, sorted by display name.
+ private(set) var steamAccounts: [SteamAccount] = [] {
+ didSet { steamAccountIDs = Set(steamAccounts.map(\.id)) }
+ }
+ @ObservationIgnored private var steamAccountIDs: Set<UInt64> = []
+ /// Games that appeared while only one account had signed in to their Steam: that account's
+ /// (SteamAccounts.earlyArrivals).
+ var steamEarlyArrivals: [Int: UInt64] = [:]
+ /// Who installed each Steam game, per environment, from the install records' LastOwner:
+ /// built with the library, so the account filter looks it up rather than scanning.
+ @ObservationIgnored private var steamInstallers: [String: [Int: UInt64]] = [:]
+ /// Kept on disk (steam-accounts.json): which account was signed in when a game first
+ /// appeared, the owners the player chose, and the games already seen.
+ private var steamBook = SteamBook()
+
+ private struct SteamBook: Codable {
+ var added: [Int: UInt64] = [:]
+ var chosen: [Int: Set<UInt64>] = [:]
+ var seen: Set<Int> = []
+ }
+
+ private var steamBookFile: URL { paths.home.appending(path: "steam-accounts.json") }
+ @ObservationIgnored private var steamBookLoaded = false
+
+ private func loadSteamBook() {
+ guard !steamBookLoaded else { return }
+ steamBookLoaded = true
+ steamBook = (try? JSONDecoder().decode(SteamBook.self, from: Data(contentsOf: steamBookFile))) ?? SteamBook()
+ }
+
+ private func saveSteamBook() {
+ try? JSONEncoder().encode(steamBook).write(to: steamBookFile, options: .atomic)
+ }
+
+ /// Games appearing for the first time are put down to the account signed in to the Steam
+ /// they appeared in (SteamAccounts.noteArrivals).
+ private func noteNewSteamGames(_ appIDsByBottle: [String: Set<Int>], signedIn: [String: UInt64]) {
+ loadSteamBook()
+ var book = steamBook
+ let firstLook = book.seen.isEmpty
+ var changed = false
+ for (bottle, appIDs) in appIDsByBottle.sorted(by: { $0.key < $1.key }) {
+ changed = SteamAccounts.noteArrivals(appIDs, signedIn: signedIn[bottle], firstLook: firstLook,
+ seen: &book.seen, added: &book.added) || changed
+ }
+ guard changed else { return }
+ steamBook = book
+ saveSteamBook()
+ }
+
+ /// Whose a Steam game is, as far as this Mac can tell (SteamAccounts.owners), among the
+ /// accounts known here; nil with one account, or no sign of a known one.
+ func steamOwners(for item: LibraryItem) -> SteamAccounts.Owners? {
+ guard item.source == .steam, steamAccountIDs.count > 1, let appID = item.steamAppID else { return nil }
+ // The game's own environment first: a second copy elsewhere may have another installer.
+ let installer = item.bottleName.flatMap { steamInstallers[$0]?[appID] }
+ ?? steamInstallers.values.lazy.compactMap { $0[appID] }.first
+ // What Highball saw arrive wins over what the first sign-ins imply.
+ let added = steamBook.added.merging(steamEarlyArrivals) { seen, _ in seen }
+ guard let owners = SteamAccounts.owners(appID: appID, installedBy: installer, added: added,
+ chosen: steamBook.chosen) else { return nil }
+ let present = owners.accounts.intersection(steamAccountIDs)
+ return present.isEmpty ? nil : SteamAccounts.Owners(accounts: present, reason: owners.reason)
+ }
+
+ /// The player's own answer to whose a game is; nil goes back to Highball's guess.
+ func setSteamOwners(_ accounts: Set<UInt64>?, for item: LibraryItem) {
+ guard let appID = item.steamAppID else { return }
+ loadSteamBook()
+ steamBook.chosen[appID] = accounts
+ saveSteamBook()
+ }
+
+ func steamAccountName(_ id: UInt64) -> String? { steamAccounts.first { $0.id == id }?.displayName }
+
// MARK: Games kept out of the library (highball#445)
/// Library ids the player hid (LibraryStore). The library leaves them out unless its Hidden
@@ -716,8 +798,29 @@ final class AppState {
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 }
+ // Whose games, per environment's Steam: its accounts (newest sign-in first), the games
+ // that appeared while only one of them had signed in, and who is signed in now, else
+ // who signed in last.
+ var accountsByBottle: [String: [SteamAccount]] = [:], early: [Int: UInt64] = [:], signedIn: [String: UInt64] = [:]
+ for bottle in bottles {
+ guard let root = SteamLibrary.steamRoot(of: bottle) else { continue }
+ let known = SteamAccounts.known(steamRoot: root)
+ accountsByBottle[bottle.name] = known
+ let appeared = Dictionary((owned[bottle.name] ?? []).compactMap { g in g.cachedAt.map { (g.appid, $0) } }, uniquingKeysWith: min)
+ early.merge(SteamAccounts.earlyArrivals(appeared, firstSignIns: SteamAccounts.firstSignIns(steamRoot: root))) { a, _ in a }
+ signedIn[bottle.name] = SteamAccounts.signedIn(bottleURL: bottle.url) ?? known.first?.id
+ }
+ await MainActor.run { [accountsByBottle, early, signedIn] in
+ guard let self else { return }
+ if accountsByBottle != self.steamAccountsByBottle {
+ self.steamAccountsByBottle = accountsByBottle
+ var seen = Set<UInt64>()
+ self.steamAccounts = accountsByBottle.values.joined().filter { seen.insert($0.id).inserted }
+ .sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending }
+ }
+ if early != self.steamEarlyArrivals { self.steamEarlyArrivals = early }
+ self.noteNewSteamGames(owned.mapValues { Set($0.map(\.appid)) }, signedIn: signedIn)
+ guard owned != self.steamOwnedByBottle else { return }
self.steamOwnedByBottle = owned
self.macAppInfoByAppID = Dictionary(owned.values.joined().map { ($0.appid, $0.macBuild) },
uniquingKeysWith: { a, _ in a })
diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swift
index f25ad0a..aa73edb 100644
--- a/Sources/HighballApp/GameDetailView.swift
+++ b/Sources/HighballApp/GameDetailView.swift
@@ -7,6 +7,7 @@ struct GameDetailView: View {
let passedItem: LibraryItem
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var storeDetails: SteamGameDetails?
+ @State private var accountNote: SteamAccounts.GameNote?
@State private var loadingDetails = true
@State private var expandedDescription = false
@State private var selectedGalleryURL: URL?
@@ -97,6 +98,21 @@ struct GameDetailView: View {
storeDetails = details
loadingDetails = false
}
+ // Who installed the game, and whether Steam is signed in to another account that may not
+ // have it. Only the signed-in account is read again, every few seconds: switching accounts
+ // happens in Steam, and the install records and accounts are already in the app's state.
+ .task(id: item.id) {
+ accountNote = nil
+ guard item.source == .steam, let appID = item.steamAppID,
+ let bottle = state.bottles.first(where: { $0.name == item.bottleName }) else { return }
+ while !Task.isCancelled {
+ let signedIn = await Task.detached { SteamAccounts.signedIn(bottleURL: bottle.url) }.value
+ let note = SteamAccounts.note(installedBy: state.gamesByBottle[bottle.name]?.first { $0.appid == appID }?.lastOwner,
+ accounts: state.steamAccountsByBottle[bottle.name] ?? [], signedIn: signedIn)
+ if note != accountNote { accountNote = note }
+ try? await Task.sleep(for: .seconds(5))
+ }
+ }
}
private func overview(scroll: ScrollViewProxy) -> some View {
@@ -194,6 +210,22 @@ struct GameDetailView: View {
VStack(alignment: .leading, spacing: 12) {
row(L("Source"), item.source == .steam ? "Steam" : item.source == .epic ? "Epic Games"
: item.source == .gog ? "GOG" : item.source == .battlenet ? "Battle.net" : L("Windows program"))
+ if item.source == .steam, let owners = state.steamOwners(for: item) { steamAccountRow(owners) }
+ if let note = accountNote {
+ VStack(alignment: .leading, spacing: 6) {
+ row(L("Installed by"), note.installedBy.displayName)
+ if let other = note.otherAccount {
+ Label(String(format: note.steamRunning
+ ? L("Steam is signed in as %@. That account may not have access to this game.")
+ : L("Steam last signed in as %@. That account may not have access to this game."),
+ other.displayName),
+ systemImage: "exclamationmark.triangle.fill")
+ .font(.caption).foregroundStyle(HB.amber)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.leading, Self.rowLabelWidth + 12) // under the row's value
+ }
+ }
+ }
if item.sizeOnDisk > 0 {
row(L("Size on disk"), ByteCountFormatter.string(fromByteCount: item.sizeOnDisk, countStyle: .file))
}
@@ -707,9 +739,38 @@ struct GameDetailView: View {
.padding(.top, 6)
}
+ /// Whose Steam game this is, by profile name, and why Highball thinks so; the menu sets it.
+ /// Shown only when Highball knows (SteamAccounts.Owners).
+ private func steamAccountRow(_ owners: SteamAccounts.Owners) -> some View {
+ let names = owners.accounts.compactMap { state.steamAccountName($0) }.sorted()
+ let why: String = switch owners.reason {
+ case .chosen: L("set by you")
+ case .installed: L("installed it")
+ case .added: L("signed in when it was added")
+ }
+ return HStack(alignment: .firstTextBaseline, spacing: 12) {
+ Text(L("Account")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading)
+ Menu {
+ ForEach(state.steamAccounts, id: \.id) { account in
+ Button(account.displayName) { state.setSteamOwners([account.id], for: item) }
+ }
+ Button(L("Every account here")) { state.setSteamOwners(Set(state.steamAccounts.map(\.id)), for: item) }
+ Divider()
+ Button(L("Let Highball guess")) { state.setSteamOwners(nil, for: item) }
+ } label: {
+ Text(names.joined(separator: ", ")).font(.callout)
+ }
+ .menuStyle(.button).buttonStyle(.plain).fixedSize()
+ .help(L("Whose Steam game this is. Highball goes by who installed it and who was signed in when it appeared; pick one to set it."))
+ Text(why).font(.caption).foregroundStyle(.secondary)
+ }
+ }
+
+ static let rowLabelWidth: CGFloat = 110
+
private func row(_ label: String, _ value: String) -> some View {
HStack(alignment: .firstTextBaseline, spacing: 12) {
- Text(label).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading)
+ Text(label).font(.caption).foregroundStyle(.secondary).frame(width: Self.rowLabelWidth, alignment: .leading)
Text(value).font(.callout).textSelection(.enabled)
}
}
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index 0d60426..cfd8be1 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -396,6 +396,22 @@ enum L10n {
"Also installed in %@": "Aussi installé dans %@",
"Source": "Source",
"Size on disk": "Taille sur le disque",
+ "Installed by": "Installé par",
+ "All Steam accounts": "Tous les comptes Steam",
+ "Steam games of one account on this Mac: the one that installed or played them, or was signed in when they appeared.":
+ "Les jeux Steam d’un seul compte sur ce Mac : celui qui les a installés ou y a joué, ou qui était connecté quand ils sont apparus.",
+ "Account": "Compte",
+ "set by you": "choisi par vous",
+ "installed it": "l’a installé",
+ "signed in when it was added": "connecté quand il a été ajouté",
+ "Whose Steam game this is. Highball goes by who installed it and who was signed in when it appeared; pick one to set it.":
+ "À qui est ce jeu Steam. Highball se fie à qui l’a installé et à qui était connecté quand il est apparu ; choisissez un compte pour le fixer.",
+ "Every account here": "Tous les comptes de ce Mac",
+ "Let Highball guess": "Laisser Highball deviner",
+ "Steam is signed in as %@. That account may not have access to this game.":
+ "Steam est connecté au compte %@. Ce compte n’a peut-être pas accès à ce jeu.",
+ "Steam last signed in as %@. That account may not have access to this game.":
+ "Steam s’est connecté en dernier au compte %@. Ce compte n’a peut-être pas accès à ce jeu.",
"Last played": "Dernière partie",
"Windows program": "Programme Windows",
"Choose cover image…": "Choisir une image de couverture…",
diff --git a/Sources/HighballApp/LibraryView.swift b/Sources/HighballApp/LibraryView.swift
index 387adcf..b2d7684 100644
--- a/Sources/HighballApp/LibraryView.swift
+++ b/Sources/HighballApp/LibraryView.swift
@@ -22,6 +22,9 @@ struct LibraryView: View {
/// that read as a bug (highball#257).
@AppStorage("library.installedOnly") private var installedOnly = false
@AppStorage("library.verifiedOnly") private var verifiedOnly = false
+ /// Steam games of one account only, under the Steam filter: "" all, else a 64-bit Steam ID
+ /// (AppState.steamOwners).
+ @AppStorage("library.steamAccount") private var steamAccount = ""
/// Shows the games the player hid, and only them, so one can be brought back (highball#445).
/// Not kept across starts: a library that opened on its hidden games alone would look emptied.
@State private var showingHidden = false
@@ -38,9 +41,14 @@ struct LibraryView: View {
}
private var filtered: [LibraryItem] {
- shown.filter { item in
+ let account = activeSteamAccount // once, not per item
+ return shown.filter { item in
if let sourceFilter, item.source != sourceFilter { return false }
if installedOnly && !item.installedAnywhere { return false }
+ if let account {
+ let owners = state.steamOwners(for: item)?.accounts
+ if !(owners?.contains(account) ?? false) { return false }
+ }
if verifiedOnly {
guard state.gameDB.entry(for: item)?.status == "verified-local" else { return false }
}
@@ -129,6 +137,8 @@ struct LibraryView: View {
HStack(spacing: 8) {
FilterChip(label: L("All"), on: sourceFilter == nil) { sourceFilter = nil }
FilterChip(label: "Steam", on: sourceFilter == .steam) { sourceFilter = .steam }
+ // Steam's own sub-filter, with more than one Steam account on this Mac: whose games.
+ if sourceFilter == .steam, state.steamAccounts.count > 1 { steamAccountMenu }
FilterChip(label: "Epic", on: sourceFilter == .epic) { sourceFilter = .epic }
FilterChip(label: "GOG", on: sourceFilter == .gog) { sourceFilter = .gog }
// Only once Battle.net has installed something: most libraries never have a game from it.
@@ -236,6 +246,43 @@ struct LibraryView: View {
}
}
+extension LibraryView {
+ /// The account filter in force: only under the Steam filter, so other stores' games never mix
+ /// in; nil when it is off, or when what was picked no longer applies (one account left, or the
+ /// picked one gone), so a stale choice never empties the library.
+ var activeSteamAccount: UInt64? {
+ guard sourceFilter == .steam, state.steamAccounts.count > 1, let id = UInt64(steamAccount) else { return nil }
+ return state.steamAccountName(id) != nil ? id : nil
+ }
+
+ private var steamAccountLabel: String {
+ activeSteamAccount.flatMap { state.steamAccountName($0) } ?? L("All Steam accounts")
+ }
+
+ var steamAccountMenu: some View {
+ Menu {
+ Button(L("All Steam accounts")) { steamAccount = "" }
+ Divider()
+ ForEach(state.steamAccounts, id: \.id) { account in
+ Button(account.displayName) { steamAccount = String(account.id) }
+ }
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "person.crop.circle").font(.system(size: 11, weight: .semibold))
+ Text(steamAccountLabel)
+ Image(systemName: "chevron.down").font(.system(size: 8, weight: .bold))
+ }
+ .font(.system(size: 12.5, weight: .semibold))
+ .padding(.horizontal, 12).padding(.vertical, 4)
+ .background(Capsule().fill(activeSteamAccount == nil ? HB.card : HB.amber))
+ .overlay(Capsule().stroke(activeSteamAccount == nil ? HB.cardStroke : HB.amber))
+ .foregroundStyle(activeSteamAccount == nil ? .secondary : Color(red: 0.13, green: 0.08, blue: 0.01))
+ }
+ .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()
+ .help(L("Steam games of one account on this Mac: the one that installed or played them, or was signed in when they appeared."))
+ }
+}
+
struct FilterChip: View {
let label: String
let on: Bool
diff --git a/Sources/HighballKit/SteamAccounts.swift b/Sources/HighballKit/SteamAccounts.swift
new file mode 100644
index 0000000..26f066a
--- /dev/null
+++ b/Sources/HighballKit/SteamAccounts.swift
@@ -0,0 +1,204 @@
+import Foundation
+
+/// A Steam account that has signed in to an environment's Steam, known by its display name only:
+/// the profile name friends see. Steam also keeps each account's sign-in name beside it
+/// (loginusers.vdf's AccountName), half of what signs in, so it is never read.
+public struct SteamAccount: Sendable, Hashable {
+ /// The 64-bit Steam ID, which install records (LastOwner) and loginusers.vdf name accounts
+ /// by; the registry and userdata use the 32-bit account ID, its offset from steamIDBase.
+ public let id: UInt64
+ public let displayName: String
+ /// When the account last signed in to this Steam.
+ public let lastSignIn: Date?
+
+ public init(id: UInt64, displayName: String, lastSignIn: Date? = nil) {
+ self.id = id; self.displayName = displayName; self.lastSignIn = lastSignIn
+ }
+}
+
+/// Which Steam accounts use an environment's Steam, which one is signed in, and which one
+/// installed a game, so a game page can say "Installed by" and warn when Steam is signed in to
+/// another account, which may not have the game (a household sharing one Mac).
+/// Read from files already on the Mac, never sent anywhere. Ownership itself is not knowable:
+/// Steam's per-account license list (userdata/<id>/config/licensecache) is encrypted.
+public enum SteamAccounts {
+ /// The first 64-bit Steam ID; an account ID (the registry's, userdata's) is the offset from it.
+ static let steamIDBase: UInt64 = 76561197960265728
+
+ /// The accounts in Steam's config/loginusers.vdf, newest sign-in first.
+ public static func known(steamRoot: URL) -> [SteamAccount] {
+ guard let text = try? String(contentsOf: steamRoot.appending(path: "config/loginusers.vdf"), encoding: .utf8)
+ else { return [] }
+ return parse(loginUsers: text)
+ }
+
+ static func parse(loginUsers text: String) -> [SteamAccount] {
+ let users = TextKeyValues.parse(text).child("users")?.children ?? []
+ let accounts = users.compactMap { key, block -> SteamAccount? in
+ // Only these two values are taken; the sign-in name beside them never leaves the file.
+ guard let id = UInt64(key), let name = block.child("personaname")?.string, !name.isEmpty else { return nil }
+ let signedIn = block.child("timestamp")?.string.flatMap(TimeInterval.init).map { Date(timeIntervalSince1970: $0) }
+ return SteamAccount(id: id, displayName: name, lastSignIn: signedIn)
+ }
+ return accounts.sorted { ($0.lastSignIn ?? .distantPast) > ($1.lastSignIn ?? .distantPast) }
+ }
+
+ /// The account Steam is signed in to while it runs: the registry's ActiveUser (an account
+ /// ID, 0 once Steam has quit), in the environment's user.reg.
+ public static func signedIn(bottleURL: URL) -> UInt64? {
+ guard let text = try? String(contentsOf: bottleURL.appending(path: "user.reg"), encoding: .utf8) else { return nil }
+ return activeUser(inRegistry: text)
+ }
+
+ static func activeUser(inRegistry text: String) -> UInt64? {
+ guard let match = text.firstMatch(of: #/"ActiveUser"=dword:([0-9a-fA-F]{8})/#),
+ let account = UInt64(match.1, radix: 16), account != 0 else { return nil }
+ return steamIDBase + account
+ }
+
+ /// What a Steam game's page says about accounts, or nil when there is nothing worth saying:
+ /// one account on this Steam, or no record of who installed the game.
+ public struct GameNote: Sendable, Equatable {
+ public let installedBy: SteamAccount
+ /// The account Steam is signed in to, or signed in to last when it is not running, when
+ /// that is another one.
+ public let otherAccount: SteamAccount?
+ /// Whether Steam runs now; when not, `otherAccount` is the one it signed in to last.
+ public let steamRunning: Bool
+ }
+
+ public static func note(installedBy owner: UInt64?, accounts: [SteamAccount], signedIn: UInt64?) -> GameNote? {
+ guard accounts.count > 1, let owner, let installer = accounts.first(where: { $0.id == owner }) else { return nil }
+ let current = signedIn.flatMap { id in accounts.first { $0.id == id } } ?? (signedIn == nil ? accounts.first : nil)
+ return GameNote(installedBy: installer, otherAccount: current.flatMap { $0.id == owner ? nil : $0 }, steamRunning: signedIn != nil)
+ }
+}
+
+// MARK: Whose games
+
+extension SteamAccounts {
+ /// When each account first signed in to this Steam: its userdata folder is made then.
+ public static func firstSignIns(steamRoot: URL) -> [UInt64: Date] {
+ let userdata = steamRoot.appending(path: "userdata", directoryHint: .isDirectory)
+ let folders = (try? FileManager.default.contentsOfDirectory(at: userdata, includingPropertiesForKeys: [.creationDateKey])) ?? []
+ return Dictionary(folders.compactMap { folder in
+ guard let account = UInt64(folder.lastPathComponent),
+ let made = try? folder.resourceValues(forKeys: [.creationDateKey]).creationDate else { return nil }
+ return (steamIDBase + account, made)
+ }, uniquingKeysWith: min)
+ }
+
+ /// Games that appeared in the library (OwnedSteamGame.cachedAt) while only one account had
+ /// ever signed in to this Steam: that account's. On a Steam one person used alone before a
+ /// second signed in, that is the whole first library. Later arrivals are noteArrivals'.
+ public static func earlyArrivals(_ appeared: [Int: Date], firstSignIns: [UInt64: Date]) -> [Int: UInt64] {
+ let order = firstSignIns.sorted { $0.value < $1.value }
+ guard let first = order.first else { return [:] }
+ let secondSignIn = order.dropFirst().first?.value ?? .distantFuture
+ return appeared.filter { $0.value < secondSignIn }.mapValues { _ in first.key }
+ }
+
+ /// Whose a Steam game is, as far as this Mac can tell, and why: what the player chose, else
+ /// every account with a sign of it (installed it, or was the one signed in when it first
+ /// appeared in the library). Ownership itself is not readable (the license list is encrypted).
+ public struct Owners: Sendable, Equatable {
+ public enum Reason: Sendable, Equatable { case chosen, installed, added }
+ public let accounts: Set<UInt64>
+ /// The strongest sign among them.
+ public let reason: Reason
+
+ public init(accounts: Set<UInt64>, reason: Reason) { self.accounts = accounts; self.reason = reason }
+ }
+
+ /// Puts the games among `appIDs` not seen before down to the account signed in, and marks
+ /// them seen. The first look of all only marks: when those games arrived is not known.
+ /// Returns whether anything changed.
+ @discardableResult
+ public static func noteArrivals(_ appIDs: Set<Int>, signedIn: UInt64?, firstLook: Bool,
+ seen: inout Set<Int>, added: inout [Int: UInt64]) -> Bool {
+ let new = appIDs.subtracting(seen)
+ guard !new.isEmpty else { return false }
+ if !firstLook, let signedIn { for id in new { added[id] = signedIn } }
+ seen.formUnion(new)
+ return true
+ }
+
+ public static func owners(appID: Int, installedBy: UInt64?, added: [Int: UInt64],
+ chosen: [Int: Set<UInt64>]) -> Owners? {
+ if let picked = chosen[appID], !picked.isEmpty { return Owners(accounts: picked, reason: .chosen) }
+ var accounts = Set<UInt64>()
+ var reason: Owners.Reason?
+ if let installedBy { accounts.insert(installedBy); reason = .installed }
+ if let adder = added[appID] { accounts.insert(adder); reason = reason ?? .added }
+ return reason.map { Owners(accounts: accounts, reason: $0) }
+ }
+}
+
+/// Valve's text KeyValues (loginusers.vdf): quoted keys and values, nested
+/// blocks in braces, backslash escapes, // comments. Keys are matched without case, as Steam does.
+enum TextKeyValues {
+ indirect enum Node {
+ case string(String)
+ case block([(key: String, value: Node)])
+
+ var string: String? { if case let .string(s) = self { return s }; return nil }
+ var children: [(key: String, value: Node)] { if case let .block(b) = self { return b }; return [] }
+ func child(_ key: String) -> Node? { children.first { $0.key.caseInsensitiveCompare(key) == .orderedSame }?.value }
+ }
+
+ static func parse(_ text: String) -> Node {
+ var tokens = tokenize(text)[...]
+ return .block(block(&tokens))
+ }
+
+ private enum Token: Equatable { case word(String), open, close }
+
+ private static func block(_ tokens: inout ArraySlice<Token>) -> [(key: String, value: Node)] {
+ var entries: [(key: String, value: Node)] = []
+ while let token = tokens.popFirst() {
+ guard case let .word(key) = token else {
+ if token == .close { return entries }
+ continue // a stray brace: skipped
+ }
+ switch tokens.first {
+ case .word(let value)?: tokens.removeFirst(); entries.append((key, .string(value)))
+ case .open?: tokens.removeFirst(); entries.append((key, .block(block(&tokens))))
+ default: break
+ }
+ }
+ return entries
+ }
+
+ private static func tokenize(_ text: String) -> [Token] {
+ var tokens: [Token] = []
+ var chars = Array(text.unicodeScalars)[...]
+ while let c = chars.popFirst() {
+ switch c {
+ case "{": tokens.append(.open)
+ case "}": tokens.append(.close)
+ case "\"":
+ var word = String.UnicodeScalarView()
+ while let d = chars.popFirst(), d != "\"" {
+ guard d == "\\", let e = chars.popFirst() else { word.append(d); continue }
+ switch e {
+ case "n": word.append("\n")
+ case "t": word.append("\t")
+ default: word.append(e) // \" and \\ and anything else: the character itself
+ }
+ }
+ tokens.append(.word(String(word)))
+ case "/" where chars.first == "/":
+ while let d = chars.popFirst(), d != "\n" {}
+ case _ where CharacterSet.whitespacesAndNewlines.contains(c):
+ continue
+ default: // an unquoted word runs to whitespace or a brace
+ var word = String.UnicodeScalarView([c])
+ while let d = chars.first, d != "{", d != "}", d != "\"", !CharacterSet.whitespacesAndNewlines.contains(d) {
+ word.append(d); chars.removeFirst()
+ }
+ tokens.append(.word(String(word)))
+ }
+ }
+ return tokens
+ }
+}
diff --git a/Sources/HighballKit/SteamLibrary.swift b/Sources/HighballKit/SteamLibrary.swift
index 1b10537..c4baa6a 100644
--- a/Sources/HighballKit/SteamLibrary.swift
+++ b/Sources/HighballKit/SteamLibrary.swift
@@ -19,12 +19,16 @@ public struct SteamGame: Identifiable, Sendable, Hashable {
/// path for Steam in an environment (`C:\\Program Files (x86)\\Steam\\steam.exe`), a Mac
/// path for Steam for Mac. nil when the manifest has none.
public let launcherPath: String?
+ /// The 64-bit Steam ID of the account that installed the game (or updated it last), as the
+ /// ACF's LastOwner records it; nil when it has none. Who installed it, not who owns it: two
+ /// accounts on one Steam may both own a game (SteamAccounts).
+ public let lastOwner: UInt64?
public init(appid: Int, name: String, installdir: String, sizeOnDisk: Int64, stateFlags: Int, lastPlayed: Date?,
- libraryRoot: URL? = nil, launcherPath: String? = nil) {
+ libraryRoot: URL? = nil, launcherPath: String? = nil, lastOwner: UInt64? = nil) {
self.appid = appid; self.name = name; self.installdir = installdir; self.sizeOnDisk = sizeOnDisk
self.stateFlags = stateFlags; self.lastPlayed = lastPlayed; self.libraryRoot = libraryRoot
- self.launcherPath = launcherPath
+ self.launcherPath = launcherPath; self.lastOwner = lastOwner
}
/// Installed by a Windows Steam, the one in an environment. A library folder both clients use
@@ -191,7 +195,8 @@ public enum SteamLibrary {
stateFlags: Int(fields["StateFlags"] ?? "") ?? 0,
lastPlayed: played > 0 ? Date(timeIntervalSince1970: played) : nil,
libraryRoot: libraryRoot,
- launcherPath: fields["LauncherPath"]
+ launcherPath: fields["LauncherPath"],
+ lastOwner: UInt64(fields["LastOwner"] ?? "").flatMap { $0 == 0 ? nil : $0 }
)
}
}
diff --git a/Sources/HighballKit/SteamOwnedLibrary.swift b/Sources/HighballKit/SteamOwnedLibrary.swift
index fdbef2c..aa46335 100644
--- a/Sources/HighballKit/SteamOwnedLibrary.swift
+++ b/Sources/HighballKit/SteamOwnedLibrary.swift
@@ -12,11 +12,14 @@ public struct OwnedSteamGame: Sendable, Hashable {
public var listsMac = false
/// What appinfo says about the Mac build: 64-bit, 32-bit only, or none (MacAppInfoBuild).
public var macBuild: MacAppInfoBuild = .absent
+ /// When the game first appeared in this Steam's library: when the client made its
+ /// librarycache folder (SteamAccounts.earlyArrivals).
+ public var cachedAt: Date? = nil
public init(appid: Int, name: String, localCapsule: URL? = nil, localHeader: URL? = nil, listsMac: Bool = false,
- macBuild: MacAppInfoBuild = .absent) {
+ macBuild: MacAppInfoBuild = .absent, cachedAt: Date? = nil) {
self.appid = appid; self.name = name; self.localCapsule = localCapsule; self.localHeader = localHeader
- self.listsMac = listsMac; self.macBuild = macBuild
+ self.listsMac = listsMac; self.macBuild = macBuild; self.cachedAt = cachedAt
}
/// Local art first: newer apps keep theirs at hashed store paths, so the fixed CDN name
@@ -57,11 +60,13 @@ public enum SteamOwnedLibrary {
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)))
+ let folder = cache.appending(path: String(appid))
+ let art = artwork(in: folder)
return OwnedSteamGame(appid: appid, name: name, localCapsule: art["library_600x900.jpg"],
localHeader: art["library_header.jpg"] ?? art["header.jpg"],
listsMac: app.oslist?.lowercased().contains("macos") ?? false,
- macBuild: app.macBuild)
+ macBuild: app.macBuild,
+ cachedAt: try? folder.resourceValues(forKeys: [.creationDateKey]).creationDate)
}
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
}
diff --git a/Tests/HighballKitTests/SteamAccountsTests.swift b/Tests/HighballKitTests/SteamAccountsTests.swift
new file mode 100644
index 0000000..6e18a2b
--- /dev/null
+++ b/Tests/HighballKitTests/SteamAccountsTests.swift
@@ -0,0 +1,137 @@
+import XCTest
+@testable import HighballKit
+
+final class SteamAccountsTests: XCTestCase {
+ /// Two made-up accounts as Steam writes them; the second signed in last.
+ let loginUsers = """
+ "users"
+ {
+ \t"76561198000000001"
+ \t{
+ \t\t"AccountName"\t\t"signin-one"
+ \t\t"PersonaName"\t\t"Alder"
+ \t\t"RememberPassword"\t\t"1"
+ \t\t"Timestamp"\t\t"1790000000"
+ \t}
+ \t"76561198000000002"
+ \t{
+ \t\t"AccountName"\t\t"signin-two"
+ \t\t"PersonaName"\t\t"Birch"
+ \t\t"timestamp"\t\t"1790000500"
+ \t}
+ }
+ """
+
+ func testAccountsAreKnownByDisplayNameNewestFirst() {
+ let accounts = SteamAccounts.parse(loginUsers: loginUsers)
+ XCTAssertEqual(accounts.map(\.displayName), ["Birch", "Alder"])
+ XCTAssertEqual(accounts.map(\.id), [76561198000000002, 76561198000000001])
+ }
+
+ /// The sign-in name is half of what signs in: an account keeps its ID, profile name and last
+ /// sign-in, and a field added to it later fails here until it is looked at.
+ func testAnAccountKeepsNoSignInName() {
+ let account = SteamAccounts.parse(loginUsers: loginUsers)[0]
+ XCTAssertEqual(Mirror(reflecting: account).children.compactMap(\.label), ["id", "displayName", "lastSignIn"])
+ XCTAssertFalse(String(describing: account).contains("signin-"))
+ }
+
+ /// Braces and escaped quotes in a profile name, and a block nested in a user's: still read.
+ func testProfileNamesWithBracesAndQuotes() {
+ let text = #"""
+ "users" { "76561198000000003" { "AccountName" "x" "PersonaName" "a {\"b\"} c" "Timestamp" "5" "extra" { "k" "v" } } }
+ """#
+ XCTAssertEqual(SteamAccounts.parse(loginUsers: text).map(\.displayName), [#"a {"b"} c"#])
+ }
+
+ func testSignedInAccountComesFromTheRegistryWhileSteamRuns() {
+ XCTAssertEqual(SteamAccounts.activeUser(inRegistry: "[Software\\\\Valve\\\\Steam\\\\ActiveProcess]\n\"ActiveUser\"=dword:023c3462\n"),
+ 76561197960265728 + 0x023c3462)
+ XCTAssertNil(SteamAccounts.activeUser(inRegistry: "\"ActiveUser\"=dword:00000000\n"), "0 once Steam has quit")
+ XCTAssertNil(SteamAccounts.activeUser(inRegistry: ""))
+ }
+
+ func testInstallRecordsNameTheAccountThatInstalled() throws {
+ let file = FileManager.default.temporaryDirectory.appending(path: "appmanifest_\(UUID().uuidString).acf")
+ defer { try? FileManager.default.removeItem(at: file) }
+ try """
+ "AppState"
+ {
+ \t"appid"\t\t"1392860"
+ \t"name"\t\t"Some Game"
+ \t"StateFlags"\t\t"4"
+ \t"LastOwner"\t\t"76561198000000001"
+ }
+ """.write(to: file, atomically: true, encoding: .utf8)
+ XCTAssertEqual(SteamLibrary.parseManifest(file)?.lastOwner, 76561198000000001)
+ try "\"AppState\" { \"appid\" \"1\" \"name\" \"X\" \"LastOwner\" \"0\" }".write(to: file, atomically: true, encoding: .utf8)
+ XCTAssertNil(SteamLibrary.parseManifest(file)?.lastOwner)
+ }
+
+ func testGameNoteWarnsOnlyWhenAnotherAccountIsSignedIn() {
+ let accounts = SteamAccounts.parse(loginUsers: loginUsers)
+ let alder: UInt64 = 76561198000000001, birch: UInt64 = 76561198000000002
+ // Another account signed in now.
+ let other = SteamAccounts.note(installedBy: alder, accounts: accounts, signedIn: birch)
+ XCTAssertEqual(other?.installedBy.displayName, "Alder")
+ XCTAssertEqual(other?.otherAccount?.displayName, "Birch")
+ XCTAssertEqual(other?.steamRunning, true)
+ // The installer is signed in: the row, no warning.
+ XCTAssertNil(SteamAccounts.note(installedBy: alder, accounts: accounts, signedIn: alder)?.otherAccount)
+ // Steam not running: the account it signed in to last.
+ let closed = SteamAccounts.note(installedBy: alder, accounts: accounts, signedIn: nil)
+ XCTAssertEqual(closed?.otherAccount?.displayName, "Birch")
+ XCTAssertEqual(closed?.steamRunning, false)
+ // Nothing to say: one account on this Steam, or no record of who installed it.
+ XCTAssertNil(SteamAccounts.note(installedBy: alder, accounts: [accounts[1]], signedIn: nil))
+ XCTAssertNil(SteamAccounts.note(installedBy: nil, accounts: accounts, signedIn: birch))
+ XCTAssertNil(SteamAccounts.note(installedBy: 76561198000000009, accounts: accounts, signedIn: birch))
+ }
+
+ /// The player's choice wins; otherwise every account with a sign, the strongest named.
+ func testOwnersComeFromTheChoiceElseEverySign() {
+ let alder: UInt64 = 76561198000000001, birch: UInt64 = 76561198000000002
+ XCTAssertEqual(SteamAccounts.owners(appID: 7, installedBy: alder, added: [7: birch], chosen: [:]),
+ SteamAccounts.Owners(accounts: [alder, birch], reason: .installed))
+ XCTAssertEqual(SteamAccounts.owners(appID: 9, installedBy: nil, added: [9: alder], chosen: [:]),
+ SteamAccounts.Owners(accounts: [alder], reason: .added))
+ XCTAssertEqual(SteamAccounts.owners(appID: 7, installedBy: alder, added: [:], chosen: [7: [birch]]),
+ SteamAccounts.Owners(accounts: [birch], reason: .chosen))
+ XCTAssertNil(SteamAccounts.owners(appID: 10, installedBy: nil, added: [:], chosen: [:]))
+ }
+
+ /// Games that appeared while only the first account had ever signed in are its; later ones
+ /// are nobody's here until seen arriving.
+ func testGamesFromBeforeASecondAccountAreTheFirstOnes() {
+ let alder: UInt64 = 76561198000000001, birch: UInt64 = 76561198000000002
+ let t = Date(timeIntervalSince1970: 1_790_000_000)
+ let signIns = [alder: t, birch: t.addingTimeInterval(86_400)]
+ let appeared = [1: t.addingTimeInterval(60), 2: t.addingTimeInterval(3_600), 3: t.addingTimeInterval(90_000)]
+ XCTAssertEqual(SteamAccounts.earlyArrivals(appeared, firstSignIns: signIns), [1: alder, 2: alder])
+ XCTAssertEqual(SteamAccounts.earlyArrivals(appeared, firstSignIns: [alder: t]), [1: alder, 2: alder, 3: alder], "one account: all its")
+ XCTAssertEqual(SteamAccounts.earlyArrivals(appeared, firstSignIns: [:]), [:])
+ }
+
+ /// Comments and escaped backslashes, as real files hold them; keys matched without case.
+ func testCommentsEscapesAndKeyCase() {
+ let text = #"""
+ // written by Steam
+ "Users" { "76561198000000004" { "PERSONANAME" "C:\\Games" "Timestamp" "7" } }
+ """#
+ XCTAssertEqual(SteamAccounts.parse(loginUsers: text).map(\.displayName), [#"C:\Games"#])
+ }
+
+ /// A game first seen is put down to the account signed in; the first look only notes.
+ func testArrivalsArePutDownToTheSignedInAccount() {
+ var seen = Set<Int>(), added = [Int: UInt64]()
+ XCTAssertTrue(SteamAccounts.noteArrivals([1, 2], signedIn: 9, firstLook: true, seen: &seen, added: &added))
+ XCTAssertEqual(added, [:], "already there before Highball looked: arrival unknown")
+ XCTAssertTrue(SteamAccounts.noteArrivals([1, 2, 3], signedIn: 9, firstLook: false, seen: &seen, added: &added))
+ XCTAssertEqual(added, [3: 9])
+ XCTAssertFalse(SteamAccounts.noteArrivals([3], signedIn: 8, firstLook: false, seen: &seen, added: &added))
+ XCTAssertEqual(added, [3: 9], "a game is put down once")
+ SteamAccounts.noteArrivals([4], signedIn: nil, firstLook: false, seen: &seen, added: &added)
+ XCTAssertNil(added[4], "nobody known signed in")
+ XCTAssertTrue(seen.contains(4))
+ }
+}