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
How much room every game takes, and the library as last seen
Gabe904f48231236
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 1e5ee74..a881cf8 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -304,6 +304,7 @@ final class AppState {sortLibraryByDisplayTitle()if let deferred = deferredPlayLink { resolvePlayLink(deferred.request) }refreshMacFlags()+ if sizePrefetch == nil, libraryItems.contains(where: { $0.source == .gog || $0.source == .epic }) { prefetchDownloadSizes() }}// MARK: Games kept out of the library (highball#445)@@ -719,6 +720,7 @@ final class AppState {await MainActor.run {guard let self, owned != self.steamOwnedByBottle else { return }self.steamOwnedByBottle = owned+ self.steamCloudAppIDs = Set(owned.values.joined().filter(\.steamCloud).map(\.appid))self.macAppInfoByAppID = Dictionary(owned.values.joined().map { ($0.appid, $0.macBuild) },uniquingKeysWith: { a, _ in a })self.rebuildLibrary()@@ -1097,13 +1099,14 @@ final class AppState {guard epicSignedIn, !epicFetchInFlight else { return }epicFetchInFlight = trueTask.detached { [store = epicStore] in- let installed = (try? store.installedGames()) ?? []+ guard let installed = try? store.installedGames() else {+ await MainActor.run { self.epicFetchInFlight = false }+ return+ }await MainActor.run { [weak self] inguard let self else { return }self.epicFetchInFlight = false- let installs = EpicStore.installMap(installed)- guard installs != self.epicInstalls else { return }- self.epicInstalls = installs+ guard self.applyEpicInstalls(installed) else { return }self.forgetProgramExecutables()self.rebuildLibrary()}@@ -1150,6 +1153,7 @@ final class AppState {libraryDisplays = libraryStore.displayChoices()hiddenItems = libraryStore.hiddenIDs()includeMacSteam = libraryStore.includesMacSteam+ loadLibraryCache()rebuildLibrary()steamOwnedRefresh()epicRefresh()@@ -3281,19 +3285,23 @@ final class AppState {func epicRefresh() {epicSignedIn = epicStore.isAuthenticated- guard epicSignedIn else { epicOwned = []; epicInstalls = [:]; return }+ guard epicSignedIn else { epicOwned = []; epicInstalls = [:]; epicInstallRecords = [:]; return }guard !epicFetchInFlight else { return }epicFetchInFlight = trueepicLoading = epicOwned.isEmptyTask.detached { [store = epicStore] in- let owned = (try? store.ownedGames()) ?? []- let installed = (try? store.installedGames()) ?? []+ // nil when legendary could not answer (offline, Epic down): the list shown, the one+ // saved last time, stays, rather than the library emptying.+ let owned = try? store.ownedGames()+ let installed = try? store.installedGames()await MainActor.run { [weak self] in- self?.epicOwned = owned.sorted { $0.app_title < $1.app_title }- self?.epicInstalls = EpicStore.installMap(installed)- self?.epicLoading = false- self?.epicFetchInFlight = false- self?.rebuildLibrary() // Epic results arrive after refresh(); fold them in+ guard let self else { return }+ if let owned { self.epicOwned = owned.sorted { $0.app_title < $1.app_title } }+ if let installed { _ = self.applyEpicInstalls(installed) }+ self.epicLoading = false+ self.epicFetchInFlight = false+ self.rebuildLibrary() // Epic results arrive after refresh(); fold them in+ if owned != nil { self.saveLibraryCache() }}}}@@ -3370,6 +3378,18 @@ final class AppState {}}+ /// legendary's install records by app name (installed size, save folder), for the game page.+ @ObservationIgnored var epicInstallRecords: [String: EpicStore.InstalledGame] = [:]++ /// Keeps legendary's records and the install map read from them. Whether the library changed.+ private func applyEpicInstalls(_ installed: [EpicStore.InstalledGame]) -> Bool {+ let installs = EpicStore.installMap(installed)+ epicInstallRecords = Dictionary(installed.map { ($0.app_name, $0) }, uniquingKeysWith: { a, _ in a })+ guard installs != epicInstalls else { return false }+ epicInstalls = installs+ return true+ }+/// Quitting the app stops an Epic download the way Stop does, so it never runs on alone,/// holding legendary's install lock with nothing on screen to stop it (highball#323).func stopEpicInstall() { epicInstallControl?.stop() }@@ -3479,7 +3499,7 @@ final class AppState {guard let self else { return }self.gogFetchInFlight = falseself.gogLoading = false- if found != self.gogGames { self.gogGames = found; self.rebuildLibrary() }+ if found != self.gogGames { self.gogGames = found; self.rebuildLibrary(); self.saveLibraryCache() }}}}@@ -3554,9 +3574,61 @@ final class AppState {func gogSignOut() {gogStore.logout()gogGames = []+ saveLibraryCache()gogRefresh()}+ // MARK: The library as last seen++ /// Epic's and GOG's lists from the last refresh, kept on disk (library-cache.json) so the+ /// library is whole the moment Highball opens: asking legendary and GOG takes seconds (Epic's+ /// two calls about 6), and the refresh that follows only changes what changed. A store signed+ /// out since is not read back. Steam needs none: its lists are read off disk at once.+ private var libraryCacheFile: URL { paths.home.appending(path: "library-cache.json") }++ private struct LibraryCache: Codable {+ struct EpicGame: Codable {+ var appName: String, title: String, artworkWide: URL?, artworkTall: URL?+ var cloudSaves: Bool?+ }+ var epicOwned: [EpicGame] = []+ var epicInstalls: [String: String] = [:]+ var gogGames: [GOGStore.Game] = []++ init(epicOwned: [EpicGame], epicInstalls: [String: String], gogGames: [GOGStore.Game]) {+ self.epicOwned = epicOwned; self.epicInstalls = epicInstalls; self.gogGames = gogGames+ }++ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ epicOwned = try c.decodeIfPresent([EpicGame].self, forKey: .epicOwned) ?? []+ epicInstalls = try c.decodeIfPresent([String: String].self, forKey: .epicInstalls) ?? [:]+ gogGames = try c.decodeIfPresent([GOGStore.Game].self, forKey: .gogGames) ?? []+ }+ }++ private func loadLibraryCache() {+ guard epicOwned.isEmpty, gogGames.isEmpty,+ let cache = try? JSONDecoder().decode(LibraryCache.self, from: Data(contentsOf: libraryCacheFile)) else { return }+ if epicStore.isAuthenticated {+ epicOwned = cache.epicOwned.map {+ var game = EpicStore.Game(app_name: $0.appName, app_title: $0.title, artworkWide: $0.artworkWide, artworkTall: $0.artworkTall)+ game.cloudSaves = $0.cloudSaves ?? false+ return game+ }+ epicInstalls = cache.epicInstalls+ }+ if gogStore.isAuthenticated { gogGames = cache.gogGames }+ }++ private func saveLibraryCache() {+ let cache = LibraryCache(+ epicOwned: epicOwned.map { .init(appName: $0.app_name, title: $0.app_title, artworkWide: $0.artworkWide, artworkTall: $0.artworkTall,+ cloudSaves: $0.cloudSaves) },+ epicInstalls: epicInstalls, gogGames: gogGames)+ try? JSONEncoder().encode(cache).write(to: libraryCacheFile, options: .atomic)+ }+/// The GOG download running now, for the strip's Stop and for quitting the app.@ObservationIgnored private var gogInstallControl: LegendaryControl?@@ -3591,6 +3663,23 @@ final class AppState {}}+ /// Steam games Steam Cloud keeps saves for (OwnedSteamGame.steamCloud).+ var steamCloudAppIDs: Set<Int> = []++ /// How GOG syncs each GOG game's saves (GOGSaves.CloudSetup), asked once a session per game.+ @ObservationIgnored private var gogCloudSetups: [String: GOGSaves.CloudSetup] = [:]++ /// How an installed GOG game's saves sync, for its page; nil when GOG could not be asked.+ func gogCloudSetup(for item: LibraryItem) async -> GOGSaves.CloudSetup? {+ guard let id = item.gogID else { return nil }+ if let known = gogCloudSetups[id] { return known }+ guard let game = bottles.first(where: { $0.name == item.bottleName }).flatMap({ gogInstalled(item, in: $0) }) else { return nil }+ let saves = GOGSaves(store: gogStore)+ let setup = await Task.detached { saves.clientID(for: game).flatMap { try? saves.cloudSetup(clientID: $0) } }.value+ if let setup { gogCloudSetups[id] = setup }+ return setup+ }+/// Updates a game gogdl installed to GOG's newest build, then runs its setup again.func gogUpdate(_ item: LibraryItem) {guard let bottleName = item.bottleName, let bottle = bottles.first(where: { $0.name == bottleName }),@@ -3919,6 +4008,161 @@ final class AppState {AchievementToast.shared.show(sample)}+ // MARK: Sizes++ /// What the store said a download takes, by item id and platform, kept on disk for a week+ /// (download-sizes.json): asking gogdl or legendary takes seconds, and a page opened again+ /// shows the size at once.+ private var downloadEstimates: [String: DownloadEstimate] = [:]+ private var downloadEstimatesFetched: [String: Date] = [:]+ private var downloadEstimatesLoaded = false+ private var downloadSizesFile: URL { paths.home.appending(path: "download-sizes.json") }+ private struct SavedEstimate: Codable { var download: Int64?; var disk: Int64?; var fetched: Date }++ private func loadDownloadEstimates() {+ guard !downloadEstimatesLoaded else { return }+ downloadEstimatesLoaded = true+ let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601+ let saved = (try? decoder.decode([String: SavedEstimate].self, from: Data(contentsOf: downloadSizesFile))) ?? [:]+ let fresh = Date().addingTimeInterval(-7 * 86_400)+ for (key, value) in saved where value.fetched > fresh {+ downloadEstimates[key] = DownloadEstimate(download: value.download, disk: value.disk)+ downloadEstimatesFetched[key] = value.fetched+ }+ }++ private func saveDownloadEstimates() {+ let saved = Dictionary(uniqueKeysWithValues: downloadEstimates.map { key, value in+ (key, SavedEstimate(download: value.download, disk: value.disk, fetched: downloadEstimatesFetched[key] ?? Date()))+ })+ let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601; encoder.outputFormatting = [.sortedKeys]+ try? encoder.encode(saved).write(to: downloadSizesFile, options: .atomic)+ }++ /// The download and installed size of a game's Windows or Mac build before it is installed:+ /// GOG's and Epic's tools ask the store, Steam's comes from its client's data on the Mac.+ /// nil when there is no saying (signed out, offline, no such build, Steam not set up).+ func downloadEstimate(for item: LibraryItem, mac: Bool, refresh: Bool = false) async -> DownloadEstimate? {+ let key = Self.estimateKey(item, mac: mac)+ loadDownloadEstimates()+ if !refresh, let cached = downloadEstimates[key] { return cached }+ let estimate: DownloadEstimate?+ switch item.source {+ case .gog:+ guard let id = item.gogID else { return nil }+ let store = gogStore+ estimate = await Task.detached {+ (try? store.info(id, platform: mac ? "osx" : "windows")).map { DownloadEstimate(download: $0.downloadSize, disk: $0.diskSize) }+ }.value+ case .epic:+ guard let app = item.epicAppName else { return nil }+ let store = epicStore+ estimate = await Task.detached { try? store.downloadEstimate(app, platform: mac ? "Mac" : "Windows") }.value+ case .steam:+ // Steam's own data in the environment's client: no request, no Steam window.+ guard let appID = item.steamAppID,+ let root = (bottles.first { $0.name == item.bottleName } ?? defaultBottle).flatMap(SteamLibrary.steamRoot(of:)) else { return nil }+ estimate = await Task.detached { () -> DownloadEstimate? in+ guard let app = (try? SteamAppInfo.read(root.appending(path: "appcache/appinfo.vdf"), only: [appID]))?[appID] else { return nil }+ return SteamDownloadSize.estimate(appID: appID, app: app, packages: SteamPackageInfo.read(steamRoot: root), mac: mac)+ }.value+ default:+ return nil+ }+ if let estimate { downloadEstimates[key] = estimate; downloadEstimatesFetched[key] = Date(); saveDownloadEstimates() }+ return estimate ?? (refresh ? downloadEstimates[key] : nil)+ }++ private static func estimateKey(_ item: LibraryItem, mac: Bool) -> String { "\(item.id)|\(mac ? "mac" : "windows")" }++ /// The size saved from an earlier check, at once, with no store asked.+ func savedEstimate(for item: LibraryItem, mac: Bool) -> DownloadEstimate? {+ loadDownloadEstimates()+ return downloadEstimates[Self.estimateKey(item, mac: mac)]+ }++ /// A saved size older than a day: worth a quiet second look when its page opens (an update+ /// can change it).+ func estimateIsStale(for item: LibraryItem, mac: Bool) -> Bool {+ (downloadEstimatesFetched[Self.estimateKey(item, mac: mac)] ?? .distantPast) < Date().addingTimeInterval(-86_400)+ }++ /// A native Mac version the store offers: Steam's (MacSteamBuild).+ func offersMacVersion(_ item: LibraryItem) -> Bool {+ item.installedOnMac || (item.source == .steam && macSteamBuild(for: item) != nil)+ }++ private var sizePrefetch: Task<Void, Never>?++ /// Once a session, in the background: the sizes of GOG and Epic games not installed yet, so a+ /// page has them before it is opened. One store question at a time (each takes seconds and+ /// holds the GOG sign-in file), none while a game runs or a task holds the progress bar, and+ /// none for sizes saved this week. Steam needs none: its sizes are read from disk at once.+ private func prefetchDownloadSizes() {+ sizePrefetch = Task { [weak self] in+ try? await Task.sleep(for: .seconds(30)) // after the libraries have come in+ guard let self else { return }+ for item in libraryItems where !item.installed && (item.source == .gog || item.source == .epic) {+ for mac in [false] + (offersMacVersion(item) && !item.installedOnMac ? [true] : []) where savedEstimate(for: item, mac: mac) == nil {+ while busy || !runningSessions.isEmpty {+ try? await Task.sleep(for: .seconds(30))+ if Task.isCancelled { return }+ }+ if Task.isCancelled { return }+ _ = await downloadEstimate(for: item, mac: mac)+ }+ }+ }+ }++ /// An installed game's folder and saves as they are on disk now.+ struct InstalledSizes: Equatable {+ /// The Windows build's folder (or a program's); nil for Steam, whose own record the page shows.+ var game: Int64?+ /// The Mac build's size: Steam for Mac's record.+ var macGame: Int64?+ /// The saves Highball knows the place of: GOG's and Epic's cloud-save folders, Steam+ /// Cloud's own copy for Steam. nil when there is no such place or nothing in it yet.+ var saves: Int64?+ }++ func installedSizes(for item: LibraryItem) async -> InstalledSizes {+ let bottle = bottles.first { $0.name == item.bottleName }+ switch item.source {+ case .steam:+ // The Windows build's size is Steam's own record (LibraryItem.sizeOnDisk); Steam for+ // Mac's install has its own record too.+ let mac = macSteamGames.first { $0.appid == item.steamAppID }.map(\.sizeOnDisk).flatMap { $0 > 0 ? $0 : nil }+ guard let appID = item.steamAppID, let root = bottle.flatMap(SteamLibrary.steamRoot(of:)) else { return InstalledSizes(macGame: mac) }+ return await Task.detached {+ InstalledSizes(macGame: mac, saves: DiskUsage.bytes(at: SteamLibrary.cloudSaveFolders(steamRoot: root, appID: appID)))+ }.value+ case .gog:+ let windows = bottle.flatMap { gogInstalled(item, in: $0) }+ let saves = GOGSaves(store: gogStore)+ return await Task.detached {+ var sizes = InstalledSizes(game: windows.flatMap { DiskUsage.bytes(at: $0.folder) })+ if let windows, let bottle, let client = saves.clientID(for: windows),+ let locations = (try? saves.locations(clientID: client)) ?? nil {+ sizes.saves = DiskUsage.bytes(at: locations.compactMap { GOGSaves.resolve($0.template, game: windows, driveC: bottle.driveC) })+ }+ return sizes+ }.value+ case .epic:+ guard let app = item.epicAppName else { return InstalledSizes() }+ let known = epicInstallRecords[app], store = epicStore+ return await Task.detached {+ guard let record = known ?? (try? store.installedGames())?.first(where: { $0.app_name == app }) else { return InstalledSizes() }+ let size = record.install_size ?? record.install_path.flatMap { DiskUsage.bytes(at: URL(fileURLWithPath: $0)) }+ return InstalledSizes(game: size, saves: record.save_path.flatMap { DiskUsage.bytes(at: URL(fileURLWithPath: $0)) })+ }.value+ default:+ // A program added by hand, a Battle.net game: the folder it lives in.+ let folder = programFolder(for: item)+ return await Task.detached { InstalledSizes(game: folder.flatMap { DiskUsage.bytes(at: $0) }) }.value+ }+ }+/// The game's cloud-save folders in this environment, empty when it has none or GOG cannot say.private func gogSaveLocations(_ game: GOGStore.InstalledGame, in bottle: Bottle) async -> [(GOGSaves.Location, URL)] {let saves = GOGSaves(store: gogStore)diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swiftindex f25ad0a..2ff9f0d 100644--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@ -7,6 +7,15 @@ struct GameDetailView: View {let passedItem: LibraryItem@Environment(\.accessibilityReduceMotion) private var reduceMotion@State private var storeDetails: SteamGameDetails?+ @State private var sizes: AppState.InstalledSizes?+ @State private var windowsEstimate: DownloadEstimate?+ @State private var macEstimate: DownloadEstimate?+ /// The estimates have been asked for and answered (or not): "Checking…" until then, "Unknown" after.+ @State private var estimatesDone = false+ /// How this GOG game's saves sync, per version; asked when the page opens.+ @State private var cloudSetup: GOGSaves.CloudSetup?+ @State private var cloudSetupAsked = false+ @State private var showCloudHelp = false@State private var loadingDetails = true@State private var expandedDescription = false@State private var selectedGalleryURL: URL?@@ -97,6 +106,41 @@ struct GameDetailView: View {storeDetails = detailsloadingDetails = false}+ .task(id: "\(item.id)|\(item.installed)|\(item.installedOnMac)|cloud") {+ cloudSetup = nil; cloudSetupAsked = false+ guard item.source == .gog, item.installedAnywhere else { return }+ cloudSetup = await state.gogCloudSetup(for: item)+ cloudSetupAsked = true+ }+ // How much room it takes: the store's estimate before an install, the folders after.+ // All three at once, each shown as it comes: a store's answer takes seconds.+ .task(id: "\(item.id)|\(item.installed)|\(item.installedOnMac)") {+ sizes = nil; windowsEstimate = nil; macEstimate = nil; estimatesDone = false+ let item = item+ let wantsWindows = !item.installed && [.gog, .epic, .steam].contains(item.source)+ let wantsMac = hasMacVersion && !item.installedOnMac+ // A size saved earlier shows at once; one older than a day is checked again quietly.+ if wantsWindows { windowsEstimate = state.savedEstimate(for: item, mac: false) }+ if wantsMac { macEstimate = state.savedEstimate(for: item, mac: true) }+ await withTaskGroup(of: Void.self) { group in+ if item.installedAnywhere {+ group.addTask { @MainActor in sizes = await state.installedSizes(for: item) }+ }+ if wantsWindows, windowsEstimate == nil || state.estimateIsStale(for: item, mac: false) {+ let refresh = windowsEstimate != nil+ group.addTask { @MainActor in+ if let fresh = await state.downloadEstimate(for: item, mac: false, refresh: refresh) { windowsEstimate = fresh }+ }+ }+ if wantsMac, macEstimate == nil || state.estimateIsStale(for: item, mac: true) {+ let refresh = macEstimate != nil+ group.addTask { @MainActor in+ if let fresh = await state.downloadEstimate(for: item, mac: true, refresh: refresh) { macEstimate = fresh }+ }+ }+ }+ estimatesDone = true+ }}private func overview(scroll: ScrollViewProxy) -> some View {@@ -194,8 +238,16 @@ 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.sizeOnDisk > 0 {- row(L("Size on disk"), ByteCountFormatter.string(fromByteCount: item.sizeOnDisk, countStyle: .file))+ // Every game says how much room it takes: what an install needs before, what is on disk after.+ if item.source != .pin || item.installed {+ row(hasMacVersion ? L("Size (Windows)") : L("Size"), windowsSize)+ }+ if hasMacVersion {+ row(L("Size (Mac)"), macSize)+ }+ if item.source == .steam || item.source == .epic || (item.source == .gog && item.installedAnywhere) { cloudSavesRow }+ if let saves = sizes?.saves {+ row(item.source == .steam ? L("Steam Cloud saves") : L("Saves"), Self.bytes(saves))}if let played = item.lastPlayed {row(L("Last played"), played.formatted(date: .abbreviated, time: .shortened))@@ -343,6 +395,129 @@ struct GameDetailView: View {.overlay(RoundedRectangle(cornerRadius: 10).stroke(.white.opacity(0.35)))}+ static func bytes(_ count: Int64) -> String { ByteCountFormatter.string(fromByteCount: count, countStyle: .file) }++ /// How the game saves, said as what it does, with an explanation a click away: Steam Cloud's+ /// and Epic's cloud from their own data, GOG's per installed version from its settings.+ private var cloudSavesRow: some View {+ HStack(alignment: .firstTextBaseline, spacing: 12) {+ Text(L("Cloud saves")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading)+ VStack(alignment: .leading, spacing: 4) {+ ForEach(cloudSaveLines, id: \.self) { Text($0).font(.callout).fixedSize(horizontal: false, vertical: true) }+ }+ Button { showCloudHelp = true } label: { Image(systemName: "info.circle") }+ .buttonStyle(.plain).foregroundStyle(.secondary).help(L("How this game's saves sync"))+ .popover(isPresented: $showCloudHelp, arrowEdge: .trailing) { cloudSavesHelp }+ }+ }++ private var cloudSaveLines: [String] {+ switch item.source {+ case .steam:+ return [item.steamAppID.map(state.steamCloudAppIDs.contains) == true+ ? L("Steam syncs this game's saves with Steam Cloud, for whichever account plays it.")+ : L("This game keeps its saves on this Mac.")]+ case .epic:+ return [state.epicOwned.first { $0.app_name == item.epicAppName }?.cloudSaves == true+ ? L("Epic's cloud keeps this game's saves when Epic's own launcher plays it. Played from Highball, they stay on this Mac.")+ : L("This game keeps its saves on this Mac.")]+ default: break+ }+ guard cloudSetupAsked else { return [L("Checking…")] }+ guard let setup = cloudSetup, let id = item.gogID else { return [L("Highball could not reach GOG to see how this game saves.")] }+ let syncing = !state.gogSettings.cloudSavesOff.contains(id)+ func line(_ folders: [GOGSaves.Location], synced: String, own: String) -> String {+ folders.isEmpty ? own : syncing ? synced : L("Kept on this Mac: Sync saves with GOG, under Game settings, syncs them.")+ }+ var lines: [String] = []+ if item.installed {+ lines.append(line(setup.windows, synced: L("The Windows version's saves sync with GOG's cloud before and after you play."),+ own: L("The game handles the Windows version's saves; some games sync them with GOG's cloud themselves while comet runs.")))+ }+ return lines+ }++ /// How the game's store syncs saves; for GOG, the two ways and the folders this game's covers.+ @ViewBuilder private var cloudSavesHelp: some View {+ switch item.source {+ case .steam:+ VStack(alignment: .leading, spacing: 10) {+ Text(L("How Steam Cloud works")).font(.headline)+ Text(L("Steam syncs a game's saves with Steam Cloud itself, before and after you play, for the account signed in to Steam. Highball starts the game through Steam, so nothing changes. The Steam Cloud saves row is Steam's copy on this Mac."))+ .font(.callout).foregroundStyle(.secondary)+ }+ .padding(16).frame(width: 380, alignment: .leading)+ case .epic:+ VStack(alignment: .leading, spacing: 10) {+ Text(L("How Epic's cloud saves work")).font(.headline)+ Text(L("Epic's launcher syncs a game's saves with Epic's cloud when the game sets a cloud save folder. Highball plays Epic games through legendary, and their saves stay on this Mac."))+ .font(.callout).foregroundStyle(.secondary)+ }+ .padding(16).frame(width: 380, alignment: .leading)+ default:+ gogCloudSavesHelp+ }+ }++ /// The two ways GOG syncs saves, and the folders this game's file sync covers.+ private var gogCloudSavesHelp: some View {+ VStack(alignment: .leading, spacing: 10) {+ Text(L("How saves sync with GOG")).font(.headline)+ Text(L("GOG syncs saves in one of two ways, chosen per game and per version.")).font(.callout)+ Text(L("Folder sync: GOG names the folders a game saves in, and Highball copies them to and from GOG's cloud before and after you play, as GOG Galaxy does. When both copies changed, Highball asks which one to keep."))+ .font(.callout).foregroundStyle(.secondary)+ Text(L("The game's own sync: some games send their saves to GOG's cloud themselves, through GOG's game kit. With Highball that works while comet runs beside the game, and the game says so when it syncs, as Cyberpunk 2077 does."))+ .font(.callout).foregroundStyle(.secondary)+ let folders = (cloudSetup.map { item.installed ? $0.windows : [] } ?? []).map(\.template)+ if !folders.isEmpty {+ Text(L("Folders this game syncs")).font(.caption.weight(.semibold)).padding(.top, 2)+ ForEach(folders, id: \.self) { Text(verbatim: $0).font(.caption.monospaced()).textSelection(.enabled) }+ }+ }+ .padding(16).frame(width: 380, alignment: .leading)+ }++ /// A native Mac version exists: Steam's (MacSteamBuild).+ private var hasMacVersion: Bool { state.offersMacVersion(item) }++ /// The Windows build (or the program): on disk when installed, the store's figure before.+ private var windowsSize: String {+ if item.installed {+ if item.sizeOnDisk > 0 { return String(format: L("Uses %@ of space"), Self.bytes(item.sizeOnDisk)) }+ if let game = sizes?.game { return String(format: L("Uses %@ of space"), Self.bytes(game)) }+ return sizes == nil ? L("Measuring…") : L("Unknown")+ }+ return Self.beforeInstall(windowsEstimate, done: estimatesDone)+ }++ private var macSize: String {+ if item.installedOnMac {+ if let mac = sizes?.macGame { return String(format: L("Uses %@ of space"), Self.bytes(mac)) }+ return sizes == nil ? L("Measuring…") : L("Unknown")+ }+ return Self.beforeInstall(macEstimate, done: estimatesDone)+ }++ /// "Takes 2.18 GB of space (301.8 MB to download)" before an install: the room on the Mac+ /// first, the compressed transfer second. "Checking…" while the store is+ /// asked, "Unknown" when it could not say, never a blank.+ static func beforeInstall(_ estimate: DownloadEstimate?, done: Bool) -> String {+ guard let estimate, estimate.disk != nil || estimate.download != nil else { return done ? L("Unknown") : L("Checking…") }+ switch (estimate.disk, estimate.download) {+ case let (disk?, download?): return String(format: L("Takes %@ of space (%@ to download)"), bytes(disk), bytes(download))+ case let (disk?, nil): return String(format: L("Takes %@ of space"), bytes(disk))+ case let (nil, download?): return String(format: L("%@ to download"), bytes(download))+ default: return L("Unknown")+ }+ }++ /// The same figure beside an install button, so the choice is made knowing the room it takes.+ @ViewBuilder private func estimateText(_ estimate: DownloadEstimate?) -> some View {+ if let estimate, estimate.download != nil || estimate.disk != nil {+ Text(Self.beforeInstall(estimate, done: true)).font(.callout).foregroundStyle(.secondary)+ }+ }+/// Only when the Windows build is the installed one: otherwise the play row already offers/// the Mac build (Play on Mac, Install on Mac).@ViewBuilder private var macButton: some View {@@ -397,6 +572,7 @@ struct GameDetailView: View {Button { state.install(item) } label: { primaryActionLabel(L("Install"), symbol: "arrow.down") }.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)+ estimateText(windowsEstimate)} else if item.source == .steam, !steamHasManifest, state.macSteamBuild(for: item) != nil {// A native build exists: that's the install on offer; the Windows one is the// way around it, not the default.@@ -409,16 +585,21 @@ struct GameDetailView: View {Text(state.steamForMacInstalled ? L("Steam for Mac asks where to put it."): L("The Mac build installs through Steam for Mac.")).font(.callout).foregroundStyle(.secondary)+ estimateText(macEstimate)+ }+ HStack(spacing: 6) {+ Button(L("Install the Windows version instead")) { state.install(item) }+ .buttonStyle(.link).font(.callout).disabled(state.busy || blocked)+ .help(L("For when the Mac build lags behind or a mod needs the Windows one."))+ estimateText(windowsEstimate)}- Button(L("Install the Windows version instead")) { state.install(item) }- .buttonStyle(.link).font(.callout).disabled(state.busy || blocked)- .help(L("For when the Mac build lags behind or a mod needs the Windows one."))}} else if item.source == .steam, !steamHasManifest {// Owned, never installed here (highball#199): Steam's own dialog takes it from here.Button { state.install(item) } label: { primaryActionLabel(L("Install"), symbol: "arrow.down") }.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber).disabled(state.busy)Text(L("Steam asks where to put it.")).font(.callout).foregroundStyle(.secondary)+ estimateText(windowsEstimate)} 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.swiftindex 0d60426..33fef2c 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -395,7 +395,41 @@ enum L10n {"Not installed in any bottle": "Installé dans aucune bouteille","Also installed in %@": "Aussi installé dans %@","Source": "Source",- "Size on disk": "Taille sur le disque",+ "How this game's saves sync": "Comment se synchronisent les sauvegardes de ce jeu",+ "Highball could not reach GOG to see how this game saves.": "Highball n’a pas pu joindre GOG pour voir comment ce jeu sauvegarde.",+ "Kept on this Mac: Sync saves with GOG, under Game settings, syncs them.": "Gardées sur ce Mac : Synchroniser avec GOG, dans les réglages du jeu, les synchronise.",+ "The Windows version's saves sync with GOG's cloud before and after you play.": "Les sauvegardes de la version Windows se synchronisent avec le cloud GOG avant et après chaque partie.",+ "The game handles the Windows version's saves; some games sync them with GOG's cloud themselves while comet runs.":+ "Le jeu gère les sauvegardes de la version Windows ; certains jeux les synchronisent eux-mêmes avec le cloud GOG quand comet tourne.",+ "How saves sync with GOG": "Comment les sauvegardes se synchronisent avec GOG",+ "GOG syncs saves in one of two ways, chosen per game and per version.": "GOG synchronise les sauvegardes de deux façons, selon le jeu et la version.",+ "Folder sync: GOG names the folders a game saves in, and Highball copies them to and from GOG's cloud before and after you play, as GOG Galaxy does. When both copies changed, Highball asks which one to keep.":+ "Synchronisation des dossiers : GOG indique les dossiers où un jeu sauvegarde, et Highball les copie vers et depuis le cloud GOG avant et après chaque partie, comme GOG Galaxy. Si les deux copies ont changé, Highball demande laquelle garder.",+ "The game's own sync: some games send their saves to GOG's cloud themselves, through GOG's game kit. With Highball that works while comet runs beside the game, and the game says so when it syncs, as Cyberpunk 2077 does.":+ "La synchronisation du jeu : certains jeux envoient eux-mêmes leurs sauvegardes au cloud GOG, par le kit de GOG. Avec Highball, cela fonctionne quand comet tourne à côté du jeu, et le jeu l’indique quand il synchronise, comme Cyberpunk 2077.",+ "Folders this game syncs": "Dossiers synchronisés par ce jeu",+ "Steam syncs this game's saves with Steam Cloud, for whichever account plays it.": "Steam synchronise les sauvegardes de ce jeu avec Steam Cloud, pour le compte qui y joue.",+ "This game keeps its saves on this Mac.": "Ce jeu garde ses sauvegardes sur ce Mac.",+ "Epic's cloud keeps this game's saves when Epic's own launcher plays it. Played from Highball, they stay on this Mac.":+ "Le cloud d’Epic garde les sauvegardes de ce jeu quand le lanceur d’Epic y joue. Lancées depuis Highball, elles restent sur ce Mac.",+ "How Steam Cloud works": "Comment fonctionne Steam Cloud",+ "Steam syncs a game's saves with Steam Cloud itself, before and after you play, for the account signed in to Steam. Highball starts the game through Steam, so nothing changes. The Steam Cloud saves row is Steam's copy on this Mac.":+ "Steam synchronise lui-même les sauvegardes d’un jeu avec Steam Cloud, avant et après chaque partie, pour le compte connecté à Steam. Highball lance le jeu par Steam, rien ne change donc. La ligne Sauvegardes Steam Cloud montre la copie de Steam sur ce Mac.",+ "How Epic's cloud saves work": "Comment fonctionnent les sauvegardes en ligne d’Epic",+ "Epic's launcher syncs a game's saves with Epic's cloud when the game sets a cloud save folder. Highball plays Epic games through legendary, and their saves stay on this Mac.":+ "Le lanceur d’Epic synchronise les sauvegardes d’un jeu avec le cloud d’Epic quand le jeu définit un dossier de sauvegarde en ligne. Highball lance les jeux Epic par legendary, et leurs sauvegardes restent sur ce Mac.",+ "Size (Windows)": "Taille (Windows)",+ "Size (Mac)": "Taille (Mac)",+ "Size": "Taille",+ "Measuring…": "Mesure…",+ "Checking…": "Vérification…",+ "Unknown": "Inconnue",+ "Takes %@ of space (%@ to download)": "Occupe %@ (%@ à télécharger)",+ "Takes %@ of space": "Occupe %@",+ "%@ to download": "%@ à télécharger",+ "Uses %@ of space": "Occupe %@",+ "Saves": "Sauvegardes",+ "Steam Cloud saves": "Sauvegardes Steam Cloud","Last played": "Dernière partie","Windows program": "Programme Windows","Choose cover image…": "Choisir une image de couverture…",diff --git a/Sources/HighballKit/EpicStore.swift b/Sources/HighballKit/EpicStore.swiftindex 0512165..d78b43e 100644--- a/Sources/HighballKit/EpicStore.swift+++ b/Sources/HighballKit/EpicStore.swift@@ -108,6 +108,9 @@ public struct EpicStore: Sendable {/// 2:3 cover for the future unified library. Same type mapping Heroic uses.public let artworkWide: URL?public let artworkTall: URL?+ /// The catalog item names a cloud save folder (metadata.customAttributes.CloudSaveFolder):+ /// Epic's cloud keeps its saves when Epic's own launcher syncs them.+ public var cloudSaves = falsepublic init(app_name: String, app_title: String, artworkWide: URL? = nil, artworkTall: URL? = nil) {self.app_name = app_name; self.app_title = app_title@@ -115,8 +118,9 @@ public struct EpicStore: Sendable {}private enum CodingKeys: String, CodingKey { case app_name, app_title, metadata }- private enum MetadataKeys: String, CodingKey { case keyImages }+ private enum MetadataKeys: String, CodingKey { case keyImages, customAttributes }private struct KeyImage: Codable { let type: String?; let url: String? }+ private struct CustomAttribute: Codable { let value: String? }public init(from decoder: Decoder) throws {let c = try decoder.container(keyedBy: CodingKeys.self)@@ -125,6 +129,8 @@ public struct EpicStore: Sendable {var images: [KeyImage] = []if let md = try? c.nestedContainer(keyedBy: MetadataKeys.self, forKey: .metadata) {images = (try? md.decode([KeyImage].self, forKey: .keyImages)) ?? []+ let attributes = (try? md.decode([String: CustomAttribute].self, forKey: .customAttributes)) ?? [:]+ cloudSaves = !(attributes["CloudSaveFolder"]?.value ?? "").isEmpty}func first(_ types: [String]) -> URL? {for t in types {@@ -153,6 +159,10 @@ public struct EpicStore: Sendable {public struct InstalledGame: Codable, Sendable {public let app_name: Stringpublic let install_path: String?+ /// legendary's record of the installed size, in bytes.+ public var install_size: Int64? = nil+ /// Where the game keeps the saves legendary syncs, once it has synced them.+ public var save_path: String? = nil}/// Everything legendary has installed, with where. Legendary's install state is globaldiff --git a/Sources/HighballKit/GOGLibrary.swift b/Sources/HighballKit/GOGLibrary.swiftindex 7eff4cc..854e1a6 100644--- a/Sources/HighballKit/GOGLibrary.swift+++ b/Sources/HighballKit/GOGLibrary.swift@@ -289,19 +289,31 @@ extension GOGStore {public let dependencies: [String]}- public func info(_ id: String) throws -> DownloadInfo {- let out = try capture(["info", id, "--os", "windows"])+ /// `platform` is gogdl's: "windows", or "osx" for a Mac build.+ public func info(_ id: String, platform: String = "windows") throws -> DownloadInfo {+ let out = try capture(["info", id, "--os", platform])guard let start = out.firstIndex(of: "{"),let obj = try JSONSerialization.jsonObject(with: Data(out[start...].utf8)) as? [String: Any] else {- throw HighballError.failed("GOG has no Windows download for this game that gogdl can read.")+ throw HighballError.failed(platform == "osx" ? "GOG has no Mac download for this game that gogdl can read."+ : "GOG has no Windows download for this game that gogdl can read.")}- let size = (obj["size"] as? [String: Any])?["*"] as? [String: Any]- return DownloadInfo(folderName: obj["folder_name"] as? String,- languages: obj["languages"] as? [String] ?? [],- downloadSize: (size?["download_size"] as? NSNumber)?.int64Value,- diskSize: (size?["disk_size"] as? NSNumber)?.int64Value,- buildID: obj["buildId"] as? String,- dependencies: obj["dependencies"] as? [String] ?? [])+ return Self.parseInfo(obj)+ }++ /// gogdl's `size` holds the files every language shares under "*" and each language's own+ /// beside it ("en-US"); a download is "*" plus the language installed. Samorost 1's Mac build:+ /// 44 bytes shared, 68 MB in English.+ static func parseInfo(_ obj: [String: Any], preferred: [String] = Locale.preferredLanguages) -> DownloadInfo {+ let languages = obj["languages"] as? [String] ?? []+ let sizes = obj["size"] as? [String: Any] ?? [:]+ let parts = ["*", language(for: languages, preferred: preferred)].compactMap { sizes[$0] as? [String: Any] }+ func total(_ key: String) -> Int64? {+ let values = parts.compactMap { ($0[key] as? NSNumber)?.int64Value }+ return values.isEmpty ? nil : values.reduce(0, +)+ }+ return DownloadInfo(folderName: obj["folder_name"] as? String, languages: languages,+ downloadSize: total("download_size"), diskSize: total("disk_size"),+ buildID: obj["buildId"] as? String, dependencies: obj["dependencies"] as? [String] ?? [])}/// The language to install: the first of the Mac's preferred languages the game has, elsediff --git a/Sources/HighballKit/GOGSaves.swift b/Sources/HighballKit/GOGSaves.swiftindex 65b116d..fc45c8d 100644--- a/Sources/HighballKit/GOGSaves.swift+++ b/Sources/HighballKit/GOGSaves.swift@@ -73,6 +73,25 @@ public struct GOGSaves: Sendable {: list}+ // MARK: How a game saves++ /// How GOG syncs a game's saves: the folders GOG's file sync copies, empty when it copies+ /// none. Such a game saves through the game itself, which may sync its own saves with GOG's+ /// cloud through GOG's SDK, unseen here.+ public struct CloudSetup: Sendable, Equatable {+ public let windows: [Location]+ }++ /// The setup, from the remote config GOG publishes per client id.+ public func cloudSetup(clientID: String) throws -> CloudSetup {+ let url = URL(string: "https://remote-config.gog.com/components/galaxy_client/clients/\(clientID)?component_version=2.0.45")!+ return Self.parseCloudSetup(try GOGStore.fetch(URLRequest(url: url)), clientID: clientID)+ }++ static func parseCloudSetup(_ data: Data, clientID: String) -> CloudSetup {+ CloudSetup(windows: parseLocations(data, clientID: clientID) ?? [])+ }+/// A location as a folder on the Mac, inside the environment. GOG's variables are the Windows/// known folders; Wine keeps them under drive_c/users/<Mac user name>. A Documents folder the/// environment links to the Mac's (UserFolders) resolves through the link, as Wine does.diff --git a/Sources/HighballKit/GameSizes.swift b/Sources/HighballKit/GameSizes.swiftnew file mode 100644index 0000000..42b8993--- /dev/null+++ b/Sources/HighballKit/GameSizes.swift@@ -0,0 +1,66 @@+import Foundation++/// How much room a game takes: before an install, what the store says the download and the+/// installed game will be; once installed, its folder and its saves as they are on disk.+public struct DownloadEstimate: Sendable, Equatable {+ public let download: Int64?+ public let disk: Int64?++ public init(download: Int64?, disk: Int64?) { self.download = download; self.disk = disk }+}++public enum DiskUsage {+ /// The space a file or folder takes on disk, as Finder counts it (allocated, not logical,+ /// size). Links are not followed, so a folder linked into an environment (the Mac's+ /// Documents) is never counted as the game's. nil when nothing is there.+ public static func bytes(at url: URL) -> Int64? {+ let fm = FileManager.default+ var isFolder: ObjCBool = false+ guard fm.fileExists(atPath: url.path, isDirectory: &isFolder) else { return nil }+ let keys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey, .isRegularFileKey]+ func size(_ file: URL) -> Int64 {+ guard let values = try? file.resourceValues(forKeys: Set(keys)), values.isRegularFile == true else { return 0 }+ return Int64(values.totalFileAllocatedSize ?? values.fileAllocatedSize ?? 0)+ }+ guard isFolder.boolValue else { return size(url) }+ var total: Int64 = 0+ let walker = fm.enumerator(at: url, includingPropertiesForKeys: keys, options: [], errorHandler: { _, _ in true })+ while let file = walker?.nextObject() as? URL { total += size(file) }+ return total+ }++ /// The total over several places, nil when none of them exists.+ public static func bytes(at urls: [URL]) -> Int64? {+ let sizes = urls.compactMap { bytes(at: $0) }+ return sizes.isEmpty ? nil : sizes.reduce(0, +)+ }+}++extension EpicStore {+ /// What legendary says a download of the game's build for `platform` ("Windows" or "Mac")+ /// takes, from its manifest: the bytes fetched and the installed size.+ public func downloadEstimate(_ appName: String, platform: String = "Windows") throws -> DownloadEstimate {+ let out = try capture(["info", appName, "--json", "--platform", platform])+ return Self.parseEstimate(Data(out.utf8)) ?? DownloadEstimate(download: nil, disk: nil)+ }++ static func parseEstimate(_ data: Data) -> DownloadEstimate? {+ guard let start = data.firstIndex(of: UInt8(ascii: "{")),+ let obj = try? JSONSerialization.jsonObject(with: data[start...]) as? [String: Any],+ let manifest = obj["manifest"] as? [String: Any] else { return nil }+ return DownloadEstimate(download: (manifest["download_size"] as? NSNumber)?.int64Value,+ disk: (manifest["disk_size"] as? NSNumber)?.int64Value)+ }+}++extension SteamLibrary {+ /// Steam's own copy of a game's cloud saves, one folder per account that has played it+ /// (userdata/<account>/<appid>). Games keeping saves elsewhere (Documents, AppData) are not+ /// in it, so this is a floor, labelled as Steam Cloud's.+ public static func cloudSaveFolders(steamRoot: URL, appID: Int) -> [URL] {+ let userdata = steamRoot.appending(path: "userdata", directoryHint: .isDirectory)+ let accounts = (try? FileManager.default.contentsOfDirectory(at: userdata, includingPropertiesForKeys: nil)) ?? []+ return accounts.map { $0.appending(path: String(appID), directoryHint: .isDirectory) }+ .filter { FileManager.default.fileExists(atPath: $0.path) }+ }+}diff --git a/Sources/HighballKit/SteamDownloadSize.swift b/Sources/HighballKit/SteamDownloadSize.swiftnew file mode 100644index 0000000..5906a19--- /dev/null+++ b/Sources/HighballKit/SteamDownloadSize.swift@@ -0,0 +1,63 @@+import Foundation++/// The purchases Steam knows on this Mac, from the client's appcache/packageinfo.vdf: one entry+/// per package an account signed in here owns (and free ones), with the apps and depots it brings.+/// Read for sizes only: which depots of a game a download would fetch.+public enum SteamPackageInfo {+ public struct Package: Sendable, Equatable {+ public let id: Int+ public let appIDs: Set<Int>+ public let depotIDs: Set<Int>+ }++ public static func read(steamRoot: URL) -> [Package] {+ guard let data = try? Data(contentsOf: steamRoot.appending(path: "appcache/packageinfo.vdf"), options: .mappedIfSafe) else { return [] }+ return parse(data)+ }++ /// v39/v40/v41: magic, universe, then per package its id, a SHA-1, a change number, a token+ /// (from v40), and a binary KeyValues object; an id of 0xFFFFFFFF ends the list.+ /// What parsed before a damaged entry, rather than nothing: one bad record must not hide every+ /// purchase. An unknown version reads as none.+ static func parse(_ data: Data) -> [Package] {+ var r = SteamAppInfo.Reader(bytes: [UInt8](data))+ guard let magic = try? r.u32(), magic & 0xFFFF_FF00 == 0x0656_5500, magic & 0xFF >= 0x27, (try? r.u32()) != nil else { return [] }+ let hasToken = magic & 0xFF >= 0x28+ var packages: [Package] = []+ while let id = try? r.u32(), id != 0xFFFF_FFFF {+ r.offset += 20 + 4 + (hasToken ? 8 : 0)+ guard let root = try? r.object(nil) else { break }+ let package = root.values.first?.object ?? root+ func ids(_ key: String) -> Set<Int> { Set((package[key]?.object ?? [:]).values.compactMap { $0.string.flatMap(Int.init) }) }+ packages.append(Package(id: Int(id), appIDs: ids("appids"), depotIDs: ids("depotids")))+ }+ return packages+ }+}++/// How much a Steam game's download is before it is installed, from Steam's own data on the Mac:+/// the depots for the platform and language that come with what the accounts here own. A game+/// can list several editions' depots (Little Nightmares III lists two of about 15 GB; the+/// purchases here bring one), so the packages decide, not a sum of everything listed.+public enum SteamDownloadSize {+ public static func estimate(appID: Int, app: SteamAppInfo.App, packages: [Package], mac: Bool,+ language: String = "english") -> DownloadEstimate? {+ guard packages.contains(where: { $0.appIDs.contains(appID) }) else { return nil }+ // Every purchase counts, not only the game's: a DLC bought on its own is a package of its+ // own, and its depots (dlcAppID) come along with the game. Depots are the game's own+ // list, so another game's in these sets never count.+ let ownedDepots = packages.reduce(into: Set<Int>()) { $0.formUnion($1.depotIDs) }+ let ownedApps = packages.reduce(into: Set<Int>()) { $0.formUnion($1.appIDs) }+ let picked = app.depots.filter { depot in+ guard ownedDepots.contains(depot.id) || (depot.dlcAppID != 0 && ownedApps.contains(depot.dlcAppID)) else { return false }+ guard !depot.restricted, depot.size > 0 else { return false }+ let os = depot.oslist.lowercased()+ guard os.isEmpty || os.contains(mac ? "macos" : "windows") else { return false }+ return depot.language.isEmpty || depot.language.lowercased() == language+ }+ guard !picked.isEmpty else { return nil }+ return DownloadEstimate(download: picked.reduce(0) { $0 + $1.download }, disk: picked.reduce(0) { $0 + $1.size })+ }++ public typealias Package = SteamPackageInfo.Package+}diff --git a/Sources/HighballKit/SteamOwnedLibrary.swift b/Sources/HighballKit/SteamOwnedLibrary.swiftindex fdbef2c..5e02203 100644--- a/Sources/HighballKit/SteamOwnedLibrary.swift+++ b/Sources/HighballKit/SteamOwnedLibrary.swift@@ -12,11 +12,13 @@ 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+ /// appinfo's `ufs` gives the game room in Steam Cloud, which Steam syncs per account.+ public var steamCloud = falsepublic init(appid: Int, name: String, localCapsule: URL? = nil, localHeader: URL? = nil, listsMac: Bool = false,- macBuild: MacAppInfoBuild = .absent) {+ macBuild: MacAppInfoBuild = .absent, steamCloud: Bool = false) {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.steamCloud = steamCloud}/// Local art first: newer apps keep theirs at hashed store paths, so the fixed CDN name@@ -61,7 +63,7 @@ public enum SteamOwnedLibrary {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, steamCloud: app.steamCloudQuota > 0)}.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }}@@ -103,6 +105,23 @@ public enum SteamAppInfo {public var osextended: String? = nil/// The `osarch` of each macOS launch entry under `config.launch`, "" for one naming none.public var macLaunchArchs: [String] = []+ /// The app's depots: the pieces Steam downloads, with their sizes (SteamDownloadSize).+ public var depots: [Depot] = []+ /// `ufs.quota`: the room the game has in Steam Cloud, 0 for a game Steam Cloud does not keep.+ public var steamCloudQuota: Int64 = 0++ public struct Depot: Sendable, Equatable {+ public let id: Int+ public var oslist = ""+ public var language = ""+ /// Set for a depot only some regions or editions get (low-violence, Steam China).+ public var restricted = false+ /// The DLC app whose purchase brings the depot, 0 for the game's own.+ public var dlcAppID = 0+ /// Installed and download size of the public branch's manifest, 0 when Steam's data has none.+ public var size: Int64 = 0+ public var download: Int64 = 0+ }public var macBuild: MacAppInfoBuild {MacAppInfoBuild(oslist: oslist, osextended: osextended, macLaunchArchs: macLaunchArchs)@@ -147,8 +166,18 @@ public enum SteamAppInfo {.compactMap { $0.object?["config"]?.object }.filter { ($0["oslist"]?.string ?? "").lowercased().contains("macos") }.map { $0["osarch"]?.string ?? "" }.sorted()+ let depots = (info["depots"]?.object ?? [:]).compactMap { key, node -> App.Depot? in+ guard let id = Int(key), let o = node.object, o["sharedinstall"] == nil, o["depotfromapp"] == nil else { return nil }+ let config = o["config"]?.object ?? [:]+ let manifest = o["manifests"]?.object?["public"]?.object+ return App.Depot(id: id, oslist: config["oslist"]?.string ?? "", language: config["language"]?.string ?? "",+ restricted: config["lowviolence"]?.string == "1" || config["realm"] != nil,+ dlcAppID: Int(o["dlcappid"]?.string ?? "") ?? 0,+ size: Int64(manifest?["size"]?.string ?? "") ?? 0, download: Int64(manifest?["download"]?.string ?? "") ?? 0)+ }.sorted { $0.id < $1.id }apps[appid] = App(name: common?["name"]?.string, type: common?["type"]?.string, oslist: common?["oslist"]?.string,- osextended: common?["osextended"]?.string, macLaunchArchs: macArchs)+ osextended: common?["osextended"]?.string, macLaunchArchs: macArchs, depots: depots,+ steamCloudQuota: Int64(info["ufs"]?.object?["quota"]?.string ?? "") ?? 0)}return apps}diff --git a/Tests/HighballKitTests/GameSizesTests.swift b/Tests/HighballKitTests/GameSizesTests.swiftnew file mode 100644index 0000000..d5efa05--- /dev/null+++ b/Tests/HighballKitTests/GameSizesTests.swift@@ -0,0 +1,164 @@+import XCTest+@testable import HighballKit++/// How much room a game takes: the store's estimate before an install, the folders after.+final class GameSizesTests: XCTestCase {+ func testFolderSizeCountsFilesAndNotLinks() throws {+ let dir = FileManager.default.temporaryDirectory.appending(path: "size-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: dir) }+ try FileManager.default.createDirectory(at: dir.appending(path: "sub"), withIntermediateDirectories: true)+ try Data(count: 10_000).write(to: dir.appending(path: "a.bin"))+ try Data(count: 50_000).write(to: dir.appending(path: "sub/b.bin"))+ let outside = FileManager.default.temporaryDirectory.appending(path: "big-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: outside) }+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ try Data(count: 500_000).write(to: outside.appending(path: "c.bin"))+ try FileManager.default.createSymbolicLink(at: dir.appending(path: "Documents"), withDestinationURL: outside)++ let size = try XCTUnwrap(DiskUsage.bytes(at: dir))+ XCTAssertGreaterThanOrEqual(size, 60_000)+ XCTAssertLessThan(size, 500_000, "a linked folder is not the game's")+ XCTAssertNil(DiskUsage.bytes(at: dir.appending(path: "missing")))+ XCTAssertNil(DiskUsage.bytes(at: [dir.appending(path: "missing")]))+ }++ func testEpicEstimateComesFromLegendarysManifest() {+ let out = #"[cli] INFO: Getting game metadata... {"game": {}, "install": {}, "manifest": {"disk_size": 356045656, "download_size": 257001326}}"#+ XCTAssertEqual(EpicStore.parseEstimate(Data(out.utf8)), DownloadEstimate(download: 257001326, disk: 356045656))+ XCTAssertNil(EpicStore.parseEstimate(Data("no json".utf8)))+ }++ func testEpicInstallRecordKeepsSizeAndSaveFolder() throws {+ let json = #"[{"app_name":"Garlic","install_path":"/x","install_size":356045656,"save_path":"/s"},{"app_name":"Old","install_path":"/y"}]"#+ let games = try JSONDecoder().decode([EpicStore.InstalledGame].self, from: Data(json.utf8))+ XCTAssertEqual(games.map(\.install_size), [356045656, nil])+ XCTAssertEqual(games.map(\.save_path), ["/s", nil])+ }++ func testSteamCloudSavesAreEachAccountsFolderForTheGame() throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "steam-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: root) }+ for account in ["1001", "1002"] {+ try FileManager.default.createDirectory(at: root.appending(path: "userdata/\(account)/7/remote"), withIntermediateDirectories: true)+ }+ try FileManager.default.createDirectory(at: root.appending(path: "userdata/1003/8"), withIntermediateDirectories: true)+ XCTAssertEqual(SteamLibrary.cloudSaveFolders(steamRoot: root, appID: 7).map { $0.deletingLastPathComponent().lastPathComponent }.sorted(),+ ["1001", "1002"])+ }+}++/// A Steam download's size from the client's own data: the depots the purchases here bring.+final class SteamDownloadSizeTests: XCTestCase {+ typealias Depot = SteamAppInfo.App.Depot++ /// Little Nightmares III as Steam lists it: two editions' depots of about 15 GB each, and+ /// the purchases on the Mac bring one (1392863), the one that was installed.+ func testOnlyTheDepotsTheOwnedPurchasesBringCount() throws {+ var app = SteamAppInfo.App()+ app.depots = [Depot(id: 1392861, oslist: "windows", size: 14_660_122_449, download: 13_911_985_088),+ Depot(id: 1392862, oslist: "windows", size: 1_050_249_020, download: 179_410_784),+ Depot(id: 1392863, size: 16_913_105_339, download: 15_980_071_584),+ Depot(id: 1392864, size: 1_079_728_799, download: 248_374_704)]+ let packages = [SteamPackageInfo.Package(id: 1096901, appIDs: [1392860], depotIDs: [1392863]),+ SteamPackageInfo.Package(id: 1345312, appIDs: [1392860, 2088780], depotIDs: [1392863])]+ let estimate = try XCTUnwrap(SteamDownloadSize.estimate(appID: 1392860, app: app, packages: packages, mac: false))+ XCTAssertEqual(estimate.disk, 16_913_105_339)+ XCTAssertEqual(estimate.download, 15_980_071_584)+ XCTAssertNil(SteamDownloadSize.estimate(appID: 1392860, app: app, packages: [], mac: false), "owned by no account here")+ }++ func testPlatformLanguageRegionAndDLCDecide() throws {+ var app = SteamAppInfo.App()+ app.depots = [Depot(id: 1, oslist: "windows", size: 100, download: 50),+ Depot(id: 2, oslist: "macos", size: 80, download: 40),+ Depot(id: 3, language: "french", size: 10, download: 5),+ Depot(id: 4, language: "english", size: 7, download: 3),+ Depot(id: 5, restricted: true, size: 1000, download: 900),+ Depot(id: 6, dlcAppID: 99, size: 20, download: 10),+ Depot(id: 7, dlcAppID: 98, size: 30, download: 15)]+ let packages = [SteamPackageInfo.Package(id: 1, appIDs: [10, 99], depotIDs: [1, 2, 3, 4, 5])]+ XCTAssertEqual(SteamDownloadSize.estimate(appID: 10, app: app, packages: packages, mac: false),+ DownloadEstimate(download: 63, disk: 127), "Windows, English, the owned DLC, no restricted depot")+ XCTAssertEqual(SteamDownloadSize.estimate(appID: 10, app: app, packages: packages, mac: true),+ DownloadEstimate(download: 53, disk: 107))+ }+}++/// Steam's binary formats as the size estimate reads them, built byte by byte: KeyValues objects+/// with inline keys (type, name, value; 0x08 ends an object), little-endian integers.+private enum SteamBinary {+ static func u32(_ v: UInt32) -> [UInt8] { withUnsafeBytes(of: v.littleEndian, Array.init) }+ static func cString(_ s: String) -> [UInt8] { Array(s.utf8) + [0] }+ indirect enum Value { case string(String), int(Int32), object([(String, Value)]) }+ static func object(_ entries: [(String, Value)]) -> [UInt8] {+ entries.flatMap { key, value -> [UInt8] in+ switch value {+ case .string(let s): return [0x01] + cString(key) + cString(s)+ case .int(let i): return [0x02] + cString(key) + u32(UInt32(bitPattern: i))+ case .object(let o): return [0x00] + cString(key) + object(o)+ }+ } + [0x08]+ }+}++final class SteamBinaryParsingTests: XCTestCase {+ /// packageinfo.vdf v40: magic, universe, then per package its id, SHA-1, change number and+ /// token before the object; 0xFFFFFFFF ends it.+ private func packageInfo(_ packages: [(Int, [Int], [Int])], damagedAfter: Int? = nil) -> Data {+ var bytes = SteamBinary.u32(0x0656_5528) + SteamBinary.u32(1)+ for (n, (id, apps, depots)) in packages.enumerated() {+ if n == damagedAfter { bytes += SteamBinary.u32(UInt32(id)) + [UInt8](repeating: 0, count: 32) + [0x09]; break }+ let body: [(String, SteamBinary.Value)] = [+ ("packageid", .int(Int32(id))),+ ("appids", .object(apps.enumerated().map { (String($0.offset), .int(Int32($0.element))) })),+ ("depotids", .object(depots.enumerated().map { (String($0.offset), .int(Int32($0.element))) }))]+ bytes += SteamBinary.u32(UInt32(id)) + [UInt8](repeating: 0, count: 20 + 4 + 8) + SteamBinary.object([(String(id), .object(body))])+ }+ if damagedAfter == nil { bytes += SteamBinary.u32(0xFFFF_FFFF) }+ return Data(bytes)+ }++ func testPackagesAreReadWithTheirAppsAndDepots() {+ let packages = SteamPackageInfo.parse(packageInfo([(1096901, [1392860], [1392863]), (7, [10, 99], [11])]))+ XCTAssertEqual(packages.map(\.id), [1096901, 7])+ XCTAssertEqual(packages.first?.appIDs, [1392860])+ XCTAssertEqual(packages.last?.depotIDs, [11])+ }++ /// One damaged entry keeps what came before it, rather than hiding every purchase.+ func testADamagedPackageKeepsTheOnesBeforeIt() {+ XCTAssertEqual(SteamPackageInfo.parse(packageInfo([(1, [10], [11]), (2, [20], [21])], damagedAfter: 1)).map(\.id), [1])+ XCTAssertEqual(SteamPackageInfo.parse(Data([0, 1, 2, 3])), [], "an unknown version reads as none")+ }++ /// appinfo.vdf v28's depots: shared redistributables left out, restrictions and sizes read.+ func testDepotsComeWithTheirSystemLanguageRestrictionAndSize() throws {+ let depots: [(String, SteamBinary.Value)] = [+ ("11", .object([("config", .object([("oslist", .string("windows")), ("language", .string("french"))])),+ ("manifests", .object([("public", .object([("size", .string("1000")), ("download", .string("400"))]))]))])),+ ("12", .object([("config", .object([("lowviolence", .string("1"))]))])),+ ("13", .object([("dlcappid", .string("99")), ("manifests", .object([("public", .object([("size", .string("50"))]))]))])),+ ("228988", .object([("sharedinstall", .string("1")), ("depotfromapp", .string("228980"))])),+ ("branches", .object([("public", .object([("buildid", .string("1"))]))]))]+ let kv = SteamBinary.object([("appinfo", .object([("common", .object([("name", .string("Game")), ("type", .string("Game"))])),+ ("ufs", .object([("quota", .int(104_857_600))])),+ ("depots", .object(depots))]))])+ let entry = SteamBinary.u32(10) + SteamBinary.u32(UInt32(60 + kv.count)) + [UInt8](repeating: 0, count: 60) + kv+ let data = Data(SteamBinary.u32(0x0756_4428) + SteamBinary.u32(1) + entry + SteamBinary.u32(0))+ let app = try XCTUnwrap(try SteamAppInfo.parse(data)[10])+ XCTAssertEqual(app.depots.map(\.id), [11, 12, 13], "the shared redistributable is not the game's")+ XCTAssertEqual(app.depots[0], SteamAppInfo.App.Depot(id: 11, oslist: "windows", language: "french", size: 1000, download: 400))+ XCTAssertTrue(app.depots[1].restricted)+ XCTAssertEqual(app.depots[2].dlcAppID, 99)+ XCTAssertEqual(app.steamCloudQuota, 104_857_600, "Steam Cloud keeps its saves")+ }++ /// A DLC bought on its own is a package without the base game; its depots still count.+ func testADLCBoughtSeparatelyCounts() {+ var app = SteamAppInfo.App()+ app.depots = [.init(id: 1, size: 100, download: 50), .init(id: 2, dlcAppID: 99, size: 20, download: 10)]+ let packages = [SteamPackageInfo.Package(id: 1, appIDs: [10], depotIDs: [1]),+ SteamPackageInfo.Package(id: 2, appIDs: [99], depotIDs: [2])]+ XCTAssertEqual(SteamDownloadSize.estimate(appID: 10, app: app, packages: packages, mac: false), DownloadEstimate(download: 60, disk: 120))+ }+}