Skip to content

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

GOG Mac: a game ends once no app of its runs, with its play task's arguments

Gabe11a87e5d8a99
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 93a9350..5bbb831 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -3544,15 +3544,19 @@ final class AppState {
/// GOG Mac builds in the Mac games folder and the Applications folders, scanned off the main
/// actor: /Applications holds every app on the Mac.
- private func refreshGOGMacInstalls() async {
+ /// What the scan found, also when a newer scan has started since and this one's result is
+ /// not applied: an install reads its own game from it.
+ @discardableResult
+ private func refreshGOGMacInstalls() async -> [String: GOGStore.MacInstalledGame] {
macScanGeneration += 1
let generation = macScanGeneration
let mac = await Task.detached { Dictionary(GOGStore.macInstalledGames().map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) }.value
// Scans overlap (the install watcher fires many times during a download): an older one
// landing last must not bring back a game moved to the Trash since.
- guard generation == macScanGeneration, mac != gogMacInstalled else { return }
+ guard generation == macScanGeneration, mac != gogMacInstalled else { return mac }
gogMacInstalled = mac
rebuildLibrary()
+ return mac
}
/// The GOG tile a program added by hand plays as (LibraryIndex.gogCoveredPins), if any, with
@@ -3717,8 +3721,7 @@ final class AppState {
try store.installMac(id, language: language, control: control, onLine: onLine)
}
busyProgress = nil; transferRate = nil
- await refreshGOGMacInstalls()
- guard let game = gogMacInstalled[id] else {
+ guard let game = await refreshGOGMacInstalls()[id] else {
throw HighballError.failed(L("The download finished, but Highball could not find the Mac version in it."))
}
appendLog("\(item.title): Mac version installed in \(game.folder.path), built for \(game.arch)")
@@ -3730,9 +3733,10 @@ final class AppState {
var macGameProcesses: [String: Process] = [:]
/// Plays a GOG game's Mac build as the Windows one plays: saves down from GOG's cloud first
- /// (GOG's Mac locations, or the Windows ones a Mac folder shares, GOGSaves.macLocations), comet
- /// beside it for achievements and the unlock card, and saves back up once it quits. The app
- /// runs as itself, no Wine; Highball starts its executable so it knows when it has quit.
+ /// (GOG's Mac locations, GOGSaves.macLocations), comet beside it for achievements and the
+ /// unlock card, and saves back up once it quits. The app runs as itself, no Wine; Highball
+ /// starts its executable, with the play task's arguments and working folder as Galaxy passes
+ /// them, so it knows when it has quit.
func gogPlayMac(_ item: LibraryItem) {
guard let id = item.gogID, let mac = gogMacInstalled[id], let app = mac.app,
let executable = Bundle(url: app)?.executableURL else {
@@ -3766,7 +3770,9 @@ final class AppState {
let process = Process()
process.executableURL = executable
- process.currentDirectoryURL = app.deletingLastPathComponent()
+ let task = game.launchTask(), launch = task.flatMap { GOGStore.launch($0, in: game) }
+ process.arguments = launch?.arguments ?? []
+ process.currentDirectoryURL = (task?.workingDir ?? "").isEmpty ? app.deletingLastPathComponent() : launch?.workingDirectory
do { try process.run() } catch {
GOGComet(store: store).stop(comet)
throw HighballError.failed(String(format: L("The Mac version of %@ did not start: %@"), item.title, error.localizedDescription))
@@ -3785,17 +3791,35 @@ final class AppState {
private func watchMacGame(_ process: Process, item: LibraryItem, game: GOGStore.InstalledGame, comet: Process?,
cometLog: URL, saveFolders: [(GOGSaves.Location, URL)]) {
let store = gogStore
- let folder = game.folder, started = Date()
+ let folder = game.folder
Task.detached { [weak self] in
- process.waitUntilExit()
- if await MacGameWatch.waitForHandover(from: folder, ranFor: Date().timeIntervalSince(started)) {
- await self?.appendLog("\(item.title): the Mac version handed over to another process, which has now quit too")
+ if await Self.macGameEnd(of: process, watching: folder) {
+ await self?.appendLog("\(item.title): the Mac version handed over to another app, which has now quit too")
}
GOGComet(store: store).stop(comet)
await self?.macGameEnded(item: item, game: game, cometRan: comet != nil, cometLog: cometLog, saveFolders: saveFolders)
}
}
+ /// Waits until a Mac game Highball started has ended: its process has quit (awaited, holding
+ /// no thread for the session), and no app from its folder runs any more
+ /// (MacGameWatch.waitForHandover). Only apps a player sees count: a crash reporter or helper
+ /// left behind would keep the game running, comet up and its saves unsynced until Highball
+ /// quits. Whether the game handed over to another app.
+ nonisolated private static func macGameEnd(of process: Process, watching folder: URL?) async -> Bool {
+ let started = Date()
+ await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) in
+ let once = OSAllocatedUnfairLock(initialState: false)
+ let finish: @Sendable () -> Void = { if once.withLock({ let first = !$0; $0 = true; return first }) { done.resume() } }
+ process.terminationHandler = { _ in finish() }
+ if !process.isRunning { finish() } // quit before the handler was set
+ }
+ guard let folder else { return false }
+ return await MacGameWatch.waitForHandover(from: folder, ranFor: Date().timeIntervalSince(started)) { folder in
+ MacGameWatch.processes(runningFrom: folder).filter { NSRunningApplication(processIdentifier: $0)?.activationPolicy == .regular }
+ }
+ }
+
private func macGameEnded(item: LibraryItem, game: GOGStore.InstalledGame, cometRan: Bool, cometLog: URL,
saveFolders: [(GOGSaves.Location, URL)]) async {
macGameProcesses[item.id] = nil
@@ -3842,7 +3866,6 @@ final class AppState {
}
}
-
/// A GOG Mac build the player asked to move to the Trash: asked first, with what goes.
var pendingGOGMacTrash: LibraryItem?
diff --git a/Sources/HighballKit/GOGMac.swift b/Sources/HighballKit/GOGMac.swift
index 6fa9c76..6fbf4a4 100644
--- a/Sources/HighballKit/GOGMac.swift
+++ b/Sources/HighballKit/GOGMac.swift
@@ -73,7 +73,6 @@ extension GOGStore {
public var asInstalledGame: InstalledGame {
InstalledGame(id: id, title: title, folder: folder, buildID: buildID, clientID: clientID, dlcIDs: dlcIDs, tasks: tasks)
}
-
}
/// Where Mac builds go: an Applications folder Spotlight and Launchpad already look in, the
@@ -127,8 +126,6 @@ extension GOGStore {
.filter { seen.insert($0.id).inserted }
}
- public static func macInstalledGames(in base: URL) -> [MacInstalledGame] { macInstalledGames(in: [base]) }
-
static func macInstalledGame(in folder: URL) -> MacInstalledGame? {
let fm = FileManager.default
let top = (try? fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []
diff --git a/Sources/HighballKit/GOGSaves.swift b/Sources/HighballKit/GOGSaves.swift
index 25ef029..1041778 100644
--- a/Sources/HighballKit/GOGSaves.swift
+++ b/Sources/HighballKit/GOGSaves.swift
@@ -61,9 +61,12 @@ public struct GOGSaves: Sendable {
/// 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)
+ Self.parseLocations(try Self.remoteConfig(clientID), clientID: clientID)
+ }
+
+ /// The remote config GOG publishes per client id, which names every version's cloud saves.
+ static func remoteConfig(_ clientID: String) throws -> Data {
+ try GOGStore.fetch(URLRequest(url: URL(string: "https://remote-config.gog.com/components/galaxy_client/clients/\(clientID)?component_version=2.0.45")!))
}
/// `platform` is GOG's: "Windows", or "MacOS" for the Mac build's own locations.
@@ -94,8 +97,7 @@ public struct GOGSaves: Sendable {
/// Both versions' setups, from the one remote config GOG publishes per client id.
public func cloudSetup(clientID: String) throws -> CloudSetup {
- let url = URL(string: "https://remote-config.gog.com/components/galaxy_client/clients/\(clientID)?component_version=2.0.45")!
- return Self.parseCloudSetup(try GOGStore.fetch(URLRequest(url: url)), clientID: clientID)
+ Self.parseCloudSetup(try Self.remoteConfig(clientID), clientID: clientID)
}
static func parseCloudSetup(_ data: Data, clientID: String) -> CloudSetup {
@@ -109,8 +111,7 @@ public struct GOGSaves: Sendable {
/// build. A game that syncs its own saves through GOG's SDK (Cyberpunk 2077 on Mac, through
/// comet) needs none from Highball, and a file sync beside it would fight it.
public func macLocations(clientID: String) throws -> [Location]? {
- let url = URL(string: "https://remote-config.gog.com/components/galaxy_client/clients/\(clientID)?component_version=2.0.45")!
- return Self.parseLocations(try GOGStore.fetch(URLRequest(url: url)), clientID: clientID, platform: "MacOS")
+ Self.parseLocations(try Self.remoteConfig(clientID), clientID: clientID, platform: "MacOS")
}
/// A Mac location as a folder, from GOG's Mac variables.
diff --git a/Tests/HighballKitTests/StoreMacVersionTests.swift b/Tests/HighballKitTests/StoreMacVersionTests.swift
index 309d1fe..9362de7 100644
--- a/Tests/HighballKitTests/StoreMacVersionTests.swift
+++ b/Tests/HighballKitTests/StoreMacVersionTests.swift
@@ -91,7 +91,7 @@ final class GOGMacBuildTests: XCTestCase {
try FileManager.default.createDirectory(at: partial, withIntermediateDirectories: true)
try Data().write(to: partial.appending(path: ".gogdl-resume"))
- let games = GOGStore.macInstalledGames(in: base)
+ let games = GOGStore.macInstalledGames(in: [base])
XCTAssertEqual(games.map(\.id), ["2006298293"])
XCTAssertEqual(games.first?.app?.lastPathComponent, "Samorost 1.app")
XCTAssertEqual(games.first?.folder.lastPathComponent, "Samorost 1.app", "the info sits in the app, so the app is the game's folder")
@@ -113,7 +113,7 @@ final class GOGMacBuildTests: XCTestCase {
try #"{"gameId":"5","name":"Zed"}"#.write(to: zed.appending(path: "goggame-5.info"), atomically: true, encoding: .utf8)
try #"{"gameId":"6","rootGameId":"1","name":"Stray"}"#.write(to: zed.appending(path: "goggame-6.info"), atomically: true, encoding: .utf8)
- let game = try XCTUnwrap(GOGStore.macInstalledGames(in: applications).first)
+ let game = try XCTUnwrap(GOGStore.macInstalledGames(in: [applications]).first)
XCTAssertEqual(game.id, "1")
XCTAssertEqual(game.dlcIDs, ["2"])
}
@@ -148,7 +148,7 @@ final class GOGMacBuildTests: XCTestCase {
try #"{"gameId":"1207658924","rootGameId":"1207658924"}"#
.write(to: resources.appending(path: "goggame-1207658924.info"), atomically: true, encoding: .utf8)
- let game = try XCTUnwrap(GOGStore.macInstalledGames(in: applications).first)
+ let game = try XCTUnwrap(GOGStore.macInstalledGames(in: [applications]).first)
XCTAssertEqual(game.folder.lastPathComponent, "Foo.app")
XCTAssertEqual(game.folder.deletingLastPathComponent().lastPathComponent, "Games")
XCTAssertEqual(game.app?.lastPathComponent, "Foo.app")
@@ -163,7 +163,7 @@ final class GOGMacBuildTests: XCTestCase {
try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)
try #"{"gameId":"2006298293","rootGameId":"2006298293","name":"Samorost 1"}"#
.write(to: resources.appending(path: "goggame-2006298293.info"), atomically: true, encoding: .utf8)
- let game = try XCTUnwrap(GOGStore.macInstalledGames(in: base).first)
+ let game = try XCTUnwrap(GOGStore.macInstalledGames(in: [base]).first)
XCTAssertEqual(game.id, "2006298293")
XCTAssertEqual(game.app?.lastPathComponent, "Samorost 1.app")
XCTAssertEqual(game.folder.lastPathComponent, "Samorost 1.app")
@@ -205,7 +205,7 @@ final class GOGMacBuildTests: XCTestCase {
try #"{"gameId":"7","rootGameId":"7","name":"Some Game","clientId":"5150","playTasks":[{"category":"tool","type":"FileTask","path":"A Config Tool.app"},{"category":"game","isPrimary":true,"type":"FileTask","path":"Some Game.app/Contents/MacOS/Some Game"}]}"#
.write(to: folder.appending(path: "Contents/Resources/goggame-7.info"), atomically: true, encoding: .utf8)
- let game = try XCTUnwrap(GOGStore.macInstalledGames(in: applications).first)
+ let game = try XCTUnwrap(GOGStore.macInstalledGames(in: [applications]).first)
XCTAssertEqual(game.app?.lastPathComponent, "Some Game.app")
XCTAssertEqual(game.folder.lastPathComponent, "Some Game")
XCTAssertEqual(game.asInstalledGame.clientID, "5150")