Skip to content

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

Merge branch 'save/final' into epic-saves/final

Gabe1bc6d182d8f4
diff --cc Sources/HighballApp/AppState.swift
index dbe7071,0d238b6..1fe8f24
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@@ -3437,103 -3381,6 +3445,112 @@@ final class AppState
}
}
+ /// Removes an Epic game through legendary, so its library stays right. Keep save data (the
+ /// default) first copies, as kept backups, the game's Epic save folder and every file the game
+ /// wrote in its install folder since Highball installed it, and stops if a copy fails; a later
+ /// install is offered them back. `deleteSaves` copies nothing and also deletes the save folder
+ /// when it lies inside the environment (EpicSaves.removeSaves).
+ private func epicUninstall(_ app: String, title: String, in bottle: Bottle, deleteSaves: Bool) {
+ let store = epicStore
+ let install = epicInstalls[app].map { URL(fileURLWithPath: $0, isDirectory: true) }
+ // Resolving the save folder runs legendary's sync-saves (moving nothing), which a player
+ // who turned Sync saves with Epic off didn't ask for.
+ let resolve = !epicCloudSavesOff.contains(app)
+ runBusy(String(format: L("Removing %@"), title),
+ done: DoneState(title: String(format: L("%@ removed"), title), ctaTitle: nil, cta: nil),
+ stop: .cancelTask(label: L("Stop"))) { [self] in
+ let saves = EpicSaves(store: store), prefix = bottle.url
+ let log: @Sendable (String) -> Void = { line in Task { @MainActor in self.appendLog(line) } }
+ var saveFolder: URL?
+ var kept: [KeptSaves.Entry] = []
+ if let install, EpicStore.isInstalled(path: install.path, inDriveC: bottle.driveC) {
+ stage = L("Finding the game's saves")
+ saveFolder = await Task.detached { saves.uninstallSaveFolder(app, install: install, prefix: prefix, resolve: resolve, onLine: log) }.value
+ if !deleteSaves {
+ // These would go with the game, so they are copied before anything runs, and a
+ // failed copy stops the removal. Never pruned.
+ stage = L("Keeping a copy of the game's saves")
+ kept = try await Task.detached { try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: saveFolder) }.value
+ for entry in kept {
+ let (files, bytes) = SaveBackups.contents(of: entry.backup)
+ let what = entry.name == EpicSaves.gameFolderName ? "the game wrote in its folder" : "in its save folder"
+ appendLog("\(title): \(files) file\(files == 1 ? "" : "s") \(what) (\(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file))) copied to \(entry.backup.path)")
+ }
+ }
+ }
+ appendLog("\(title): asking the Epic tools to uninstall it")
+ _ = try await Task.detached { try store.uninstall(app, onLine: log) }.value
+ if let install, !FileManager.default.fileExists(atPath: install.path) {
+ EpicSaves.forgetHistory(app: app, driveC: bottle.driveC)
+ if deleteSaves, let saveFolder, !EpicSaves.isInside(saveFolder, roots: [install]) {
+ if saves.removeSaves(app, folder: saveFolder, install: install, prefix: prefix) {
+ appendLog("\(title): saves at \(saveFolder.path) deleted, as asked")
+ } else if FileManager.default.fileExists(atPath: saveFolder.path) {
+ appendLog("\(title): saves at \(saveFolder.path) left in place: they are outside this environment, or hold other things Highball keeps")
+ }
+ }
+ // Recorded once the folder is gone, so this install is never offered its own saves.
+ saves.keep(kept, of: app)
+ }
+ await MainActor.run { self.refresh() }
+ }
+ }
+
+ /// Saves an uninstall kept, offered to a new install of the game (EpicSaves.keep).
+ struct EpicSavesToPutBack {
+ let app: String
+ let title: String
+ let install: URL
+ let bottle: Bottle
+ let kept: KeptSaves
+ }
+ var epicSavesToPutBack: EpicSavesToPutBack?
+
++ /// Installs whose put-back question was answered Not now, as GOG's (gogPutBackLater).
++ private var epicPutBackLater: Set<String> = []
++
+ /// Offers, once per install, to put back saves an uninstall kept of the same game. Only for
+ /// an install Highball made (EpicSaves.history), and while the game isn't running.
+ private func offerKeptEpicSaves() {
+ guard epicSavesToPutBack == nil else { return }
+ let all = EpicSaves(store: epicStore).keptSaves() // one read, not one per installed game
+ guard !all.isEmpty else { return }
+ for (app, path) in epicInstalls.sorted(by: { $0.key < $1.key }) {
+ let install = URL(fileURLWithPath: path, isDirectory: true)
+ guard let bottle = bottles.first(where: { EpicStore.isInstalled(path: path, inDriveC: $0.driveC) }),
+ let kept = KeptSavesFile.toOffer(all[app], install: install),
++ !epicPutBackLater.contains(install.standardizedFileURL.path),
+ EpicSaves.history(app: app, driveC: bottle.driveC).firstSetup != nil,
+ !runningSessions.contains(where: { $0.libraryID == "epic:\(app)" }) else { continue }
+ let title = epicOwned.first { $0.app_name == app }?.app_title ?? app
+ epicSavesToPutBack = EpicSavesToPutBack(app: app, title: title, install: install, bottle: bottle, kept: kept)
+ return
+ }
+ }
+
- /// The answer to the put-back question; either way that install isn't asked again.
- func epicPutBackSaves(_ putBack: Bool) {
++ /// The answer to the put-back question, as GOG's: Not now asks again the next time Highball
++ /// starts, the other two answer that install for good.
++ func epicPutBackSaves(_ answer: PutBackAnswer) {
+ guard let pending = epicSavesToPutBack else { return }
+ epicSavesToPutBack = nil
+ let saves = EpicSaves(store: epicStore)
- saves.markAsked(pending.app, install: pending.install)
- guard putBack else { offerKeptEpicSaves(); return }
++ if answer == .notNow {
++ epicPutBackLater.insert(pending.install.standardizedFileURL.path)
++ } else {
++ saves.markAsked(pending.app, install: pending.install)
++ }
++ guard answer == .putBack else { offerKeptEpicSaves(); return }
+ Task {
+ do {
+ let count = try await Task.detached { try saves.putBack(pending.kept, app: pending.app, install: pending.install, prefix: pending.bottle.url) }.value
+ appendLog("\(pending.title): \(count) saved file\(count == 1 ? "" : "s") put back from \(pending.kept.date.formatted()), what was there copied to save-backups first")
+ } catch {
+ fail(HighballError.failed(String(format: L("Highball could not put back all of %@'s saves: %@"), pending.title, error.localizedDescription)))
+ }
+ offerKeptEpicSaves()
+ }
+ }
+
/// Quitting the app stops an Epic download the way Stop does, so it never runs on alone,
/// holding legendary's install lock with nothing on screen to stop it (highball#323).
func stopEpicInstall() { epicInstallControl?.stop() }
diff --cc Sources/HighballApp/HighballApp.swift
index ee76343,d27c608..22ff277
--- a/Sources/HighballApp/HighballApp.swift
+++ b/Sources/HighballApp/HighballApp.swift
@@@ -579,20 -575,6 +580,21 @@@ private extension View
}
}
+ /// An uninstall kept this Epic game's saves, and it is installed again: offered once per install.
+ @MainActor func epicPutBackSavesAsk(_ state: AppState) -> some View {
+ self.alert(state.epicSavesToPutBack.map { String(format: L("Put back your saves from %@?"),
+ $0.kept.date.formatted(date: .abbreviated, time: .omitted)) } ?? "",
+ // As GOG's: the buttons answer, the dismissal never answers the next game's question.
+ isPresented: .init(get: { state.epicSavesToPutBack != nil }, set: { _ in }),
+ presenting: state.epicSavesToPutBack) { _ in
- Button(L("Put them back")) { state.epicPutBackSaves(true) }.keyboardShortcut(.defaultAction)
- Button(L("Not now"), role: .cancel) { state.epicPutBackSaves(false) }
++ Button(L("Put them back")) { state.epicPutBackSaves(.putBack) }.keyboardShortcut(.defaultAction)
++ Button(L("Not now"), role: .cancel) { state.epicPutBackSaves(.notNow) }
++ Button(L("Don't ask again")) { state.epicPutBackSaves(.dontAskAgain) }
+ } message: { pending in
- Text(String(format: L("Highball kept %@'s saves when it was removed. Put them back copies them to where they were; 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 to where they were; anything already there is copied to save-backups first. Not now asks again the next time Highball starts."), pending.title))
+ }
+ }
+
/// Some of a game's saves can't be backed up before it is removed (GOG unreachable, or saves
/// kept directly in the game's folder). Nothing is removed unless the player agrees.
@MainActor func gogRemovalWithoutBackupAsk(_ state: AppState) -> some View {
diff --cc Sources/HighballApp/L10n.swift
index a8b8b9e,cdcbfca..a854b45
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@@ -257,8 -237,12 +257,13 @@@ 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.",
- "Highball kept %@'s saves when it was removed. Put them back copies them to where they were; anything already there is copied to save-backups first.": "Highball a gardé les sauvegardes de %@ lors de sa suppression. Les remettre les copie là où elles étaient ; 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 kept %@'s saves when it was removed. Put them back copies them to where they were; 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 là où elles étaient ; 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 --cc Sources/HighballKit/GOGLibrary.swift
index 0f2225f,4481fa3..79564cf
--- a/Sources/HighballKit/GOGLibrary.swift
+++ b/Sources/HighballKit/GOGLibrary.swift
@@@ -541,17 -554,43 +541,40 @@@ 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()
+ var history = InstallHistory.read(historyFile(for: game, driveC: driveC)) ?? InstallHistory()
if history.firstSetup == nil {
history.firstSetup = try? setupMarker(for: game, driveC: driveC).resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
}
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)
- try? JSONEncoder().encode(history).write(to: url, options: .atomic)
+ history.write(to: historyFile(for: game, driveC: driveC))
}
/// An update ran from `start` to `end`: what changed in the game's folder then is the patch's.
diff --cc Sources/HighballKit/GOGSaves.swift
index 0a52ed7,bbab224..ded250c
--- a/Sources/HighballKit/GOGSaves.swift
+++ b/Sources/HighballKit/GOGSaves.swift
@@@ -254,8 -348,35 +256,25 @@@ public struct GOGSaves: Sendable
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)) ?? []
- let bytes = all.reduce(Int64(0)) { $0 + Int64((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }
- return (all.count, bytes)
- }
-
- /// Stored next to the backup rather than inside it, so restoring a backup by hand never puts
- /// this file in the game's folder, where gogdl would upload it with the saves.
- static func fingerprintFile(of backup: URL) -> URL {
- backup.deletingLastPathComponent().appending(path: backup.lastPathComponent + ".fingerprint")
- }
+ public static func contents(of backup: URL) -> (files: Int, bytes: Int64) { SaveBackups.contents(of: backup) }
/// GOG's whole cloud listing for the game, from a gogdl run that can't move anything: an
/// empty folder and a location name no cloud file starts with, so gogdl finds no files on