Skip to content

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

GOG: pins give way only to their exact program; old Mac apps, carry-over and tool updates

Gabe53db0ec499fc
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index c4c893a..236b90f 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -292,7 +292,7 @@ final class AppState {
libraryItems = LibraryIndex.build(bottles: bottles, steamByBottle: gamesByBottle,
steamOwnedByBottle: steamOwnedByBottle, macInstalled: macSteamGames,
epicOwned: epicOwned, epicInstalls: epicInstalls,
- gogGames: gogGames, gogInstalledByBottle: gogInstalledByBottle,
+ gogGames: gogGames, gogInstalledByBottle: gogInstalledByBottle, gogLaunchChoice: gogSettings.launchChoice,
plays: libraryPlays, defaultBottle: defaultBottle?.name,
pinExists: { bottle, pin in
// follows links, so a link to a file that is gone counts as missing
@@ -1932,7 +1932,10 @@ final class AppState {
}
private func resolvePlayLink(_ request: PlayLink.Request) {
- if let item = libraryItems.first(where: { $0.id == request.target.libraryID }) {
+ // A program its GOG tile now stands for has no tile of its own: a Mac app made for it before
+ // still plays it, as the GOG game (launch(pin:)), and does not say it is not in the library.
+ if let item = libraryItems.first(where: { $0.id == request.target.libraryID })
+ ?? LibraryIndex.coveredPinItem(forLink: request.target, bottles: bottles, gogInstalledByBottle: gogInstalledByBottle) {
deferredPlayLink = nil
if request.token == PlayLink.token(in: paths) { play(item) } else { pendingPlayLink = item }
return
@@ -2608,9 +2611,11 @@ final class AppState {
func launch(pin: Pin, in bottle: Bottle) {
// A program its GOG tile stands for plays as that game, with comet and cloud saves,
// wherever it was started from (the environment's Programs list, a tile from before).
- if let item = gogItem(standingFor: pin, in: bottle) {
+ // It runs the program and arguments the player picked, whatever the GOG tile plays.
+ if let standing = gogItem(standingFor: pin, in: bottle) {
+ let (item, covered) = standing
appendLog("\(pin.name): playing it as \(item.title) from GOG, for achievements and cloud saves")
- gogPlay(item, in: bottle, renderer: pin.renderer)
+ gogPlay(item, in: bottle, renderer: pin.renderer, as: covered)
return
}
guard let engine = engine(for: bottle) else { return }
@@ -3295,45 +3300,36 @@ final class AppState {
if !newIDs.isEmpty, !gogFetchInFlight { gogRefresh() }
}
- /// The GOG tile that stands for a program added by hand (LibraryIndex.gogCoveredPins), if any.
- /// Read off the environment's saved pins, so a launch-time mode on `pin` does not hide it.
- private func gogItem(standingFor pin: Pin, in bottle: Bottle) -> LibraryItem? {
+ /// The GOG tile a program added by hand plays as (LibraryIndex.gogCoveredPins), if any, with
+ /// what the program runs. Read off the environment's saved pins, so a launch-time mode on
+ /// `pin` does not hide it.
+ private func gogItem(standingFor pin: Pin, in bottle: Bottle) -> (LibraryItem, LibraryIndex.CoveredPin)? {
let id = "pin:\(bottle.name):\(pin.id.uuidString)"
guard let covered = LibraryIndex.gogCoveredPins(bottles: [bottle], gogInstalledByBottle: gogInstalledByBottle)
- .first(where: { $0.pinItemID == id }) else { return nil }
- return libraryItems.first { $0.id == covered.gogItemID }
+ .first(where: { $0.pinItemID == id }),
+ let item = libraryItems.first(where: { $0.id == covered.gogItemID }) else { return nil }
+ return (item, covered)
}
/// 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.
+ /// hands its settings, name and cover to that tile once (LibraryIndex.carryOver),
+ /// so the pin's tile can leave the library without the game playing or looking different.
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) }
+ let covered = LibraryIndex.gogCoveredPins(bottles: bottles, gogInstalledByBottle: gogInstalledByBottle, launchChoice: settings.launchChoice)
+ .filter { $0.tilePlaysIt && !LibraryIndex.wasCarriedOver($0.pinItemID, in: settings.carriedOverPins) }
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")
- }
+ for line in LibraryIndex.carryOver(covered, paths: paths, settings: &settings) { appendLog(line) }
settings.save(gogStore)
gogSettings = settings
+ let store = libraryStore
libraryOverrides = store.rendererOverrides()
libraryLaunchArgs = store.launchArguments()
libraryDisplays = store.displayChoices()
+ customNames = nameStore.names()
+ coverVersion += 1
}
/// The copy of a GOG game in an environment, read from disk.
@@ -3507,7 +3503,10 @@ final class AppState {
/// 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) {
+ /// `pin` is a program added by hand that plays as this game (LibraryIndex.CoveredPin): its own
+ /// task and arguments run instead of the ones the game's page picks.
+ func gogPlay(_ item: LibraryItem, in bottle: Bottle, renderer: Renderer? = nil, as pin: LibraryIndex.CoveredPin? = 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
@@ -3516,13 +3515,13 @@ final class AppState {
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 {
+ guard let task = pin?.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 extraArguments = pin?.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
@@ -3595,7 +3594,7 @@ final class AppState {
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)
+ self.gogPlay(item, in: fresh, renderer: renderer, as: pin, retryingWithoutComet: true)
}
}
return
@@ -3795,6 +3794,7 @@ final class AppState {
gogSettings.launchChoice[id] = index
gogSettings.save(gogStore)
forgetProgramExecutables()
+ rebuildLibrary() // a program added by hand shows its own tile only while the GOG tile plays another
}
/// Removes a GOG game from an environment: its own uninstaller first when an offline installer
diff --git a/Sources/HighballKit/GOGComet.swift b/Sources/HighballKit/GOGComet.swift
index e2ad462..730cf0f 100644
--- a/Sources/HighballKit/GOGComet.swift
+++ b/Sources/HighballKit/GOGComet.swift
@@ -136,9 +136,8 @@ public struct GOGSettings: Codable, Sendable, Equatable {
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.
+ /// Programs added by hand whose settings, name and cover were carried to their GOG tile once
+ /// (LibraryIndex.carryOver); never again, so a later change on the GOG tile stays.
public var carriedOverPins: Set<String> = []
public init() {}
diff --git a/Sources/HighballKit/GOGStore.swift b/Sources/HighballKit/GOGStore.swift
index 3dc4320..3ee8e7e 100644
--- a/Sources/HighballKit/GOGStore.swift
+++ b/Sources/HighballKit/GOGStore.swift
@@ -49,32 +49,75 @@ public struct GOGStore: Sendable {
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 }
+ /// Downloads and verifies a pinned tool when it is missing, or when the file there is not the
+ /// pinned build: a pin moved to a newer gogdl or comet reaches existing installs, and a
+ /// damaged copy is replaced. The new file is written beside the old one and renamed over it,
+ /// so a gogdl or comet running at that moment keeps its own file and nothing ever runs half a
+ /// copy.
+ func ensure(_ component: EngineManifest.Component, name: String, at binary: URL,
+ progress: DownloadProgress?) async throws -> URL {
+ if isPinned(binary, sha256: component.sha256) { 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)
+ let folder = binary.deletingLastPathComponent()
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ let staged = folder.appending(path: ".\(binary.lastPathComponent).\(UUID().uuidString).new")
+ defer { try? FileManager.default.removeItem(at: staged) }
+ try FileManager.default.copyItem(at: file, to: staged)
+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: staged.path)
// Checksum-verified above; quarantine would otherwise block the unsigned binaries.
- try? Shell.run("/usr/bin/xattr", ["-c", binary.path])
+ try? Shell.run("/usr/bin/xattr", ["-c", staged.path])
+ guard rename(staged.path, binary.path) == 0 else {
+ throw HighballError.failed("Could not put \(name) in place: \(String(cString: strerror(errno)))")
+ }
+ Self.rememberVerified(binary, sha256: component.sha256)
return binary
}
+ /// Files whose checksum matched, by path, with the size and modification date they had then:
+ /// a tool is hashed again only when it changed, not on every sign-in check or launch.
+ private static let verified = OSAllocatedUnfairLock(initialState: [String: (size: Int64, modified: Date, sha256: String)]())
+
+ /// Whether the file at `binary` is the pinned build.
+ func isPinned(_ binary: URL, sha256 expected: String) -> Bool {
+ guard let stamp = Self.fileStamp(binary) else { return false }
+ let expected = expected.lowercased()
+ if let known = Self.verified.withLock({ $0[binary.path] }), known.size == stamp.size, known.modified == stamp.modified {
+ return known.sha256 == expected
+ }
+ guard let actual = try? EngineStore(paths: paths).sha256(of: binary) else { return false }
+ Self.verified.withLock { $0[binary.path] = (stamp.size, stamp.modified, actual) }
+ return actual == expected
+ }
+
+ private static func rememberVerified(_ binary: URL, sha256: String) {
+ guard let stamp = fileStamp(binary) else { return }
+ verified.withLock { $0[binary.path] = (stamp.size, stamp.modified, sha256.lowercased()) }
+ }
+
+ private static func fileStamp(_ url: URL) -> (size: Int64, modified: Date)? {
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),
+ let size = (attributes[.size] as? NSNumber)?.int64Value,
+ let modified = attributes[.modificationDate] as? Date else { return nil }
+ return (size, modified)
+ }
+
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).
+ /// comet and its placeholder service. Failing here never stops a launch (see GOGComet). The
+ /// service is unpacked again when the pinned archive changes: the archive's checksum is kept
+ /// beside it.
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 stamp = dummyServiceDir.appending(path: ".sha256")
+ let unpacked = (try? String(contentsOf: stamp, encoding: .utf8))?.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !FileManager.default.fileExists(atPath: exe.path) || unpacked != Self.dummyService.sha256.lowercased() {
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])
+ try? Self.dummyService.sha256.lowercased().write(to: stamp, atomically: true, encoding: .utf8)
}
return (comet, exe)
}
diff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swift
index 3e8ae97..d0364f4 100644
--- a/Sources/HighballKit/Library.swift
+++ b/Sources/HighballKit/Library.swift
@@ -95,50 +95,129 @@ public enum LibraryIndex {
}
/// 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.
+ /// (a pin made before Connect GOG, or for a game an offline installer put there): it runs
+ /// exactly one of the programs the GOG tile can play, the game's own launch task or one of
+ /// the choices on its page. Started itself, it plays as that game, with comet and cloud saves,
+ /// and runs that program (AppState.launch(pin:)). Its own tile is left out only while the GOG
+ /// tile's Play runs the same program; the pin itself stays in the environment's settings.
+ /// Anything else keeps its tile and plays the program the player picked: a variant beside the
+ /// main one (Control_DX11.exe next to Control.exe, which GOG's Play would not run), a tool in
+ /// the folder, and a pin with its own variables or graphics mode, which the GOG tile could not
+ /// carry. Installs are read from disk, so this holds for players who never connect GOG too.
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
+ /// The pin's arguments beyond the ones its 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]
+ /// The GOG launch task the pin runs.
+ public let task: GOGStore.PlayTask
+ /// Whether the GOG tile's Play runs that task too, with the launch choice made on the game's
+ /// page: only then does the tile stand for the pin's own (Ghostrunner pinned with -dx12
+ /// keeps its tile while the page plays the game's default).
+ public let tilePlaysIt: Bool
}
- public static func gogCoveredPins(bottles: [Bottle], gogInstalledByBottle: [String: [GOGStore.InstalledGame]]) -> [CoveredPin] {
+ /// `launchChoice` is GOGSettings.launchChoice, what each GOG tile's Play runs.
+ public static func gogCoveredPins(bottles: [Bottle], gogInstalledByBottle: [String: [GOGStore.InstalledGame]],
+ launchChoice: [String: Int] = [:]) -> [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 }
+ let file = pin.launchURL(driveC: bottle.driveC)
+ guard let found = games.lazy.compactMap({ game in gogTask(game, runBy: file, arguments: pin.arguments).map { (game, $0) } }).first
+ else { continue }
+ let (game, task) = found
var extra = pin.arguments
- let taskArguments = game.launchTask().flatMap { GOGStore.launch($0, in: game) }?.arguments ?? []
+ let taskArguments = GOGStore.launch(task, 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))
+ extraArguments: extra, task: task,
+ tilePlaysIt: game.launchTask(choice: launchChoice[game.id]) == task))
}
}
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 + "_")
+ /// The task of the game's that runs `file`, when the GOG tile can play it: the default launch
+ /// task, or one of the page's launch choices. Only the exact program counts, compared without
+ /// case as Windows paths are; a file beside it does not. Several tasks running the same
+ /// program (Ghostrunner and Ghostrunner DX12) are told apart by the arguments: the one whose
+ /// own arguments the pin passes, the most of them first, the default before a choice.
+ static func gogTask(_ game: GOGStore.InstalledGame, runBy file: URL, arguments: [String]) -> GOGStore.PlayTask? {
+ let path = file.standardizedFileURL.path.lowercased()
+ let candidates: [(task: GOGStore.PlayTask, arguments: [String])] = ([game.launchTask()].compactMap { $0 } + game.launchChoices).compactMap { task in
+ guard let launch = GOGStore.launch(task, in: game), launch.executable.standardizedFileURL.path.lowercased() == path else { return nil }
+ return (task, launch.arguments)
+ }
+ func passes(_ wanted: [String]) -> Bool {
+ var left = arguments
+ for argument in wanted {
+ guard let i = left.firstIndex(of: argument) else { return false }
+ left.remove(at: i)
+ }
+ return true
+ }
+ return (candidates.filter { passes($0.arguments) }.max { $0.arguments.count < $1.arguments.count } ?? candidates.first)?.task
+ }
+
+ /// The program a play link names when the library leaves its tile out for its GOG tile
+ /// (gogCoveredPins), so a Mac app made for it before keeps working: Play still runs that
+ /// program, as the GOG game (AppState.launch(pin:)), whatever the GOG tile plays. Found by its
+ /// own id too when its environment was renamed since (PinID).
+ public static func coveredPinItem(forLink target: PlayLink.Target, bottles: [Bottle],
+ gogInstalledByBottle: [String: [GOGStore.InstalledGame]]) -> LibraryItem? {
+ guard case let .pin(_, uuid) = target else { return nil }
+ let covered = gogCoveredPins(bottles: bottles, gogInstalledByBottle: gogInstalledByBottle)
+ guard let found = covered.first(where: { $0.pinItemID == target.libraryID })
+ ?? covered.first(where: { PinID.uuid(in: $0.pinItemID) == uuid.uuidString }),
+ let bottle = bottles.first(where: { found.pinItemID == "pin:\($0.name):\(uuid.uuidString)" }),
+ let pin = bottle.settings.pins.first(where: { $0.id == uuid }) else { return nil }
+ return LibraryItem(source: .pin, id: found.pinItemID, title: pin.name, bottleName: bottle.name, installed: true, pinID: pin.id)
+ }
+
+ /// Hands what a program added by hand had to the GOG tile that now stands for it
+ /// (gogCoveredPins, while the tile plays the same program), once per program, so the program's
+ /// tile can leave the library without the game playing or looking different: the arguments its
+ /// GOG task does not already pass, the display, the graphics mode, and the name and cover the
+ /// player gave it. A setting goes only where the GOG tile has none of its own, since one set
+ /// there was the player's choice for the game. When it was last played needs no carrying: the
+ /// GOG tile shows the latest play of the programs it stands for (build). The program keeps its
+ /// own copy of everything, so its tile comes back as it was when the GOG tile stops standing
+ /// for it. Returns a line per program for the log.
+ @discardableResult
+ public static func carryOver(_ covered: [CoveredPin], paths: HighballPaths, settings: inout GOGSettings) -> [String] {
+ let store = LibraryStore(paths: paths), names = NameStore(paths: paths), covers = CoverStore(paths: paths)
+ var lines: [String] = []
+ for pin in covered where pin.tilePlaysIt && !wasCarriedOver(pin.pinItemID, in: settings.carriedOverPins) {
+ let (from, to) = (pin.pinItemID, pin.gogItemID)
+ if !pin.extraArguments.isEmpty, store.launchArguments()[to] == nil {
+ store.setLaunchArguments(pin.extraArguments, for: to)
+ }
+ let displays = store.displayChoices()
+ if let display = displays[from], displays[to] == nil { store.setDisplay(display, for: to) }
+ let overrides = store.rendererOverrides()
+ if let renderer = overrides[from], overrides[to] == nil { store.setRendererOverride(renderer, for: to) }
+ let custom = names.names()
+ if let name = NameStore.name(for: from, in: custom), NameStore.name(for: to, in: custom) == nil {
+ try? names.setName(name, for: to)
+ }
+ if covers.coverURL(for: from) != nil, covers.coverURL(for: to) == nil { try? covers.copyCover(from: from, to: to) }
+ settings.carriedOverPins.insert(from)
+ lines.append("\(from): shown as its GOG game (\(to)) from now on; its settings, name and cover went along")
+ }
+ return lines
+ }
+
+ /// Whether a program's things went to its GOG tile already, also under an earlier name of its
+ /// environment (PinID): a rename gives the program a new id, and carrying again would put back
+ /// a name or cover the player has since cleared on the GOG tile.
+ public static func wasCarriedOver(_ pinItemID: String, in carried: Set<String>) -> Bool {
+ if carried.contains(pinItemID) { return true }
+ guard let uuid = PinID.uuid(in: pinItemID) else { return false }
+ return carried.contains { PinID.uuid(in: $0) == uuid }
}
/// Builds the unified item list. Pure: takes exactly what AppState already holds.
@@ -156,6 +235,7 @@ public enum LibraryIndex {
epicInstalls: [String: String],
gogGames: [GOGStore.Game] = [],
gogInstalledByBottle: [String: [GOGStore.InstalledGame]] = [:],
+ gogLaunchChoice: [String: Int] = [:],
plays: [String: LibraryStore.PlayRecord] = [:],
defaultBottle: String? = nil,
pinExists: (Bottle, Pin) -> Bool = { _, _ in true }) -> [LibraryItem] {
@@ -246,6 +326,10 @@ public enum LibraryIndex {
for bottle in bottles {
for game in gogInstalledByBottle[bottle.name] ?? [] { gogCopies[game.id, default: []].append((bottle.name, game)) }
}
+ // Programs the GOG tile stands for leave the library (below); their plays show on it.
+ let standing = gogCoveredPins(bottles: bottles, gogInstalledByBottle: gogInstalledByBottle, launchChoice: gogLaunchChoice)
+ .filter(\.tilePlaysIt)
+ let coveredPins = Set(standing.map(\.pinItemID))
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) {
@@ -263,14 +347,13 @@ public enum LibraryIndex {
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))
+ lastPlayed: ([itemID] + standing.filter { $0.gogItemID == itemID }.map(\.pinItemID)).compactMap { plays[$0]?.lastPlayedAt }.max()))
}
// 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)"
@@ -553,6 +636,15 @@ public struct CoverStore: Sendable {
guard (try? FileManager.default.removeItem(at: existing)) != nil else { return }
}
}
+
+ /// Copies one item's chosen cover, as it is, to another item (a program's cover to the GOG
+ /// tile that now stands for it). Nothing happens when the first has none.
+ public func copyCover(from source: String, to target: String) throws {
+ guard let file = coverURL(for: source) else { return }
+ clearCover(for: target)
+ let dest = dir.appending(path: Self.filename(for: target)).appendingPathExtension(file.pathExtension.lowercased())
+ try FileManager.default.copyItem(at: file, to: dest)
+ }
}
/// A program's library id carries its environment's name ("pin:<bottle>:<uuid>"), so renaming or
diff --git a/Tests/HighballKitTests/GOGStoreTests.swift b/Tests/HighballKitTests/GOGStoreTests.swift
index b24a7f5..27c86e0 100644
--- a/Tests/HighballKitTests/GOGStoreTests.swift
+++ b/Tests/HighballKitTests/GOGStoreTests.swift
@@ -337,18 +337,395 @@ final class GOGStoreTests: XCTestCase {
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.map(\.pinItemID), ["pin:Games:\(quakePin.id.uuidString)", "pin:Games:\(grPin.id.uuidString)"],
+ "the game's own programs give way; a variant beside the main one, 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")
+ XCTAssertTrue(covered.allSatisfy(\.tilePlaysIt), "the GOG tile's Play runs the same program")
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 == .pin }.map(\.title).sorted(), ["Control", "Control settings", "Not Quake", "Quake setup", "Quake tuned", "Something else"])
XCTAssertEqual(items.filter { $0.source == .gog }.count, 3)
}
+ /// Owner review on #539: Control_DX11.exe pinned beside Control.exe gave way to the GOG tile,
+ /// and Play then ran Control.exe, for players who never connected GOG too (installs are read
+ /// off disk). It keeps its own tile, which plays the program the player picked.
+ func testAVariantBesideTheMainProgramKeepsItsTileAndItsProgram() throws {
+ var games = Bottle(url: URL(fileURLWithPath: "/tmp/hb-gog-tests/bottles/Games"), settings: BottleSettings(name: "Games", engineID: "e"))
+ let tasks = try JSONDecoder().decode([GOGStore.PlayTask].self, from: Data(#"[{"isPrimary":true,"name":"Control","path":"Control.exe","category":"launcher","type":"FileTask"}]"#.utf8))
+ let control = GOGStore.InstalledGame(id: "2049187585", title: "Control", folder: games.driveC.appending(path: "GOG Games/Control"),
+ buildID: nil, clientID: nil, dlcIDs: [], tasks: tasks)
+ let dx11 = Pin(name: "Control DX11", path: "GOG Games/Control/Control_DX11.exe")
+ let main = Pin(name: "Control", path: "GOG Games/control/CONTROL.EXE")
+ games.settings.pins = [dx11, main]
+ let installs = ["Games": [control]]
+
+ let covered = LibraryIndex.gogCoveredPins(bottles: [games], gogInstalledByBottle: installs)
+ XCTAssertEqual(covered.map(\.pinItemID), ["pin:Games:\(main.id.uuidString)"], "only the exact program, whatever its case, gives way")
+ XCTAssertEqual(covered[0].task.path, "Control.exe")
+
+ // No account: the GOG games list is empty, the install alone makes the tile.
+ let items = LibraryIndex.build(bottles: [games], steamByBottle: [:], epicOwned: [], epicInstalls: [:], gogGames: [],
+ gogInstalledByBottle: installs)
+ let tile = try XCTUnwrap(items.first { $0.id == "pin:Games:\(dx11.id.uuidString)" })
+ XCTAssertEqual(tile.source, .pin)
+ let pin = try XCTUnwrap(games.settings.pins.first { $0.id == tile.pinID })
+ XCTAssertEqual(pin.launchURL(driveC: games.driveC).lastPathComponent, "Control_DX11.exe", "Play runs the pinned program")
+ XCTAssertFalse(items.contains { $0.id == "pin:Games:\(main.id.uuidString)" })
+ }
+
+ /// A pin on another of the page's launch choices plays as the GOG game with its own task, but
+ /// keeps its tile while the GOG tile plays something else: the tile stands for a pin only when
+ /// its Play would run the same program. Changing the choice on the page swaps which one shows.
+ func testAPinOnAnotherLaunchChoiceKeepsItsTaskAndItsTile() throws {
+ var games = Bottle(url: URL(fileURLWithPath: "/tmp/hb-gog-tests/bottles/Games"), settings: BottleSettings(name: "Games", engineID: "e"))
+ let tasks = try JSONDecoder().decode([GOGStore.PlayTask].self, from: Data(#"""
+ [{"isPrimary":true,"category":"game","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"},
+ {"category":"tool","name":"Benchmark","path":"Bench.exe","type":"FileTask"}]
+ """#.utf8))
+ let gr = GOGStore.InstalledGame(id: "1957528513", title: "Ghostrunner", folder: games.driveC.appending(path: "GOG Games/Ghostrunner"),
+ buildID: nil, clientID: nil, dlcIDs: [], tasks: tasks)
+ let exe = "GOG Games/Ghostrunner/Ghostrunner/Binaries/Win64/Ghostrunner-Win64-Shipping.exe"
+ let dx12 = Pin(name: "Ghostrunner DX12", path: exe, arguments: ["-GOG", "-dx12", "-novid"])
+ let main = Pin(name: "Ghostrunner", path: exe, arguments: ["-GOG"])
+ let bench = Pin(name: "Benchmark", path: "GOG Games/Ghostrunner/Bench.exe")
+ games.settings.pins = [dx12, main, bench]
+ let installs = ["Games": [gr]]
+
+ let covered = LibraryIndex.gogCoveredPins(bottles: [games], gogInstalledByBottle: installs)
+ XCTAssertEqual(covered.map(\.task.name), ["Ghostrunner DX12", "Ghostrunner", "Benchmark"], "the task whose own arguments the pin passes")
+ XCTAssertEqual(covered[0].extraArguments, ["-novid"])
+ XCTAssertEqual(covered.map(\.tilePlaysIt), [false, true, false], "with no choice made, the GOG tile plays the default")
+
+ func pinTiles(_ choice: [String: Int]) -> [String] {
+ LibraryIndex.build(bottles: [games], steamByBottle: [:], epicOwned: [], epicInstalls: [:], gogInstalledByBottle: installs,
+ gogLaunchChoice: choice).filter { $0.source == .pin }.map(\.title).sorted()
+ }
+ XCTAssertEqual(pinTiles([:]), ["Benchmark", "Ghostrunner DX12"])
+ XCTAssertEqual(pinTiles(["1957528513": 1]), ["Benchmark", "Ghostrunner"], "the page now plays DX12, so the default's pin shows instead")
+ let chosen = LibraryIndex.gogCoveredPins(bottles: [games], gogInstalledByBottle: installs, launchChoice: ["1957528513": 1])
+ XCTAssertEqual(chosen.map(\.tilePlaysIt), [true, false, false])
+ }
+
+ /// Owner review on #539: a Mac app made for a program before its GOG tile stood for it ended
+ /// with "not in this Highball's library". Its link now finds the program, whose Play runs it
+ /// as the GOG game (AppState.launch(pin:), with the CoveredPin's task and arguments), not
+ /// whatever the GOG tile plays.
+ func testAPlayLinkToACoveredProgramStillFindsTheProgram() throws {
+ var games = Bottle(url: URL(fileURLWithPath: "/tmp/hb-gog-tests/bottles/Games"), settings: BottleSettings(name: "Games", engineID: "e"))
+ let tasks = try JSONDecoder().decode([GOGStore.PlayTask].self, from: Data(#"[{"isPrimary":true,"name":"Quake II RTX","path":"q2rtx.exe","type":"FileTask"}]"#.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: tasks)
+ let covered = Pin(name: "Quake II", path: "GOG Games/Quake II RTX/q2rtx.exe", arguments: ["+set", "vid_rtx", "0"])
+ let own = Pin(name: "Setup", path: "GOG Games/Quake II RTX/setup.exe")
+ games.settings.pins = [covered, own]
+ let installs = ["Games": [quake]]
+ let items = LibraryIndex.build(bottles: [games], steamByBottle: [:], epicOwned: [], epicInstalls: [:], gogInstalledByBottle: installs)
+ XCTAssertFalse(items.contains { $0.pinID == covered.id }, "the GOG tile stands for it in the library")
+ func open(_ target: PlayLink.Target) -> HighballKit.LibraryItem? {
+ LibraryIndex.coveredPinItem(forLink: target, bottles: [games], gogInstalledByBottle: installs)
+ }
+
+ let link = try XCTUnwrap(PlayLink.parse(PlayLink.url(for: .pin(bottle: "Games", id: covered.id), token: "t")))
+ let item = try XCTUnwrap(open(link.target))
+ XCTAssertEqual(item.id, "pin:Games:\(covered.id.uuidString)")
+ XCTAssertEqual(item.source, .pin)
+ XCTAssertEqual(item.pinID, covered.id)
+ XCTAssertEqual(item.bottleName, "Games")
+ XCTAssertEqual(item.title, "Quake II", "the confirmation names what the Mac app was made for")
+ XCTAssertEqual(open(.pin(bottle: "Old name", id: covered.id))?.id, item.id, "made before the environment was renamed")
+ XCTAssertNil(open(.pin(bottle: "Games", id: own.id)), "a program with its own tile is found in the library as before")
+ XCTAssertNil(open(.gog(id: "1825786806")))
+ XCTAssertNil(open(.pin(bottle: "Games", id: UUID())), "a program that is gone stays an error")
+
+ // What that Play runs: the program's own task and arguments, as the GOG game.
+ let standing = try XCTUnwrap(LibraryIndex.gogCoveredPins(bottles: [games], gogInstalledByBottle: installs).first { $0.pinItemID == item.id })
+ XCTAssertEqual(standing.gogItemID, "gog:1825786806")
+ XCTAssertEqual(standing.task.path, "q2rtx.exe")
+ XCTAssertEqual(standing.extraArguments, ["+set", "vid_rtx", "0"])
+ }
+
+ /// Owner review on #539: the carry-over took the arguments, display and graphics mode, but the
+ /// name and cover the program had stayed behind. They go now, never over a choice the GOG tile
+ /// already has, and only once. (Its plays show on the GOG tile without carrying: see
+ /// testAProgramsPlaysShowOnTheTileThatStandsForIt.)
+ func testCarryOverTakesNameAndCoverOnce() throws {
+ let home = FileManager.default.temporaryDirectory.appending(path: "gog-carry-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: home) }
+ let paths = HighballPaths(home: home)
+ let store = LibraryStore(paths: paths), names = NameStore(paths: paths), covers = CoverStore(paths: paths)
+ let task = GOGStore.PlayTask(name: "DX12", path: "Game.exe", arguments: "-dx12")
+ func pin(_ uuid: UUID, _ gog: String, extra: [String] = [], tilePlaysIt: Bool = true) -> LibraryIndex.CoveredPin {
+ LibraryIndex.CoveredPin(pinItemID: "pin:Games:\(uuid.uuidString)", gogItemID: "gog:\(gog)", extraArguments: extra, task: task, tilePlaysIt: tilePlaysIt)
+ }
+ let a = UUID(), b = UUID(), c = UUID()
+ let first = pin(a, "1", extra: ["-novid"]), second = pin(b, "2")
+ // A program on a task the GOG tile does not play keeps its tile, and so its things.
+ let elsewhere = pin(c, "3", extra: ["-other"], tilePlaysIt: false)
+ try names.setName("Kept", for: elsewhere.pinItemID)
+
+ // The first program has everything; its GOG tile nothing. The second one's GOG tile was
+ // renamed by the player.
+ try names.setName("My Game", for: first.pinItemID)
+ try FileManager.default.createDirectory(at: covers.dir, withIntermediateDirectories: true)
+ try Data("png".utf8).write(to: covers.dir.appending(path: "pin_Games_\(a.uuidString).png"))
+ store.setDisplay("DISPLAY-UUID", for: first.pinItemID)
+ store.setRendererOverride(.dxvk, for: first.pinItemID)
+ try names.setName("Old", for: second.pinItemID)
+ try names.setName("Mine", for: second.gogItemID)
+
+ var settings = GOGSettings()
+ let lines = LibraryIndex.carryOver([first, second, elsewhere], paths: paths, settings: &settings)
+ XCTAssertEqual(lines.count, 2)
+
+ XCTAssertEqual(names.name(for: "gog:1"), "My Game")
+ XCTAssertEqual(covers.coverURL(for: "gog:1")?.lastPathComponent, "gog_1.png")
+ XCTAssertEqual(store.displayChoices()["gog:1"], "DISPLAY-UUID")
+ XCTAssertEqual(store.rendererOverrides()["gog:1"], .dxvk)
+ XCTAssertEqual(store.launchArguments()["gog:1"], ["-novid"])
+
+ XCTAssertEqual(names.name(for: "gog:2"), "Mine", "a name the player gave the GOG tile stays")
+ XCTAssertNil(covers.coverURL(for: "gog:2"))
+
+ XCTAssertEqual(names.name(for: first.pinItemID), "My Game", "the program keeps its own copy, for when its tile comes back")
+ XCTAssertEqual(settings.carriedOverPins, [first.pinItemID, second.pinItemID])
+ XCTAssertNil(names.name(for: "gog:3"))
+ XCTAssertNil(store.launchArguments()["gog:3"])
+
+ // Once only: a later change on the GOG tile is not undone by the next rebuild.
+ try names.setName("Renamed again", for: "gog:1")
+ XCTAssertTrue(LibraryIndex.carryOver([first], paths: paths, settings: &settings).isEmpty)
+ XCTAssertEqual(names.name(for: "gog:1"), "Renamed again")
+ }
+
+ // MARK: Launch option swaps (round 3)
+
+ /// Ghostrunner with a default task, a DX12 choice, a Benchmark choice nobody pinned, and a
+ /// hidden crash reporter; pins on the default, on DX12 (with an extra argument) and on the
+ /// hidden task.
+ private func swapFixture(bottleName: String = "Games") throws -> (bottle: Bottle, game: GOGStore.InstalledGame, main: Pin, dx12: Pin, hidden: Pin) {
+ var games = Bottle(url: URL(fileURLWithPath: "/tmp/hb-gog-tests/bottles/\(bottleName)"), settings: BottleSettings(name: bottleName, engineID: "e"))
+ let tasks = try JSONDecoder().decode([GOGStore.PlayTask].self, from: Data(#"""
+ [{"isPrimary":true,"category":"game","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"},
+ {"category":"tool","name":"Benchmark","path":"Bench.exe","type":"FileTask"},
+ {"name":"Crash reporter","path":"CrashReporter.exe","isHidden":true,"type":"FileTask"}]
+ """#.utf8))
+ let gr = GOGStore.InstalledGame(id: "1957528513", title: "Ghostrunner", folder: games.driveC.appending(path: "GOG Games/Ghostrunner"),
+ buildID: nil, clientID: nil, dlcIDs: [], tasks: tasks)
+ let exe = "GOG Games/Ghostrunner/Ghostrunner/Binaries/Win64/Ghostrunner-Win64-Shipping.exe"
+ let main = Pin(name: "Ghostrunner", path: exe, arguments: ["-GOG"])
+ let dx12 = Pin(name: "Ghostrunner DX12", path: exe, arguments: ["-GOG", "-dx12", "-novid"])
+ let hidden = Pin(name: "Crash reporter", path: "GOG Games/Ghostrunner/CrashReporter.exe")
+ games.settings.pins = [main, dx12, hidden]
+ return (games, gr, main, dx12, hidden)
+ }
+
+ /// What Play on a tile runs, decided as AppState does: the GOG tile its page's choice
+ /// (gogPlay), a program the GOG game when it runs one of its tasks, with its own task and
+ /// arguments (launch(pin:) → gogPlay(as:)), any other program itself.
+ private func playTarget(_ item: HighballKit.LibraryItem, bottles: [Bottle], installs: [String: [GOGStore.InstalledGame]],
+ choice: [String: Int]) -> (exe: String, arguments: [String], asGOG: Bool)? {
+ switch item.source {
+ case .gog:
+ guard let game = installs[item.bottleName ?? ""]?.first(where: { $0.id == item.gogID }),
+ let launch = game.launchTask(choice: choice[game.id]).flatMap({ GOGStore.launch($0, in: game) }) else { return nil }
+ return (launch.executable.lastPathComponent, launch.arguments, true)
+ case .pin:
+ guard let bottle = bottles.first(where: { $0.name == item.bottleName }),
+ let pin = bottle.settings.pins.first(where: { $0.id == item.pinID }) else { return nil }
+ if let covered = LibraryIndex.gogCoveredPins(bottles: [bottle], gogInstalledByBottle: installs).first(where: { $0.pinItemID == item.id }),
+ let game = installs[bottle.name]?.first(where: { "gog:\($0.id)" == covered.gogItemID }),
+ let launch = GOGStore.launch(covered.task, in: game) {
+ return (launch.executable.lastPathComponent, launch.arguments + covered.extraArguments, true)
+ }
+ return (pin.launchURL(driveC: bottle.driveC).lastPathComponent, pin.arguments, false)
+ default:
+ return nil
+ }
+ }
+
+ /// The launch option switched between two pinned programs, to one nobody pinned, and back,
+ /// several times: the tiles swap each time, every tile on screen plays what it shows, and
+ /// the same choice always gives the same library (no drift, no duplicate tiles).
+ func testSwitchingTheLaunchOptionSwapsTilesAndComesBackTheSame() throws {
+ let f = try swapFixture()
+ let bottles = [f.bottle], installs = ["Games": [f.game]]
+ let main = "pin:Games:\(f.main.id.uuidString)", dx12 = "pin:Games:\(f.dx12.id.uuidString)", hidden = "pin:Games:\(f.hidden.id.uuidString)"
+ func library(_ choice: [String: Int]) -> [HighballKit.LibraryItem] {
+ LibraryIndex.build(bottles: bottles, steamByBottle: [:], epicOwned: [], epicInstalls: [:], gogInstalledByBottle: installs,
+ gogLaunchChoice: choice)
+ }
+ func check(_ choice: [String: Int], shows pins: Set<String>, gogPlays exe: String, _ gogArguments: [String],
+ file: StaticString = #filePath, line: UInt = #line) {
+ let items = library(choice)
+ XCTAssertEqual(items, library(choice), "a second rebuild gives the same library", file: file, line: line)
+ XCTAssertEqual(Set(items.map(\.id)).count, items.count, "no tile twice", file: file, line: line)
+ XCTAssertEqual(Set(items.filter { $0.source == .pin }.map(\.id)), pins, file: file, line: line)
+ XCTAssertEqual(items.filter { $0.source == .gog }.map(\.id), ["gog:1957528513"], file: file, line: line)
+ var targets: [String: (exe: String, arguments: [String], asGOG: Bool)] = [:]
+ for item in items { targets[item.id] = playTarget(item, bottles: bottles, installs: installs, choice: choice) }
+ XCTAssertEqual(targets["gog:1957528513"]?.exe, exe, file: file, line: line)
+ XCTAssertEqual(targets["gog:1957528513"]?.arguments, gogArguments, file: file, line: line)
+ if let t = targets[main] {
+ XCTAssertEqual(t.arguments, ["-GOG"], file: file, line: line); XCTAssertTrue(t.asGOG, file: file, line: line)
+ }
+ if let t = targets[dx12] {
+ XCTAssertEqual(t.arguments, ["-GOG", "-dx12", "-novid"], file: file, line: line); XCTAssertTrue(t.asGOG, file: file, line: line)
+ }
+ XCTAssertEqual(targets[hidden]?.exe, "CrashReporter.exe", file: file, line: line)
+ XCTAssertEqual(targets[hidden]?.asGOG, false, "a hidden task is not one the GOG tile plays: a plain program", file: file, line: line)
+ // A pin hidden behind the GOG tile runs exactly what the GOG tile runs.
+ for pin in LibraryIndex.gogCoveredPins(bottles: bottles, gogInstalledByBottle: installs, launchChoice: choice) where pin.tilePlaysIt {
+ XCTAssertFalse(pins.contains(pin.pinItemID), file: file, line: line)
+ XCTAssertEqual(f.game.launchTask(choice: choice[f.game.id]), pin.task, file: file, line: line)
+ }
+ }
+ let first = library([:])
+ for _ in 0..<3 {
+ check([:], shows: [dx12, hidden], gogPlays: "Ghostrunner-Win64-Shipping.exe", ["-GOG"])
+ check(["1957528513": 1], shows: [main, hidden], gogPlays: "Ghostrunner-Win64-Shipping.exe", ["-GOG", "-dx12"])
+ check(["1957528513": 2], shows: [main, dx12, hidden], gogPlays: "Bench.exe", [])
+ check(["1957528513": 0], shows: [dx12, hidden], gogPlays: "Ghostrunner-Win64-Shipping.exe", ["-GOG"]) // the page's own entry for the default
+ check(["1957528513": 9], shows: [dx12, hidden], gogPlays: "Ghostrunner-Win64-Shipping.exe", ["-GOG"]) // a choice gone after an update
+ }
+ XCTAssertEqual(library([:]), first, "back where it started")
+ XCTAssertEqual(LibraryIndex.gogCoveredPins(bottles: bottles, gogInstalledByBottle: installs).map(\.pinItemID), [main, dx12],
+ "the hidden task's program is never covered")
+ }
+
+ /// Program paths and GOG's task paths are matched as Windows would: case, \ against /, and a
+ /// path with . or .. in it; a file beside the program never counts.
+ func testProgramPathsMatchTheTaskWhateverTheirSpelling() throws {
+ let f = try swapFixture()
+ var bottle = f.bottle
+ let drive = bottle.driveC.path
+ let spellings = ["gog games/GHOSTRUNNER/ghostrunner/binaries/win64/GHOSTRUNNER-WIN64-SHIPPING.EXE",
+ "GOG Games/Ghostrunner/./Ghostrunner/Binaries/Win64/../Win64/Ghostrunner-Win64-Shipping.exe",
+ "\(drive)/GOG Games/Ghostrunner/Ghostrunner/Binaries/Win64/Ghostrunner-Win64-Shipping.exe"]
+ let pins = spellings.map { Pin(name: $0, path: $0, arguments: ["-GOG"]) }
+ let beside = Pin(name: "Beside", path: "GOG Games/Ghostrunner/Ghostrunner/Binaries/Win64/Ghostrunner-Win64-Shipping_DX11.exe", arguments: ["-GOG"])
+ bottle.settings.pins = pins + [beside]
+ let covered = LibraryIndex.gogCoveredPins(bottles: [bottle], gogInstalledByBottle: ["Games": [f.game]])
+ XCTAssertEqual(covered.map(\.pinItemID), pins.map { "pin:Games:\($0.id.uuidString)" })
+ XCTAssertTrue(covered.allSatisfy { $0.task.name == "Ghostrunner" && $0.tilePlaysIt })
+ }
+
+ /// The name and cover go to the GOG tile once per program, however often swaps hide and show
+ /// it, and not again after its environment is renamed (its id changes then).
+ func testCarryOverRunsOncePerProgramThroughSwapsAndARename() throws {
+ let home = FileManager.default.temporaryDirectory.appending(path: "gog-swap-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: home) }
+ let paths = HighballPaths(home: home)
+ let names = NameStore(paths: paths), store = LibraryStore(paths: paths)
+ var f = try swapFixture()
+ var installs = ["Games": [f.game]]
+ try names.setName("My Ghostrunner", for: "pin:Games:\(f.main.id.uuidString)")
+ try names.setName("DX12 run", for: "pin:Games:\(f.dx12.id.uuidString)")
+ store.setDisplay("PIN-DISPLAY", for: "pin:Games:\(f.main.id.uuidString)")
+ store.setDisplay("TILE-DISPLAY", for: "gog:1957528513")
+ var settings = GOGSettings()
+ // What rebuildLibrary does before building (AppState.carryOverGOGCoveredPins).
+ func rebuild(_ choice: [String: Int]) -> [String] {
+ let covered = LibraryIndex.gogCoveredPins(bottles: [f.bottle], gogInstalledByBottle: installs, launchChoice: choice)
+ .filter { $0.tilePlaysIt && !LibraryIndex.wasCarriedOver($0.pinItemID, in: settings.carriedOverPins) }
+ return LibraryIndex.carryOver(covered, paths: paths, settings: &settings)
+ }
+
+ XCTAssertEqual(rebuild([:]).count, 1)
+ XCTAssertEqual(names.name(for: "gog:1957528513"), "My Ghostrunner")
+ XCTAssertEqual(store.displayChoices()["gog:1957528513"], "TILE-DISPLAY", "the GOG tile's own display stays")
+ try names.setName(nil, for: "gog:1957528513") // the player clears it on the GOG tile
+
+ XCTAssertEqual(rebuild(["1957528513": 1]).count, 1, "the DX12 program is hidden for the first time")
+ XCTAssertEqual(names.name(for: "gog:1957528513"), "DX12 run")
+ try names.setName("Mine", for: "gog:1957528513")
+ for choice in [[:], ["1957528513": 1], [:], ["1957528513": 2], [:]] as [[String: Int]] {
+ XCTAssertTrue(rebuild(choice).isEmpty, "hidden again: nothing goes twice")
+ }
+ XCTAssertEqual(names.name(for: "gog:1957528513"), "Mine")
+
+ // The environment is renamed: the programs get new ids, which were carried under the old one.
+ f.bottle.settings.name = "Games 2"
+ f.bottle = Bottle(url: URL(fileURLWithPath: "/tmp/hb-gog-tests/bottles/Games 2"), settings: f.bottle.settings)
+ // Installs are read off disk again, from the renamed environment's folder.
+ installs = ["Games 2": [GOGStore.InstalledGame(id: f.game.id, title: f.game.title, folder: f.bottle.driveC.appending(path: "GOG Games/Ghostrunner"),
+ buildID: nil, clientID: nil, dlcIDs: [], tasks: f.game.tasks)]]
+ try names.setName(nil, for: "gog:1957528513")
+ XCTAssertEqual(LibraryIndex.gogCoveredPins(bottles: [f.bottle], gogInstalledByBottle: installs).filter(\.tilePlaysIt).map(\.pinItemID),
+ ["pin:Games 2:\(f.main.id.uuidString)"], "hiding still follows the program")
+ XCTAssertTrue(rebuild([:]).isEmpty, "not carried again after a rename")
+ XCTAssertNil(names.name(for: "gog:1957528513"), "a name cleared on the GOG tile stays cleared")
+ XCTAssertEqual(settings.carriedOverPins.count, 2)
+ }
+
+ /// When a program was last played shows on whichever tile stands for it now: the GOG tile while
+ /// it is hidden behind it, its own tile when a swap shows it again. A play is never lost and
+ /// never on two tiles.
+ func testAProgramsPlaysShowOnTheTileThatStandsForIt() throws {
+ let f = try swapFixture()
+ let installs = ["Games": [f.game]]
+ let main = "pin:Games:\(f.main.id.uuidString)", dx12 = "pin:Games:\(f.dx12.id.uuidString)"
+ let t = (gog: Date(timeIntervalSince1970: 1_000), main: Date(timeIntervalSince1970: 2_000), dx12: Date(timeIntervalSince1970: 3_000))
+ let plays = ["gog:1957528513": LibraryStore.PlayRecord(lastPlayedAt: t.gog, bottle: "Games"),
+ main: LibraryStore.PlayRecord(lastPlayedAt: t.main, bottle: "Games"),
+ dx12: LibraryStore.PlayRecord(lastPlayedAt: t.dx12, bottle: "Games")]
+ func lastPlayed(_ choice: [String: Int]) -> [String: Date] {
+ let items = LibraryIndex.build(bottles: [f.bottle], steamByBottle: [:], epicOwned: [], epicInstalls: [:], gogInstalledByBottle: installs,
+ gogLaunchChoice: choice, plays: plays)
+ return Dictionary(uniqueKeysWithValues: items.compactMap { item in item.lastPlayed.map { (item.id, $0) } })
+ }
+ XCTAssertEqual(lastPlayed([:]), ["gog:1957528513": t.main, dx12: t.dx12])
+ XCTAssertEqual(lastPlayed(["1957528513": 1]), ["gog:1957528513": t.dx12, main: t.main])
+ XCTAssertEqual(lastPlayed(["1957528513": 2]), ["gog:1957528513": t.gog, main: t.main, dx12: t.dx12], "nothing hidden: each its own")
+ XCTAssertEqual(lastPlayed([:]), ["gog:1957528513": t.main, dx12: t.dx12])
+ }
+
+ /// A Mac app made for a program finds it whether its tile is shown or hidden at the time, and
+ /// plays its own task and arguments as the GOG game either way, also after a rename.
+ func testAPlayLinkRunsTheProgramWhetherItsTileIsShownOrHidden() throws {
+ let f = try swapFixture()
+ let bottles = [f.bottle], installs = ["Games": [f.game]]
+ for choice in [[:], ["1957528513": 1]] as [[String: Int]] {
+ let items = LibraryIndex.build(bottles: bottles, steamByBottle: [:], epicOwned: [], epicInstalls: [:], gogInstalledByBottle: installs,
+ gogLaunchChoice: choice)
+ for (pin, arguments) in [(f.main, ["-GOG"]), (f.dx12, ["-GOG", "-dx12", "-novid"])] {
+ for target in [PlayLink.Target.pin(bottle: "Games", id: pin.id), .pin(bottle: "Before a rename", id: pin.id)] {
+ // AppState.resolvePlayLink: the library first, then the program behind its GOG tile.
+ let item = try XCTUnwrap(items.first { $0.id == target.libraryID }
+ ?? LibraryIndex.coveredPinItem(forLink: target, bottles: bottles, gogInstalledByBottle: installs))
+ XCTAssertEqual(item.pinID, pin.id)
+ let played = try XCTUnwrap(playTarget(item, bottles: bottles, installs: installs, choice: choice))
+ XCTAssertEqual(played.arguments, arguments)
+ XCTAssertTrue(played.asGOG)
+ }
+ }
+ }
+ }
+
+ /// Without the game installed in a program's own environment nothing is hidden and every
+ /// program plays itself; a GOG account is not needed for an install on disk to stand in.
+ func testNothingIsHiddenWithoutTheGameInThatEnvironment() throws {
+ let f = try swapFixture()
+ let other = Bottle(url: URL(fileURLWithPath: "/tmp/hb-gog-tests/bottles/Other"), settings: BottleSettings(name: "Other", engineID: "e"))
+ for installs in [[:], ["Other": [f.game]]] as [[String: [GOGStore.InstalledGame]]] {
+ XCTAssertTrue(LibraryIndex.gogCoveredPins(bottles: [f.bottle, other], gogInstalledByBottle: installs).isEmpty)
+ let items = LibraryIndex.build(bottles: [f.bottle, other], steamByBottle: [:], epicOwned: [], epicInstalls: [:], gogInstalledByBottle: installs)
+ XCTAssertEqual(items.filter { $0.source == .pin }.count, 3)
+ for item in items where item.source == .pin {
+ XCTAssertEqual(playTarget(item, bottles: [f.bottle, other], installs: installs, choice: [:])?.asGOG, false)
+ }
+ }
+ // Not signed in (no account games), installed here: the install alone stands in.
+ let items = LibraryIndex.build(bottles: [f.bottle], steamByBottle: [:], epicOwned: [], epicInstalls: [:], gogGames: [],
+ gogInstalledByBottle: ["Games": [f.game]])
+ XCTAssertEqual(items.filter { $0.source == .pin }.count, 2)
+ }
+
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)
@@ -433,4 +810,66 @@ final class GOGStoreTests: XCTestCase {
XCTAssertEqual(found.rarityLevel, "Uncommon")
XCTAssertEqual(GOGAchievements.details(key: "OTHER", name: "logged", database: db), GOGAchievement(key: "OTHER", name: "logged"))
}
+
+ // MARK: Pinned tools
+
+ /// Owner review on #539: ensure() kept whatever sat at tools/gogdl, so moving the pin to a
+ /// newer gogdl or comet never reached existing installs. The file there is checked against the
+ /// pinned checksum and replaced when it differs; a right one is left alone. No network: the
+ /// "release" is a local file, which EngineStore.download verifies the same way.
+ func testPinnedToolIsReplacedWhenItIsNotThePinnedBuild() async throws {
+ let root = FileManager.default.temporaryDirectory.appending(path: "gog-tools-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let gog = GOGStore(paths: HighballPaths(home: root.appending(path: "home")))
+ let release = root.appending(path: "gogdl-1.4.0")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ try Data("gogdl 1.4.0".utf8).write(to: release)
+ let sha = try EngineStore(paths: gog.paths).sha256(of: release)
+ func component(_ url: URL) -> EngineManifest.Component {
+ EngineManifest.Component(kind: "tool", url: url, sha256: sha, size: nil, license: nil, optional: nil,
+ acceptance: nil, extract: nil, note: nil, version: "1.4.0")
+ }
+ let binary = gog.gogdlBinary
+ try FileManager.default.createDirectory(at: binary.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("gogdl 1.3.1".utf8).write(to: binary)
+ XCTAssertFalse(gog.isPinned(binary, sha256: sha))
+
+ _ = try await gog.ensure(component(release), name: "gogdl", at: binary, progress: nil)
+ XCTAssertEqual(try Data(contentsOf: binary), Data("gogdl 1.4.0".utf8), "the old build is replaced")
+ XCTAssertEqual((try FileManager.default.attributesOfItem(atPath: binary.path)[.posixPermissions] as? NSNumber)?.intValue, 0o755)
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: binary.deletingLastPathComponent().path), ["gogdl"],
+ "nothing staged is left beside it")
+
+ // Now right: a release that cannot be fetched is never asked for.
+ let gone = root.appending(path: "missing")
+ _ = try await gog.ensure(component(gone), name: "gogdl", at: binary, progress: nil)
+
+ // Changed on disk since it was checked (a damaged copy): checked again, and replaced.
+ try Data("damaged!!!!".utf8).write(to: binary)
+ XCTAssertFalse(gog.isPinned(binary, sha256: sha))
+ _ = try await gog.ensure(component(release), name: "gogdl", at: binary, progress: nil)
+ XCTAssertTrue(gog.isPinned(binary, sha256: sha))
+ }
+
+ /// The program running from the old file keeps it: the new one is renamed over the path, so
+ /// an open handle on the old file still reads the old build.
+ func testReplacingAToolLeavesARunningCopyItsFile() async throws {
+ let root = FileManager.default.temporaryDirectory.appending(path: "gog-tools-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let gog = GOGStore(paths: HighballPaths(home: root.appending(path: "home")))
+ let release = root.appending(path: "comet-0.4.1")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ try Data("comet 0.4.1".utf8).write(to: release)
+ let component = EngineManifest.Component(kind: "tool", url: release, sha256: try EngineStore(paths: gog.paths).sha256(of: release),
+ size: nil, license: nil, optional: nil, acceptance: nil, extract: nil, note: nil, version: "0.4.1")
+ let binary = gog.cometBinary
+ try FileManager.default.createDirectory(at: binary.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("comet 0.4.0".utf8).write(to: binary)
+ let running = try FileHandle(forReadingFrom: binary)
+ defer { try? running.close() }
+
+ _ = try await gog.ensure(component, name: "comet", at: binary, progress: nil)
+ XCTAssertEqual(try running.readToEnd(), Data("comet 0.4.0".utf8))
+ XCTAssertEqual(try Data(contentsOf: binary), Data("comet 0.4.1".utf8))
+ }
}