Skip to content

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

GOG saves: offline installs date from their info file, Stop during Keep stops, and Not now asks again

Gabedcd4782cac7c
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index c5203b3..0d238b6 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -1402,6 +1402,14 @@ final class AppState {
}
}
+ /// Throws once the player pressed Stop. For a step after detached work, which runs on through
+ /// a cancel: checked on the main task, and on `stopRequested` too, since a Stop that kills the
+ /// environment first cancels only once the kill returns.
+ private func checkStopped() throws {
+ try Task.checkCancellation()
+ if stopRequested { throw CancellationError() }
+ }
+
/// The strip's Stop button. What it does depends on the operation (see `BusyStop`); the
/// operation's own error path then reads as "stopped", never as a failure.
func stopBusy() {
@@ -4039,6 +4047,9 @@ final class AppState {
/// What can still be backed up, and the locations that can't; nil when GOG couldn't be
/// reached to say where the saves are.
let plan: GOGSaves.UninstallPlan?
+ /// Nothing dates the install (GOGStore.history), so the files the game wrote in its folder
+ /// can't be told from the installer's and none are copied.
+ var gameFolderUncopied = false
}
var gogRemovalWithoutBackup: GOGRemovalWithoutBackup?
@@ -4050,6 +4061,10 @@ final class AppState {
}
var gogSavesToPutBack: GOGSavesToPutBack?
+ /// Installs whose put-back question was answered Not now: asked again the next time Highball
+ /// starts, not in this run.
+ private var gogPutBackLater: Set<String> = []
+
/// Offers, once per install, to put back saves an uninstall kept of the same game. Only once
/// Highball has set the install up (its setup could replace what is put back) and while the
/// game isn't running.
@@ -4061,6 +4076,7 @@ final class AppState {
for bottle in bottles {
for game in gogInstalledByBottle[bottle.name] ?? [] {
guard let kept = GOGSaves.toOffer(all[game.id], to: game),
+ !gogPutBackLater.contains(game.folder.standardizedFileURL.path),
!gogStore.hasManifest(game) || GOGStore.setupDone(for: game, driveC: bottle.driveC),
!runningSessions.contains(where: { $0.libraryID == "gog:\(game.id)" && $0.bottleName == bottle.name }) else { continue }
gogSavesToPutBack = GOGSavesToPutBack(game: game, title: game.title, kept: kept)
@@ -4069,13 +4085,20 @@ final class AppState {
}
}
- /// The answer to the put-back question; either way that install isn't asked again.
- func gogPutBackSaves(_ putBack: Bool) {
+ enum PutBackAnswer { case putBack, notNow, dontAskAgain }
+
+ /// The answer to the put-back question. Not now asks again the next time Highball starts;
+ /// the other two answer that install for good.
+ func gogPutBackSaves(_ answer: PutBackAnswer) {
guard let pending = gogSavesToPutBack else { return }
gogSavesToPutBack = nil
let saves = GOGSaves(store: gogStore)
- saves.markAsked(pending.game)
- guard putBack else { offerKeptGOGSaves(); return }
+ if answer == .notNow {
+ gogPutBackLater.insert(pending.game.folder.standardizedFileURL.path)
+ } else {
+ saves.markAsked(pending.game)
+ }
+ guard answer == .putBack else { offerKeptGOGSaves(); return }
Task {
do {
let count = try await Task.detached { try saves.putBack(pending.kept, into: pending.game) }.value
@@ -4099,7 +4122,8 @@ final class AppState {
/// cloud-save folders, and what the game wrote there since Highball set it up), runs the
/// game's own uninstaller when an offline installer left one (it cleans the registry), then
/// deletes the folder and what gogdl kept about the game. When some saves can't be backed up
- /// (GOG unreachable, or a location Highball can't resolve), the player is asked first
+ /// (GOG unreachable, a location Highball can't resolve, or nothing dates the install so the
+ /// game's own files in its folder can't be told apart), the player is asked first
/// (gogRemovalWithoutBackup); `agreed` is their go-ahead. `deleteSaves` copies nothing and
/// also deletes the game's save folders elsewhere in the environment.
private func gogUninstall(id: String, title: String, in bottle: Bottle, deleteSaves: Bool = false,
@@ -4110,6 +4134,9 @@ final class AppState {
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
+ // The game folder copy tells the game's files from the installer's by when the install
+ // was set up or installed; with neither, Keep can't copy them and must say so.
+ let datable = GOGSaves.canTellGameFiles(game, driveC: bottle.driveC)
let plan: GOGSaves.UninstallPlan
if let agreed {
plan = agreed.plan ?? GOGSaves.UninstallPlan()
@@ -4119,13 +4146,15 @@ final class AppState {
if deleteSaves {
plan = found ?? GOGSaves.UninstallPlan()
if found == nil { appendLog("\(title): GOG couldn't be reached, so save folders outside the game's folder stay") }
- } else if let found, found.cannotBackUp.isEmpty {
+ } else if let found, found.cannotBackUp.isEmpty, datable {
plan = found
} else {
- gogRemovalWithoutBackup = GOGRemovalWithoutBackup(id: id, title: title, bottle: bottle, plan: found)
+ gogRemovalWithoutBackup = GOGRemovalWithoutBackup(id: id, title: title, bottle: bottle, plan: found,
+ gameFolderUncopied: !datable)
busyDoneOverride = .handedOff // the question takes over; nothing was removed
return
}
+ try checkStopped()
}
// Saves inside the game's folder would be deleted with it, so back them up before
// anything runs, and stop if a backup fails. These backups are never pruned.
@@ -4138,6 +4167,7 @@ final class AppState {
appendLog("\(title): saves inside the game's folder copied to \(copy.path)")
kept.append((location.name, folder, copy))
}
+ try checkStopped() // a detached copy runs on through a Stop: nothing is removed after one
}
let skipping = plan.backUp.map(\.folder)
if let copy = try await Task.detached(operation: { try saves.backUpGameFolder(game, driveC: bottle.driveC, skipping: skipping) }).value {
@@ -4146,6 +4176,7 @@ final class AppState {
kept.append((GOGSaves.gameFolder.name, game.folder, copy))
}
}
+ try checkStopped()
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")
diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swift
index 65acd08..d27c608 100644
--- a/Sources/HighballApp/HighballApp.swift
+++ b/Sources/HighballApp/HighballApp.swift
@@ -567,10 +567,11 @@ private extension View {
// the next game's question, which an answer may already have raised.
isPresented: .init(get: { state.gogSavesToPutBack != nil }, set: { _ in }),
presenting: state.gogSavesToPutBack) { _ in
- Button(L("Put them back")) { state.gogPutBackSaves(true) }.keyboardShortcut(.defaultAction)
- Button(L("Not now"), role: .cancel) { state.gogPutBackSaves(false) }
+ Button(L("Put them back")) { state.gogPutBackSaves(.putBack) }.keyboardShortcut(.defaultAction)
+ Button(L("Not now"), role: .cancel) { state.gogPutBackSaves(.notNow) }
+ Button(L("Don't ask again")) { state.gogPutBackSaves(.dontAskAgain) }
} message: { pending in
- Text(String(format: L("Highball kept %@'s saves when it was removed. Put them back copies them into the game's folder; anything already there is copied to save-backups first."), pending.title))
+ Text(String(format: L("Highball kept %@'s saves when it was removed. Put them back copies them into the game's folder; anything already there is copied to save-backups first. Not now asks again the next time Highball starts."), pending.title))
}
}
@@ -583,9 +584,21 @@ private extension View {
Button(L("Remove anyway"), role: .destructive) { state.gogRemoveWithoutBackup() }
Button(L("Cancel"), role: .cancel) { state.gogRemovalWithoutBackup = nil }
} message: { pending in
- Text(pending.plan == nil
- ? String(format: L("Highball couldn't reach GOG to find out where %@ keeps its saves, so the save folders GOG names inside the game's folder are deleted with it. Files the game changed in its folder since you first played it are still copied to save-backups first, and saves already in GOG's cloud are not affected. To keep every save, cancel and try again once GOG can be reached."), pending.title)
- : String(format: L("GOG says %@ keeps some of its saves directly in the game's folder, which Highball can't copy as one save folder. Files the game changed in its folder since you first played it are still copied to save-backups first, along with its other save folders, and saves already in GOG's cloud are not affected."), pending.title))
+ Text(Self.removalWithoutBackupMessage(pending))
+ }
+ }
+
+ /// What is and isn't copied first, in the case the removal is in.
+ static func removalWithoutBackupMessage(_ pending: AppState.GOGRemovalWithoutBackup) -> String {
+ switch (pending.plan == nil, pending.gameFolderUncopied) {
+ case (true, false):
+ String(format: L("Highball couldn't reach GOG to find out where %@ keeps its saves, so the save folders GOG names inside the game's folder are deleted with it. Files the game changed in its folder since you first played it are still copied to save-backups first, and saves already in GOG's cloud are not affected. To keep every save, cancel and try again once GOG can be reached."), pending.title)
+ case (false, false):
+ String(format: L("GOG says %@ keeps some of its saves directly in the game's folder, which Highball can't copy as one save folder. Files the game changed in its folder since you first played it are still copied to save-backups first, along with its other save folders, and saves already in GOG's cloud are not affected."), pending.title)
+ case (true, true):
+ String(format: L("Highball couldn't reach GOG to find out where %@ keeps its saves, and can't tell which files in the game's folder the game wrote, because nothing records when it was installed. So nothing in the game's folder is copied first, and saves there are deleted with it. Saves already in GOG's cloud are not affected. To keep its save folders, cancel and try again once GOG can be reached."), pending.title)
+ case (false, true):
+ String(format: L("Highball can't tell which files in %@'s folder the game wrote, because nothing records when it was installed. Only the save folders GOG names are copied to save-backups first; any other save the game kept in its folder is deleted with it. Saves already in GOG's cloud are not affected."), pending.title)
}
}
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index f9ff6d2..cdcbfca 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -237,7 +237,12 @@ enum L10n {
"Delete save data too": "Supprimer aussi les sauvegardes",
"Put back your saves from %@?": "Remettre vos sauvegardes du %@ ?",
"Put them back": "Les remettre",
- "Highball kept %@'s saves when it was removed. Put them back copies them into the game's folder; anything already there is copied to save-backups first.": "Highball a gardé les sauvegardes de %@ lors de sa suppression. Les remettre les copie dans le dossier du jeu ; ce qui s’y trouve déjà est d’abord copié dans save-backups.",
+ "Don't ask again": "Ne plus demander",
+ "Highball kept %@'s saves when it was removed. Put them back copies them into the game's folder; anything already there is copied to save-backups first. Not now asks again the next time Highball starts.": "Highball a gardé les sauvegardes de %@ lors de sa suppression. Les remettre les copie dans le dossier du jeu ; ce qui s’y trouve déjà est d’abord copié dans save-backups. Pas maintenant redemandera au prochain lancement de Highball.",
+ "Highball couldn't reach GOG to find out where %@ keeps its saves, and can't tell which files in the game's folder the game wrote, because nothing records when it was installed. So nothing in the game's folder is copied first, and saves there are deleted with it. Saves already in GOG's cloud are not affected. To keep its save folders, cancel and try again once GOG can be reached.":
+ "Highball n’a pas pu joindre GOG pour savoir où %@ garde ses sauvegardes, et ne peut pas savoir quels fichiers du dossier du jeu le jeu a écrits, car rien n’indique quand il a été installé. Rien dans le dossier du jeu n’est donc copié d’abord, et les sauvegardes qui s’y trouvent sont supprimées avec lui. Les sauvegardes déjà dans le cloud GOG ne sont pas touchées. Pour garder ses dossiers de sauvegarde, annulez et réessayez quand GOG est joignable.",
+ "Highball can't tell which files in %@'s folder the game wrote, because nothing records when it was installed. Only the save folders GOG names are copied to save-backups first; any other save the game kept in its folder is deleted with it. Saves already in GOG's cloud are not affected.":
+ "Highball ne peut pas savoir quels fichiers du dossier de %@ le jeu a écrits, car rien n’indique quand il a été installé. Seuls les dossiers de sauvegarde indiqués par GOG sont d’abord copiés dans save-backups ; toute autre sauvegarde que le jeu gardait dans son dossier est supprimée avec lui. Les sauvegardes déjà dans le cloud GOG ne sont pas touchées.",
"Highball could not put back all of %@'s saves: %@": "Highball n’a pas pu remettre toutes les sauvegardes de %@ : %@",
"GOG says %@ keeps some of its saves directly in the game's folder, which Highball can't copy as one save folder. Files the game changed in its folder since you first played it are still copied to save-backups first, along with its other save folders, and saves already in GOG's cloud are not affected.":
"Selon GOG, %@ garde une partie de ses sauvegardes directement dans le dossier du jeu, que Highball ne peut pas copier comme un dossier de sauvegardes. Les fichiers que le jeu a modifiés dans son dossier depuis votre première partie sont tout de même copiés dans save-backups, avec ses autres dossiers de sauvegardes, et celles déjà dans le cloud GOG ne sont pas touchées.",
diff --git a/Sources/HighballKit/GOGLibrary.swift b/Sources/HighballKit/GOGLibrary.swift
index da8b101..4481fa3 100644
--- a/Sources/HighballKit/GOGLibrary.swift
+++ b/Sources/HighballKit/GOGLibrary.swift
@@ -524,7 +524,7 @@ extension GOGStore {
public static func markSetupDone(for game: InstalledGame, driveC: URL) {
// Read before the marker is rewritten: an install from before the history falls back
// to the marker's old date.
- var history = history(for: game, driveC: driveC)
+ var history = storedHistory(for: game, driveC: driveC)
if history.firstSetup == nil { history.firstSetup = Date() }
save(history, for: game, driveC: driveC)
let url = setupMarker(for: game, driveC: driveC)
@@ -554,8 +554,20 @@ extension GOGStore {
}
/// An install set up before the history was kept falls back to the marker's date for its
- /// first setup.
+ /// first setup. One Highball never set up (an offline installer's: no manifest, so no setup
+ /// and no marker) falls back to when its goggame-<id>.info file landed on this disk, which
+ /// the install wrote. nil firstSetup: none of them exists, so nothing tells the game's files
+ /// from the installer's.
public static func history(for game: InstalledGame, driveC: URL) -> InstallHistory {
+ var history = storedHistory(for: game, driveC: driveC)
+ if history.firstSetup == nil { history.firstSetup = installedDate(of: game) }
+ return history
+ }
+
+ /// The history file, or the marker's date. Not the info file's: setup and updates record
+ /// from this, and setup runs after gogdl wrote the info file, so what it put down would
+ /// count as the game's.
+ private static func storedHistory(for game: InstalledGame, driveC: URL) -> InstallHistory {
var history = (try? Data(contentsOf: historyFile(for: game, driveC: driveC)))
.flatMap { try? JSONDecoder().decode(InstallHistory.self, from: $0) } ?? InstallHistory()
if history.firstSetup == nil {
@@ -564,6 +576,17 @@ extension GOGStore {
return history
}
+ /// When the install wrote the game's goggame-<id>.info file: when the file was created, or
+ /// the game's folder if that is earlier (a patch rewrites the file, never the folder). Its
+ /// modification date only when the disk keeps no creation dates: an offline installer gives
+ /// the files it unpacks the date they were built, before the install.
+ static func installedDate(of game: InstalledGame) -> Date? {
+ let info = game.folder.appending(path: "goggame-\(game.id).info")
+ guard let values = try? info.resourceValues(forKeys: [.contentModificationDateKey, .creationDateKey]) else { return nil }
+ let folderCreated = try? game.folder.resourceValues(forKeys: [.creationDateKey]).creationDate
+ return [values.creationDate, folderCreated].compactMap { $0 }.min() ?? values.contentModificationDate
+ }
+
private static func save(_ history: InstallHistory, for game: InstalledGame, driveC: URL) {
let url = historyFile(for: game, driveC: driveC)
try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
@@ -572,7 +595,7 @@ extension GOGStore {
/// An update ran from `start` to `end`: what changed in the game's folder then is the patch's.
public static func recordUpdate(for game: InstalledGame, driveC: URL, start: Date, end: Date) {
- var history = history(for: game, driveC: driveC)
+ var history = storedHistory(for: game, driveC: driveC)
history.updates.append(.init(start: start, end: end))
save(history, for: game, driveC: driveC)
}
diff --git a/Sources/HighballKit/GOGSaves.swift b/Sources/HighballKit/GOGSaves.swift
index ca9758b..bbab224 100644
--- a/Sources/HighballKit/GOGSaves.swift
+++ b/Sources/HighballKit/GOGSaves.swift
@@ -330,22 +330,41 @@ public struct GOGSaves: Sendable {
}
/// Before an uninstall, backs up (kept) every file the game wrote in its own folder: changed
- /// after Highball first set it up there and outside its updates (GOGStore.InstallHistory),
- /// which is where a game without cloud saves often keeps them. Files under `skipping` (the
- /// locations backed up on their own) are left out. nil when Highball never set the game up
- /// in this environment, or it wrote nothing. Throws if the backup fails; the uninstall must
- /// then stop.
+ /// after Highball first set it up there (or, never set up, after it was installed) and
+ /// outside its updates (GOGStore.InstallHistory), which is where a game without cloud saves
+ /// often keeps them. Files under `skipping` (the locations backed up on their own) and the
+ /// install's own records are left out. nil when nothing dates the install, or the game wrote
+ /// nothing. Throws if the backup fails; the uninstall must then stop.
public func backUpGameFolder(_ game: GOGStore.InstalledGame, driveC: URL, skipping: [URL] = []) throws -> URL? {
let history = GOGStore.history(for: game, driveC: driveC)
guard history.firstSetup != nil else { return nil }
let skipped = skipping.map { $0.standardizedFileURL.path + "/" }
+ let top = game.folder.standardizedFileURL.path + "/"
let written = try Self.files(in: game.folder, writtenPer: history).filter { file in
- !skipped.contains { file.standardizedFileURL.path.hasPrefix($0) }
+ let path = file.standardizedFileURL.path
+ return !skipped.contains { path.hasPrefix($0) } && !Self.isInstallerRecord(path, in: top)
}
guard !written.isEmpty else { return nil }
return try backUpLocal(game, location: Self.gameFolder, folder: game.folder, kept: true, only: written)
}
+ /// Whether backUpGameFolder can tell the files the game wrote from the installer's: something
+ /// dates the install. When it can't, an uninstall that keeps saves must say so first.
+ public static func canTellGameFiles(_ game: GOGStore.InstalledGame, driveC: URL) -> Bool {
+ GOGStore.history(for: game, driveC: driveC).firstSetup != nil
+ }
+
+ /// The uninstaller's and GOG's own records at the top of the game's folder (unins000.dat,
+ /// goggame-<id>.info, …): written by the install, not the game, and putting an old one back
+ /// into a new install would break its uninstaller.
+ static func isInstallerRecord(_ path: String, in top: String) -> Bool {
+ guard path.hasPrefix(top) else { return false }
+ let rest = path.dropFirst(top.count)
+ guard !rest.contains("/") else { return false }
+ let name = rest.lowercased()
+ return name.hasPrefix("unins") || name.hasPrefix("goggame-")
+ }
+
/// How many files a backup holds and their size, for the log.
public static func contents(of backup: URL) -> (files: Int, bytes: Int64) {
let all = (try? files(in: backup)) ?? []
diff --git a/Tests/HighballKitTests/GOGSaveSafetyTests.swift b/Tests/HighballKitTests/GOGSaveSafetyTests.swift
index 134bd69..b698fd6 100644
--- a/Tests/HighballKitTests/GOGSaveSafetyTests.swift
+++ b/Tests/HighballKitTests/GOGSaveSafetyTests.swift
@@ -265,6 +265,38 @@ final class GOGSaveSafetyTests: XCTestCase {
XCTAssertEqual(GOGStore.history(for: game, driveC: driveC).firstSetup, marked, "the marker's old date, read before it is rewritten")
}
+ /// An offline installer's game (no manifest, so never set up and no marker) counts from when
+ /// its goggame-<id>.info file was created, or its folder if earlier (a patch rewrites the
+ /// info file). The installer's files, dated when they were built, and its records at the top
+ /// of the folder aren't the game's. With no info file nothing dates it, and Keep can't copy.
+ func testAnOfflineInstallCountsFromItsInfoFile() throws {
+ let saves = GOGSaves(store: GOGStore(paths: HighballPaths(home: root.appending(path: "home"))))
+ let driveC = root.appending(path: "drive_c")
+ let game = GOGStore.InstalledGame(id: "7", title: "Game", folder: driveC.appending(path: "GOG Games/Game"), buildID: nil, clientID: nil, dlcIDs: [], tasks: [])
+ try FileManager.default.createDirectory(at: game.folder, withIntermediateDirectories: true)
+ XCTAssertFalse(GOGSaves.canTellGameFiles(game, driveC: driveC), "no info file: nothing dates the install")
+ XCTAssertNil(try saves.backUpGameFolder(game, driveC: driveC))
+ let installed = Date().addingTimeInterval(-86400)
+ let built = installed.addingTimeInterval(-86400 * 300)
+ let info = game.folder.appending(path: "goggame-7.info")
+ try write(#"{"gameId":"7","name":"Game"}"#, to: info, dated: built)
+ try FileManager.default.setAttributes([.creationDate: installed], ofItemAtPath: info.path)
+ try FileManager.default.setAttributes([.creationDate: installed.addingTimeInterval(60)], ofItemAtPath: game.folder.path)
+ XCTAssertEqual(GOGStore.history(for: game, driveC: driveC).firstSetup, installed, "the info file's creation, not its built date")
+ XCTAssertTrue(GOGSaves.canTellGameFiles(game, driveC: driveC))
+ try write("exe", to: game.folder.appending(path: "game.exe"), dated: built)
+ try write("uninstaller", to: game.folder.appending(path: "unins000.dat"), dated: installed.addingTimeInterval(5))
+ try write("save", to: game.folder.appending(path: "save/slot1.sav"), dated: installed.addingTimeInterval(3600))
+ let copy = try XCTUnwrap(try saves.backUpGameFolder(game, driveC: driveC))
+ XCTAssertEqual(try GOGSaves.files(in: copy).map { GOGSaves.relativePath(of: $0, in: copy) }, ["save/slot1.sav"])
+ // A patch rewrites the info file; the folder still dates the install.
+ try FileManager.default.setAttributes([.creationDate: installed.addingTimeInterval(7200)], ofItemAtPath: info.path)
+ XCTAssertEqual(GOGStore.history(for: game, driveC: driveC).firstSetup, installed.addingTimeInterval(60))
+ // Setup records its own date, never the info file's: what setup puts down isn't the game's.
+ GOGStore.markSetupDone(for: game, driveC: driveC)
+ XCTAssertGreaterThan(try XCTUnwrap(GOGStore.history(for: game, driveC: driveC).firstSetup), Date().addingTimeInterval(-60))
+ }
+
/// Deleting saves with the game removes the folders GOG names elsewhere, and never a whole or
/// shared folder, Highball's save-backups (even through a link), or one holding the game.
func testDeletingSavesLeavesSharedFoldersAndBackupsAlone() throws {