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
Add GOG: library, installs, comet achievements and cloud saves
Gabeba480028f749
diff --git a/README.md b/README.mdindex a92b36d..69c09ed 100644--- a/README.md+++ b/README.md@@ -59,8 +59,8 @@ titles as impossible before you download 80 GB.Cyberpunk 2077, for one, runs 60–82 fps on an M5 (D3DMetal + FSR 2.1), and Red DeadRedemption 2 plays on an M1 Pro after a MoltenVK fix that is now a pull request upstream.-Renderer switching, 32-bit apps via Wine's WoW64, Windows runtimes, ReShade, and your Epic-library via Legendary work too.+Renderer switching, 32-bit apps via Wine's WoW64, Windows runtimes, ReShade, your Epic+library via Legendary and your GOG library via gogdl work too.## Launchers@@ -70,8 +70,11 @@ engine (built from the CrossOver 26.3 tree); Play offers that engine when a gameyou can move an environment to it in Settings. Rockstar signs in and runs GTA V and Red DeadRedemption 2 here, the EA app signs in and runs The Sims 4, Ubisoft Connect and Battle.net showtheir sign-in windows but no game has been played through them here yet. GOG Galaxy still comes-up black, so you can't sign in; GOG's DRM-free offline installers run directly in an environment-instead. Each case is tracked in the launcher recipe's `knownIssues`.+up black, so you can't sign in through it; Connect GOG does Galaxy's jobs instead, through+Heroic's gogdl and comet: sign in on GOG's page in your browser, and your GOG library installs+straight into an environment with its covers, achievements and cloud saves. GOG games you+installed from offline installers show up as GOG games too. Each launcher case is tracked in its+recipe's `knownIssues`.## Getting starteddiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 56546b1..46374a8 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -43,11 +43,11 @@ brew install --cask highball### [在数据库里搜索你的游戏 →](https://gethighball.com/database/)-举个例子,《赛博朋克 2077》在 M5 上能跑到 60 到 82 fps(D3DMetal 加 FSR 2.1)。《荒野大镖客:救赎 2》在修复了 MoltenVK 的一个问题之后可以在 M1 Pro 上游玩,这个修复已经作为拉取请求提交给上游。图形模式切换、通过 Wine 的 WoW64 运行 32 位程序、Windows 运行库、ReShade,以及通过 Legendary 使用 Epic 游戏库,也都可以正常工作。+举个例子,《赛博朋克 2077》在 M5 上能跑到 60 到 82 fps(D3DMetal 加 FSR 2.1)。《荒野大镖客:救赎 2》在修复了 MoltenVK 的一个问题之后可以在 M1 Pro 上游玩,这个修复已经作为拉取请求提交给上游。图形模式切换、通过 Wine 的 WoW64 运行 32 位程序、Windows 运行库、ReShade,通过 Legendary 使用 Epic 游戏库,以及通过 gogdl 使用 GOG 游戏库,也都可以正常工作。## 游戏平台-Steam 和 Epic(通过 Legendary)在默认引擎上就能用。Rockstar、EA app 和 Ubisoft Connect 的登录窗口使用内嵌浏览器,需要 Highball 的 Wine 11 引擎(基于 CrossOver 26.3 的源码构建)。游戏需要时,点击 Play 会主动提供这个引擎,你也可以在设置里把某个环境切换过去。在这里,Rockstar 能登录并运行 GTA V 和《荒野大镖客:救赎 2》,EA app 能登录并运行《模拟人生 4》。Ubisoft Connect 和 Battle.net 能显示登录窗口,但还没有在这里通过它们实际玩过游戏。GOG Galaxy 仍然是黑屏,无法登录,不过 GOG 的无 DRM 离线安装包可以直接在环境里运行。每种情况都记录在对应启动器配方的 `knownIssues` 里。+Steam 和 Epic(通过 Legendary)在默认引擎上就能用。Rockstar、EA app 和 Ubisoft Connect 的登录窗口使用内嵌浏览器,需要 Highball 的 Wine 11 引擎(基于 CrossOver 26.3 的源码构建)。游戏需要时,点击 Play 会主动提供这个引擎,你也可以在设置里把某个环境切换过去。在这里,Rockstar 能登录并运行 GTA V 和《荒野大镖客:救赎 2》,EA app 能登录并运行《模拟人生 4》。Ubisoft Connect 和 Battle.net 能显示登录窗口,但还没有在这里通过它们实际玩过游戏。GOG Galaxy 仍然是黑屏,无法通过它登录;“连接 GOG”改用 Heroic 的 gogdl 和 comet 来完成 Galaxy 的工作:在浏览器里登录 GOG 的页面,你的 GOG 游戏库就会带着封面、成就和云存档直接安装到环境里。用离线安装包安装的 GOG 游戏也会显示为 GOG 游戏。每种情况都记录在对应启动器配方的 `knownIssues` 里。## 开始使用diff --git a/Sources/HighballApp/AddGamesView.swift b/Sources/HighballApp/AddGamesView.swiftindex 8baf597..a92e569 100644--- a/Sources/HighballApp/AddGamesView.swift+++ b/Sources/HighballApp/AddGamesView.swift@@ -28,6 +28,12 @@ struct AddGamesView: View {connected: state.epicSignedIn) {state.showEpicSignIn = true}+ sourceCard("GOG", symbol: "g.circle.fill",+ description: L("Connect your GOG account to see and download your games."),+ action: state.gogSignedIn ? L("GOG account connected") : L("Connect GOG account…"),+ connected: state.gogSignedIn, manage: { state.showGOGSignIn = true }) {+ state.showGOGSignIn = true+ }sourceCard(L("A Windows program I have…"), symbol: "app.dashed",description: L("Choose an .exe, .msi or .bat file, or drop it on this window."),action: L("Choose a file…")) {@@ -37,7 +43,9 @@ struct AddGamesView: View {VStack(alignment: .leading, spacing: 12) {HB.eyebrow(L("Launchers"))LazyVGrid(columns: [GridItem(.adaptive(minimum: 120, maximum: 170), spacing: 12)], spacing: 12) {- ForEach(BottleView.launcherMeta.filter { $0.id != "steam" }, id: \.id) { meta in+ // Steam and GOG have their own cards above; GOG Galaxy's own client stays blocked+ // (its sign-in window draws black), and Connect GOG does its jobs instead.+ ForEach(BottleView.launcherMeta.filter { $0.id != "steam" && $0.id != "gog-galaxy" }, id: \.id) { meta inif let recipe = AppState.recipe(meta.id) {LauncherTile(title: meta.short, symbol: meta.symbol,installed: state.launcherInstalled(meta.id), busy: unavailable,@@ -66,7 +74,8 @@ struct AddGamesView: View {}private func sourceCard(_ title: String, symbol: String, description: String,- action: String, connected: Bool = false, perform: @escaping () -> Void) -> some View {+ action: String, connected: Bool = false, manage: (() -> Void)? = nil,+ perform: @escaping () -> Void) -> some View {VStack(alignment: .leading, spacing: 12) {Image(systemName: symbol).font(.title).foregroundStyle(HB.amber).accessibilityHidden(true)@@ -75,8 +84,15 @@ struct AddGamesView: View {.fixedSize(horizontal: false, vertical: true)Spacer(minLength: 8)if connected {- Label(action, systemImage: "checkmark.circle.fill")- .font(.callout).foregroundStyle(HB.good)+ HStack {+ Label(action, systemImage: "checkmark.circle.fill")+ .font(.callout).foregroundStyle(HB.good)+ // The way back to a connected account: switching accounts, or disconnecting.+ if let manage {+ Spacer()+ Button(L("Manage…"), action: manage).buttonStyle(.plain).font(.callout).foregroundStyle(HB.amber)+ }+ }} else {Button(action, action: perform).buttonStyle(.bordered).disabled(unavailable)}diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex b9d4f8a..6235bb1 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -7,6 +7,17 @@ import os/// The three Settings tabs, so a deep link can select one.enum SettingsTab: Hashable { case environments, engine, troubleshooting }+/// A GOG cloud-save conflict: this Mac's saves and GOG's both changed since the last sync, so+/// gogdl moved nothing and the player picks which copy wins (GOGSaves).+struct GOGSaveConflict: Identifiable {+ enum Choice { case useCloud, keepMac, skip }+ let id = UUID()+ let title: String+ /// Asked before Play (the launch waits) or after the game ended.+ let beforePlay: Bool+ let resolve: (Choice) -> Void+}+@Observable @MainActorfinal class AppState {var engines: [InstalledEngine] = []@@ -277,9 +288,11 @@ final class AppState {func rebuildLibrary() {customNames = nameStore.names()+ carryOverGOGCoveredPins()libraryItems = LibraryIndex.build(bottles: bottles, steamByBottle: gamesByBottle,steamOwnedByBottle: steamOwnedByBottle, macInstalled: macSteamGames,epicOwned: epicOwned, epicInstalls: epicInstalls,+ gogGames: gogGames, gogInstalledByBottle: gogInstalledByBottle,plays: libraryPlays, defaultBottle: defaultBottle?.name,pinExists: { bottle, pin in// follows links, so a link to a file that is gone counts as missing@@ -659,6 +672,8 @@ final class AppState {guard let game = epicOwned.first(where: { $0.app_name == item.epicAppName }) else { return }epicPlay(game, in: bottle, renderer: renderer,throughEpicLauncherStandIn: fixRecipe(for: item)?.requires?.contains("rockstar") == true)+ case .gog:+ gogPlay(item, in: bottle, renderer: renderer)case .pin:guard let pin = bottle.settings.pins.first(where: { $0.id == item.pinID }) else { return }launch(pin: pin.launching(with: renderer), in: bottle)@@ -738,6 +753,11 @@ final class AppState {/// menu in the detail view refines it, never a modal prerequisite. Steam hands off to Steam.func install(_ item: LibraryItem) {if item.source == .steam { installSteamGame(item); return }+ if item.source == .gog {+ guard let target = item.bottleName.flatMap({ name in bottles.first { $0.name == name } }) ?? defaultBottle else { return }+ gogInstall(item, in: target)+ return+ }guard item.source == .epic,let game = epicOwned.first(where: { $0.app_name == item.epicAppName }) else { return }guard let target = item.bottleName.flatMap({ name in bottles.first { $0.name == name } }) ?? defaultBottle else { return }@@ -809,6 +829,21 @@ final class AppState {private var epicFetchInFlight = falsevar showEpicSignIn = false+ // GOG (via gogdl and comet; see GOGStore)+ var gogSignedIn = false+ var gogAccountName: String?+ /// The account's games, plus any GOG game installed in an environment that the account list+ /// does not name (an offline installer's, while signed out), looked up in GOG's database.+ var gogGames: [GOGStore.Game] = []+ /// What each environment holds, read from the goggame-<id>.info files on disk.+ var gogInstalledByBottle: [String: [GOGStore.InstalledGame]] = [:]+ var gogLoading = false+ private var gogFetchInFlight = false+ var showGOGSignIn = false+ var gogSettings = GOGSettings()+ /// A cloud-save conflict waiting for the player's choice (GOGSaves.Outcome.conflict).+ var gogSaveConflict: GOGSaveConflict?+/// A Windows program awaiting the run/pin choice (from drag-drop, the File menu, or the button).var pendingRun: URL?/// The environment a dropped program runs in: the page it was dropped on, else the default.@@ -974,9 +1009,10 @@ final class AppState {@ObservationIgnored private var installWatcher: DirectoryWatcher?/// The directories whose entries change when a game is installed or removed: the steamapps- /// of each Steam library folder (appmanifest files) and the folder Epic installs land in.+ /// of each Steam library folder (appmanifest files), the folder Epic installs land in, and the+ /// folders GOG installs land in (the first of which is that same Games folder).private func installDirectories(of bottle: Bottle) -> [URL] {- [bottle.driveC.appending(path: "Games")] + SteamLibrary.steamappsDirectories(of: bottle)+ GOGStore.installRoots(driveC: bottle.driveC) + SteamLibrary.steamappsDirectories(of: bottle)}/// The cheap part of `refresh`: installed games only. Runs on every install-record change,@@ -987,6 +1023,7 @@ final class AppState {let mac = MacSteam.installedGames()if mac != macSteamGames { macSteamGames = mac; rebuildLibrary() }refreshEpicInstalls()+ refreshGOGInstalls()}/// The Windows Steam part of `refreshInstalledGames`, without legendary, so the client watch@@ -1057,6 +1094,7 @@ final class AppState {rebuildLibrary()steamOwnedRefresh()epicRefresh()+ gogRefresh()maybeAutoUpdateEngine()if gameDB.byAppID.isEmpty {var dirs: [URL] = []@@ -1949,6 +1987,11 @@ final class AppState {switch item.source {case .steam, .epic:return programFolder(for: item).flatMap { PEIcon.bestExecutable(in: $0) }+ case .gog:+ // The file Play runs, so the per-program settings (display mode) apply to the game itself.+ guard let game = gogInstalled(item, in: bottle), let task = game.launchTask(choice: gogSettings.launchChoice[game.id]),+ let launch = GOGStore.launch(task, in: game) else { return nil }+ return launch.executablecase .pin:return item.pinID.flatMap { id in bottle.settings.pins.first { $0.id == id } }.map { $0.executableURL(driveC: bottle.driveC) }}@@ -1967,6 +2010,8 @@ final class AppState {folder = game.installFolder ?? bottle.driveC.appending(path: "Program Files (x86)/Steam/steamapps/common/\(game.installdir)", directoryHint: .isDirectory)case .epic:folder = item.epicAppName.flatMap { epicInstalls[$0] }.map { URL(fileURLWithPath: $0, isDirectory: true) }+ case .gog:+ folder = gogInstalled(item, in: bottle)?.foldercase .pin:folder = item.pinID.flatMap { id in bottle.settings.pins.first { $0.id == id } }.map { $0.executableURL(driveC: bottle.driveC).deletingLastPathComponent() }}@@ -2085,11 +2130,27 @@ final class AppState {pendingUninstall = (item, Uninstall.route(for: item))}+ /// What is holding the progress strip when removing `item` needs it (Epic and GOG removals+ /// run there, one operation at a time), so the button can say why it waits. Nil otherwise.+ func uninstallWaitsFor(_ item: LibraryItem) -> String? {+ guard busy else { return nil }+ switch Uninstall.route(for: item) {+ case .epic, .gog: return busyTitle+ default: return nil+ }+ }+/// Carries out the route the ask offered.func uninstallConfirmed() {guard let (item, route) = pendingUninstall else { return }pendingUninstall = nilguard let bottleName = item.bottleName, let bottle = bottles.first(where: { $0.name == bottleName }) else { return }+ // runBusy drops a second operation, so a removal confirmed while another one runs (the+ // ask opened just before it started) would do nothing at all: say so instead.+ if let holder = uninstallWaitsFor(item) {+ errorMessage = String(format: L("Highball is still busy with “%@”. Remove %@ once that has finished, or stop it in the bar at the bottom."), holder, item.title)+ return+ }switch route {case let .steam(appID):guard let engine = engine(for: bottle) else { return }@@ -2115,6 +2176,8 @@ final class AppState {_ = try store.uninstall(appName) { line in Task { @MainActor in self.appendLog(line) } }await MainActor.run { self.refresh() }}+ case let .gog(id):+ gogUninstall(id: id, title: item.title, in: bottle)case .windowsUninstaller:openUninstaller(in: bottle)case .none:@@ -2485,9 +2548,15 @@ final class AppState {return windows.contains { ($0[kCGWindowOwnerPID as String] as? pid_t) == pid && ($0[kCGWindowLayer as String] as? Int) == 0 }}+ /// Work a launch leaves for the end of its session (a GOG game's comet and save upload).+ @ObservationIgnored private var sessionEndActions: [UUID: (SessionRecord) -> Void] = [:]+private func endSession(_ session: GameSession, reason: String) {guard runningSessions.contains(session) else { return }runningSessions.removeAll { $0.id == session.id }+ defer {+ if let action = sessionEndActions.removeValue(forKey: session.id), let record = lastEndedSession { action(record) }+ }discordEnvironments[session.id] = nilif runningSessions.isEmpty { stopDiscordWatch() }sessionWatchers[session.id]?.cancel()@@ -2914,6 +2983,9 @@ final class AppState {}crashed(result); return false}+ // A launcher that starts the game and exits cleanly between two polls: the+ // game is already up, and that is the hand-off.+ if await started() { box.handedOff = true; return true }if exitEndsWait { return false }exited = true}@@ -3167,6 +3239,514 @@ final class AppState {return target}+ // MARK: GOG++ var gogStore: GOGStore { GOGStore(paths: paths) }++ /// Signed-in state, what is installed (from disk, cheap) and the account's games (from GOG,+ /// cached per game in GOGStore, so a refresh is one or two library requests).+ func gogRefresh() {+ gogSignedIn = gogStore.isAuthenticated+ gogAccountName = gogSignedIn ? gogStore.username : nil+ gogSettings = GOGSettings.load(gogStore)+ refreshGOGInstalls()+ guard !gogFetchInFlight else { return }+ gogFetchInFlight = true+ gogLoading = gogSignedIn && gogGames.isEmpty+ let signedIn = gogSignedIn+ let installedIDs = Set(gogInstalledByBottle.values.joined().map(\.id))+ Task.detached { [store = gogStore] in+ GOGComet(store: store).removeStaleTokens()+ var games = signedIn ? ((try? await store.ownedGames()) ?? []) : []+ // A GOG game in an environment that the account list does not name still gets its+ // title, cover and database match.+ let known = Set(games.map(\.id))+ for id in installedIDs.subtracting(known).sorted() {+ if let game = store.game(id) { games.append(game) }+ }+ let found = games+ await MainActor.run { [weak self] in+ guard let self else { return }+ self.gogFetchInFlight = false+ self.gogLoading = false+ if found != self.gogGames { self.gogGames = found; self.rebuildLibrary() }+ }+ }+ }++ /// The disk half of `gogRefresh`: goggame-<id>.info files under each environment's install+ /// folders. Runs on every install-record change, like Steam's.+ private func refreshGOGInstalls() {+ let found = Dictionary(bottles.map { ($0.name, GOGStore.installedGames(driveC: $0.driveC)) }, uniquingKeysWith: { a, _ in a })+ let store = gogStore+ for game in found.values.joined() { store.adoptManifest(for: game) }+ guard found != gogInstalledByBottle else { return }+ let newIDs = Set(found.values.joined().map(\.id)).subtracting(gogGames.map(\.id))+ gogInstalledByBottle = found+ forgetProgramExecutables()+ rebuildLibrary()+ if !newIDs.isEmpty, !gogFetchInFlight { gogRefresh() }+ }++ /// A program added by hand that its GOG tile now stands for (LibraryIndex.gogCoveredPins)+ /// hands its settings to that tile once: arguments the GOG task does not already pass, the+ /// display, the graphics mode. Only where the GOG tile has none of its own, and only once per+ /// pin, so the pin's tile can leave the library without the game playing differently.+ private func carryOverGOGCoveredPins() {+ // Read from disk, not `gogSettings`: a rebuild can come before gogRefresh has loaded it,+ // and saving the empty default would wipe the player's GOG choices.+ var settings = GOGSettings.load(gogStore)+ let covered = LibraryIndex.gogCoveredPins(bottles: bottles, gogInstalledByBottle: gogInstalledByBottle)+ .filter { !settings.carriedOverPins.contains($0.pinItemID) }+ guard !covered.isEmpty else { return }+ let store = libraryStore+ for pin in covered {+ if !pin.extraArguments.isEmpty, libraryLaunchArgs[pin.gogItemID] == nil {+ store.setLaunchArguments(pin.extraArguments, for: pin.gogItemID)+ }+ if let display = libraryDisplays[pin.pinItemID], libraryDisplays[pin.gogItemID] == nil {+ store.setDisplay(display, for: pin.gogItemID)+ }+ if let renderer = libraryOverrides[pin.pinItemID], libraryOverrides[pin.gogItemID] == nil {+ store.setRendererOverride(renderer, for: pin.gogItemID)+ }+ settings.carriedOverPins.insert(pin.pinItemID)+ appendLog("\(pin.pinItemID): shown as its GOG game (\(pin.gogItemID)) from now on; its settings went along")+ }+ settings.save(gogStore)+ gogSettings = settings+ libraryOverrides = store.rendererOverrides()+ libraryLaunchArgs = store.launchArguments()+ libraryDisplays = store.displayChoices()+ }++ /// The copy of a GOG game in an environment, read from disk.+ func gogInstalled(_ item: LibraryItem, in bottle: Bottle) -> GOGStore.InstalledGame? {+ guard let id = item.gogID else { return nil }+ return gogInstalledByBottle[bottle.name]?.first { $0.id == id }+ }++ /// Connects the account from the sign-in sheet, which stays open to show progress and says in+ /// place what went wrong. The first connect also downloads gogdl.+ func gogConnect(code: String) async throws {+ let store = gogStore+ do {+ try await store.ensureInstalled()+ } catch {+ appendLog("GOG: could not download gogdl: \(error.localizedDescription)")+ throw HighballError.failed(L("Highball could not download the small tool it uses to connect to GOG. Check your internet connection, then try again."))+ }+ try await Task.detached { try store.authenticate(code: code) }.value+ gogRefresh()+ }++ func gogSignOut() {+ gogStore.logout()+ gogGames = []+ gogRefresh()+ }++ /// The GOG download running now, for the strip's Stop and for quitting the app.+ @ObservationIgnored private var gogInstallControl: LegendaryControl?++ /// Downloads a GOG game into an environment with gogdl, then does what GOG's installer would+ /// have done (GOGStore.setupSteps).+ func gogInstall(_ item: LibraryItem, in bottle: Bottle) {+ guard let id = item.gogID else { return }+ runBusy(String(format: L("Installing %@"), item.title), expected: L("a large download; you can leave it running"),+ stop: .cancelTask(label: L("Stop")), cleanup: { [weak self] in self?.gogInstallControl = nil }) { [self] in+ let store = gogStore+ try await store.ensureInstalled()+ stage = L("Asking GOG about the download")+ let info = try await Task.detached { try store.info(id) }.value+ let language = GOGStore.language(for: info.languages)+ appendLog("\(item.title): GOG build \(info.buildID ?? "?"), language \(language), \(info.diskSize.map { ByteCountFormatter.string(fromByteCount: $0, countStyle: .file) } ?? "size unknown") on disk")+ if !info.dependencies.isEmpty {+ stage = L("Fetching the Windows runtimes the game needs")+ let status = try? await Task.detached { try store.downloadRedists(info.dependencies) { line in Task { @MainActor in self.appendLog(line) } } }.value+ if status != 0 { appendLog("\(item.title): the shared Windows runtimes did not all download; the game may ask for them") }+ }+ stage = String(format: L("Downloading %@"), item.title)+ try await gogDownload(title: item.title, command: "gogdl download", completed: { store.downloadCompleted(id) }) { control, onLine in+ try store.install(id, into: bottle, language: language, control: control, onLine: onLine)+ }+ busyProgress = nil; transferRate = nil+ refreshGOGInstalls()+ if let game = gogInstalledByBottle[bottle.name]?.first(where: { $0.id == id }) {+ store.keepManifest(for: game)+ try await gogRunSetup(game, title: item.title, in: bottle, language: language)+ }+ await MainActor.run { self.gogRefresh() }+ }+ }++ /// 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 }),+ let game = gogInstalled(item, in: bottle) else { return }+ runBusy(String(format: L("Updating %@"), item.title), expected: L("a large download; you can leave it running"),+ stop: .cancelTask(label: L("Stop")), cleanup: { [weak self] in self?.gogInstallControl = nil }) { [self] in+ let store = gogStore+ try await store.ensureInstalled()+ let info = try await Task.detached { try store.info(game.id) }.value+ let language = GOGStore.language(for: info.languages)+ try await gogDownload(title: item.title, command: "gogdl update", completed: { true }) { control, onLine in+ try store.update(game, language: language, control: control, onLine: onLine)+ }+ busyProgress = nil; transferRate = nil+ store.keepManifest(for: game)+ refreshGOGInstalls()+ if let fresh = gogInstalledByBottle[bottle.name]?.first(where: { $0.id == game.id }) {+ try await gogRunSetup(fresh, title: item.title, in: bottle, language: language)+ }+ }+ }++ /// One gogdl transfer (an install or an update) under the strip: progress and rate, Stop, and+ /// the stall watchdog. gogdl's downloads sometimes stall with the connection still open; a+ /// transfer with no progress for two minutes is stopped and resumed where it was, up to five+ /// times, so a stall never needs the player.+ private func gogDownload(title: String, command: String, completed: @escaping @Sendable () -> Bool,+ run: @escaping @Sendable (LegendaryControl, @escaping @Sendable (String) -> Void) throws -> Int32) async throws {+ for attempt in 1...5 {+ let control = LegendaryControl()+ gogInstallControl = control+ let failure = OSAllocatedUnfairLock<String?>(initialState: nil)+ // Signs of life: bytes written going up, or any line that is not a progress line (gogdl+ // checks files for a long time before a resume or an update). A progress line alone+ // proves nothing: gogdl keeps printing one each second through a stall.+ let lastProgress = OSAllocatedUnfairLock(initialState: (at: Date(), written: Int64(-1)))+ let stalled = OSAllocatedUnfairLock(initialState: false)+ let watchdog = Task.detached {+ while !Task.isCancelled {+ try? await Task.sleep(for: .seconds(15))+ if Date().timeIntervalSince(lastProgress.withLock { $0.at }) > 120 {+ stalled.withLock { $0 = true }+ control.stop()+ return+ }+ }+ }+ let status = try await withTaskCancellationHandler {+ try await Task.detached {+ try run(control) { line in+ if let why = GOGStore.installFailure(line) { failure.withLock { if $0 == nil { $0 = why } } }+ let progress = GOGStore.progress(inGogdlLine: line)+ lastProgress.withLock { last in+ if let p = progress {+ if p.written > last.written { last = (Date(), p.written) }+ } else if !line.contains("[PROGRESS]") {+ last.at = Date()+ }+ }+ Task { @MainActor in+ if progress == nil, !line.contains("[PROGRESS]") { self.appendLog(line) }+ if let p = progress, self.busy { self.recordTransfer(received: p.written, total: p.total > 0 ? p.total : nil) }+ }+ }+ }.value+ } onCancel: { control.stop() }+ watchdog.cancel()+ try Task.checkCancellation()+ if stalled.withLock({ $0 }), attempt < 5 {+ appendLog("\(title): the download stalled for two minutes, resuming it (attempt \(attempt + 1) of 5)")+ try await Task.sleep(for: .seconds(12)) // the stopped gogdl lets go of its files+ continue+ }+ if let why = failure.withLock({ $0 }) { throw HighballError.failed(why) }+ guard status == 0, completed() else {+ throw HighballError.processFailed(command: command, status: status == 0 ? 1 : status,+ output: "the download did not finish; press the button again to resume it")+ }+ return+ }+ }++ /// Quitting the app stops a GOG download the way Stop does; gogdl resumes it next time.+ func stopGOGInstall() { gogInstallControl?.stop() }++ /// Runs what GOG's installer would have: the Windows runtimes the game lists, then its install+ /// scripts. A step that fails is logged and the next one runs; nothing here stops the game+ /// from being played, which is how Galaxy behaves when a runtime is already newer.+ private func gogRunSetup(_ game: GOGStore.InstalledGame, title: String, in bottle: Bottle, language: String) async throws {+ guard let engine = engine(for: bottle) else { return }+ var ran = 0+ try await gogStore.runSetup(game, language: language, runner: WineRunner(paths: paths, engine: engine, bottle: bottle),+ onStep: { n, total, label in+ ran = total+ self.stage = String(format: L("Setting up %@: %@ (%d of %d)"), title, label, n, total)+ },+ onLine: { line in Task { @MainActor in self.appendLog(line) } },+ onFailure: { label, code in+ self.appendLog("\(title): \(label) ended with code \(code); carrying on (a newer copy is often already there)")+ })+ if ran > 0 { appendLog("\(title): GOG setup done (\(ran) step\(ran == 1 ? "" : "s"))") }+ }++ /// Plays a GOG game: its setup if this build has not had it here, saves down from GOG's cloud,+ /// comet beside it for achievements, then the game's own launch task. Saves go back up and+ /// comet stops when the session ends.+ ///+ /// comet never costs a launch: one that cannot start is skipped, and a game that crashes at+ /// once with comet running starts again straight away without it. When that second start+ /// works, the game is remembered as one that runs without comet (its page says so and can+ /// turn it back on); when it crashes too, comet was not the cause and nothing is remembered.+ func gogPlay(_ item: LibraryItem, in bottle: Bottle, renderer: Renderer? = nil, retryingWithoutComet: Bool = false) {+ guard let engine = engine(for: bottle), let game = gogInstalled(item, in: bottle) else {+ fail(HighballError.failed("\(item.title) is not installed in \(bottle.name)."))+ return+ }+ if runningSessions.contains(where: { $0.libraryID == item.id && $0.bottleName == bottle.name }) {+ fail(HighballError.failed("\(item.title) is already running."))+ return+ }+ guard let task = game.launchTask(choice: gogSettings.launchChoice[game.id]), let launch = GOGStore.launch(task, in: game) else {+ fail(HighballError.failed("\(item.title)'s GOG files name no program to run. Show the game's folder and add its .exe as a program instead."))+ return+ }+ let store = gogStore+ let settings = gogSettings+ let extraArguments = launchArguments(for: item) // the page's Launch arguments, after the task's own+ let useComet = !retryingWithoutComet && gogSignedIn && settings.cometOff[game.id] == nil+ let useSaves = gogSignedIn && !settings.cloudSavesOff.contains(game.id)+ runBusy(String(format: L("Starting %@"), item.title), done: .handedOff, stop: .killBottle(bottle, label: L("Stop"))) { [self] in+ await removeMacMetadataFiles(from: game.folder, of: item.title)+ if store.hasManifest(game), !GOGStore.setupDone(for: game, driveC: bottle.driveC) {+ let info = try? await Task.detached { try store.info(game.id) }.value+ try await gogRunSetup(game, title: item.title, in: bottle, language: GOGStore.language(for: info?.languages ?? []))+ }+ let saveFolders = useSaves ? await gogSaveLocations(game, in: bottle) : []+ for (location, folder) in saveFolders {+ stage = L("Bringing your saves down from GOG")+ try await gogSync(game, title: item.title, location: location, folder: folder, direction: .download, beforePlay: true)+ }+ // Stop during the steps before the game (setup, saves) ends the launch there: the+ // strip already reads "Stopped", so nothing may start after it.+ try Task.checkCancellation()++ var comet: Process?+ let cometLog = paths.logs.appending(path: "\(ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: ""))-comet-\(game.id).log")+ if useComet {+ stage = L("Starting comet for achievements")+ comet = await gogStartComet(for: game, in: bottle, engine: engine, log: cometLog)+ }+ if Task.isCancelled {+ GOGComet(store: store).stop(comet)+ throw CancellationError()+ }++ let runner = WineRunner(paths: paths, engine: engine, bottle: bottle)+ let box = LaunchOutcome()+ let log = logLine(box)+ let row = gameDB.entry(for: item)+ let gameEnvironment = bottle.settings.environment(forGame: row?.id)+ watchedLaunch(box) {+ try await runner.start(launch.executable, arguments: launch.arguments + extraArguments, renderer: renderer,+ extraEnvironment: gameEnvironment, workingDirectory: launch.workingDirectory, onOutput: log)+ }+ // Every program in the game's folder: a launcher task hands over to another .exe and exits.+ let markers = await Task.detached { game.sessionMarkers(launching: launch.executable) }.value+ var crashedWithComet = false+ let handedOff: Bool+ do {+ handedOff = try await awaitHandoff(box, program: item.title, timeout: 360) {+ let processes = await Self.processList()+ box.processList = processes+ // This environment's processes only: a same-named program elsewhere is not this game.+ let prefix = bottle.url+ return await Task.detached { !SessionWatch.pids(ofPrefix: prefix, markers: markers).isEmpty }.value+ } crashed: { result in+ if comet != nil {+ crashedWithComet = true+ return+ }+ let current = renderer ?? bottle.settings.renderer+ self.crashSuggestion = CrashSuggestion(program: item.title, bottleName: bottle.name,+ renderer: Renderer.suggestion(after: current, d3dmetalAvailable: engine.rendererDir("d3dmetal") != nil, vkd3dAvailable: engine.rendererDir("vkd3d") != nil),+ logPath: result.log.path, current: current, seconds: Int(result.duration),+ alternateEngine: self.alternateEngine(for: bottle))+ }+ } catch {+ // Never started, failed to start, or Stop: comet must not outlive the launch+ // (it would hold port 9977 and its copy of the tokens).+ GOGComet(store: store).stop(comet)+ throw error+ }+ guard handedOff else {+ GOGComet(store: store).stop(comet)+ if crashedWithComet {+ appendLog("\(item.title) closed right away with comet running; starting it again without comet")+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in+ guard let self, let fresh = self.bottles.first(where: { $0.name == bottle.name }) else { return }+ self.gogPlay(item, in: fresh, renderer: renderer, retryingWithoutComet: true)+ }+ }+ return+ }+ if retryingWithoutComet, gogSettings.cometOff[game.id] == nil, gogSignedIn {+ gogSettings.cometOff[game.id] = GOGSettings.crashedWithComet+ gogSettings.save(store)+ appendLog("\(item.title) runs without comet from now on (it closed at once with it); its page can turn comet back on")+ }+ if comet != nil, !GOGComet.isListening(log: cometLog) {+ appendLog("\(item.title): comet did not come up (its log is \(cometLog.lastPathComponent)); the game runs without achievements this time")+ }+ let session = GameSession(title: item.title, bottleName: bottle.name, appid: nil, markers: markers,+ renderer: (renderer ?? bottle.settings.renderer).rawValue, libraryID: item.id,+ startNotice: row?.startNotice, startNoticeMinutes: row?.startNoticeMinutes)+ sessionEndActions[session.id] = { [weak self] _ in+ GOGComet(store: store).stop(comet)+ guard let self, !saveFolders.isEmpty else { return }+ Task { @MainActor in+ for (location, folder) in saveFolders {+ try? await self.gogSync(game, title: item.title, location: location, folder: folder, direction: .upload, beforePlay: false)+ }+ }+ }+ beginSession(session, processList: box.processList)+ }+ }++ /// comet up and listening, or nil: never an error. The placeholder service it needs is set up+ /// once per environment.+ private func gogStartComet(for game: GOGStore.InstalledGame, in bottle: Bottle, engine: InstalledEngine, log: URL) async -> Process? {+ let store = gogStore+ let comet = GOGComet(store: store)+ do {+ let tools = try await store.ensureComet()+ if try await GOGComet.installService(from: tools.service, runner: WineRunner(paths: paths, engine: engine, bottle: bottle)) {+ appendLog("\(bottle.name): registered the GalaxyCommunication placeholder comet uses")+ }+ // Only GOG sessions leave an end action, so none means no game of ours uses a comet.+ let noOtherGame = sessionEndActions.isEmpty+ let process = try await Task.detached {+ if noOtherGame { comet.stopStrays() }+ return try comet.start(log: log)+ }.value+ for _ in 0..<20 where !GOGComet.isListening(log: log) && process.isRunning {+ try? await Task.sleep(for: .milliseconds(250))+ }+ guard process.isRunning else {+ appendLog("\(game.title): comet exited at start (log \(log.lastPathComponent)); playing without achievements")+ comet.stop(nil)+ return nil+ }+ appendLog("\(game.title): comet is running for achievements and stats")+ return process+ } catch {+ appendLog("\(game.title): comet could not start (\(error.localizedDescription)); playing without achievements")+ comet.stop(nil)+ return nil+ }+ }++ /// 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)+ // Both can reach GOG (an offline install's client id comes from its build manifest).+ let locations = await Task.detached { () -> [GOGSaves.Location]? in+ guard let client = saves.clientID(for: game) else { return nil }+ return (try? saves.locations(clientID: client)) ?? nil+ }.value+ return (locations ?? []).compactMap { location in+ guard let folder = GOGSaves.resolve(location.template, game: game, driveC: bottle.driveC) else {+ appendLog("\(game.title): cloud saves at \(location.template) have no folder here, skipping that one")+ return nil+ }+ return (location, folder)+ }+ }++ /// Answers the open save question once: the alert's buttons and its dismissal both land here,+ /// and only the first answer reaches the waiting sync.+ func resolveGOGSaveConflict(_ choice: GOGSaveConflict.Choice) {+ guard let conflict = gogSaveConflict else { return }+ gogSaveConflict = nil+ conflict.resolve(choice)+ }++ /// One sync, asking the player on a conflict. Before Play the launch waits for the answer;+ /// after the game it is asked whenever the player is back.+ private func gogSync(_ game: GOGStore.InstalledGame, title: String, location: GOGSaves.Location, folder: URL,+ direction: GOGSaves.Direction, beforePlay: Bool) async throws {+ let saves = GOGSaves(store: gogStore)+ let outcome = await Task.detached { saves.sync(game, location: location, folder: folder, direction: direction) { line in+ Task { @MainActor in self.appendLog(line) }+ } }.value+ switch outcome {+ case .synced:+ return+ case let .failed(why):+ appendLog("\(title): cloud saves did not sync (\(why)); \(beforePlay ? "playing with the saves on this Mac" : "they stay on this Mac until the next sync")")+ case .conflict:+ let choice: GOGSaveConflict.Choice = await withCheckedContinuation { continuation in+ // One question at a time: an earlier one still open (another game's) is answered+ // "decide later", which leaves both copies alone, so its launch never waits forever.+ if let pending = gogSaveConflict {+ appendLog("\(pending.title): cloud saves left as they are this time (\(title) needed the question)")+ resolveGOGSaveConflict(.skip)+ }+ gogSaveConflict = GOGSaveConflict(title: title, beforePlay: beforePlay) { continuation.resume(returning: $0) }+ }+ let forced: GOGSaves.Direction+ switch choice {+ case .useCloud: forced = .forceDownload+ case .keepMac: forced = .forceUpload+ case .skip:+ appendLog("\(title): cloud saves left as they are this time")+ return+ }+ let again = await Task.detached { saves.sync(game, location: location, folder: folder, direction: forced) }.value+ appendLog("\(title): cloud saves \(again == .synced ? (choice == .useCloud ? "replaced with GOG's copy" : "uploaded from this Mac") : "did not sync")")+ }+ }++ func gogSetComet(_ on: Bool, for id: String) {+ if on { gogSettings.cometOff[id] = nil } else { gogSettings.cometOff[id] = GOGSettings.turnedOff }+ gogSettings.save(gogStore)+ }++ func gogSetCloudSaves(_ on: Bool, for id: String) {+ if on { gogSettings.cloudSavesOff.remove(id) } else { gogSettings.cloudSavesOff.insert(id) }+ gogSettings.save(gogStore)+ }++ func gogSetLaunchChoice(_ index: Int?, for id: String) {+ gogSettings.launchChoice[id] = index+ gogSettings.save(gogStore)+ forgetProgramExecutables()+ }++ /// Removes a GOG game from an environment: its own uninstaller first when an offline installer+ /// left one (it cleans the registry), then the folder, then what gogdl kept about it.+ private func gogUninstall(id: String, title: String, in bottle: Bottle) {+ guard let game = gogInstalledByBottle[bottle.name]?.first(where: { $0.id == id }) else { return }+ let store = gogStore+ runBusy(String(format: L("Removing %@"), title),+ done: DoneState(title: String(format: L("%@ removed"), title), ctaTitle: nil, cta: nil),+ stop: .killBottle(bottle, label: L("Stop"))) { [self] in+ let uninstaller = game.folder.appending(path: "unins000.exe")+ if FileManager.default.fileExists(atPath: uninstaller.path), let engine = engine(for: bottle) {+ stage = L("Running the game's own uninstaller")+ appendLog("\(title): running its own uninstaller")+ let runner = WineRunner(paths: paths, engine: engine, bottle: bottle)+ _ = try? await runner.run([uninstaller.path, "/VERYSILENT", "/ProductId=\(id)", "/galaxyclient", "/KEEPSAVES"],+ renderer: .wined3d, label: "gog-uninstall-\(id)")+ }+ if FileManager.default.fileExists(atPath: game.folder.path) {+ // One call with no progress of its own, and a big game is tens of thousands of files.+ stage = L("Deleting the game's files")+ try await Task.detached { try FileManager.default.removeItem(at: game.folder) }.value+ }+ let elsewhere = gogInstalledByBottle.contains { $0.key != bottle.name && $0.value.contains { $0.id == id } }+ store.forget(id, otherInstallsRemain: elsewhere)+ GOGSaves(store: store).forget(game)+ try? FileManager.default.removeItem(at: GOGStore.setupMarker(for: game, driveC: bottle.driveC))+ appendLog("\(title): removed from \(bottle.name)")+ refreshInstalledGames() // the tile leaves now, not at the next folder watch+ }+ }+func setDpi(_ scale: Int, retinaAt100: Bool? = nil, in bottle: Bottle) {guard let engine = engine(for: bottle) else { return }var copy = bottle@@ -3196,6 +3776,9 @@ final class AppState {for bottle in bottles { killBottle(bottle) }}+ /// Quitting with Stop Everything: comet is a Mac process, outside the environments.+ func stopGOGComets() { GOGComet(store: gogStore).stopStrays() }+func loadGPTKLicense() {for candidate in [Self.repoRoot?.appending(path: "spike/d3dmetal-license.txt"),Bundle.main.url(forResource: "d3dmetal-license", withExtension: "txt")].compactMap({ $0 }) {diff --git a/Sources/HighballApp/BottleView.swift b/Sources/HighballApp/BottleView.swiftindex ab2832b..2205d76 100644--- a/Sources/HighballApp/BottleView.swift+++ b/Sources/HighballApp/BottleView.swift@@ -123,7 +123,9 @@ struct BottleView: View {VStack(alignment: .leading, spacing: 12) {HB.eyebrow(L("Launchers"))LazyVGrid(columns: [GridItem(.adaptive(minimum: 108, maximum: 140), spacing: 12)], spacing: 12) {- ForEach(Self.launcherMeta, id: \.id) { meta in+ // GOG Galaxy's blocked client gives way to Connect GOG, as in Add games, unless+ // this environment already has it.+ ForEach(Self.launcherMeta.filter { $0.id != "gog-galaxy" || bottle.settings.recipes.contains($0.id) }, id: \.id) { meta inif let recipe = AppState.recipe(meta.id) {let installed = bottle.settings.recipes.contains(meta.id)let pin = bottle.settings.pins.first { $0.name.lowercased().hasPrefix(meta.short.lowercased().prefix(5)) }@@ -763,6 +765,125 @@ struct EpicSignInSheet: View {}+/// GOG sign-in, written for someone who has never copied a link: GOG's own page in the browser,+/// which ends on an almost empty embed.gog.com page whose link carries a one-time code. Each step+/// says what to click and what the player will see. Pasting the link connects at once; the sheet+/// stays open while it does, and says what went wrong in place, so a bad paste or an expired+/// link is fixed without hunting for the button again.+struct GOGSignInSheet: View {+ @Environment(AppState.self) private var state+ @Environment(\.dismiss) private var dismiss+ @State private var pasted = ""+ @State private var connecting = false+ @State private var problem: String?++ var body: some View {+ let reading = GOGStore.readSignIn(pasted)+ VStack(alignment: .leading, spacing: 16) {+ VStack(alignment: .leading, spacing: 4) {+ Text(state.gogSignedIn ? L("Your GOG account") : L("Connect your GOG account")).font(.title2.bold())+ Text(state.gogSignedIn+ ? L("To use a different GOG account, follow the steps again and sign in with it. You sign in on GOG's own website, so Highball never sees your password.")+ : L("It takes about a minute. You sign in on GOG's own website, so Highball never sees your password."))+ .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }+ if state.gogSignedIn {+ Label(state.gogAccountName.map { String(format: L("Connected as %@"), $0) } ?? L("GOG account connected"),+ systemImage: "checkmark.circle.fill").foregroundStyle(HB.good)+ }+ step(1, L("Sign in to GOG in your browser.")) {+ Button(L("Open GOG sign-in")) { NSWorkspace.shared.open(GOGStore.loginURL) }+ }+ step(2, L("After you sign in, GOG shows an almost empty page. That is normal: it means it worked."))+ step(3, L("Copy that page's link: click the address bar at the top of your browser, then press ⌘C."))+ step(4, L("Come back here and paste it.")) {+ HStack(spacing: 8) {+ PasteButton(payloadType: String.self) { strings in+ Task { @MainActor in+ pasted = strings.first ?? ""+ if GOGStore.authorizationCode(from: pasted) != nil { connect() }+ }+ }+ TextField(L("or paste the link here"), text: $pasted).textFieldStyle(.roundedBorder).frame(width: 240)+ .onSubmit { if case .code = reading { connect() } }+ }+ .disabled(connecting)+ }+ Group {+ if connecting {+ HStack(spacing: 8) {+ ProgressView().controlSize(.small)+ Text(L("Connecting to GOG…"))+ }+ } else if let problem {+ Label(problem, systemImage: "exclamationmark.triangle.fill").foregroundStyle(HB.amber)+ } else if let hint = Self.hint(for: reading) {+ Label(hint.text, systemImage: hint.ok ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")+ .foregroundStyle(hint.ok ? HB.good : HB.amber)+ }+ }+ .font(.callout).frame(maxWidth: 420, alignment: .leading).fixedSize(horizontal: false, vertical: true)+ Text(L("Highball connects through gogdl, the open source tool the Heroic launcher uses. You can disconnect at any time."))+ .font(.caption).foregroundStyle(.secondary).frame(maxWidth: 420, alignment: .leading)+ .fixedSize(horizontal: false, vertical: true)+ HStack {+ if state.gogSignedIn {+ Button(L("Disconnect GOG"), role: .destructive) { dismiss(); state.gogSignOut() }+ }+ Spacer()+ Button(L("Cancel")) { dismiss() }.keyboardShortcut(.cancelAction)+ Button(L("Connect")) { connect() }+ .keyboardShortcut(.defaultAction)+ .disabled(connecting || GOGStore.authorizationCode(from: pasted) == nil)+ }+ }+ .padding(24)+ .frame(width: 480)+ // A new paste replaces the last problem; the field emptied after a failure keeps it shown.+ .onChange(of: pasted) { _, new in if !new.isEmpty { problem = nil } }+ }++ /// One numbered instruction, with the control it needs (if any) under its text.+ private func step(_ number: Int, _ text: String, @ViewBuilder control: () -> some View = { EmptyView() }) -> some View {+ HStack(alignment: .firstTextBaseline, spacing: 10) {+ Text("\(number)").font(.callout.weight(.semibold).monospacedDigit())+ .frame(width: 20, height: 20).background(Circle().fill(.quaternary))+ VStack(alignment: .leading, spacing: 8) {+ Text(text).fixedSize(horizontal: false, vertical: true)+ control()+ }+ }+ }++ private func connect() {+ guard !connecting, let code = GOGStore.authorizationCode(from: pasted) else { return }+ connecting = true+ problem = nil+ Task {+ do {+ try await state.gogConnect(code: code)+ dismiss()+ } catch {+ connecting = false+ problem = L(AppState.message(for: error)) // the kit's sign-in messages have French entries+ pasted = ""+ }+ }+ }++ /// What the sheet says about the pasted text; nothing while it is empty.+ static func hint(for reading: GOGStore.PastedSignIn) -> (text: String, ok: Bool)? {+ switch reading {+ case .empty: nil+ case .code: (L("That is the right link. Click Connect."), true)+ case .signInPage: (L("That is the link of the sign-in page. Sign in on that page first, then copy the link of the almost empty page you land on."), false)+ case .noCode: (L("That is a GOG page, but not the right one. Copy the link of the almost empty page GOG shows right after you sign in."), false)+ case .notGOG: (L("That does not look like a link from GOG. Copy the link of the almost empty page GOG shows after you sign in."), false)+ }+ }+}++/// Per-program settings: launch arguments, environment, renderer override in one place.struct PinSettingsSheet: View {@Environment(AppState.self) private var statediff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swiftindex 73d5bd6..e155163 100644--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@ -133,9 +133,66 @@ struct GameDetailView: View {}}+ /// A GOG game's own settings, one row each like the rest of the page: comet (achievements and+ /// stats), cloud saves, which launch task Play runs, and an update for a game gogdl installed.+ @ViewBuilder private func gogSettings(_ game: GOGStore.InstalledGame) -> some View {+ let cometOff = state.gogSettings.cometOff[game.id]+ HStack(alignment: .top, spacing: 12) {+ Text(L("Achievements")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 2)+ VStack(alignment: .leading, spacing: 4) {+ Toggle(L("Achievements and stats (comet)"), isOn: Binding(+ get: { cometOff == nil }, set: { state.gogSetComet($0, for: game.id) }))+ .toggleStyle(.checkbox).disabled(!state.gogSignedIn)+ Text(cometOff == GOGSettings.crashedWithComet+ ? L("Turned off after the game closed at once with comet running and then started fine without it. Turn it back on to try again.")+ : L("comet stands in for GOG Galaxy while the game runs, so achievements, stats and play time reach your GOG account. If the game won't start with it, Highball starts it again without."))+ .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }+ }+ HStack(alignment: .top, spacing: 12) {+ Text(L("Cloud saves")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 2)+ VStack(alignment: .leading, spacing: 4) {+ Toggle(L("Sync saves with GOG"), isOn: Binding(+ get: { !state.gogSettings.cloudSavesOff.contains(game.id) }, set: { state.gogSetCloudSaves($0, for: game.id) }))+ .toggleStyle(.checkbox).disabled(!state.gogSignedIn)+ Text(L("Saves come down from GOG's cloud before Play and go back up when the game ends. If both copies changed, Highball asks which one wins."))+ .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ if !state.gogSignedIn {+ Button(L("Connect GOG")) { state.showGOGSignIn = true }.controlSize(.small)+ }+ }+ }+ if !game.launchChoices.isEmpty {+ HStack(alignment: .top, spacing: 12) {+ Text(L("Launch option")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 4)+ Picker("", selection: Binding(+ get: { state.gogSettings.launchChoice[game.id] ?? -1 },+ set: { state.gogSetLaunchChoice($0 < 0 ? nil : $0, for: game.id) })) {+ Text(L("GOG's default")).tag(-1)+ ForEach(Array(game.launchChoices.enumerated()), id: \.offset) { index, task in+ Text(verbatim: task.name ?? task.path ?? "").tag(index)+ }+ }.labelsHidden().frame(maxWidth: 360)+ }+ }+ if state.gogStore.hasManifest(game) {+ HStack(alignment: .top, spacing: 12) {+ Text(L("Version")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 2)+ VStack(alignment: .leading, spacing: 4) {+ HStack(spacing: 8) {+ Text(verbatim: game.buildID.map { String(format: L("GOG build %@"), $0) } ?? "GOG").font(.callout)+ Button(L("Update from GOG")) { state.gogUpdate(item) }.controlSize(.small).disabled(state.busy)+ }+ Text(L("Downloads only what changed since this build. Nothing happens when it is already the newest."))+ .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }+ }+ }+ }+private var libraryInfo: some View {VStack(alignment: .leading, spacing: 12) {- row(L("Source"), item.source == .steam ? "Steam" : item.source == .epic ? "Epic Games" : L("Windows program"))+ row(L("Source"), item.source == .steam ? "Steam" : item.source == .epic ? "Epic Games" : item.source == .gog ? "GOG" : L("Windows program"))if item.sizeOnDisk > 0 {row(L("Size on disk"), ByteCountFormatter.string(fromByteCount: item.sizeOnDisk, countStyle: .file))}@@ -323,7 +380,7 @@ struct GameDetailView: View {: L("Its anti-cheat does not run on macOS.")).font(.callout).foregroundStyle(.secondary)}- } else if item.source == .epic {+ } else if item.source == .epic || item.source == .gog {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)@@ -493,7 +550,7 @@ struct GameDetailView: View {.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)}}- if item.source == .steam {+ if item.source == .steam || item.source == .gog {HStack(alignment: .top, spacing: 12) {Text(L("Launch arguments")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 4)VStack(alignment: .leading, spacing: 4) {@@ -510,6 +567,9 @@ struct GameDetailView: View {}.onDisappear { state.setLaunchArguments(argsText, for: item) }}+ if item.source == .gog, let game = state.gogInstalled(item, in: bottle) {+ gogSettings(game)+ }// The engine is the environment's, so the page says so and can change it// through the same switch page as the environment's settings, which lists// every program that moves along (highball#262: an engine shown here that@@ -576,7 +636,9 @@ struct GameDetailView: View {Button(L("Show the Windows drive")) { NSWorkspace.shared.open(bottle.driveC) }.controlSize(.small)if item.installed {Button(L("Uninstall…"), role: .destructive) { state.askUninstall(item) }.controlSize(.small)- .help(L("Steam and the Epic tools do their own uninstalling, so their libraries stay right."))+ .disabled(state.uninstallWaitsFor(item) != nil)+ .help(state.uninstallWaitsFor(item).map { String(format: L("Available once “%@” has finished."), $0) }+ ?? L("Steam and the Epic tools do their own uninstalling, so their libraries stay right."))}if MacAppStub.existing(for: item.title) != nil {Button(L("Remove the Mac app")) { state.removeMacApp(title: item.title) }.controlSize(.small)diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex a7256a5..025cb79 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -134,6 +134,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {switch alert.runModal() {case .alertFirstButtonReturn:state.killAllBottles()+ state.stopGOGComets()return .terminateNowcase .alertSecondButtonReturn:return .terminateNow@@ -144,6 +145,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {func applicationWillTerminate(_ notification: Notification) {appState?.stopEpicInstall()+ appState?.stopGOGInstall()DiscordPresence.shared.setEnabled(false)DiscordPresence.shared.stop()}@@ -238,6 +240,8 @@ struct ContentView: View {.modesetTrialAsk(state).homeMoveAsk(state).sheet(isPresented: $state.showEpicSignIn) { EpicSignInSheet() }+ .sheet(isPresented: $state.showGOGSignIn) { GOGSignInSheet() }+ .gogSaveConflictAsk(state).sheet(item: $state.engineTransition) { t in EngineTransitionSheet(transition: t) }#if DEBUG// Screenshot runs only: HB_SHOW_ENGINE_SWITCH="<environment>><engine id>" opens the switch@@ -506,6 +510,22 @@ private extension View {}}+ /// Both this Mac's saves and GOG's changed since the last sync (GOGSaves): nothing moved, and+ /// the player picks the copy that wins. Before Play the launch waits for this answer.+ @MainActor func gogSaveConflictAsk(_ state: AppState) -> some View {+ self.alert(state.gogSaveConflict.map { String(format: L("Which %@ saves should win?"), $0.title) } ?? "",+ isPresented: .init(get: { state.gogSaveConflict != nil }, set: { if !$0 { state.resolveGOGSaveConflict(.skip) } }),+ presenting: state.gogSaveConflict) { _ in+ Button(L("Use GOG's cloud saves")) { state.resolveGOGSaveConflict(.useCloud) }+ Button(L("Keep this Mac's saves")) { state.resolveGOGSaveConflict(.keepMac) }+ Button(L("Decide later"), role: .cancel) { state.resolveGOGSaveConflict(.skip) }+ } message: { conflict in+ Text(conflict.beforePlay+ ? L("The saves on this Mac and the ones in GOG's cloud have both changed since they were last in step, so neither was copied. The copy you don't pick is replaced. Decide later plays with this Mac's saves and leaves the cloud alone.")+ : L("The saves on this Mac and the ones in GOG's cloud have both changed since they were last in step, so neither was copied. The copy you don't pick is replaced. Decide later leaves both as they are until the next time you play."))+ }+ }+@MainActor func rendererTrialAsk(_ state: AppState) -> some View {self.alert(state.rendererTrial.map { String(format: L("Try %@ for %@ next time?"), GamePageCopy.plainName($0.next), $0.title) } ?? "",isPresented: .init(get: { state.rendererTrial != nil }, set: { if !$0 { state.rendererTrial = nil } }),diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex 355f4be..5231991 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -152,6 +152,82 @@ enum L10n {"Connect": "Connecter","Connecting your Epic account": "Connexion de votre compte Epic","Loading your Epic library…": "Chargement de votre bibliothèque Epic…",+ "Connect your GOG account to see and download your games.": "Connectez votre compte GOG pour voir et télécharger vos jeux.",+ "Connect GOG account…": "Connecter un compte GOG…",+ "GOG account connected": "Compte GOG connecté",+ "Connect GOG": "Connecter GOG",+ "Connect your GOG account. Your games install straight into Highball.": "Connectez votre compte GOG. Vos jeux s'installent directement dans Highball.",+ "Connect your GOG account": "Connecter votre compte GOG",+ "It takes about a minute. You sign in on GOG's own website, so Highball never sees your password.":+ "Cela prend environ une minute. Vous vous connectez sur le site de GOG, Highball ne voit donc jamais votre mot de passe.",+ "Connected as %@": "Connecté en tant que %@",+ "Manage…": "Gérer…",+ "Your GOG account": "Votre compte GOG",+ "To use a different GOG account, follow the steps again and sign in with it. You sign in on GOG's own website, so Highball never sees your password.":+ "Pour utiliser un autre compte GOG, refaites les étapes et connectez-vous avec. Vous vous connectez sur le site de GOG, Highball ne voit donc jamais votre mot de passe.",+ "Sign in to GOG in your browser.": "Connectez-vous à GOG dans votre navigateur.",+ "Open GOG sign-in": "Ouvrir la connexion GOG",+ "After you sign in, GOG shows an almost empty page. That is normal: it means it worked.":+ "Une fois connecté, GOG affiche une page presque vide. C'est normal : cela veut dire que ça a marché.",+ "Copy that page's link: click the address bar at the top of your browser, then press ⌘C.":+ "Copiez le lien de cette page : cliquez sur la barre d'adresse en haut du navigateur, puis appuyez sur ⌘C.",+ "Come back here and paste it.": "Revenez ici et collez-le.",+ "or paste the link here": "ou collez le lien ici",+ "Connecting to GOG…": "Connexion à GOG…",+ "Highball connects through gogdl, the open source tool the Heroic launcher uses. You can disconnect at any time.":+ "Highball se connecte avec gogdl, l'outil libre qu'utilise Heroic. Vous pouvez vous déconnecter à tout moment.",+ "That is the right link. Click Connect.": "C'est le bon lien. Cliquez sur Connecter.",+ "That is the link of the sign-in page. Sign in on that page first, then copy the link of the almost empty page you land on.":+ "C'est le lien de la page de connexion. Connectez-vous d'abord sur cette page, puis copiez le lien de la page presque vide qui s'affiche.",+ "That is a GOG page, but not the right one. Copy the link of the almost empty page GOG shows right after you sign in.":+ "C'est une page GOG, mais pas la bonne. Copiez le lien de la page presque vide que GOG affiche juste après la connexion.",+ "That does not look like a link from GOG. Copy the link of the almost empty page GOG shows after you sign in.":+ "Ce lien ne semble pas venir de GOG. Copiez le lien de la page presque vide que GOG affiche après la connexion.",+ "Highball could not download the small tool it uses to connect to GOG. Check your internet connection, then try again.":+ "Highball n'a pas pu télécharger le petit outil qui lui sert à se connecter à GOG. Vérifiez votre connexion Internet, puis réessayez.",+ "Disconnect GOG": "Déconnecter GOG",+ "Highball is still busy with “%@”. Remove %@ once that has finished, or stop it in the bar at the bottom.":+ "Highball est encore occupé par « %@ ». Supprimez %@ une fois cette opération terminée, ou arrêtez-la dans la barre en bas.",+ "Available once “%@” has finished.": "Disponible une fois « %@ » terminé.",+ "Running the game's own uninstaller": "Exécution du désinstalleur du jeu",+ "Deleting the game's files": "Suppression des fichiers du jeu",+ "Highball could not finish connecting to GOG. Check your internet connection, then try again.":+ "Highball n'a pas pu terminer la connexion à GOG. Vérifiez votre connexion Internet, puis réessayez.",+ "That link has expired or was already used. Click Open GOG sign-in again: GOG gives you a fresh link straight away, often without asking for your password.":+ "Ce lien a expiré ou a déjà servi. Cliquez à nouveau sur Ouvrir la connexion GOG : GOG vous donne aussitôt un nouveau lien, souvent sans redemander votre mot de passe.",+ "Achievements": "Succès",+ "Cloud saves": "Sauvegardes dans le cloud",+ "Sync saves with GOG": "Synchroniser les sauvegardes avec GOG",+ "Achievements and stats (comet)": "Succès et statistiques (comet)",+ "comet stands in for GOG Galaxy while the game runs, so achievements, stats and play time reach your GOG account. If the game won't start with it, Highball starts it again without.":+ "comet remplace GOG Galaxy pendant que le jeu tourne, pour que les succès, les statistiques et le temps de jeu arrivent sur votre compte GOG. Si le jeu ne démarre pas avec, Highball le relance sans.",+ "Turned off after the game closed at once with comet running and then started fine without it. Turn it back on to try again.":+ "Désactivé : le jeu s'est fermé aussitôt avec comet, puis a bien démarré sans. Réactivez-le pour réessayer.",+ "Saves come down from GOG's cloud before Play and go back up when the game ends. If both copies changed, Highball asks which one wins.":+ "Les sauvegardes sont récupérées du cloud GOG avant de jouer et y retournent à la fin de la partie. Si les deux copies ont changé, Highball vous demande laquelle garder.",+ "Launch option": "Option de lancement",+ "GOG's default": "Choix par défaut de GOG",+ "Version": "Version",+ "GOG build %@": "Build GOG %@",+ "Update from GOG": "Mettre à jour depuis GOG",+ "Downloads only what changed since this build. Nothing happens when it is already the newest.":+ "Ne télécharge que ce qui a changé depuis ce build. Rien ne se passe s'il est déjà le plus récent.",+ "Which %@ saves should win?": "Quelles sauvegardes de %@ garder ?",+ "Use GOG's cloud saves": "Utiliser les sauvegardes du cloud GOG",+ "Keep this Mac's saves": "Garder les sauvegardes de ce Mac",+ "Decide later": "Décider plus tard",+ "The saves on this Mac and the ones in GOG's cloud have both changed since they were last in step, so neither was copied. The copy you don't pick is replaced. Decide later plays with this Mac's saves and leaves the cloud alone.":+ "Les sauvegardes de ce Mac et celles du cloud GOG ont toutes deux changé depuis leur dernière synchronisation, donc aucune n'a été copiée. La copie que vous ne choisissez pas est remplacée. Décider plus tard lance le jeu avec les sauvegardes de ce Mac sans toucher au cloud.",+ "The saves on this Mac and the ones in GOG's cloud have both changed since they were last in step, so neither was copied. The copy you don't pick is replaced. Decide later leaves both as they are until the next time you play.":+ "Les sauvegardes de ce Mac et celles du cloud GOG ont toutes deux changé depuis leur dernière synchronisation, donc aucune n'a été copiée. La copie que vous ne choisissez pas est remplacée. Décider plus tard laisse les deux telles quelles jusqu'à votre prochaine partie.",+ "Installing %@": "Installation de %@",+ "Updating %@": "Mise à jour de %@",+ "Starting %@": "Lancement de %@",+ "Asking GOG about the download": "Demande des informations de téléchargement à GOG",+ "Fetching the Windows runtimes the game needs": "Récupération des composants Windows nécessaires au jeu",+ "Setting up %@: %@ (%d of %d)": "Configuration de %@ : %@ (%d sur %d)",+ "Bringing your saves down from GOG": "Récupération de vos sauvegardes depuis GOG",+ "Starting comet for achievements": "Démarrage de comet pour les succès","Advanced": "Avancé","Enable DLSS (MetalFX)": "Activer DLSS (MetalFX)","Lets games that support DLSS use the MetalFX translation in DXMT or D3DMetal. Turn DLSS on in the game's own graphics settings too. Stop and relaunch the environment after changing this.":@@ -447,7 +523,7 @@ enum L10n {"Also installed in": "Aussi installé dans","An installer or game from your Mac. Or drop it onto this window.": "Un installateur ou un jeu présent sur votre Mac. Ou déposez-le sur cette fenêtre.","Apply the %@ fix now": "Appliquer le correctif %@ maintenant",- "Battle.net, GOG Galaxy, the EA app, Ubisoft Connect and Rockstar are under Add games.": "Battle.net, GOG Galaxy, l'app EA, Ubisoft Connect et Rockstar sont sous Ajouter des jeux.",+ "Battle.net, the EA app, Ubisoft Connect and Rockstar are under Add games.": "Battle.net, l'app EA, Ubisoft Connect et Rockstar sont sous Ajouter des jeux.","Blocked": "Bloqué","Blocked on the current engine: ": "Bloqué sur le moteur actuel : ","Choose a file…": "Choisir un fichier…",diff --git a/Sources/HighballApp/LibraryView.swift b/Sources/HighballApp/LibraryView.swiftindex 46bd2da..3ddeb2a 100644--- a/Sources/HighballApp/LibraryView.swift+++ b/Sources/HighballApp/LibraryView.swift@@ -122,6 +122,7 @@ struct LibraryView: View {FilterChip(label: L("All"), on: sourceFilter == nil) { sourceFilter = nil }FilterChip(label: "Steam", on: sourceFilter == .steam) { sourceFilter = .steam }FilterChip(label: "Epic", on: sourceFilter == .epic) { sourceFilter = .epic }+ FilterChip(label: "GOG", on: sourceFilter == .gog) { sourceFilter = .gog }FilterChip(label: L("Programs"), on: sourceFilter == .pin) { sourceFilter = .pin }Divider().frame(height: 16)FilterChip(label: L("Installed"), on: installedOnly) { installedOnly.toggle() }@@ -169,24 +170,33 @@ struct LibraryView: View {Text(L("Where are your games?")).font(.title.weight(.semibold))Text(L("Pick one to start. You can add the others any time.")).foregroundStyle(.secondary)}- HStack(alignment: .top, spacing: 14) {- sourceCard(symbol: "gamecontroller.fill", accent: true, title: L("Steam"),- text: L("Install Steam and sign in. Your Steam library shows up here. Its first start takes 15 to 25 minutes."),- button: state.defaultBottle.map(state.steamInstalled) == true ? L("Open Steam") : L("Install Steam")) { state.installSteam() }- sourceCard(symbol: "bag.fill", accent: false, title: L("Epic Games"),- text: L("Connect your Epic account. Your games install straight into Highball."),- button: L("Connect Epic")) { state.showEpicSignIn = true }- sourceCard(symbol: "folder.fill", accent: false, title: L("A Windows program I have"),- text: L("An installer or game from your Mac. Or drop it onto this window."),- button: L("Choose a file…")) { state.chooseProgramToRun() }+ // Four cards in a row where the window is wide enough, two by two where it isn't.+ ViewThatFits(in: .horizontal) {+ HStack(alignment: .top, spacing: 14) { sourceCards }+ LazyVGrid(columns: [GridItem(.fixed(250), spacing: 14), GridItem(.fixed(250), spacing: 14)], spacing: 14) { sourceCards }}- Text(L("Battle.net, GOG Galaxy, the EA app, Ubisoft Connect and Rockstar are under Add games."))+ Text(L("Battle.net, the EA app, Ubisoft Connect and Rockstar are under Add games.")).font(.caption).foregroundStyle(.tertiary)}.frame(maxWidth: .infinity).padding(.top, 40)}+ @ViewBuilder private var sourceCards: some View {+ sourceCard(symbol: "gamecontroller.fill", accent: true, title: L("Steam"),+ text: L("Install Steam and sign in. Your Steam library shows up here. Its first start takes 15 to 25 minutes."),+ button: state.defaultBottle.map(state.steamInstalled) == true ? L("Open Steam") : L("Install Steam")) { state.installSteam() }+ sourceCard(symbol: "bag.fill", accent: false, title: L("Epic Games"),+ text: L("Connect your Epic account. Your games install straight into Highball."),+ button: L("Connect Epic")) { state.showEpicSignIn = true }+ sourceCard(symbol: "g.circle.fill", accent: false, title: "GOG",+ text: L("Connect your GOG account. Your games install straight into Highball."),+ button: L("Connect GOG")) { state.showGOGSignIn = true }+ sourceCard(symbol: "folder.fill", accent: false, title: L("A Windows program I have"),+ text: L("An installer or game from your Mac. Or drop it onto this window."),+ button: L("Choose a file…")) { state.chooseProgramToRun() }+ }+private func sourceCard(symbol: String, accent: Bool, title: String, text: String, button: String, action: @escaping () -> Void) -> some View {VStack(alignment: .leading, spacing: 12) {Image(systemName: symbol).font(.title3)@@ -400,6 +410,7 @@ struct LibraryTile: View {if item.installed {Divider()Button(L("Uninstall…"), role: .destructive) { state.askUninstall(item) }+ .disabled(state.uninstallWaitsFor(item) != nil)}}.accessibilityLabel("\(item.title), \(item.source.rawValue)\(item.installedOnMac ? ", " + L("Installed in Steam for Mac") : item.installed ? "" : ", " + L("Not installed"))")@@ -426,7 +437,7 @@ struct SourceBadge: View {/// whole badge lit when Steam for Mac has it installed.var mac: MacSteamBuild? = nilprivate var label: String {- switch source { case .steam: "STEAM"; case .epic: "EPIC"; case .pin: "EXE" }+ switch source { case .steam: "STEAM"; case .epic: "EPIC"; case .gog: "GOG"; case .pin: "EXE" }}private var lit: Bool { mac == .installed }var body: some View {diff --git a/Sources/HighballKit/GOGComet.swift b/Sources/HighballKit/GOGComet.swiftnew file mode 100644index 0000000..4b6c303--- /dev/null+++ b/Sources/HighballKit/GOGComet.swift@@ -0,0 +1,163 @@+import Foundation++/// comet beside a GOG game: the stand-in for Galaxy's communication service that GOG's SDK in the+/// game talks to, on 127.0.0.1:9977, which Wine's processes reach as the Mac's own. With it a game+/// signs in, achievements and stats reach the player's account, and the "could not restore your+/// progress" notice some games show without Galaxy goes away.+///+/// comet is a helper, never a requirement: if it cannot start, the game starts without it, and a+/// game that crashes at once with comet running is started again without it and remembered, so a+/// comet problem costs that game its achievements and nothing else.+public struct GOGComet: Sendable {+ public let store: GOGStore+ public init(store: GOGStore) { self.store = store }++ /// comet's home: it reads Heroic's auth file from $HOME/Library/Application Support/heroic,+ /// so a private HOME hands it the tokens through a file (never the command line, which a process+ /// list shows) and keeps its own data inside the Highball home.+ var home: URL { store.dir.appending(path: "comet-home", directoryHint: .isDirectory) }+ var authCopy: URL { home.appending(path: "Library/Application Support/heroic/gog_store/auth.json") }++ /// The arguments: the account name only. `--quit` ends comet once every game has disconnected.+ static func arguments(username: String) -> [String] { ["--from-heroic", "--username", username, "--quit"] }++ /// Starts comet with fresh tokens. Throws when it cannot (not signed in, no name, no binary);+ /// the caller launches the game anyway.+ public func start(log: URL) throws -> Process {+ guard let username = store.username ?? (try? store.refreshUser()) ?? nil else {+ throw HighballError.failed("comet needs the GOG account name, which GOG did not return")+ }+ _ = try store.credentials() // refreshes an expired token into auth.json first+ try FileManager.default.createDirectory(at: authCopy.deletingLastPathComponent(), withIntermediateDirectories: true)+ try? FileManager.default.removeItem(at: authCopy)+ try store.withAuthFile { try FileManager.default.copyItem(at: store.authFile, to: authCopy) } // never mid-rewrite+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: authCopy.path)+ FileManager.default.createFile(atPath: log.path, contents: nil)+ let handle = try FileHandle(forWritingTo: log)+ let p = Process()+ p.executableURL = store.cometBinary+ p.arguments = Self.arguments(username: username)+ var env = ProcessInfo.processInfo.environment+ env["HOME"] = home.path+ // Long enough for a game that restarts itself once (a launcher handing over to the game).+ env["COMET_IDLE_WAIT"] = "30"+ p.environment = env+ p.standardOutput = handle+ p.standardError = handle+ defer { try? handle.close() } // comet holds its own copy once it runs+ try p.run()+ return p+ }++ /// Ends comet and removes its copy of the tokens.+ public func stop(_ process: Process?) {+ if let process, process.isRunning { process.terminate() }+ try? FileManager.default.removeItem(at: authCopy)+ }++ /// Removes a copy of the tokens left by a session that never reached `stop` (Highball or the+ /// command line quit mid-game), unless a comet is still running on it. pgrep exits 1 when+ /// nothing matches, which `capture` throws for.+ public func removeStaleTokens() {+ guard FileManager.default.fileExists(atPath: authCopy.path) else { return }+ let running = (try? Shell.capture("/usr/bin/pgrep", ["-f", store.cometBinary.path])) != nil+ if !running { try? FileManager.default.removeItem(at: authCopy) }+ }++ /// Ends every comet on this Mac and removes the token copy. One left by a Highball that quit+ /// or crashed mid-game keeps running when no game ever connected to it (`--quit` waits for+ /// one) and holds port 9977, so the next comet could not listen.+ public func stopStrays() {+ _ = try? Shell.capture("/usr/bin/pkill", ["-f", store.cometBinary.path])+ try? FileManager.default.removeItem(at: authCopy)+ }++ /// Whether comet came up and is listening, read from its log ("Listening on port 9977").+ public static func isListening(log: URL) -> Bool {+ ((try? String(contentsOf: log, encoding: .utf8)) ?? "").contains("Listening on port")+ }++ /// Whether the game reached comet during the run ("Client identified as …").+ public static func gameConnected(log: URL) -> Bool {+ ((try? String(contentsOf: log, encoding: .utf8)) ?? "").contains("Client identified")+ }++ /// The placeholder service some SDK versions wait for: GalaxyCommunication.exe where Galaxy+ /// puts it, registered as a service, and Galaxy's install path in the registry, which is what+ /// Heroic sets up in each prefix. Wine commands to run once per environment, in order.+ public static let servicePath = #"C:\ProgramData\GOG.com\Galaxy\redists\GalaxyCommunication.exe"#++ public static func serviceFile(driveC: URL) -> URL {+ driveC.appending(path: "ProgramData/GOG.com/Galaxy/redists/GalaxyCommunication.exe")+ }++ /// Puts the placeholder service in the environment once: the file where Galaxy keeps it, then+ /// the registration commands. True when it was set up now, false when it already was.+ @discardableResult+ public static func installService(from file: URL, runner: WineRunner) async throws -> Bool {+ let target = serviceFile(driveC: runner.bottle.driveC)+ guard !FileManager.default.fileExists(atPath: target.path) else { return false }+ try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.copyItem(at: file, to: target)+ // The registry entry is what the SDK checks; `sc create` may report a service that is+ // already there. Without the entry, no file either, so the next Play tries again.+ var registered = false+ do {+ for command in serviceCommands {+ let result = try await runner.run(command, renderer: .wined3d, label: "gog-comet-service")+ if command.first == "reg" { registered = result.exitStatus == 0 }+ }+ } catch {+ try? FileManager.default.removeItem(at: target)+ throw error+ }+ guard registered else {+ try? FileManager.default.removeItem(at: target)+ throw HighballError.failed("Wine could not register GOG's service placeholder for comet")+ }+ return true+ }++ static var serviceCommands: [[String]] {+ [["sc", "create", "GalaxyCommunication", "binpath=\(servicePath)"],+ ["reg", "add", #"HKLM\SOFTWARE\WOW6432Node\GOG.com\GalaxyClient\paths"#, "/v", "client", "/t", "REG_SZ",+ "/d", #"C:\Program Files\GOG Galaxy"#, "/f"]]+ }+}++/// The player's per-game GOG choices, beside the tokens: the launch task picked on a game's page,+/// games that run without comet (turned off, or after a crash with it), games without cloud saves.+public struct GOGSettings: Codable, Sendable, Equatable {+ public var launchChoice: [String: Int] = [:]+ public var cometOff: [String: String] = [:] // game id → why: turnedOff or crashedWithComet+ public static let turnedOff = "turned off"+ public static let crashedWithComet = "crashed with comet"+ public var cloudSavesOff: Set<String> = []+ /// Programs added by hand whose settings (arguments, display, graphics mode) were carried+ /// to their GOG tile once (LibraryIndex.gogCoveredPins); never again, so a later change on+ /// the GOG tile stays.+ public var carriedOverPins: Set<String> = []++ public init() {}++ // Every field optional on read: a file written before a field existed keeps the rest.+ public init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ launchChoice = try c.decodeIfPresent([String: Int].self, forKey: .launchChoice) ?? [:]+ cometOff = try c.decodeIfPresent([String: String].self, forKey: .cometOff) ?? [:]+ cloudSavesOff = try c.decodeIfPresent(Set<String>.self, forKey: .cloudSavesOff) ?? []+ carriedOverPins = try c.decodeIfPresent(Set<String>.self, forKey: .carriedOverPins) ?? []+ }++ static func file(_ store: GOGStore) -> URL { store.dir.appending(path: "settings.json") }++ public static func load(_ store: GOGStore) -> GOGSettings {+ (try? JSONDecoder().decode(GOGSettings.self, from: Data(contentsOf: file(store)))) ?? GOGSettings()+ }++ public func save(_ store: GOGStore) {+ store.secureDirectory()+ let enc = JSONEncoder(); enc.outputFormatting = [.prettyPrinted, .sortedKeys]+ try? enc.encode(self).write(to: Self.file(store), options: .atomic)+ }+}diff --git a/Sources/HighballKit/GOGLibrary.swift b/Sources/HighballKit/GOGLibrary.swiftnew file mode 100644index 0000000..7eff4cc--- /dev/null+++ b/Sources/HighballKit/GOGLibrary.swift@@ -0,0 +1,529 @@+import Foundation++// MARK: The owned library++extension GOGStore {+ /// A game the account owns, as the library shows it. GOG's own tall art is 342×482 at every+ /// source (gamesdb's vertical_cover, the store's boxArtImage), soft on a cover tile. GOG's+ /// database also names the same game's Steam release, and where it does the cover is Steam's+ /// 600×900 capsule, the art Highball shows for Steam games, and the compatibility database is+ /// matched by that Steam id, so a GOG copy gets the row, verdict and fix the Steam copy has.+ public struct Game: Codable, Sendable, Equatable {+ public let id: String+ public let title: String+ /// The Steam app id of the same game in GOG's database, nil when it has none.+ public let steamAppID: Int?+ public let gogVerticalCover: URL?+ public let gogWide: URL?++ public init(id: String, title: String, steamAppID: Int? = nil, gogVerticalCover: URL? = nil, gogWide: URL? = nil) {+ self.id = id; self.title = title; self.steamAppID = steamAppID+ self.gogVerticalCover = gogVerticalCover; self.gogWide = gogWide+ }++ public var artworkTall: URL? {+ steamAppID.map { URL(string: "https://cdn.akamai.steamstatic.com/steam/apps/\($0)/library_600x900.jpg")! } ?? gogVerticalCover+ }+ public var artworkWide: URL? {+ steamAppID.map { URL(string: "https://cdn.akamai.steamstatic.com/steam/apps/\($0)/header.jpg")! } ?? gogWide+ }+ }++ /// What gamesdb says about one release, kept between refreshes: a library of hundreds of games+ /// is one request per game the first time and none after, until the entry is a week old.+ struct CachedRelease: Codable {+ var game: Game? // nil: not a game the library shows (DLC, hidden, movie)+ var fetched: Date+ }++ var libraryCacheFile: URL { dir.appending(path: "library.json") }++ /// Games the account owns. Pages through galaxy-library's releases (the list Galaxy itself+ /// reads) and looks each one up in gamesdb, keeping games and mods it marks visible in the+ /// library, the filter Heroic uses: DLC and hidden entries stay out.+ public func ownedGames() async throws -> [Game] {+ let creds = try credentials()+ var releases: [(id: String, certificate: String?)] = []+ var page: String?+ repeat {+ var url = URLComponents(string: "https://galaxy-library.gog.com/users/\(creds.userID)/releases")!+ if let page { url.queryItems = [URLQueryItem(name: "page_token", value: page)] }+ var request = URLRequest(url: url.url!)+ request.setValue("Bearer \(creds.accessToken)", forHTTPHeaderField: "Authorization")+ let data = try await Self.fetch(async: request)+ let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:]+ for item in obj["items"] as? [[String: Any]] ?? [] {+ guard item["platform_id"] as? String == "gog", let id = item["external_id"] as? String else { continue }+ if let owned = item["owned"] as? Bool, !owned { continue }+ releases.append((id, item["certificate"] as? String))+ }+ page = (obj["next_page_token"] as? String).flatMap { $0.isEmpty ? nil : $0 }+ } while page != nil++ var cache = (try? JSONDecoder.highball.decode([String: CachedRelease].self, from: Data(contentsOf: libraryCacheFile))) ?? [:]+ let stale = Date().addingTimeInterval(-7 * 86_400)+ let missing = releases.filter { (cache[$0.id]?.fetched ?? .distantPast) < stale }+ try await withThrowingTaskGroup(of: (String, CachedRelease?).self) { group in+ var next = missing.makeIterator()+ func add() -> Bool {+ guard let r = next.next() else { return false }+ group.addTask { (r.id, try? await Self.release(r.id, certificate: r.certificate, token: creds.accessToken)) }+ return true+ }+ for _ in 0..<8 where add() {}+ while let (id, entry) = try await group.next() {+ if let entry { cache[id] = entry }+ _ = add()+ }+ }+ secureDirectory()+ try? JSONEncoder.highball.encode(cache).write(to: libraryCacheFile, options: .atomic)+ let owned = Set(releases.map(\.id))+ return cache.filter { owned.contains($0.key) }.compactMap(\.value.game)+ .sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == .orderedAscending }+ }++ static func releaseRequest(_ id: String, certificate: String?, token: String?) -> URLRequest {+ var request = URLRequest(url: URL(string: "https://gamesdb.gog.com/platforms/gog/external_releases/\(id)")!)+ if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }+ if let certificate { request.setValue(certificate, forHTTPHeaderField: "X-GOG-Library-Cert") }+ return request+ }++ static func release(_ id: String, certificate: String?, token: String?) async throws -> CachedRelease {+ CachedRelease(game: parseRelease(id: id, data: try await fetch(async: releaseRequest(id, certificate: certificate, token: token))), fetched: Date())+ }++ /// One gamesdb release as a library game, nil for anything the library does not show.+ static func parseRelease(id: String, data: Data) -> Game? {+ guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let game = obj["game"] as? [String: Any] else { return nil }+ let type = (obj["type"] as? String) ?? (game["type"] as? String) ?? "game"+ guard type == "game" || type == "mod", (game["visible_in_library"] as? Bool) ?? true else { return nil }+ func text(_ any: Any?) -> String? { ((any as? [String: Any])?["*"] as? String)?.trimmingCharacters(in: .whitespaces) }+ guard let title = text(obj["title"]) ?? text(game["title"]), !title.isEmpty else { return nil }+ // gamesdb image URLs carry {formatter} (a size suffix; empty is the original) and {ext}.+ func image(_ key: String) -> URL? {+ guard let format = (game[key] as? [String: Any])?["url_format"] as? String else { return nil }+ return URL(string: format.replacingOccurrences(of: "{formatter}", with: "").replacingOccurrences(of: "{ext}", with: "jpg"))+ }+ let steam = (game["releases"] as? [[String: Any]] ?? [])+ .first { $0["platform_id"] as? String == "steam" }+ .flatMap { ($0["external_id"] as? String).flatMap(Int.init) }+ return Game(id: id, title: title, steamAppID: steam,+ gogVerticalCover: image("vertical_cover"), gogWide: image("horizontal_artwork") ?? image("background"))+ }++ /// Looks up games the account may not list (an installed game from an offline installer while+ /// signed out): gamesdb answers without a token.+ public func game(_ id: String) -> Game? {+ if let cached = (try? JSONDecoder.highball.decode([String: CachedRelease].self, from: Data(contentsOf: libraryCacheFile)))?[id],+ cached.fetched > Date().addingTimeInterval(-7 * 86_400) {+ return cached.game+ }+ return (try? Self.fetch(Self.releaseRequest(id, certificate: nil, token: nil))).flatMap { Self.parseRelease(id: id, data: $0) }+ }+}++// MARK: Installed games, read from disk++extension GOGStore {+ /// A launch task from goggame-<id>.info, what Galaxy's Play button runs.+ public struct PlayTask: Codable, Sendable, Equatable {+ public let name: String?+ public let type: String?+ public let path: String?+ public let arguments: String?+ public let workingDir: String?+ public let category: String?+ public let isPrimary: Bool?+ public let isHidden: Bool?++ public init(name: String? = nil, type: String? = "FileTask", path: String?, arguments: String? = nil,+ workingDir: String? = nil, category: String? = "game", isPrimary: Bool? = nil, isHidden: Bool? = nil) {+ self.name = name; self.type = type; self.path = path; self.arguments = arguments; self.workingDir = workingDir+ self.category = category; self.isPrimary = isPrimary; self.isHidden = isHidden+ }++ var isFile: Bool { (type ?? "FileTask") == "FileTask" && !(path ?? "").isEmpty }+ }++ struct InfoFile: Codable {+ let gameId: String+ let rootGameId: String?+ let name: String?+ let buildId: String?+ let clientId: String?+ let playTasks: [PlayTask]?+ }++ /// A GOG game installed in an environment.+ public struct InstalledGame: Sendable, Equatable {+ public let id: String+ public let title: String+ public let folder: URL+ public let buildID: String?+ public let clientID: String?+ public let dlcIDs: [String]+ public let tasks: [PlayTask]++ /// The tasks a player can choose between: visible files that are not a manual (Heroic's+ /// rule), offered only when there are at least two.+ public var launchChoices: [PlayTask] {+ let visible = tasks.filter { $0.isFile && $0.isHidden != true && $0.category != "document" }+ return visible.count >= 2 ? visible : []+ }++ /// What Play runs: the chosen task when there is one, else the primary task, which is+ /// what Galaxy and gogdl run, else the first file task.+ public func launchTask(choice: Int? = nil) -> PlayTask? {+ if let choice, launchChoices.indices.contains(choice) { return launchChoices[choice] }+ return tasks.first { $0.isPrimary == true && $0.isFile } ?? tasks.first { $0.isFile }+ }++ /// What tells the game is still running: the name of every program in its folder, since a+ /// GOG launch task is often a launcher that hands over to another .exe beside it and exits+ /// (Control.exe starts Control_DX11.exe), and Wine shows a process by its file name only.+ /// Uninstallers, bundled runtime installers and generic helpers (crash reporters, setup and+ /// settings tools, updaters) are left out: their names are common enough to match another+ /// game's process. The program Play started always counts.+ public func sessionMarkers(launching executable: URL) -> [String] {+ let skip = ["__redist", "_commonredist", "redist", "directx", "vcredist", "support"]+ var names: Set<String> = []+ let items = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: nil,+ options: [.skipsHiddenFiles, .skipsPackageDescendants])+ while let url = items?.nextObject() as? URL {+ let name = url.lastPathComponent.lowercased()+ if skip.contains(name) || (items?.level ?? 0) >= 4 { items?.skipDescendants() }+ guard name.hasSuffix(".exe"), !name.hasPrefix("unins"),+ !["crash", "setup", "config", "launcher", "redist", "update", "report"].contains(where: name.contains),+ name != "start.exe" else { continue }+ names.insert(url.lastPathComponent)+ }+ names.formUnion(SessionWatch.markers(executable: executable)) // what Play started, whatever its name or place+ return names.sorted()+ }+ }++ /// The folders GOG installs land in: Highball's own (gogdl, like Epic), and the defaults of+ /// GOG's offline installers and of Galaxy.+ public static func installRoots(driveC: URL) -> [URL] {+ ["Games", "GOG Games", "Program Files (x86)/GOG Galaxy/Games", "Program Files/GOG Galaxy/Games"]+ .map { driveC.appending(path: $0, directoryHint: .isDirectory) }+ }++ /// Every GOG game installed in the environment: a folder directly under an install root that+ /// holds goggame-<id>.info files. The base game is the file whose id is its own root id; the+ /// others are its DLC. A folder gogdl is still downloading into (.gogdl-resume) is skipped.+ public static func installedGames(driveC: URL) -> [InstalledGame] {+ let fm = FileManager.default+ var games: [InstalledGame] = []+ for root in installRoots(driveC: driveC) {+ let folders = (try? fm.contentsOfDirectory(at: root, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles])) ?? []+ for folder in folders where (try? folder.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true {+ if fm.fileExists(atPath: folder.appending(path: ".gogdl-resume").path) { continue }+ if let game = installedGame(in: folder) { games.append(game) }+ }+ }+ return games+ }++ static func installedGame(in folder: URL) -> InstalledGame? {+ let files = ((try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? [])+ .filter { $0.lastPathComponent.hasPrefix("goggame-") && $0.pathExtension == "info" }+ let infos = files.compactMap { try? JSONDecoder().decode(InfoFile.self, from: Data(contentsOf: $0)) }+ guard let base = infos.first(where: { $0.rootGameId == nil || $0.rootGameId == $0.gameId }) else { return nil }+ let dlcs = infos.filter { $0.gameId != base.gameId && ($0.rootGameId ?? base.gameId) == base.gameId }.map(\.gameId).sorted()+ return InstalledGame(id: base.gameId, title: base.name ?? folder.lastPathComponent, folder: folder,+ buildID: base.buildId, clientID: base.clientId, dlcIDs: dlcs, tasks: base.playTasks ?? [])+ }++ /// The executable, arguments and working folder a task names, resolved the way gogdl's launch+ /// does: Windows separators become Unix ones, an argument string is split like a shell would,+ /// the working folder defaults to the game's, and a name whose case differs on disk is found.+ public static func launch(_ task: PlayTask, in game: InstalledGame) -> (executable: URL, arguments: [String], workingDirectory: URL)? {+ guard task.isFile, let path = task.path else { return nil }+ let exe = resolve(path, in: game.folder)+ let args = task.arguments.map { ArgumentLine.split($0.replacingOccurrences(of: "\\", with: "/")) } ?? []+ let work = (task.workingDir ?? "").isEmpty ? game.folder : resolve(task.workingDir!, in: game.folder)+ return (exe, args, work)+ }++ /// A relative path from an info file under `folder`, matched case-insensitively component by+ /// component when the exact spelling is not on disk.+ static func resolve(_ relative: String, in folder: URL) -> URL {+ let parts = relative.replacingOccurrences(of: "\\", with: "/").split(separator: "/").map(String.init)+ var url = folder+ for part in parts {+ let exact = url.appending(path: part)+ if FileManager.default.fileExists(atPath: exact.path) { url = exact; continue }+ let names = (try? FileManager.default.contentsOfDirectory(atPath: url.path)) ?? []+ url = url.appending(path: names.first { $0.caseInsensitiveCompare(part) == .orderedSame } ?? part)+ }+ return url+ }+}++// MARK: Installing, updating, removing++extension GOGStore {+ var manifestsDir: URL { dir.appending(path: "heroic_gogdl/manifests", directoryHint: .isDirectory) }+ /// The manifest gogdl reads and writes: one per game id for the whole Highball home.+ func manifest(_ id: String) -> URL { manifestsDir.appending(path: id) }+ /// Each install's own copy, beside its files. A game can sit in several environments, at+ /// different builds; gogdl knows one manifest per game, so the install's copy is what Highball+ /// trusts (update, setup, the page's Version) and it goes into gogdl's place before gogdl+ /// patches that install. Uninstalling removes it with the folder.+ func installManifest(_ game: InstalledGame) -> URL { game.folder.appending(path: ".highball-gogdl-manifest") }+ func supportDir(_ id: String) -> URL { dir.appending(path: "support/\(id)", directoryHint: .isDirectory) }+ var redistDir: URL { dir.appending(path: "redist", directoryHint: .isDirectory) }++ /// What `gogdl info` says before a download: the folder it will make, the languages, the size+ /// and the Windows runtimes the game lists.+ public struct DownloadInfo: Sendable {+ public let folderName: String?+ public let languages: [String]+ public let downloadSize: Int64?+ public let diskSize: Int64?+ public let buildID: String?+ public let dependencies: [String]+ }++ public func info(_ id: String) throws -> DownloadInfo {+ let out = try capture(["info", id, "--os", "windows"])+ 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.")+ }+ 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] ?? [])+ }++ /// The language to install: the first of the Mac's preferred languages the game has, else+ /// English, else the game's first. GOG names them "en-US", Macs "en-US" or "en".+ public static func language(for available: [String], preferred: [String] = Locale.preferredLanguages) -> String {+ for wanted in preferred {+ if let exact = available.first(where: { $0.caseInsensitiveCompare(wanted) == .orderedSame }) { return exact }+ let base = wanted.split(separator: "-").first.map(String.init) ?? wanted+ if let close = available.first(where: { $0.lowercased().hasPrefix(base.lowercased() + "-") || $0.lowercased() == base.lowercased() }) { return close }+ }+ return available.first { $0.hasPrefix("en") } ?? available.first ?? "en-US"+ }++ /// gogdl appends the game's own folder name to `--path` for a download, and takes the game's+ /// folder itself for an update. DLC comes along: what the account owns installs with the game.+ static func downloadArguments(id: String, into base: String, support: String, language: String, update: Bool) -> [String] {+ [update ? "update" : "download", id, "--platform", "windows", "--path", base,+ "--support", support, "--with-dlcs", "--lang", language]+ }++ /// Downloads a game's Windows build into the environment's Games folder. Returns the folder.+ @discardableResult+ public func install(_ id: String, into bottle: Bottle, language: String, control: LegendaryControl? = nil,+ onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ let base = bottle.driveC.appending(path: "Games", directoryHint: .isDirectory)+ try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)+ // Another environment's install of this game left gogdl's manifest behind (its own copy+ // stays beside it): cleared, so a manifest after this download is this download's.+ try? FileManager.default.removeItem(at: manifest(id))+ return try runStreaming(Self.downloadArguments(id: id, into: base.path, support: supportDir(id).path, language: language, update: false),+ control: control, onLine: onLine)+ }++ /// Brings an installed game to GOG's newest build. gogdl patches against the manifest it kept+ /// from the download, so only games gogdl installed can update here.+ @discardableResult+ public func update(_ game: InstalledGame, language: String, control: LegendaryControl? = nil,+ onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ // gogdl patches against its manifest: this install's, not another environment's build.+ try? FileManager.default.removeItem(at: manifest(game.id))+ try FileManager.default.copyItem(at: installManifest(game), to: manifest(game.id))+ return try runStreaming(Self.downloadArguments(id: game.id, into: game.folder.path, support: supportDir(game.id).path, language: language, update: true),+ control: control, onLine: onLine)+ }++ /// gogdl downloaded this install and Highball kept its manifest: it can update the game and+ /// knows the setup it needs. An offline installer's game has none, and its installer did the setup.+ public func hasManifest(_ game: InstalledGame) -> Bool { FileManager.default.fileExists(atPath: installManifest(game).path) }++ /// An install gogdl made before installs kept their own manifest: takes gogdl's when it+ /// describes this very build (same build id as the install's info file), once.+ public func adoptManifest(for game: InstalledGame) {+ let fm = FileManager.default+ guard !fm.fileExists(atPath: installManifest(game).path), let build = game.buildID,+ let data = try? Data(contentsOf: manifest(game.id)),+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ obj["buildId"] as? String == build else { return }+ try? fm.copyItem(at: manifest(game.id), to: installManifest(game))+ }++ /// After a finished download or update: keeps gogdl's manifest beside the install it describes.+ public func keepManifest(for game: InstalledGame) {+ try? FileManager.default.removeItem(at: installManifest(game))+ try? FileManager.default.copyItem(at: manifest(game.id), to: installManifest(game))+ }++ /// gogdl prints `= Progress: 12.34 123456/999999, Running for: …` about once a second: the+ /// bytes written so far and the total on disk. Nil for any other line.+ public static func progress(inGogdlLine line: String) -> (written: Int64, total: Int64)? {+ guard let r = line.range(of: "= Progress: ") else { return nil }+ let fields = line[r.upperBound...].split(separator: " ")+ guard fields.count >= 2 else { return nil }+ let pair = fields[1].split(separator: "/")+ guard pair.count == 2, let written = Int64(pair[0]), let total = Int64(pair[1].trimmingCharacters(in: CharacterSet(charactersIn: ","))) else { return nil }+ return (written, total)+ }++ /// A line that explains why a download stopped, as a sentence for the player. Nil otherwise.+ public static func installFailure(_ line: String) -> String? {+ if line.contains("Not enough disk space") {+ return "This Mac doesn't have enough free space for the game. Free some space, then press Install again."+ }+ if line.contains("doesn't support content system api") {+ return "GOG has no Galaxy-style Windows download for this game, so it can't be installed from here. Its offline installer from gog.com still works: download it from your GOG library and drop it on Highball."+ }+ guard let r = line.range(of: "] ERROR: ") ?? line.range(of: "] CRITICAL: ") else { return nil }+ let message = line[r.upperBound...].trimmingCharacters(in: .whitespaces)+ return message.isEmpty ? nil : "GOG's downloader stopped with this message. \(message)"+ }++ /// gogdl can end a download that failed partway with status 0 and no manifest (its executor+ /// returns "cancelled" on a fatal error), so a finished install is one whose manifest exists.+ public func downloadCompleted(_ id: String) -> Bool { FileManager.default.fileExists(atPath: manifest(id).path) }++ /// Forgets what gogdl kept about a game once no environment holds it any more, so it never+ /// tries to patch a game that is not there. While another install remains, its state stays.+ public func forget(_ id: String, otherInstallsRemain: Bool) {+ guard !otherInstallsRemain else { return }+ try? FileManager.default.removeItem(at: manifest(id))+ try? FileManager.default.removeItem(at: supportDir(id))+ }+}++// MARK: First-run setup (what GOG's installer would have done)++extension GOGStore {+ /// One program to run in the environment after a download, in order.+ public struct SetupStep: Sendable, Equatable {+ public let label: String+ /// The program to run; nil runs Wine's own msiexec with the arguments (an .msi runtime).+ public let executable: URL?+ public let arguments: [String]+ public let workingDirectory: URL++ public var command: [String] { [executable?.path ?? "msiexec"] + arguments }+ }++ /// Runs what GOG's installer would have, in the environment: the runtimes the game lists,+ /// then its install scripts, then the marker that says this build has had its setup. A step+ /// that fails is reported and the next one runs; nothing here stops the game from being+ /// played, which is how Galaxy behaves when a runtime is already newer. Shared by the app+ /// and the CLI.+ public func runSetup(_ game: InstalledGame, language: String, runner: WineRunner,+ onStep: (_ number: Int, _ of: Int, _ label: String) async -> Void = { _, _, _ in },+ onLine: (@Sendable (String) -> Void)? = nil,+ onFailure: (_ label: String, _ exitCode: Int32) async -> Void = { _, _ in }) async throws {+ let needed = dependencies(of: game)+ if needed.contains(where: { $0 != "ISI" }) {+ let store = self+ _ = try? await Task.detached { try store.downloadRedists(needed, onLine: onLine) }.value+ }+ let steps = setupSteps(for: game, language: language)+ for (n, step) in steps.enumerated() {+ try Task.checkCancellation()+ await onStep(n + 1, steps.count, step.label)+ let result = try? await runner.run(step.command, renderer: .wined3d, label: "gog-setup-\(game.id)",+ workingDirectory: step.workingDirectory, onOutput: onLine)+ if let code = result?.exitStatus, code != 0 { await onFailure(step.label, code) }+ }+ Self.markSetupDone(for: game, driveC: runner.bottle.driveC)+ }++ /// The Windows runtimes a game's manifest lists, plus ISI (GOG's ScriptInterpreter), which+ /// runs a game's install scripts.+ public func dependencies(of game: InstalledGame) -> [String] {+ guard let data = try? Data(contentsOf: installManifest(game)),+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [] }+ if let deps = obj["dependencies"] as? [String] { return deps }+ // v1 manifests list them per depot.+ let products = (obj["product"] as? [String: Any])?["depots"] as? [[String: Any]] ?? []+ return products.compactMap { $0["redist"] as? String }+ }++ /// Fetches the shared runtimes into the Highball home (once, shared by every game).+ @discardableResult+ public func downloadRedists(_ ids: [String], onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ try FileManager.default.createDirectory(at: redistDir, withIntermediateDirectories: true)+ return try runStreaming(["redist", "--ids", (["ISI"] + ids).joined(separator: ","), "--path", redistDir.path], onLine: onLine)+ }++ /// What GOG's own installer would have run, in Heroic's order: each runtime the game lists,+ /// with the silent arguments GOG's repository gives it, then the game's install scripts+ /// (ScriptInterpreter for a v2 manifest that asks for it, else each product's own setup+ /// program). Paths stay Unix paths; Wine maps them through Z:.+ public func setupSteps(for game: InstalledGame, language: String) -> [SetupStep] {+ guard let data = try? Data(contentsOf: installManifest(game)),+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [] }+ var steps: [SetupStep] = []+ let repo = (try? Data(contentsOf: redistDir.appending(path: ".gogdl-redist-manifest")))+ .flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }+ let depots = repo?["depots"] as? [[String: Any]] ?? []+ for dep in dependencies(of: game) where dep != "ISI" {+ guard let depot = depots.first(where: { $0["dependencyId"] as? String == dep }),+ let exe = depot["executable"] as? [String: Any], let path = exe["path"] as? String, !path.isEmpty else { continue }+ let file = redistDir.appending(path: path)+ guard FileManager.default.fileExists(atPath: file.path) else { continue }+ var args = ArgumentLine.split(exe["arguments"] as? String ?? "")+ var executable: URL? = file+ if dep == "PHYSXLEGACY" { args = ["/i", file.path] + args + ["/qb"]; executable = nil }+ steps.append(SetupStep(label: depot["readableName"] as? String ?? dep, executable: executable,+ arguments: args, workingDirectory: redistDir))+ }+ let languageName = Locale(identifier: "en").localizedString(forLanguageCode: String(language.prefix(2))) ?? "English"+ let common = ["/VERYSILENT", "/DIR=\(game.folder.path)", "/galaxyclient", "/buildId=\(game.buildID ?? "")",+ "/versionName=\(obj["versionName"] as? String ?? "")", "/lang-code=\(language)",+ "/nodesktopshorctut", "/nodesktopshortcut"]+ let products = (obj["products"] as? [[String: Any]] ?? []).compactMap { p -> (id: String, temp: String?)? in+ guard let id = p["productId"] as? String else { return nil }+ return (id, p["temp_executable"] as? String)+ }.filter { $0.id == game.id || game.dlcIDs.contains($0.id) }+ let isi = redistDir.appending(path: "__redist/ISI/scriptinterpreter.exe")+ if obj["scriptInterpreter"] as? Bool == true, FileManager.default.fileExists(atPath: isi.path) {+ for p in products {+ steps.append(SetupStep(label: "GOG install script", executable: isi,+ arguments: common + ["/Language=\(languageName)", "/LANG=\(languageName)", "/ProductId=\(p.id)",+ "/supportDir=\(supportDir(game.id).path)"],+ workingDirectory: game.folder))+ }+ } else {+ for p in products {+ guard let temp = p.temp, !temp.isEmpty else { continue }+ let exe = supportDir(game.id).appending(path: "\(game.id)/\(p.id)/\(temp)")+ guard FileManager.default.fileExists(atPath: exe.path) else { continue }+ steps.append(SetupStep(label: "GOG install script", executable: exe,+ arguments: common + ["/Language=\(languageName.lowercased())", "/LANG=\(languageName.lowercased())", "/ProductId=\(p.id)"],+ workingDirectory: game.folder))+ }+ }+ return steps+ }++ /// Setup has run for this build in this environment. A marker in the environment, so another+ /// environment holding the same game runs its own, and an update runs it again.+ public static func setupMarker(for game: InstalledGame, driveC: URL) -> URL {+ driveC.appending(path: "highball/gog-setup/\(game.id)")+ }+ public static func setupDone(for game: InstalledGame, driveC: URL) -> Bool {+ (try? String(contentsOf: setupMarker(for: game, driveC: driveC), encoding: .utf8)) == (game.buildID ?? "")+ }+ public static func markSetupDone(for game: InstalledGame, driveC: URL) {+ let url = setupMarker(for: game, driveC: driveC)+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try? (game.buildID ?? "").write(to: url, atomically: true, encoding: .utf8)+ }+}diff --git a/Sources/HighballKit/GOGSaves.swift b/Sources/HighballKit/GOGSaves.swiftnew file mode 100644index 0000000..65b116d--- /dev/null+++ b/Sources/HighballKit/GOGSaves.swift@@ -0,0 +1,196 @@+import Foundation+import os++/// GOG cloud saves through gogdl's save-sync. Where a game keeps its saves comes from GOG's own+/// client configuration (remote-config, the file Galaxy reads); the folders are resolved inside the+/// environment, saves come down before Play and go up after the game ends, as Galaxy does.+///+/// gogdl notices a conflict (both sides changed since the last sync), transfers nothing and still+/// prints a fresh timestamp; storing that timestamp would make the next sync overwrite one side+/// unasked. So a conflict is detected from its log line and the timestamp is kept back until the+/// player chooses which copy wins.+public struct GOGSaves: Sendable {+ public let store: GOGStore+ public init(store: GOGStore) { self.store = store }++ public struct Location: Sendable, Equatable {+ public let name: String+ /// GOG's template, e.g. "<?SAVED_GAMES?>/Remedy/Control".+ public let template: String+ }++ /// The client id cloud storage is keyed by: the info file's, else the manifest gogdl kept+ /// (Control's info file has none; its manifest does), else GOG's latest build manifest for an+ /// install with neither (an offline installer, a gogdl install from elsewhere), remembered.+ public func clientID(for game: GOGStore.InstalledGame) -> String? {+ if let id = game.clientID, !id.isEmpty { return id }+ if let data = try? Data(contentsOf: store.installManifest(game)),+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let id = obj["clientId"] as? String { return id }+ let cacheFile = store.dir.appending(path: "client-ids.json")+ var cache = (try? JSONDecoder().decode([String: String].self, from: Data(contentsOf: cacheFile))) ?? [:]+ if let id = cache[game.id] { return id }+ guard let id = try? Self.publishedClientID(productID: game.id) else { return nil }+ cache[game.id] = id+ try? JSONEncoder().encode(cache).write(to: cacheFile, options: .atomic)+ return id+ }++ /// The client id in the newest Windows build's manifest. The build list and manifests are+ /// public; a v2 manifest is zlib-compressed JSON.+ static func publishedClientID(productID: String) throws -> String? {+ let list = URL(string: "https://content-system.gog.com/products/\(productID)/os/windows/builds?generation=2")!+ guard let builds = try JSONSerialization.jsonObject(with: GOGStore.fetch(URLRequest(url: list))) as? [String: Any],+ let link = ((builds["items"] as? [[String: Any]])?.first?["link"] as? String).flatMap(URL.init(string:)) else { return nil }+ return clientID(inManifest: try GOGStore.fetch(URLRequest(url: link)))+ }++ static func clientID(inManifest data: Data) -> String? {+ // zlib = a 2-byte header, raw DEFLATE, then a checksum; Foundation's .zlib reads raw DEFLATE.+ let json = data.first == 0x78 ? (try? (data.dropFirst(2) as NSData).decompressed(using: .zlib) as Data) : data+ guard let json, let obj = try? JSONSerialization.jsonObject(with: json) as? [String: Any] else { return nil }+ return obj["clientId"] as? String+ }++ /// Where the game keeps its saves, nil when it has no cloud saves. An empty list from GOG means+ /// the SDK's own storage folder, which Galaxy names __default.+ public func locations(clientID: String) throws -> [Location]? {+ let url = URL(string: "https://remote-config.gog.com/components/galaxy_client/clients/\(clientID)?component_version=2.0.45")!+ let data = try GOGStore.fetch(URLRequest(url: url))+ return Self.parseLocations(data, clientID: clientID)+ }++ static func parseLocations(_ data: Data, clientID: String) -> [Location]? {+ guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let windows = (obj["content"] as? [String: Any])?["Windows"] as? [String: Any],+ let cloud = windows["cloudStorage"] as? [String: Any], cloud["enabled"] as? Bool == true else { return nil }+ let list = (cloud["locations"] as? [[String: Any]] ?? []).compactMap { l -> Location? in+ guard let name = l["name"] as? String, let location = l["location"] as? String else { return nil }+ return Location(name: name, template: location)+ }+ return list.isEmpty+ ? [Location(name: "__default", template: "<?APPLICATION_DATA_LOCAL?>/GOG.com/Galaxy/Applications/\(clientID)/Storage/Shared/Files")]+ : list+ }++ /// 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.+ public static func resolve(_ template: String, game: GOGStore.InstalledGame, driveC: URL,+ userName: String = NSUserName()) -> URL? {+ let users = UserFolders.userDirectories(driveC: driveC)+ let user = users.first { $0.lastPathComponent == userName } ?? users.first+ ?? driveC.appending(path: "users/\(userName)", directoryHint: .isDirectory)+ let values: [String: URL] = [+ "INSTALL": game.folder,+ "SAVED_GAMES": user.appending(path: "Saved Games"),+ "APPLICATION_DATA_LOCAL": user.appending(path: "AppData/Local"),+ "APPLICATION_DATA_LOCAL_LOW": user.appending(path: "AppData/LocalLow"),+ "APPLICATION_DATA_ROAMING": user.appending(path: "AppData/Roaming"),+ "DOCUMENTS": user.appending(path: "Documents"),+ ]+ var path = template.replacingOccurrences(of: "\\", with: "/")+ guard let open = path.range(of: "<?"), let close = path.range(of: "?>", range: open.upperBound..<path.endIndex),+ open.lowerBound == path.startIndex else { return nil }+ let variable = String(path[open.upperBound..<close.lowerBound])+ guard let base = values[variable] else { return nil } // a Mac-only variable, or one GOG adds later+ path.removeSubrange(path.startIndex..<close.upperBound)+ // Any %VARIABLE% left inside is a Windows environment variable no known folder covers.+ guard !path.contains("%"), !path.contains("<?") else { return nil }+ // gogdl deletes local files the cloud lacks, so a template naming a whole known folder (or+ // climbing out of one) could empty the game or the Mac's Documents: never sync those.+ let parts = path.split(separator: "/").map(String.init)+ guard !parts.isEmpty, !parts.contains(where: { $0 == "." || $0 == ".." }) else { return nil }+ return parts.reduce(base) { $0.appending(path: $1) }+ }++ // MARK: Sync++ public enum Direction: Sendable { case download, upload, forceDownload, forceUpload }++ public enum Outcome: Sendable, Equatable {+ case synced+ /// Both sides changed since the last sync: nothing moved, the player chooses.+ case conflict+ case failed(String)+ }++ var timestampsFile: URL { store.dir.appending(path: "saves.json") }++ func timestamps() -> [String: String] {+ (try? JSONDecoder().decode([String: String].self, from: Data(contentsOf: timestampsFile))) ?? [:]+ }++ /// Read, change and write saves.json as one step: two games' syncs can end together.+ private static let timestampsLock = NSLock()+ private func updateTimestamps(_ change: (inout [String: String]) -> Void) {+ Self.timestampsLock.withLock {+ var all = timestamps()+ change(&all)+ store.secureDirectory()+ try? JSONEncoder().encode(all).write(to: timestampsFile, options: .atomic)+ }+ }++ /// Per install, not per game: the same game in two environments has two sets of saves, each+ /// with its own last sync.+ func key(_ game: GOGStore.InstalledGame, _ location: Location) -> String {+ "\(game.id).\(location.name)@\(game.folder.standardizedFileURL.path)"+ }++ static func arguments(folder: URL, id: String, location: Location, timestamp: String, direction: Direction) -> [String] {+ let flag: String+ switch direction {+ case .download: flag = "--skip-upload"+ case .upload: flag = "--skip-download"+ case .forceDownload: flag = "--force-download"+ case .forceUpload: flag = "--force-upload"+ }+ return ["save-sync", folder.path, id, "--os", "windows", "--ts", timestamp, "--name", location.name, flag]+ }++ /// gogdl's only stdout is the new timestamp, a bare number written without a newline, so on+ /// the shared pipe it usually arrives glued to the log line after it ("1793193913.87[SAVES] INFO:+ /// Done"). Returns the number and what follows it.+ static func timestamp(in line: String) -> (String, String)? {+ guard let match = line.firstMatch(of: #/^\s*(\d+(?:\.\d+)?)/#),+ let value = Double(match.1), value > 0 else { return nil }+ return (String(match.1), String(line[match.range.upperBound...]))+ }++ /// gogdl's line for a conflict: it moved nothing.+ static func isConflict(_ line: String) -> Bool { line.contains("Files in conflict") }++ /// Syncs one location. The new timestamp is kept only when something was decided.+ public func sync(_ game: GOGStore.InstalledGame, location: Location, folder: URL, direction: Direction,+ onLine: (@Sendable (String) -> Void)? = nil) -> Outcome {+ try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ let ts = timestamps()[key(game, location)] ?? "0"+ let conflict = OSAllocatedUnfairLock(initialState: false)+ let stdout = OSAllocatedUnfairLock<String?>(initialState: nil)+ let status: Int32+ do {+ // save-sync refreshes the game's own token into auth.json.+ status = try store.withAuthFile { try store.runStreaming(Self.arguments(folder: folder, id: game.id, location: location, timestamp: ts, direction: direction)) { line in+ if Self.isConflict(line) { conflict.withLock { $0 = true } }+ if let (value, rest) = Self.timestamp(in: line) {+ stdout.withLock { $0 = value }+ if !rest.isEmpty { onLine?(rest) }+ } else { onLine?(line) }+ } }+ } catch { return .failed(error.localizedDescription) }+ guard status == 0 else { return .failed("gogdl save-sync exited with \(status)") }+ if conflict.withLock({ $0 }) { return .conflict }+ if let new = stdout.withLock({ $0 }) {+ updateTimestamps { $0[key(game, location)] = new }+ }+ return .synced+ }++ /// Forgets an install's sync history (uninstall), so a reinstall starts by asking the cloud.+ /// Other environments' copies of the game keep theirs.+ public func forget(_ game: GOGStore.InstalledGame) {+ let suffix = "@\(game.folder.standardizedFileURL.path)"+ updateTimestamps { all in all = all.filter { !($0.key.hasPrefix(game.id + ".") && $0.key.hasSuffix(suffix)) } }+ }+}diff --git a/Sources/HighballKit/GOGStore.swift b/Sources/HighballKit/GOGStore.swiftnew file mode 100644index 0000000..3dc4320--- /dev/null+++ b/Sources/HighballKit/GOGStore.swift@@ -0,0 +1,342 @@+import Foundation+import os++/// GOG games without GOG Galaxy (highball#8, #149). Galaxy's sign-in window is Chromium inside Qt+/// WebEngine, which draws black on the Wine 10 engines and crashes on the Wine 11 ones, so the+/// client cannot sign in under Wine at all. Its jobs are done here by the tools Heroic uses:+/// gogdl (github.com/Heroic-Games-Launcher/heroic-gogdl, GPL-3 like Highball) signs in, downloads+/// a game's Windows build straight into an environment, fetches the Windows runtimes it lists and+/// syncs cloud saves; comet (github.com/imLinguin/comet, Apache-2.0) stands in for Galaxy's+/// communication service while a game runs, so achievements, stats and play time reach the+/// player's GOG account. Sign-in happens on GOG's own page in the player's browser.+///+/// Install state is read from disk rather than kept: every GOG game, whether gogdl downloaded it+/// or an offline installer from gog.com put it there, carries a goggame-<id>.info naming its id,+/// title, build and launch tasks. So a game installed by hand earlier shows up as the GOG game it+/// is, with its cover, and there is no record to go stale when a folder is deleted.+public struct GOGStore: Sendable {+ public let paths: HighballPaths+ public init(paths: HighballPaths = HighballPaths()) { self.paths = paths }++ // Pinned like an engine component. Update deliberately, never float.+ static let gogdl = EngineManifest.Component(+ kind: "tool", url: URL(string: "https://github.com/Heroic-Games-Launcher/heroic-gogdl/releases/download/v1.3.1/gogdl_macos_arm64")!,+ sha256: "33a6d9b329c35f1caa7968009bf2f4f0a6f57cd00f749a4d2cb2204f3e794d2e", size: 11_031_600,+ license: nil, optional: nil, acceptance: nil, extract: nil, note: nil, version: "1.3.1")+ static let comet = EngineManifest.Component(+ kind: "tool", url: URL(string: "https://github.com/imLinguin/comet/releases/download/v0.4.0/comet-aarch64-apple-darwin")!,+ sha256: "53152b17b86baf118f47a299c83e8dc101653655da7d9d9a6aa36bfeb982c489", size: 11_209_264,+ license: nil, optional: nil, acceptance: nil, extract: nil, note: nil, version: "0.4.0")+ /// comet's GalaxyCommunication.exe placeholder: some Galaxy SDK versions refuse to talk to+ /// anything until a Windows service of that name is registered (comet's dummy-service/README).+ static let dummyService = EngineManifest.Component(+ kind: "tool", url: URL(string: "https://github.com/imLinguin/comet/releases/download/v0.4.0/dummy-service.zip")!,+ sha256: "4a3bb0889662a976fb84445c46eafbe44f7b9c8ea761a5761266f451e4dfcaf7", size: 36_795,+ license: nil, optional: nil, acceptance: nil, extract: nil, note: nil, version: "0.4.0")++ /// Galaxy's public client, the one gogdl, Heroic, Lutris and comet all sign in as.+ static let clientID = "46899977096215655"++ /// GOG's sign-in page, opened in the player's own browser so the password never passes through+ /// Highball. It ends on embed.gog.com/on_login_success?origin=client&code=…, and the player+ /// pastes that address (or just the code) back.+ public static let loginURL = URL(string: "https://auth.gog.com/auth?client_id=\(clientID)&layout=galaxy&redirect_uri=https%3A%2F%2Fembed.gog.com%2Fon_login_success%3Forigin%3Dclient&response_type=code")!++ public var gogdlBinary: URL { paths.home.appending(path: "tools/gogdl", directoryHint: .notDirectory) }+ public var cometBinary: URL { paths.home.appending(path: "tools/comet", directoryHint: .notDirectory) }+ var dir: URL { paths.home.appending(path: "gog", directoryHint: .isDirectory) }+ var authFile: URL { dir.appending(path: "auth.json") }+ var userFile: URL { dir.appending(path: "user.json") }+ var dummyServiceDir: URL { paths.home.appending(path: "tools/comet-dummy-service", directoryHint: .isDirectory) }++ /// Downloads and verifies a pinned tool if missing.+ private func ensure(_ component: EngineManifest.Component, name: String, at binary: URL,+ progress: DownloadProgress?) async throws -> URL {+ if FileManager.default.fileExists(atPath: binary.path) { return binary }+ let file = try await EngineStore(paths: paths).download(component, name: name, progress: progress)+ try FileManager.default.createDirectory(at: binary.deletingLastPathComponent(), withIntermediateDirectories: true)+ try? FileManager.default.removeItem(at: binary)+ try FileManager.default.copyItem(at: file, to: binary)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: binary.path)+ // Checksum-verified above; quarantine would otherwise block the unsigned binaries.+ try? Shell.run("/usr/bin/xattr", ["-c", binary.path])+ return binary+ }++ public func ensureInstalled(progress: DownloadProgress? = nil) async throws {+ _ = try await ensure(Self.gogdl, name: "gogdl", at: gogdlBinary, progress: progress)+ }++ /// comet and its placeholder service. Failing here never stops a launch (see GOGComet).+ public func ensureComet(progress: DownloadProgress? = nil) async throws -> (comet: URL, service: URL) {+ let comet = try await ensure(Self.comet, name: "comet", at: cometBinary, progress: progress)+ let exe = dummyServiceDir.appending(path: "GalaxyCommunication.exe")+ if !FileManager.default.fileExists(atPath: exe.path) {+ let zip = try await EngineStore(paths: paths).download(Self.dummyService, name: "comet-dummy-service", progress: progress)+ try FileManager.default.createDirectory(at: dummyServiceDir, withIntermediateDirectories: true)+ try Shell.run("/usr/bin/ditto", ["-x", "-k", zip.path, dummyServiceDir.path])+ }+ return (comet, exe)+ }++ /// gogdl keeps its manifests under $GOGDL_CONFIG_PATH/heroic_gogdl; inside the Highball home+ /// they move with it, and deleting the home stays a full uninstall.+ var environment: [String: String] { ["GOGDL_CONFIG_PATH": dir.path] }++ /// The arguments every gogdl call starts with.+ var baseArguments: [String] { ["--auth-config-path", authFile.path] }++ /// gogdl reads auth.json when it starts and rewrites it in place when it refreshes a token, so+ /// two calls at once can put a stale token pair back, or read a half-written file and look+ /// signed out. The short calls take turns; downloads, which run for minutes, do not.+ private static let authFileLock = NSLock()+ func withAuthFile<T>(_ body: () throws -> T) rethrows -> T { try Self.authFileLock.withLock(body) }++ /// Captures stdout only: gogdl logs to stderr and prints its JSON to stdout.+ @discardableResult+ func capture(_ args: [String]) throws -> String {+ try withAuthFile { try captureUnlocked(args) }+ }++ private func captureUnlocked(_ args: [String]) throws -> String {+ secureDirectory()+ let p = Process()+ p.executableURL = gogdlBinary+ p.arguments = baseArguments + args+ p.environment = ProcessInfo.processInfo.environment.merging(environment) { $1 }+ let out = Pipe(), err = Pipe()+ p.standardOutput = out+ p.standardError = err+ try p.run()+ // Read stderr alongside: a full pipe would otherwise stall gogdl on a long call.+ let errData = OSAllocatedUnfairLock(initialState: Data())+ let errRead = DispatchGroup()+ DispatchQueue.global().async(group: errRead) {+ let data = err.fileHandleForReading.readDataToEndOfFile()+ errData.withLock { $0 = data }+ }+ let data = out.fileHandleForReading.readDataToEndOfFile()+ p.waitUntilExit()+ errRead.wait()+ guard p.terminationStatus == 0 else {+ throw HighballError.processFailed(command: "gogdl " + (args.first ?? ""),+ status: p.terminationStatus,+ output: Self.redacted(String(decoding: errData.withLock { $0 }.suffix(2000), as: UTF8.self)))+ }+ return String(decoding: data, as: UTF8.self)+ }++ /// Runs gogdl streaming each output line (downloads are long and progress matters). `control`+ /// stops it the way Ctrl-C in a terminal does; gogdl keeps the progress and resumes.+ @discardableResult+ public func runStreaming(_ args: [String], control: LegendaryControl? = nil,+ onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ secureDirectory()+ let p = Process()+ p.executableURL = gogdlBinary+ p.arguments = baseArguments + args+ p.environment = ProcessInfo.processInfo.environment.merging(environment) { $1 }+ let pipe = Pipe()+ p.standardOutput = pipe+ p.standardError = pipe+ try p.run()+ control?.started(p)+ let reader = pipe.fileHandleForReading+ var buffer = Data()+ while true {+ let chunk = reader.availableData+ if chunk.isEmpty { break }+ buffer.append(chunk)+ while let nl = buffer.firstIndex(of: 0x0A) {+ onLine?(Self.redacted(String(decoding: buffer[..<nl], as: UTF8.self)))+ buffer.removeSubrange(...nl)+ }+ }+ if !buffer.isEmpty { onLine?(Self.redacted(String(decoding: buffer, as: UTF8.self))) }+ p.waitUntilExit()+ return p.terminationStatus+ }++ // MARK: Signing in++ public var isAuthenticated: Bool { FileManager.default.fileExists(atPath: authFile.path) }++ /// What the player pasted into the sign-in sheet, read before anything is sent anywhere, so+ /// the sheet can say what is wrong while they are still on it.+ public enum PastedSignIn: Equatable, Sendable {+ case empty+ case code(String)+ /// GOG's sign-in page itself (auth.gog.com, login.gog.com): copied before logging in.+ case signInPage+ /// A gog.com address without a code, such as the store or the account page.+ case noCode+ /// Not a GOG address, or not shaped like a code. Nothing from it is used.+ case notGOG+ }++ /// Reads the whole on_login_success address (with or without its scheme) or the bare code.+ /// A code is only ever taken from a gog.com address, so a pasted link from anywhere else+ /// never reaches gogdl.+ public static func readSignIn(_ pasted: String) -> PastedSignIn {+ let text = pasted.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !text.isEmpty else { return .empty }+ let isCode: (String) -> Bool = { value in+ value.count >= 8 && value.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }+ }+ guard text.contains("/") || text.contains("?") || text.contains(".") else {+ return isCode(text) ? .code(text) : .notGOG+ }+ guard !text.contains(where: \.isWhitespace),+ let components = URLComponents(string: text.contains("://") ? text : "https://" + text),+ ["http", "https"].contains(components.scheme?.lowercased() ?? ""),+ // The encoded host, checked by character: "evil.com%2F.gog.com" decodes to a host+ // that ends in .gog.com.+ let host = components.percentEncodedHost?.lowercased(),+ host.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "." || $0 == "-") }),+ host == "gog.com" || host.hasSuffix(".gog.com") else {+ return .notGOG+ }+ if let code = components.queryItems?.first(where: { $0.name == "code" })?.value, isCode(code) {+ return .code(code)+ }+ return host == "auth.gog.com" || host == "login.gog.com" ? .signInPage : .noCode+ }++ public static func authorizationCode(from pasted: String) -> String? {+ if case let .code(code) = readSignIn(pasted) { return code }+ return nil+ }++ /// gogdl's output with token values blanked, for anything shown or written to a log: its+ /// errors can echo the token reply, and a log can end up pasted into a public issue.+ static func redacted(_ text: String) -> String {+ let patterns = [+ #"(["']?(?:access_token|refresh_token|id_token|session_id)["']?\s*[:=]\s*["']?)[^"'&\s,}]+"#,+ #"(\b(?:code|token)=)[^&\s"']+"#,+ #"(--code\s+)\S+"#,+ #"(Bearer\s+)\S+"#,+ ]+ return patterns.reduce(text) {+ $0.replacingOccurrences(of: $1, with: "$1[redacted]", options: [.regularExpression, .caseInsensitive])+ }+ }++ /// The folder holding the tokens, the account's game list and the save records: this user+ /// only, whatever mode the files inside are written with.+ func secureDirectory() {+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])+ try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: dir.path)+ }++ public func authenticate(code: String) throws {+ secureDirectory()+ // A refused code must not cost a working sign-in: keep the current tokens to put back.+ let previous = try? Data(contentsOf: authFile)+ let out: String+ do {+ out = try capture(["auth", "--code", code])+ } catch {+ restore(previous)+ throw HighballError.failed("Highball could not finish connecting to GOG. Check your internet connection, then try again.")+ }+ // gogdl prints {"error": true} and exits 0 when GOG refuses the code.+ guard let obj = try? JSONSerialization.jsonObject(with: Data(out.utf8)) as? [String: Any],+ obj["access_token"] != nil else {+ restore(previous)+ throw HighballError.failed("That link has expired or was already used. Click Open GOG sign-in again: GOG gives you a fresh link straight away, often without asking for your password.")+ }+ protectAuthFile()+ _ = try? refreshUser()+ }++ /// Puts back the sign-in a failed attempt may have overwritten (or none, if there was none).+ private func restore(_ previous: Data?) {+ if let previous {+ try? previous.write(to: authFile, options: .atomic)+ protectAuthFile()+ } else {+ try? FileManager.default.removeItem(at: authFile)+ }+ }++ /// gogdl writes the tokens with the default file mode and rewrites them on every refresh;+ /// they are the account's keys, so only this user reads them.+ func protectAuthFile() {+ try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: authFile.path)+ }++ public func logout() {+ try? FileManager.default.removeItem(at: authFile)+ try? FileManager.default.removeItem(at: userFile)+ }++ public struct Credentials: Sendable {+ public let accessToken: String+ public let refreshToken: String+ public let userID: String+ }++ /// Current tokens. gogdl refreshes the access token when it has expired and saves the new pair,+ /// so this is the one place tokens come from. Never log or persist the result elsewhere.+ public func credentials() throws -> Credentials {+ let out = try capture(["auth"])+ protectAuthFile() // `auth` may have just written a refreshed pair+ guard let obj = try JSONSerialization.jsonObject(with: Data(out.utf8)) as? [String: Any],+ let access = obj["access_token"] as? String, let refresh = obj["refresh_token"] as? String else {+ throw HighballError.failed("GOG signed this Mac out. Connect your GOG account again.")+ }+ let user = (obj["user_id"] as? String) ?? (obj["user_id"] as? NSNumber)?.stringValue ?? ""+ return Credentials(accessToken: access, refreshToken: refresh, userID: user)+ }++ /// The account's name, which comet needs. Kept beside the tokens; no secret in it.+ public var username: String? {+ guard let data = try? Data(contentsOf: userFile),+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }+ return obj["username"] as? String+ }++ @discardableResult+ public func refreshUser() throws -> String? {+ let creds = try credentials()+ var request = URLRequest(url: URL(string: "https://embed.gog.com/userData.json")!)+ request.setValue("Bearer \(creds.accessToken)", forHTTPHeaderField: "Authorization")+ let data = try Self.fetch(request)+ guard let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any],+ let name = obj["username"] as? String else { return nil }+ try JSONSerialization.data(withJSONObject: ["username": name]).write(to: userFile, options: .atomic)+ return name+ }++ /// A GET for async callers: the wait holds no thread, so the library's parallel lookups+ /// leave the shared pool free.+ static func fetch(async request: URLRequest) async throws -> Data {+ var request = request+ request.timeoutInterval = 30+ let (data, response) = try await URLSession.shared.data(for: request)+ if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {+ throw HighballError.invalid("HTTP \(http.statusCode) for \(request.url?.absoluteString ?? "")")+ }+ return data+ }++ /// A blocking GET for callers already off the main thread (gogdl-side work, one request at a time).+ static func fetch(_ request: URLRequest) throws -> Data {+ var request = request+ request.timeoutInterval = 30+ let result = OSAllocatedUnfairLock<(data: Data, failure: String?)>(initialState: (Data(), nil))+ let address = request.url?.absoluteString ?? ""+ let done = DispatchSemaphore(value: 0)+ URLSession.shared.dataTask(with: request) { data, response, error in+ let failure: String? = if let error { error.localizedDescription }+ else if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { "HTTP \(http.statusCode) for \(address)" }+ else { nil }+ result.withLock { $0 = (data ?? Data(), failure) }+ done.signal()+ }.resume()+ done.wait()+ let (data, failure) = result.withLock { $0 }+ if let failure { throw HighballError.invalid(failure) }+ return data+ }+}diff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swiftindex 772f99c..3e8ae97 100644--- a/Sources/HighballKit/Library.swift+++ b/Sources/HighballKit/Library.swift@@ -7,7 +7,7 @@ import ImageIO// section; the bottle is a per-game property, never the navigation.public enum LibrarySource: String, Sendable, Codable {- case steam, epic, pin+ case steam, epic, gog, pin}/// A playable item in the unified library. Pure value: no Bottle, no GameDBEntry — the app@@ -16,16 +16,21 @@ public enum LibrarySource: String, Sendable, Codable {public struct LibraryItem: Identifiable, Sendable, Hashable {public let source: LibrarySource/// Stable identity, also the persistence key in library.json — never change its shape:- /// "steam:<appid>" | "epic:<app_name>" | "pin:<bottle>:<uuid>".+ /// "steam:<appid>" | "epic:<app_name>" | "gog:<product id>" | "pin:<bottle>:<uuid>".public let id: Stringpublic let title: String- /// Where it lives. nil only for an Epic title owned but not installed in any bottle.+ /// Where it lives. nil only for an Epic or GOG title owned but not installed in any bottle.public let bottleName: String?public let installed: Bool/// Steam for Mac has its native build installed (MacSteam); Play goes there first.public let installedOnMac: Boolpublic let steamAppID: Int?public let epicAppName: String?+ /// GOG's product id, for a game from the GOG account or a GOG install found on disk.+ public let gogID: String?+ /// The Steam app id GOG's database gives the same game: the compatibility database is matched+ /// by it, never Steam itself (`steamAppID` stays nil, so nothing treats the copy as a Steam one).+ public let gogSteamAppID: Int?public let pinID: UUID?public let artworkTall: URL?public let artworkWide: URL?@@ -36,11 +41,12 @@ public struct LibraryItem: Identifiable, Sendable, Hashable {public init(source: LibrarySource, id: String, title: String, bottleName: String?,installed: Bool, installedOnMac: Bool = false, steamAppID: Int? = nil, epicAppName: String? = nil,- pinID: UUID? = nil, artworkTall: URL? = nil, artworkWide: URL? = nil,+ gogID: String? = nil, gogSteamAppID: Int? = nil, pinID: UUID? = nil, artworkTall: URL? = nil, artworkWide: URL? = nil,otherBottles: [String] = [], sizeOnDisk: Int64 = 0, lastPlayed: Date? = nil) {self.source = source; self.id = id; self.title = title; self.bottleName = bottleNameself.installed = installed; self.installedOnMac = installedOnMacself.steamAppID = steamAppID; self.epicAppName = epicAppName+ self.gogID = gogID; self.gogSteamAppID = gogSteamAppIDself.pinID = pinID; self.artworkTall = artworkTall; self.artworkWide = artworkWideself.otherBottles = otherBottles; self.sizeOnDisk = sizeOnDisk; self.lastPlayed = lastPlayed}@@ -58,7 +64,7 @@ public struct LibraryItem: Identifiable, Sendable, Hashable {let others = (otherBottles.filter { $0 != bottle } + (installed ? [bottleName].compactMap { $0 } : [])).sorted()return LibraryItem(source: source, id: id, title: title, bottleName: bottle, installed: holds,installedOnMac: installedOnMac, steamAppID: steamAppID, epicAppName: epicAppName,- pinID: pinID, artworkTall: artworkTall, artworkWide: artworkWide,+ gogID: gogID, gogSteamAppID: gogSteamAppID, pinID: pinID, artworkTall: artworkTall, artworkWide: artworkWide,otherBottles: others, sizeOnDisk: holds ? 0 : sizeOnDisk, lastPlayed: lastPlayed)}}@@ -88,6 +94,53 @@ public enum LibraryIndex {return launcherNames.contains(pin.name.lowercased())}+ /// A program added by hand that is a GOG game the library now shows, in the same environment+ /// (a pin made before Connect GOG, or for a game an offline installer put there): it runs one+ /// of the game's own launch programs, or a variant beside the main one (Control_DX11.exe next+ /// to Control.exe). The GOG tile stands for it, so the pin's own tile is left out; the pin+ /// itself stays in the environment's settings. Anything else in the folder (a settings tool,+ /// a mod launcher) keeps its tile, and so does a pin with its own variables or graphics mode,+ /// which the GOG tile could not carry.+ public struct CoveredPin: Equatable, Sendable {+ public let pinItemID: String+ public let gogItemID: String+ /// The pin's arguments beyond the ones the GOG launch task already passes, for the GOG+ /// tile's launch arguments (Quake II RTX pinned with +set vid_rtx 0 keeps it).+ public let extraArguments: [String]+ }++ public static func gogCoveredPins(bottles: [Bottle], gogInstalledByBottle: [String: [GOGStore.InstalledGame]]) -> [CoveredPin] {+ var covered: [CoveredPin] = []+ for bottle in bottles {+ let games = gogInstalledByBottle[bottle.name] ?? []+ guard !games.isEmpty else { continue }+ for pin in bottle.settings.pins where !isLauncherPin(pin) && pin.environment.isEmpty && pin.renderer == nil {+ let file = pin.launchURL(driveC: bottle.driveC).standardizedFileURL+ guard let game = games.first(where: { gogLaunches($0, file) }) else { continue }+ var extra = pin.arguments+ let taskArguments = game.launchTask().flatMap { GOGStore.launch($0, in: game) }?.arguments ?? []+ for argument in taskArguments { if let i = extra.firstIndex(of: argument) { extra.remove(at: i) } }+ covered.append(CoveredPin(pinItemID: "pin:\(bottle.name):\(pin.id.uuidString)", gogItemID: "gog:\(game.id)",+ extraArguments: extra))+ }+ }+ return covered+ }++ /// Whether `file` is one of the game's launch programs, or a build variant beside the main one.+ /// Compared without case, as Windows paths are.+ static func gogLaunches(_ game: GOGStore.InstalledGame, _ file: URL) -> Bool {+ let path = file.path.lowercased()+ let programs = game.tasks.filter(\.isFile).compactMap { GOGStore.launch($0, in: game)?.executable.standardizedFileURL }+ if programs.contains(where: { $0.path.lowercased() == path }) { return true }+ guard let main = game.launchTask().flatMap({ GOGStore.launch($0, in: game) })?.executable.standardizedFileURL else { return false }+ // A build variant is the main name plus "_<something>" (Control_DX11, Control_DX12); a+ // name that merely starts the same (ControlConfig, ControlLauncher) is a tool.+ let stem = main.deletingPathExtension().lastPathComponent.lowercased()+ return file.deletingLastPathComponent().path.lowercased() == main.deletingLastPathComponent().path.lowercased()+ && file.deletingPathExtension().lastPathComponent.lowercased().hasPrefix(stem + "_")+ }+/// Builds the unified item list. Pure: takes exactly what AppState already holds./// Steam games dedup by appid across bottles — one tile per game, never per install;/// the primary bottle is where it was last played, then a ready copy, then name order.@@ -101,6 +154,8 @@ public enum LibraryIndex {macInstalled: [SteamGame] = [],epicOwned: [EpicStore.Game],epicInstalls: [String: String],+ gogGames: [GOGStore.Game] = [],+ gogInstalledByBottle: [String: [GOGStore.InstalledGame]] = [:],plays: [String: LibraryStore.PlayRecord] = [:],defaultBottle: String? = nil,pinExists: (Bottle, Pin) -> Bool = { _, _ in true }) -> [LibraryItem] {@@ -184,13 +239,42 @@ public enum LibraryIndex {lastPlayed: plays[id]?.lastPlayedAt))}+ // GOG: one tile per game. Installs are read from disk (GOGStore.installedGames), so a game+ // an offline installer put in an environment is the GOG game too. Several environments+ // holding it: the one it was last played in, then the default, then by name, like Steam.+ var gogCopies: [String: [(bottle: String, game: GOGStore.InstalledGame)]] = [:]+ for bottle in bottles {+ for game in gogInstalledByBottle[bottle.name] ?? [] { gogCopies[game.id, default: []].append((bottle.name, game)) }+ }+ var gogSeen = Set<String>()+ let gogKnown = Dictionary(gogGames.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })+ for id in gogGames.map(\.id) + gogCopies.keys.sorted() where !gogSeen.contains(id) {+ gogSeen.insert(id)+ let itemID = "gog:\(id)"+ let copies = gogCopies[id] ?? []+ let lastPlayedBottle = plays[itemID]?.bottle+ let primary = copies.min { a, b in+ if let lp = lastPlayedBottle, (a.bottle == lp) != (b.bottle == lp) { return a.bottle == lp }+ return before(a.bottle, b.bottle)+ }+ let meta = gogKnown[id]+ items.append(LibraryItem(+ source: .gog, id: itemID, title: meta?.title ?? primary?.game.title ?? id, bottleName: primary?.bottle,+ installed: primary != nil, gogID: id, gogSteamAppID: meta?.steamAppID,+ artworkTall: meta?.artworkTall, artworkWide: meta?.artworkWide,+ otherBottles: copies.map(\.bottle).filter { $0 != primary?.bottle }.sorted(),+ lastPlayed: plays[itemID]?.lastPlayedAt))+ }+// Custom pins (dropped exes, preinstalled games), no artwork. Installed when the program's// file is there: one on a drive that is unplugged, or deleted since, is not (highball#269,// the Installed filter kept listing them). `pinExists` is the app's check of the disk;// without one every pin counts, so the index stays testable without a filesystem.+ let coveredPins = Set(gogCoveredPins(bottles: bottles, gogInstalledByBottle: gogInstalledByBottle).map(\.pinItemID))for bottle in bottles {for pin in bottle.settings.pins where !isLauncherPin(pin) {let id = "pin:\(bottle.name):\(pin.id.uuidString)"+ if coveredPins.contains(id) { continue } // its GOG tile stands for ititems.append(LibraryItem(source: .pin, id: id, title: pin.name, bottleName: bottle.name,installed: pinExists(bottle, pin), pinID: pin.id,diff --git a/Sources/HighballKit/PlayLink.swift b/Sources/HighballKit/PlayLink.swiftindex 38cc626..5ea181f 100644--- a/Sources/HighballKit/PlayLink.swift+++ b/Sources/HighballKit/PlayLink.swift@@ -9,6 +9,7 @@ public enum PlayLink {public enum Target: Equatable, Sendable {case steam(appid: Int)case epic(appName: String)+ case gog(id: String)case pin(bottle: String, id: UUID)/// A launcher (Steam, Epic, …) by recipe id: `highball://open/launcher/steam`. Opens it,/// installing it first if needed (issue #53: Mac icons for launchers too).@@ -20,6 +21,7 @@ public enum PlayLink {switch self {case let .steam(appid): return "steam:\(appid)"case let .epic(name): return "epic:\(name)"+ case let .gog(id): return "gog:\(id)"case let .pin(bottle, id): return "pin:\(bottle):\(id.uuidString)"case let .launcher(id): return "launcher:\(id)"}@@ -32,6 +34,7 @@ public enum PlayLink {}/// Parses `highball://play/steam/620?t=<token>`, `highball://play/epic/<name>?t=...`,+ /// `highball://play/gog/<product id>?t=...`,/// `highball://play/pin/<bottle>/<uuid>?t=...` and `highball://open/launcher/<id>?t=...`./// Anything else is nil: no other action exists behind the scheme.public static func parse(_ url: URL) -> Request? {@@ -51,6 +54,9 @@ public enum PlayLink {case "epic":guard parts.count == 2, !parts[1].isEmpty else { return nil }return Request(target: .epic(appName: parts[1]), token: token)+ case "gog":+ guard parts.count == 2, !parts[1].isEmpty, parts[1].allSatisfy(\.isNumber) else { return nil }+ return Request(target: .gog(id: parts[1]), token: token)case "pin":guard parts.count == 3, !parts[1].isEmpty, let id = UUID(uuidString: parts[2]) else { return nil }return Request(target: .pin(bottle: parts[1], id: id), token: token)@@ -65,6 +71,7 @@ public enum PlayLink {switch target {case let .steam(appid): c.path = "/steam/\(appid)"case let .epic(name): c.path = "/epic/\(name)"+ case let .gog(id): c.path = "/gog/\(id)"case let .pin(bottle, id): c.path = "/pin/\(bottle)/\(id.uuidString)"case let .launcher(id): c.host = "open"; c.path = "/launcher/\(id)"}@@ -75,6 +82,7 @@ public enum PlayLink {public static func target(for item: LibraryItem) -> Target? {if let appid = item.steamAppID { return .steam(appid: appid) }if let name = item.epicAppName { return .epic(appName: name) }+ if let id = item.gogID { return .gog(id: id) }if let id = item.pinID, let bottle = item.bottleName { return .pin(bottle: bottle, id: id) }return nil}diff --git a/Sources/HighballKit/SteamLibrary.swift b/Sources/HighballKit/SteamLibrary.swiftindex 6b9b7a5..1b10537 100644--- a/Sources/HighballKit/SteamLibrary.swift+++ b/Sources/HighballKit/SteamLibrary.swift@@ -334,10 +334,10 @@ public struct GameDB: Sendable {return String(kept).split(separator: " ").joined(separator: " ")}- /// The row for a library item, whatever store it came from: the Steam id first, then the- /// Epic app name, then the normalized title. Nil for a program the database does not know.+ /// The row for a library item, whatever store it came from: the Steam id first (for a GOG copy,+ /// the Steam id GOG's database gives it), then the Epic app name, then the normalized title. Nil for a program the database does not know.public func entry(for item: LibraryItem) -> GameDBEntry? {- if let appid = item.steamAppID, let e = byAppID[appid] { return e }+ if let appid = item.steamAppID ?? item.gogSteamAppID, let e = byAppID[appid] { return e }if let name = item.epicAppName, let e = byEpicAppName[name] { return e }let normalized = Self.normalizedTitle(item.title)if let e = byTitle[normalized] { return e }diff --git a/Sources/HighballKit/Uninstall.swift b/Sources/HighballKit/Uninstall.swiftindex 22d3316..8329970 100644--- a/Sources/HighballKit/Uninstall.swift+++ b/Sources/HighballKit/Uninstall.swift@@ -10,7 +10,9 @@ import Foundation/// The rule that shapes this: a store's library is the store's to keep. Deleting a Steam game's/// folder from underneath the client leaves Steam believing it is installed, and the next launch/// repairs or redownloads it, so a Steam game is handed to Steam's own uninstall dialog and-/// Highball does not touch the files. The same goes for Epic through legendary.+/// Highball does not touch the files. The same goes for Epic through legendary. GOG games have no+/// client keeping a library: their files are the record (GOGStore), so Highball removes them+/// itself, running the game's own uninstaller first when an offline installer left one.public enum Uninstall {public enum Route: Equatable, Sendable {/// Hand it to the running Steam client (`steam://uninstall/<appid>`), which asks its own@@ -18,6 +20,8 @@ public enum Uninstall {case steam(appID: Int)/// Legendary owns Epic installs, so it does the removing.case epic(appName: String)+ /// Highball removes the game's folder, after its unins000.exe when it has one.+ case gog(id: String)/// Wine's Add/Remove Programs, for a program that came with its own uninstaller.case windowsUninstaller/// Nothing can be run for it. The reason is shown to the person, who then decides.@@ -38,6 +42,11 @@ public enum Uninstall {return .none(reason: "Highball does not know this game's Epic id, so the Epic tools cannot be asked to remove it.")}return .epic(appName: name)+ case .gog:+ guard let id = item.gogID, item.installed else {+ return .none(reason: "This GOG game is not installed in an environment.")+ }+ return .gog(id: id)case .pin:return .windowsUninstaller}@@ -53,6 +62,8 @@ public enum Uninstall {return "Steam does the uninstalling and asks you to confirm in its own window, so its library stays right.\(size)"case .epic:return "The Epic tools do the uninstalling, so their library stays right.\(size)"+ case .gog:+ return "Highball deletes the game's folder from this environment. Saves synced to GOG's cloud stay there, and the game stays in your GOG library to install again.\(size)"case .windowsUninstaller:return "Highball opens Windows' Add or Remove Programs in this environment, where you pick it from the list. A game with no uninstaller of its own will not be in that list, and then the only way to remove it is to delete the environment."case let .none(reason):diff --git a/Sources/highball/main.swift b/Sources/highball/main.swiftindex f36254b..7c9c7d1 100644--- a/Sources/highball/main.swift+++ b/Sources/highball/main.swift@@ -7,7 +7,7 @@ struct Highball: AsyncParsableCommand {static let configuration = CommandConfiguration(commandName: "highball",abstract: "Highball — run Windows games on Apple Silicon. Free, open, engine-agnostic.",- subcommands: [Config.self, Engine.self, Bottle.self, Run.self, PinCommand.self, Recipe.self, Tricks.self, Env.self, Epic.self, Report.self, BugReportCommand.self, Verify.self],+ subcommands: [Config.self, Engine.self, Bottle.self, Run.self, PinCommand.self, Recipe.self, Tricks.self, Env.self, Epic.self, GOG.self, Report.self, BugReportCommand.self, Verify.self],defaultSubcommand: nil)}@@ -735,6 +735,157 @@ struct Epic: AsyncParsableCommand {}}+struct GOG: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "gog",+ abstract: "Install and play GOG games through gogdl, with comet for achievements and gogdl for cloud saves (GOG Galaxy cannot sign in under Wine).",+ subcommands: [Login.self, Auth.self, List.self, Install.self, Launch.self])++ struct Login: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Print the GOG sign-in URL; paste the address it ends on into 'highball gog auth'.")+ func run() async throws {+ try await GOGStore().ensureInstalled()+ print("1. Open: \(GOGStore.loginURL.absoluteString)")+ print("2. Sign in. GOG ends on a mostly blank embed.gog.com page: copy its whole address.")+ print("3. Run: highball gog auth, and paste the address when asked.")+ }+ }++ struct Auth: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Finish sign-in with the address (or the code) the login page ended on; asks for it when not given, which keeps it out of shell history.")+ @Argument var pasted: String?+ func run() async throws {+ let store = GOGStore()+ try await store.ensureInstalled()+ var text = pasted+ if text == nil {+ print("Paste the address GOG's sign-in page ended on: ", terminator: "")+ text = readLine()+ }+ let reading = GOGStore.readSignIn(text ?? "")+ guard case let .code(code) = reading else {+ switch reading {+ case .signInPage: fail("that is the sign-in page itself; log in on it, then paste the address of the page it ends on")+ case .noCode: fail("that GOG address has no code; paste the address shown right after you log in")+ default: fail("no code in that; paste the whole embed.gog.com address")+ }+ }+ try store.authenticate(code: code)+ print("signed in\(store.username.map { " as \($0)" } ?? "")")+ }+ }++ struct List: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "List the account's games, and where each installed one lives.")+ func run() async throws {+ let store = GOGStore()+ try await store.ensureInstalled()+ guard store.isAuthenticated else { fail("not signed in — run 'highball gog login' first") }+ var installed: [String: String] = [:]+ for b in (try? BottleStore().list()) ?? [] {+ for g in GOGStore.installedGames(driveC: b.driveC) { installed[g.id] = b.name }+ }+ for g in try await store.ownedGames() {+ let mark = installed[g.id].map { "[installed: \($0)] " } ?? ""+ print("\(mark)\(g.id)\t\(g.title)")+ }+ }+ }++ struct Install: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Download a game's Windows build into a bottle (drive_c/Games) and run its GOG setup.")+ @Argument var bottle: String+ @Argument(help: "Product id from 'highball gog list'.") var id: String+ func run() async throws {+ let store = GOGStore()+ try await store.ensureInstalled()+ guard store.isAuthenticated else { fail("not signed in — run 'highball gog login' first") }+ let b = try BottleStore().get(bottle)+ let info = try store.info(id)+ let language = GOGStore.language(for: info.languages)+ if !info.dependencies.isEmpty { _ = try? store.downloadRedists(info.dependencies) { print($0) } }+ let status = try store.install(id, into: b, language: language) { line in+ if !line.contains("[PROGRESS]") || line.contains("= Progress:") { print(line) }+ }+ guard status == 0, store.downloadCompleted(id) else { fail("gogdl download did not finish (exit \(status)); run the same command to resume") }+ guard let game = GOGStore.installedGames(driveC: b.driveC).first(where: { $0.id == id }) else { fail("downloaded, but no goggame-\(id).info turned up in \(b.name)") }+ store.keepManifest(for: game)+ let eng = try EngineStore().engine(b.settings.engineID)+ let runner = WineRunner(engine: eng, bottle: b)+ try await store.runSetup(game, language: language, runner: runner,+ onStep: { n, total, label in print("setup \(n)/\(total): \(label)") },+ onFailure: { label, code in print("setup: \(label) ended with code \(code); carrying on") })+ print("installed \(game.title) into \(b.name): \(game.folder.path)")+ }+ }++ struct Launch: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Launch an installed GOG game in a bottle, with comet and cloud saves unless turned off.")+ @Argument var bottle: String+ @Argument var id: String+ @Option var renderer: HighballKit.Renderer?+ @Flag(help: "Run without comet (no achievements).") var noComet = false+ @Flag(help: "Skip the cloud-save sync before and after.") var noSaves = false+ func run() async throws {+ let store = GOGStore()+ let b = try BottleStore().get(bottle)+ guard let game = GOGStore.installedGames(driveC: b.driveC).first(where: { $0.id == id }),+ let task = game.launchTask(choice: GOGSettings.load(store).launchChoice[id]),+ let launch = GOGStore.launch(task, in: game) else { fail("GOG game \(id) is not installed in \(b.name)") }+ let eng = try EngineStore().engine(b.settings.engineID)+ let runner = WineRunner(engine: eng, bottle: b)+ let saves = GOGSaves(store: store)+ let settings = GOGSettings.load(store) // the game page's choices hold here too+ var folders: [(GOGSaves.Location, URL)] = []+ if !noSaves, !settings.cloudSavesOff.contains(id), store.isAuthenticated, let client = saves.clientID(for: game), let locations = try? saves.locations(clientID: client) {+ folders = locations.compactMap { l in GOGSaves.resolve(l.template, game: game, driveC: b.driveC).map { (l, $0) } }+ for (l, f) in folders { print("saves \(l.name) down: \(Self.describe(saves.sync(game, location: l, folder: f, direction: .download)))") }+ }+ var comet: Process?+ if !noComet, settings.cometOff[id] == nil, store.isAuthenticated {+ if let tools = try? await store.ensureComet() { _ = try? await GOGComet.installService(from: tools.service, runner: runner) }+ let log = HighballPaths().logs.appending(path: "comet-\(id).log")+ comet = try? GOGComet(store: store).start(log: log)+ print(comet != nil ? "comet running (log \(log.path))" : "comet did not start; playing without achievements")+ }+ let result: LaunchResult+ do {+ result = try await runner.start(launch.executable, arguments: launch.arguments, renderer: renderer,+ workingDirectory: launch.workingDirectory)+ } catch {+ GOGComet(store: store).stop(comet) // it would hold port 9977 and its copy of the tokens+ throw error+ }+ print("exit=\(result.exitStatus) — log: \(result.log.path)")+ // A launcher task hands over to another program in the folder and exits: the session+ // lasts while any of them runs in this bottle, so comet and the save upload wait for+ // the game itself.+ let markers = game.sessionMarkers(launching: launch.executable)+ var handedOver = false+ for _ in 0..<5 { // the program it hands to can take a moment to appear+ if !SessionWatch.pids(ofPrefix: b.url, markers: markers).isEmpty { handedOver = true; break }+ try await Task.sleep(for: .seconds(2))+ }+ if handedOver {+ print("the game is still running (handed over from \(launch.executable.lastPathComponent)); waiting for it to close")+ while !SessionWatch.pids(ofPrefix: b.url, markers: markers).isEmpty {+ try await Task.sleep(for: .seconds(2))+ }+ }+ GOGComet(store: store).stop(comet)+ for (l, f) in folders { print("saves \(l.name) up: \(Self.describe(saves.sync(game, location: l, folder: f, direction: .upload)))") }+ }++ static func describe(_ outcome: GOGSaves.Outcome) -> String {+ switch outcome {+ case .synced: return "synced"+ case .conflict: return "both copies changed, nothing moved; play from the app to choose which to keep"+ case .failed(let why): return "failed (\(why))"+ }+ }+ }+}+struct BugReportCommand: AsyncParsableCommand {static let configuration = CommandConfiguration(commandName: "bugreport", abstract: "Print a pre-filled GitHub bug-report URL (system info + newest log tail).")func run() async throws {diff --git a/Tests/HighballKitTests/GOGStoreTests.swift b/Tests/HighballKitTests/GOGStoreTests.swiftnew file mode 100644index 0000000..248d3c2--- /dev/null+++ b/Tests/HighballKitTests/GOGStoreTests.swift@@ -0,0 +1,380 @@+import XCTest+@testable import HighballKit++final class GOGStoreTests: XCTestCase {+ /// The temporary folder is reached as /var and as /private/var; compare one spelling.+ private func norm(_ url: URL?) -> String? {+ url.map { $0.path.hasPrefix("/private/var/") ? String($0.path.dropFirst("/private".count)) : $0.path }+ }++ /// GOG's sign-in ends on embed.gog.com/on_login_success; people paste the whole address, the+ /// address without its scheme, or the code alone.+ func testAuthorizationCodeFromWhatPeoplePaste() {+ XCTAssertEqual(GOGStore.authorizationCode(from: "https://embed.gog.com/on_login_success?origin=client&code=AbC-123_x"), "AbC-123_x")+ XCTAssertEqual(GOGStore.authorizationCode(from: " embed.gog.com/on_login_success?origin=client&code=AbC12345 \n"), "AbC12345")+ XCTAssertEqual(GOGStore.authorizationCode(from: "AbC123def"), "AbC123def")+ XCTAssertNil(GOGStore.authorizationCode(from: "two words"))+ XCTAssertNil(GOGStore.authorizationCode(from: ""))+ }++ /// The sheet names the usual wrong pastes, and a code is only taken from a gog.com address.+ func testWrongPastesAreNamedAndNeverSent() {+ XCTAssertEqual(GOGStore.readSignIn(""), .empty)+ XCTAssertEqual(GOGStore.readSignIn(GOGStore.loginURL.absoluteString), .signInPage, "copied before logging in")+ XCTAssertEqual(GOGStore.readSignIn("https://login.gog.com/login?code=x"), .signInPage)+ XCTAssertEqual(GOGStore.readSignIn("https://embed.gog.com/on_login_success?origin=client"), .noCode)+ XCTAssertEqual(GOGStore.readSignIn("https://www.gog.com/en/account"), .noCode)+ XCTAssertEqual(GOGStore.readSignIn("https://example.com/on_login_success?code=AbC12345"), .notGOG)+ XCTAssertEqual(GOGStore.readSignIn("https://embed.gog.com.example.com/?code=AbC12345"), .notGOG)+ XCTAssertEqual(GOGStore.readSignIn("https://notgog.com/?code=AbC12345"), .notGOG)+ XCTAssertEqual(GOGStore.readSignIn("file:///etc/?code=AbC12345"), .notGOG)+ XCTAssertEqual(GOGStore.readSignIn("https://[email protected]/?code=AbC12345"), .notGOG)+ XCTAssertEqual(GOGStore.readSignIn("https://example.com%2F.gog.com/?code=AbC12345"), .notGOG, "an encoded slash is not a gog.com host")+ XCTAssertEqual(GOGStore.readSignIn("https://embed.gog.com/on_login_success?xcode=AbC12345"), .noCode)+ XCTAssertEqual(GOGStore.readSignIn("short"), .notGOG)+ }++ /// Token values never reach an error message or a log line, however gogdl prints them.+ func testGogdlOutputIsRedacted() {+ let out = GOGStore.redacted(#"{"access_token": "aaa111", "refresh_token":"bbb222", "user_id": "42"} 'session_id': 'ccc333' code=ddd444&x=1 Authorization: Bearer eee555 auth --code fff666"#)+ for secret in ["aaa111", "bbb222", "ccc333", "ddd444", "eee555", "fff666"] { XCTAssertFalse(out.contains(secret), secret) }+ XCTAssertTrue(out.contains(#""user_id": "42""#), "the rest stays readable")+ let progress = "[PROGRESS] INFO: = Progress: 0.00 137861/45061146188, Running for: 00:00:02"+ XCTAssertEqual(GOGStore.redacted(progress), progress)+ }++ /// The folder with the tokens is this user's only, even when it already existed.+ func testGOGFolderIsPrivate() throws {+ let home = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: home) }+ let store = GOGStore(paths: HighballPaths(home: home))+ try FileManager.default.createDirectory(at: store.dir, withIntermediateDirectories: true)+ store.secureDirectory()+ let mode = try FileManager.default.attributesOfItem(atPath: store.dir.path)[.posixPermissions] as? Int+ XCTAssertEqual(mode, 0o700)+ }++ func testLoginURLIsGalaxysPublicClient() {+ let c = URLComponents(url: GOGStore.loginURL, resolvingAgainstBaseURL: false)!+ XCTAssertEqual(c.queryItems?.first { $0.name == "client_id" }?.value, "46899977096215655")+ XCTAssertEqual(c.queryItems?.first { $0.name == "redirect_uri" }?.value, "https://embed.gog.com/on_login_success?origin=client")+ XCTAssertEqual(c.queryItems?.first { $0.name == "response_type" }?.value, "code")+ }++ /// gogdl's progress lines as a Control download printed them (2026-10-28).+ func testProgressLines() {+ let p = GOGStore.progress(inGogdlLine: "[PROGRESS] INFO: = Progress: 0.00 137861/45061146188, Running for: 00:00:02, ETA: 271:03:22")+ XCTAssertEqual(p?.written, 137861)+ XCTAssertEqual(p?.total, 45061146188)+ for other in ["[PROGRESS] INFO: = Downloaded: 27.50 MiB, Written: 0.00 MiB",+ "[PROGRESS] INFO: + Download\t- 27.50 MiB/s (raw) / 64.99 MiB/s (decompressed)",+ "[V2] INFO: Initialized V2 Download Manager"] {+ XCTAssertNil(GOGStore.progress(inGogdlLine: other), other)+ }+ }++ func testInstallFailuresBecomeSentences() {+ XCTAssertEqual(GOGStore.installFailure("[TASK_EXECUTOR] ERROR: Unable to proceed, Not enough disk space"),+ "This Mac doesn't have enough free space for the game. Free some space, then press Install again.")+ XCTAssertNotNil(GOGStore.installFailure("[CLI] ERROR: Game doesn't support content system api, unable to proceed using platform windows"))+ XCTAssertEqual(GOGStore.installFailure("[API] ERROR: Failed to get manifest"), "GOG's downloader stopped with this message. Failed to get manifest")+ XCTAssertNil(GOGStore.installFailure("[PROGRESS] INFO: = Progress: 12.00 1/2, Running for: 00:00:01, ETA: 00:00:01"))+ }++ func testDownloadAndUpdateArguments() {+ let download = GOGStore.downloadArguments(id: "1957528513", into: "/c/Games", support: "/s", language: "en-US", update: false)+ XCTAssertEqual(Array(download.prefix(2)), ["download", "1957528513"])+ XCTAssertEqual(download[download.firstIndex(of: "--path")! + 1], "/c/Games")+ XCTAssertEqual(download[download.firstIndex(of: "--platform")! + 1], "windows")+ XCTAssertTrue(download.contains("--with-dlcs"))+ let update = GOGStore.downloadArguments(id: "1957528513", into: "/c/Games/Ghostrunner", support: "/s", language: "en-US", update: true)+ XCTAssertEqual(update.first, "update")+ }++ func testLanguageFollowsTheMac() {+ XCTAssertEqual(GOGStore.language(for: ["en-US", "fr-FR", "de-DE"], preferred: ["fr-CA", "en-US"]), "fr-FR")+ XCTAssertEqual(GOGStore.language(for: ["en-US", "de-DE"], preferred: ["ja-JP"]), "en-US")+ XCTAssertEqual(GOGStore.language(for: ["de-DE"], preferred: ["ja-JP"]), "de-DE")+ XCTAssertEqual(GOGStore.language(for: [], preferred: ["ja-JP"]), "en-US")+ }++ // MARK: gamesdb++ /// A trimmed gamesdb release: Steam id taken from GOG's own release list, so the cover is+ /// Steam's 600×900 capsule and the compatibility row matches by Steam id.+ func testReleaseUsesTheSteamIDGOGGives() throws {+ let json = """+ {"type":"game","title":{"*":"Ghostrunner "},"game":{"visible_in_library":true,+ "releases":[{"platform_id":"gog","external_id":"1957528513"},{"platform_id":"steam","external_id":"1139900"}],+ "vertical_cover":{"url_format":"https://images.gog.com/abc{formatter}.{ext}?namespace=gamesdb"},+ "background":{"url_format":"https://images.gog.com/bg{formatter}.{ext}?namespace=gamesdb"}}}+ """+ let game = try XCTUnwrap(GOGStore.parseRelease(id: "1957528513", data: Data(json.utf8)))+ XCTAssertEqual(game.title, "Ghostrunner")+ XCTAssertEqual(game.steamAppID, 1139900)+ XCTAssertEqual(game.artworkTall?.absoluteString, "https://cdn.akamai.steamstatic.com/steam/apps/1139900/library_600x900.jpg")+ XCTAssertEqual(game.gogVerticalCover?.absoluteString, "https://images.gog.com/abc.jpg?namespace=gamesdb")+ }++ func testReleaseWithoutSteamFallsBackToGOGArt() throws {+ let json = """+ {"type":"game","title":{"*":"Quake II RTX"},"game":{"releases":[],+ "vertical_cover":{"url_format":"https://images.gog.com/q2{formatter}.{ext}?namespace=gamesdb"}}}+ """+ let game = try XCTUnwrap(GOGStore.parseRelease(id: "1825786806", data: Data(json.utf8)))+ XCTAssertNil(game.steamAppID)+ XCTAssertEqual(game.artworkTall?.absoluteString, "https://images.gog.com/q2.jpg?namespace=gamesdb")+ }++ func testDLCAndHiddenReleasesStayOutOfTheLibrary() {+ let dlc = #"{"type":"dlc","title":{"*":"Ghostrunner - Katana Pack"},"game":{"visible_in_library":true}}"#+ let hidden = #"{"type":"game","title":{"*":"Hidden"},"game":{"visible_in_library":false}}"#+ XCTAssertNil(GOGStore.parseRelease(id: "1", data: Data(dlc.utf8)))+ XCTAssertNil(GOGStore.parseRelease(id: "2", data: Data(hidden.utf8)))+ }++ // MARK: Installs on disk++ private func makeGame(_ root: URL, folder: String, infos: [String: String]) throws -> URL {+ let dir = root.appending(path: folder, directoryHint: .isDirectory)+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ for (name, json) in infos { try json.write(to: dir.appending(path: name), atomically: true, encoding: .utf8) }+ return dir+ }++ /// Ghostrunner as gogdl installed it, with its DLC's info file beside the game's, and Control+ /// from an offline installer in GOG's default folder: both found, with the DLC attached.+ func testInstalledGamesComeFromInfoFiles() throws {+ let driveC = FileManager.default.temporaryDirectory.appending(path: "gog-\(UUID().uuidString)/drive_c")+ defer { try? FileManager.default.removeItem(at: driveC.deletingLastPathComponent()) }+ let gr = try makeGame(driveC.appending(path: "Games"), folder: "Ghostrunner", infos: [+ "goggame-1957528513.info": #"{"gameId":"1957528513","rootGameId":"1957528513","name":"Ghostrunner","buildId":"555","clientId":"533","playTasks":[{"category":"game","isPrimary":true,"name":"Ghostrunner","path":"Ghostrunner\\Binaries\\Win64\\Ghostrunner-Win64-Shipping.exe","arguments":"-GOG","type":"FileTask"},{"category":"game","name":"Ghostrunner DX12","path":"Ghostrunner/Binaries/Win64/Ghostrunner-Win64-Shipping.exe","arguments":"-GOG -dx12","type":"FileTask"}]}"#,+ "goggame-2009792833.info": #"{"gameId":"2009792833","rootGameId":"1957528513","name":"Ghostrunner - Katana Pack"}"#,+ ])+ try FileManager.default.createDirectory(at: gr.appending(path: "Ghostrunner/Binaries/Win64"), withIntermediateDirectories: true)+ _ = try makeGame(driveC.appending(path: "GOG Games"), folder: "Control", infos: [+ "goggame-2049187585.info": #"{"gameId":"2049187585","rootGameId":"2049187585","name":"Control Ultimate Edition","buildId":"592","playTasks":[{"isPrimary":true,"name":"Control","path":"Control.exe","category":"launcher","type":"FileTask"},{"name":"Support","type":"URLTask","path":"","category":"document","url":"http://www.gog.com/support"}]}"#,+ ])+ // A download still running is not an install yet.+ let partial = try makeGame(driveC.appending(path: "Games"), folder: "Half", infos: ["goggame-1.info": #"{"gameId":"1","name":"Half"}"#])+ try "".write(to: partial.appending(path: ".gogdl-resume"), atomically: true, encoding: .utf8)++ let games = GOGStore.installedGames(driveC: driveC).sorted { $0.title < $1.title }+ XCTAssertEqual(games.map(\.id), ["2049187585", "1957528513"])+ let ghostrunner = games[1]+ XCTAssertEqual(ghostrunner.dlcIDs, ["2009792833"])+ XCTAssertEqual(ghostrunner.clientID, "533")+ XCTAssertEqual(ghostrunner.launchChoices.count, 2, "two visible game tasks: a choice on the page")++ let primary = try XCTUnwrap(ghostrunner.launchTask())+ let launch = try XCTUnwrap(GOGStore.launch(primary, in: ghostrunner))+ XCTAssertEqual(norm(launch.executable), norm(gr.appending(path: "Ghostrunner/Binaries/Win64/Ghostrunner-Win64-Shipping.exe")),+ "Windows separators become Unix ones")+ XCTAssertEqual(launch.arguments, ["-GOG"])+ XCTAssertEqual(norm(launch.workingDirectory), norm(gr))+ XCTAssertEqual(ghostrunner.launchTask(choice: 1)?.arguments, "-GOG -dx12")++ // Control.exe is a launcher that hands over to Control_DX11.exe and exits: the session+ // watches every program in the folder, not the redist installers or the uninstaller.+ let controlFolder = driveC.appending(path: "GOG Games/Control")+ for exe in ["Control.exe", "Control_DX11.exe", "unins000.exe", "__redist/DirectX/DXSETUP.exe", "_CommonRedist/vcredist_x64.exe"] {+ let file = controlFolder.appending(path: exe)+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)+ FileManager.default.createFile(atPath: file.path, contents: Data())+ }+ XCTAssertEqual(games[0].sessionMarkers(launching: controlFolder.appending(path: "Control.exe")), ["Control.exe", "Control_DX11.exe"])+ XCTAssertTrue(SessionWatch.isAlive(markers: games[0].sessionMarkers(launching: controlFolder.appending(path: "Control.exe")), ps: "77480 Control_DX11.exe \n"))++ let control = games[0]+ XCTAssertTrue(control.launchChoices.isEmpty, "a manual is not a launch option")+ XCTAssertEqual(control.launchTask()?.path, "Control.exe")+ }++ /// Info files are written on Windows, where case does not matter; the Mac volume may care.+ func testPathsAreFoundWhateverTheirCase() throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "gogcase-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: root) }+ try FileManager.default.createDirectory(at: root.appending(path: "Bin"), withIntermediateDirectories: true)+ try "".write(to: root.appending(path: "Bin/Game.exe"), atomically: true, encoding: .utf8)+ // On a case-insensitive volume the spelling as written already opens; on a case-sensitive+ // one the lookup finds the file's own spelling. Either way the file is there.+ XCTAssertTrue(FileManager.default.fileExists(atPath: GOGStore.resolve(#"bin\GAME.EXE"#, in: root).path))+ }++ // MARK: Cloud saves++ func testSaveLocationsFromRemoteConfig() {+ let json = #"{"content":{"Windows":{"cloudStorage":{"enabled":true,"locations":[{"name":"saves","location":"<?SAVED_GAMES?>/Remedy/Control"}]}}}}"#+ XCTAssertEqual(GOGSaves.parseLocations(Data(json.utf8), clientID: "c"), [.init(name: "saves", template: "<?SAVED_GAMES?>/Remedy/Control")])+ let empty = #"{"content":{"Windows":{"cloudStorage":{"enabled":true,"locations":[]}}}}"#+ XCTAssertEqual(GOGSaves.parseLocations(Data(empty.utf8), clientID: "533")?.first?.name, "__default",+ "an empty list is the SDK's own storage folder")+ XCTAssertEqual(GOGSaves.parseLocations(Data(empty.utf8), clientID: "533")?.first?.template,+ "<?APPLICATION_DATA_LOCAL?>/GOG.com/Galaxy/Applications/533/Storage/Shared/Files")+ let off = #"{"content":{"Windows":{"cloudStorage":{"enabled":false}}}}"#+ XCTAssertNil(GOGSaves.parseLocations(Data(off.utf8), clientID: "c"))+ }++ func testClientIDFromCompressedBuildManifest() throws {+ let json = Data(#"{"baseProductId":"2049187585","clientId":"53538800219319237"}"#.utf8)+ // A v2 manifest as GOG serves it: zlib header, raw DEFLATE (checksum left off; not read).+ let zlib = Data([0x78, 0x9c]) + (try (json as NSData).compressed(using: .zlib) as Data)+ XCTAssertEqual(GOGSaves.clientID(inManifest: zlib), "53538800219319237")+ XCTAssertEqual(GOGSaves.clientID(inManifest: json), "53538800219319237", "plain JSON reads too")+ XCTAssertNil(GOGSaves.clientID(inManifest: Data([0x78, 0x9c, 0x00])))+ }++ func testSaveFoldersResolveInsideTheEnvironment() throws {+ let driveC = FileManager.default.temporaryDirectory.appending(path: "gogsaves-\(UUID().uuidString)/drive_c")+ defer { try? FileManager.default.removeItem(at: driveC.deletingLastPathComponent()) }+ try FileManager.default.createDirectory(at: driveC.appending(path: "users/player"), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: driveC.appending(path: "users/Public"), withIntermediateDirectories: true)+ let game = GOGStore.InstalledGame(id: "1", title: "G", folder: driveC.appending(path: "Games/G"), buildID: nil, clientID: nil, dlcIDs: [], tasks: [])+ let user = driveC.appending(path: "users/player")+ func path(_ template: String) -> String? { norm(GOGSaves.resolve(template, game: game, driveC: driveC, userName: "player")) }+ XCTAssertEqual(path("<?SAVED_GAMES?>/Remedy/Control"),+ norm(user.appending(path: "Saved Games/Remedy/Control")))+ XCTAssertEqual(path(#"<?APPLICATION_DATA_LOCAL_LOW?>\Studio\Game"#),+ norm(user.appending(path: "AppData/LocalLow/Studio/Game")))+ XCTAssertEqual(GOGSaves.resolve("<?INSTALL?>/saves", game: game, driveC: driveC)?.path, game.folder.appending(path: "saves").path)+ XCTAssertNil(GOGSaves.resolve("<?APPLICATION_SUPPORT?>/x", game: game, driveC: driveC), "a Mac-native variable has no Windows folder")+ XCTAssertNil(GOGSaves.resolve("<?DOCUMENTS?>/%USERNAME%/x", game: game, driveC: driveC), "an unknown Windows variable is not guessed")+ XCTAssertNil(GOGSaves.resolve("<?DOCUMENTS?>", game: game, driveC: driveC), "a whole known folder is never synced")+ XCTAssertNil(GOGSaves.resolve("<?INSTALL?>/", game: game, driveC: driveC))+ XCTAssertNil(GOGSaves.resolve("<?INSTALL?>/../..", game: game, driveC: driveC), "nor one outside it")+ }++ /// gogdl's conflict line, and the flags each direction passes (gogdl/saves.py).+ func testSaveSyncArgumentsAndConflictLine() {+ let location = GOGSaves.Location(name: "saves", template: "")+ let down = GOGSaves.arguments(folder: URL(fileURLWithPath: "/s"), id: "1", location: location, timestamp: "0", direction: .download)+ XCTAssertEqual(down, ["save-sync", "/s", "1", "--os", "windows", "--ts", "0", "--name", "saves", "--skip-upload"])+ XCTAssertEqual(GOGSaves.arguments(folder: URL(fileURLWithPath: "/s"), id: "1", location: location, timestamp: "5", direction: .upload).last, "--skip-download")+ XCTAssertEqual(GOGSaves.arguments(folder: URL(fileURLWithPath: "/s"), id: "1", location: location, timestamp: "5", direction: .forceDownload).last, "--force-download")+ XCTAssertTrue(GOGSaves.isConflict("[SAVES] WARNING: Files in conflict force downloading or uploading of files"))+ XCTAssertFalse(GOGSaves.isConflict("[SAVES] INFO: Downloading 3 files"))+ }++ /// The new timestamp is written without a newline, so it reaches the shared pipe glued to the+ /// next log line (gogdl/saves.py), and still has to be kept.+ func testSaveTimestampIsReadOffAGluedLine() throws {+ let glued = try XCTUnwrap(GOGSaves.timestamp(in: "1793193913.871504[SAVES] INFO: Done"))+ XCTAssertEqual(glued.0, "1793193913.871504")+ XCTAssertEqual(glued.1, "[SAVES] INFO: Done")+ XCTAssertEqual(GOGSaves.timestamp(in: "1793193913.871504")?.1, "")+ XCTAssertNil(GOGSaves.timestamp(in: "0"), "the unchanged 0 is not a sync")+ XCTAssertNil(GOGSaves.timestamp(in: "[SAVES] INFO: Downloading 3 files"))+ }++ // MARK: comet++ /// Tokens reach comet through a file in its private HOME, never its command line.+ func testCometArgumentsCarryNoTokens() {+ let args = GOGComet.arguments(username: "player")+ XCTAssertEqual(args, ["--from-heroic", "--username", "player", "--quit"])+ XCTAssertFalse(args.contains { $0.contains("token") })+ }++ func testCometSettingsRoundTrip() throws {+ var s = GOGSettings()+ s.cometOff["1"] = "crashed with comet"+ s.cloudSavesOff.insert("2")+ s.launchChoice["3"] = 1+ let back = try JSONDecoder().decode(GOGSettings.self, from: JSONEncoder().encode(s))+ XCTAssertEqual(back, s)+ }++ // MARK: Library, play links, uninstall++ func testLibraryBuildsOneGOGTilePerGame() throws {+ func bottle(_ name: String) -> Bottle {+ Bottle(url: URL(fileURLWithPath: "/tmp/hb-gog-tests/bottles/\(name)"), settings: BottleSettings(name: name, engineID: "e"))+ }+ let games = bottle("Games"), clean = bottle("Clean")+ let installed = GOGStore.InstalledGame(id: "1957528513", title: "Ghostrunner", folder: games.driveC.appending(path: "Games/Ghostrunner"),+ buildID: "1", clientID: nil, dlcIDs: [], tasks: [])+ let offline = GOGStore.InstalledGame(id: "42", title: "From an offline installer", folder: clean.driveC.appending(path: "GOG Games/X"),+ buildID: nil, clientID: nil, dlcIDs: [], tasks: [])+ let items = LibraryIndex.build(bottles: [games, clean], steamByBottle: [:], epicOwned: [], epicInstalls: [:],+ gogGames: [GOGStore.Game(id: "1957528513", title: "Ghostrunner", steamAppID: 1139900),+ GOGStore.Game(id: "7", title: "Owned, not installed")],+ gogInstalledByBottle: ["Games": [installed], "Clean": [offline]],+ defaultBottle: "Games")+ let gog = items.filter { $0.source == .gog }+ XCTAssertEqual(gog.count, 3)+ let gr = try XCTUnwrap(gog.first { $0.gogID == "1957528513" })+ XCTAssertEqual(gr.bottleName, "Games")+ XCTAssertTrue(gr.installed)+ XCTAssertNil(gr.steamAppID, "a GOG copy is never treated as a Steam game")+ XCTAssertEqual(gr.gogSteamAppID, 1139900)+ XCTAssertEqual(gr.artworkTall?.absoluteString, "https://cdn.akamai.steamstatic.com/steam/apps/1139900/library_600x900.jpg")+ let notInstalled = try XCTUnwrap(gog.first { $0.gogID == "7" })+ XCTAssertNil(notInstalled.bottleName)+ XCTAssertFalse(notInstalled.installed)+ let found = try XCTUnwrap(gog.first { $0.gogID == "42" }, "an install the account list does not name still gets a tile")+ XCTAssertEqual(found.bottleName, "Clean")+ }++ func testPinsInsideAGOGGameFolderGiveWayToItsTile() throws {+ var games = Bottle(url: URL(fileURLWithPath: "/tmp/hb-gog-tests/bottles/Games"), settings: BottleSettings(name: "Games", engineID: "e"))+ func tasks(_ json: String) throws -> [GOGStore.PlayTask] { try JSONDecoder().decode([GOGStore.PlayTask].self, from: Data(json.utf8)) }+ let quake = GOGStore.InstalledGame(id: "1825786806", title: "Quake II RTX", folder: games.driveC.appending(path: "GOG Games/Quake II RTX"),+ buildID: nil, clientID: nil, dlcIDs: [], tasks: try tasks(#"[{"isPrimary":true,"name":"Quake II RTX","path":"q2rtx.exe","type":"FileTask"}]"#))+ let control = GOGStore.InstalledGame(id: "2049187585", title: "Control", folder: games.driveC.appending(path: "GOG Games/Control"),+ buildID: nil, clientID: nil, dlcIDs: [], tasks: try tasks(#"[{"isPrimary":true,"name":"Control","path":"Control.exe","type":"FileTask"}]"#))+ let ghostrunner = GOGStore.InstalledGame(+ id: "1957528513", title: "Ghostrunner", folder: games.driveC.appending(path: "GOG Games/Ghostrunner"), buildID: nil, clientID: nil, dlcIDs: [],+ tasks: try tasks(#"[{"isPrimary":true,"name":"Ghostrunner","path":"Ghostrunner\\Binaries\\Win64\\Ghostrunner-Win64-Shipping.exe","arguments":"-GOG","type":"FileTask"}]"#))+ let quakePin = Pin(name: "Quake II", path: "GOG Games/Quake II RTX/q2rtx.exe", arguments: ["+set", "vid_rtx", "0"])+ let grPin = Pin(name: "Ghostrunner", path: "GOG Games/ghostrunner/Ghostrunner/Binaries/Win64/Ghostrunner-Win64-Shipping.exe", arguments: ["-GOG"])+ let tuned = Pin(name: "Quake tuned", path: "GOG Games/Quake II RTX/q2rtx.exe", environment: ["DXVK_HUD": "1"])+ let other = Pin(name: "Something else", path: "Games/Other/other.exe")+ let lookalike = Pin(name: "Not Quake", path: "GOG Games/Quake II RTX Mod/mod.exe")+ let tool = Pin(name: "Quake setup", path: "GOG Games/Quake II RTX/setup/Quake2RTX-Steam-Setup.exe")+ let dx11 = Pin(name: "Control", path: "GOG Games/Control/Control_DX11.exe")+ let controlTool = Pin(name: "Control settings", path: "GOG Games/Control/ControlConfig.exe")+ games.settings.pins = [quakePin, grPin, tuned, other, lookalike, tool, dx11, controlTool]+ let installs = ["Games": [quake, ghostrunner, control]]++ let covered = LibraryIndex.gogCoveredPins(bottles: [games], gogInstalledByBottle: installs)+ XCTAssertEqual(covered.map(\.pinItemID), ["pin:Games:\(quakePin.id.uuidString)", "pin:Games:\(grPin.id.uuidString)", "pin:Games:\(dx11.id.uuidString)"],+ "the game's own programs and a variant beside the main one give way; a tool in the folder, a pin with its own variables and a folder that only starts the same keep their tiles")+ XCTAssertEqual(covered[0].gogItemID, "gog:1825786806")+ XCTAssertEqual(covered[0].extraArguments, ["+set", "vid_rtx", "0"], "the pin's arguments go to the GOG tile")+ XCTAssertEqual(covered[1].extraArguments, [], "-GOG is already what the GOG task passes, so it is not added twice")++ let items = LibraryIndex.build(bottles: [games], steamByBottle: [:], epicOwned: [], epicInstalls: [:],+ gogInstalledByBottle: installs)+ XCTAssertEqual(items.filter { $0.source == .pin }.map(\.title).sorted(), ["Control settings", "Not Quake", "Quake setup", "Quake tuned", "Something else"])+ XCTAssertEqual(items.filter { $0.source == .gog }.count, 3)+ }++ func testSetupStepCommands() {+ let dir = URL(fileURLWithPath: "/tmp/redist")+ let msi = GOGStore.SetupStep(label: "PhysX", executable: nil, arguments: ["/i", "/tmp/redist/physx.msi", "/qb"], workingDirectory: dir)+ XCTAssertEqual(msi.command, ["msiexec", "/i", "/tmp/redist/physx.msi", "/qb"], "an .msi runtime runs through Wine's own msiexec, by name")+ let exe = GOGStore.SetupStep(label: "VC++", executable: dir.appending(path: "vcredist.exe"), arguments: ["/quiet"], workingDirectory: dir)+ XCTAssertEqual(exe.command, ["/tmp/redist/vcredist.exe", "/quiet"])+ }++ func testGOGSettingsReadAFileWrittenBeforeANewField() throws {+ let old = Data(#"{"cometOff":{"1":"turned off"},"cloudSavesOff":["2"],"launchChoice":{"3":1}}"#.utf8)+ let s = try JSONDecoder().decode(GOGSettings.self, from: old)+ XCTAssertEqual(s.cometOff["1"], GOGSettings.turnedOff)+ XCTAssertEqual(s.cloudSavesOff, ["2"])+ XCTAssertTrue(s.carriedOverPins.isEmpty)+ }++ func testPlayLinkAndUninstallForGOG() {+ let item = LibraryItem(source: .gog, id: "gog:1957528513", title: "Ghostrunner", bottleName: "Games", installed: true, gogID: "1957528513")+ let target = PlayLink.target(for: item)+ XCTAssertEqual(target, .gog(id: "1957528513"))+ let url = PlayLink.url(for: target!, token: "t")+ XCTAssertEqual(url.absoluteString, "highball://play/gog/1957528513?t=t")+ XCTAssertEqual(PlayLink.parse(url)?.target.libraryID, "gog:1957528513")+ XCTAssertNil(PlayLink.parse(URL(string: "highball://play/gog/../../x?t=t")!), "ids are numbers only")+ XCTAssertEqual(Uninstall.route(for: item), .gog(id: "1957528513"))+ let notHere = LibraryItem(source: .gog, id: "gog:7", title: "X", bottleName: nil, installed: false, gogID: "7")+ XCTAssertFalse(Uninstall.isActionable(Uninstall.route(for: notHere)))+ }+}