Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.
Swift apple-silicond3dmetaldxmtdxvkfexgame-porting-toolkitgamingmac-gamingmacosmetalmoltenvksteamswiftuivkd3d-protonwhisky-alternativewindows-gameswinewine-wrapper
Merge branch 'feat/gog-mac' into feat/epic-mac
Gabe6e6f3f6780e7
diff --cc Sources/HighballApp/AppState.swiftindex 30674d6,f5e93a1..292d8a8--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@@ -1298,7 -1297,8 +1301,8 @@@ final class AppStateawait MainActor.run { [weak self] inguard let self else { return }self.epicFetchInFlight = false+ defer { self.offerKeptEpicSaves() }- guard self.applyEpicInstalls(installed) else { return }+ guard self.applyEpicInstalls(installed, archs: archs) else { return }self.forgetProgramExecutables()self.rebuildLibrary()}@@@ -3597,47 -3608,44 +3614,60 @@@@ObservationIgnored private var epicInstallControl: LegendaryControl?func epicInstall(_ game: EpicStore.Game, in bottle: Bottle) {- epicDownload(title: "Installing \(game.app_title)") { store, control, onLine in++ epicDownload(title: "Installing \(game.app_title)", history: (game.app_name, bottle.driveC)) { store, control, onLine in+ try store.install(game.app_name, into: bottle, control: control, onLine: onLine)+ }+ }++ /// One legendary download under the strip (an install of either build): progress, Stop as a+ /// Ctrl-C that keeps the progress, and legendary's refusals turned into sentences. `wrap`+ /// runs around the download inside the same task (EpicBuildSwitch, when replacing a build).- private func epicDownload(title: String,++ private func epicDownload(title: String, history: (app: String, driveC: URL)? = nil,+ wrap: (@MainActor (_ download: @escaping @MainActor () async throws -> Void) async throws -> Void)? = nil,+ install: @escaping @Sendable (EpicStore, LegendaryControl, @escaping @Sendable (String) -> Void) throws -> Int32) {let control = LegendaryControl()- runBusy("Installing \(game.app_title)", expected: L("a large download; you can leave it running"),+ runBusy(title, expected: L("a large download; you can leave it running"),stop: .cancelTask(label: L("Stop")), cleanup: { [weak self] in self?.epicInstallControl = nil }) { [self] in- epicInstallControl = control- let store = epicStore- epicDownloadTotal = nil- let refused = OSAllocatedUnfairLock(initialState: false)- let failure = OSAllocatedUnfairLock<String?>(initialState: nil)- // What changes in the game's folder while legendary installs or updates it is- // legendary's, not saves (EpicSaves.historyFile).- let start = Date()- // Stop cancels this task, and the cancellation reaches legendary as a Ctrl-C, which- // keeps the download's progress for the next Install.- let status: Int32- do {- status = try await withTaskCancellationHandler {- try await Task.detached {- try store.install(game.app_name, into: bottle, control: control) { line in- if EpicStore.refusedForLock(line) { refused.withLock { $0 = true } }- if let why = EpicStore.installFailure(line) { failure.withLock { if $0 == nil { $0 = why } } }- Task { @MainActor in self.appendLog(line); self.reportEpicDownload(line) }- }- }.value- } onCancel: { control.stop() }- } catch {- EpicSaves.recordInstall(app: game.app_name, driveC: bottle.driveC, start: start, end: Date(), finished: false)- throw error- }- EpicSaves.recordInstall(app: game.app_name, driveC: bottle.driveC, start: start, end: Date(),- finished: status == 0 && !refused.withLock({ $0 }) && !Task.isCancelled)- try Task.checkCancellation()- if refused.withLock({ $0 }) {- throw HighballError.failed(L("Another Epic download is still running, and legendary installs one game at a time. If Highball shows none, one started before Highball last quit is still going, so quit legendary in Activity Monitor and press Install again."))- }- guard status == 0 else {- if let why = failure.withLock({ $0 }) { throw HighballError.failed(why) }- throw HighballError.processFailed(command: "epic install", status: status, output: "see the log above")+ let download: @MainActor () async throws -> Void = { [self] in+ epicInstallControl = control+ let store = epicStore+ epicDownloadTotal = nil+ let refused = OSAllocatedUnfairLock(initialState: false)+ let failure = OSAllocatedUnfairLock<String?>(initialState: nil)++ // What changes in an environment's game folder while legendary installs or updates++ // it is legendary's, not saves (EpicSaves.historyFile).++ let start = Date()++ func record(finished: Bool) {++ if let history { EpicSaves.recordInstall(app: history.app, driveC: history.driveC, start: start, end: Date(), finished: finished) }++ }+ // Stop cancels this task, and the cancellation reaches legendary as a Ctrl-C, which+ // keeps the download's progress for the next Install.- let status = try await withTaskCancellationHandler {- try await Task.detached {- try install(store, control) { line in- if EpicStore.refusedForLock(line) { refused.withLock { $0 = true } }- if let why = EpicStore.installFailure(line) { failure.withLock { if $0 == nil { $0 = why } } }- Task { @MainActor in self.appendLog(line); self.reportEpicDownload(line) }- }- }.value- } onCancel: { control.stop() }++ let status: Int32++ do {++ status = try await withTaskCancellationHandler {++ try await Task.detached {++ try install(store, control) { line in++ if EpicStore.refusedForLock(line) { refused.withLock { $0 = true } }++ if let why = EpicStore.installFailure(line) { failure.withLock { if $0 == nil { $0 = why } } }++ Task { @MainActor in self.appendLog(line); self.reportEpicDownload(line) }++ }++ }.value++ } onCancel: { control.stop() }++ } catch {++ record(finished: false)++ throw error++ }++ record(finished: status == 0 && !refused.withLock({ $0 }) && !Task.isCancelled)+ try Task.checkCancellation()+ if refused.withLock({ $0 }) {+ throw HighballError.failed(L("Another Epic download is still running, and legendary installs one game at a time. If Highball shows none, one started before Highball last quit is still going, so quit legendary in Activity Monitor and press Install again."))+ }+ guard status == 0 else {+ if let why = failure.withLock({ $0 }) { throw HighballError.failed(why) }+ throw HighballError.processFailed(command: "epic install", status: status, output: "see the log above")+ }}+ if let wrap { try await wrap(download) } else { try await download() }await MainActor.run { self.epicRefresh() }}}@@@ -3660,257 -3662,168 +3690,419 @@@return true}+ nonisolated private static func macArchs(_ installed: [EpicStore.InstalledGame]) -> [String: MacBinaryArch] {+ Dictionary(installed.filter(\.isMac).compactMap { record in+ record.install_path.map { (record.app_name, MacBinaryArch.ofApp(at: URL(fileURLWithPath: $0))) }+ }, uniquingKeysWith: { a, _ in a })+ }++ /// The Windows build is installed and legendary keeps one build per game: switching asks+ /// first (the Windows copy is removed once the Mac one is in, its settings stay).+ var pendingEpicMacSwitch: LibraryItem?+ /// An Epic Mac build the player asked to remove: asked first, it is a long download back.+ var pendingEpicMacUninstall: LibraryItem?+ /// An Epic game whose installed Mac build does not run (32-bit), switching to the Windows one:+ /// asked first, as the Mac build is removed.+ var pendingEpicWindowsSwitch: LibraryItem?++ /// Removes an Epic game's installed build through legendary (one per game), its lines in the log.+ private func legendaryUninstall(_ app: String) async throws {+ let store = epicStore+ let log: @Sendable (String) -> Void = { line in Task { @MainActor in self.appendLog(line) } }+ let status: Int32 = try await Task.detached { try store.uninstall(app, onLine: log) }.value+ guard status == 0 else { throw HighballError.processFailed(command: "legendary uninstall", status: status, output: "see the log above") }+ }++ /// Replaces an Epic game's Mac build with the Windows one in the default environment+ /// (legendary keeps one build per game), through EpicBuildSwitch: the Mac files stay until+ /// the Windows build is in, and a Stop or a failure puts the Mac build back as it was.+ func epicSwitchToWindows(_ item: LibraryItem) {+ guard let app = item.epicAppName, let game = epicOwned.first(where: { $0.app_name == app }),+ refuseWhileRunning(item) else { return }+ guard let bottle = defaultBottle else {+ fail(HighballError.failed(L("Make an environment first: the Windows version installs into one.")))+ return+ }- epicDownload(title: "Installing \(game.app_title)",++ epicDownload(title: "Installing \(game.app_title)", history: (app, bottle.driveC),+ wrap: epicBuildSwitch(item, app: app, oldPath: epicMacInstalls[app], oldPlatform: "Mac", hasNewBuild: { true })) { store, control, onLine in+ try store.install(app, into: bottle, control: control, onLine: onLine)+ }+ }++ /// Installs an Epic game's Mac build. With the Windows build installed, the player says yes+ /// first (pendingEpicMacSwitch) and EpicBuildSwitch replaces it. Before anything changes,+ /// legendary is asked whether Epic has a Mac build for this account: with none, its install+ /// would fall back to the Windows build and put it in the Mac games folder, outside every+ /// environment (EpicStore.installMac stops that). The Windows files stay until the Mac build+ /// is in, and a Stop or a failure puts the Windows build back as it was.+ func epicInstallMac(_ item: LibraryItem, replacingWindows: Bool = false) {+ guard let app = item.epicAppName else { return }+ if item.installed && !replacingWindows { pendingEpicMacSwitch = item; return }+ guard refuseWhileRunning(item) else { return }+ let store = epicStore+ let hasMac: @MainActor () async throws -> Bool = { [self] in+ stage = L("Asking Epic about the Mac version")+ do {+ return try await Task.detached { try store.hasMacBuild(app) }.value+ } catch {+ appendLog("\(item.title): legendary info --platform Mac failed: \(error)")+ throw HighballError.failed(L("Highball could not ask Epic whether a Mac build of this game is there to download, so nothing was changed. Check your connection, then try again."))+ }+ }+ epicDownload(title: String(format: L("Installing the Mac version of %@"), item.title),+ wrap: epicBuildSwitch(item, app: app, oldPath: replacingWindows ? epicInstalls[app] : nil,+ oldPlatform: "Windows", hasNewBuild: hasMac)) { store, control, onLine in+ try store.installMac(app, control: control, onLine: onLine)+ }+ }++ /// The EpicBuildSwitch steps around `epicDownload`'s download. `oldPath`, the installed+ /// build's folder; nil when there is none to replace. The old files are deleted only from a+ /// folder Highball installs into.+ private func epicBuildSwitch(_ item: LibraryItem, app: String, oldPath: String?, oldPlatform: String,+ hasNewBuild: @escaping @MainActor () async throws -> Bool)+ -> @MainActor (_ download: @escaping @MainActor () async throws -> Void) async throws -> Void {+ let store = epicStore+ let log: @Sendable (String) -> Void = { line in Task { @MainActor in self.appendLog(line) } }+ let roots = epicInstallRoots+ let removing = oldPlatform == "Mac" ? String(format: L("Removing the Mac version of %@"), item.title)+ : String(format: L("Removing the Windows version of %@"), item.title)+ return { [self] download in+ let steps = EpicBuildSwitch.Steps(+ hasNewBuild: hasNewBuild,+ // legendary's record of the old build is kept aside first (EpicStore.saveRecord),+ // so the undo puts it back from disk: no sign-in, no network, either build.+ dropOldRecord: oldPath.map { _ in { [self] in+ stage = removing+ try await Task.detached { try store.saveRecord(app) }.value+ let status = try await Task.detached { try store.forgetRecordKeepingFiles(app, onLine: log) }.value+ guard status == 0 else {+ _ = try? await Task.detached { try store.restoreSavedRecord(app) }.value+ throw HighballError.processFailed(command: "legendary uninstall --keep-files", status: status, output: "see the log above")+ }+ // legendary exits 0 without touching its records when another legendary holds+ // its lock: the switch goes on only once the record is really gone.+ guard await Task.detached(operation: { store.recordsGame(app) }).value == false else {+ _ = try? await Task.detached { try store.restoreSavedRecord(app) }.value+ throw HighballError.failed(String(format: L("The Epic tools didn't let go of %@'s installed version (another of their tasks may be running), so nothing was changed. Try again in a moment."), item.title))+ }+ } },+ install: download,+ restoreOldRecord: { [self] in+ guard let oldPath else { return }+ do {+ let back = try await Task.detached { try store.restoreSavedRecord(app) }.value+ appendLog(back ? "\(item.title): the \(oldPlatform) version is back as it was"+ : "\(item.title): legendary records the game already, so its record was left as it is")+ } catch {+ appendLog("\(item.title): could not put the \(oldPlatform) version's record back yet (\(error.localizedDescription)); its files are still in \(oldPath), and Highball finishes this when it next opens")+ epicRefresh()+ // The alert says this, not only the download's error: the game is missing+ // from Epic's list until the next launch puts it back.+ throw HighballError.failed(String(format: L("The switch didn't finish, and the %@ version couldn't be put back yet, so %@ is missing from Epic's list until Highball next opens. Its files are still in %@."), oldPlatform, item.title, oldPath))+ }+ epicRefresh()+ },+ deleteOldFiles: { [self] in+ guard let oldPath else { return }+ stage = removing+ let result = await Task.detached { store.deleteOldBuild(app, at: oldPath, roots: roots) }.value+ appendLog(Self.oldBuildDeletionLine(item.title, platform: oldPlatform, path: oldPath, result))+ })+ do { try await EpicBuildSwitch.run(steps) } catch EpicBuildSwitch.Failure.noNewBuild {+ throw HighballError.failed(L("Epic lists a Mac version of this game, but has no Mac build to download for your account, so nothing was changed."))+ }+ }+ }++ @ObservationIgnored private var epicSwitchesFinished = false++ /// The folders Highball installs Epic builds into: an old build's files are deleted only from+ /// inside one of them (EpicBuildSwitch.isSafeToDelete).+ private var epicInstallRoots: [URL] {+ bottles.map { $0.driveC.appending(path: "Games", directoryHint: .isDirectory) } + [GOGStore.macGamesDir]+ }++ /// Completes a build switch Highball quit in the middle of (EpicStore.switchesInFlight), off+ /// the main thread, then runs `then` (the Epic refresh, so it sees a record put back): the old+ /// build's record goes back from where the switch kept it, or, when legendary records the new+ /// build in another folder, the old build's files go as legendary's uninstall deletes them+ /// (EpicStore.finishSwitch, deleteOldBuild). Once, at launch.+ private func finishEpicSwitches(then: @escaping @MainActor () -> Void) {+ guard !epicSwitchesFinished else { then(); return }+ epicSwitchesFinished = true+ let store = epicStore, roots = epicInstallRoots+ Task { [self] in+ let lines = await Task.detached { () -> [String] in+ var lines: [String] = []+ for app in store.switchesInFlight() {+ do {+ switch try store.finishSwitch(app) {+ case .restored:+ lines.append("\(app): a switch between Epic builds did not finish, so the old build is back as it was")+ case .deleteOldBuild(let oldPath):+ lines.append("\(app): a switch between Epic builds finished as Highball quit; deleting the old build's files in \(oldPath)")+ lines.append(Self.oldBuildDeletionLine(app, platform: nil, path: oldPath,+ store.deleteOldBuild(app, at: oldPath, roots: roots)))+ case .unreadable:+ lines.append("\(app): a switch between Epic builds did not finish, and legendary's installed.json could not be read, so nothing was changed; Highball tries again when it next opens")+ case .leftAsItWas:+ break+ }+ } catch {+ lines.append("\(app): a switch between Epic builds did not finish, and its old record could not go back yet (\(error.localizedDescription)); Highball tries again when it next opens")+ }+ }+ return lines+ }.value+ lines.forEach(appendLog)+ then()+ }+ }++ /// The log line for an old build's files after a switch (EpicStore.deleteOldBuild).+ nonisolated static func oldBuildDeletionLine(_ name: String, platform: String?, path: String,+ _ result: EpicStore.OldBuildDeletion) -> String {+ let build = platform.map { "old \($0) files" } ?? "old build's files"+ switch result {+ case .deleted(let files, 0):+ return "\(name): deleted the \(build) in \(path) (\(files) files from its manifest; anything else the game wrote there stays)"+ case .deleted(let files, let failed):+ return "\(name): deleted \(files) of the \(build) in \(path); \(failed) could not be deleted and stay there"+ case .outsideGameFolders:+ return "\(name): left the \(build) in \(path), outside Highball's game folders"+ case .noFileList(let why):+ return "\(name): left the \(build) in \(path): legendary could not list them (\(why)), so nothing there was deleted"+ case .stillRecorded:+ return "\(name): left the \(build) in \(path): legendary still records the game there, so it is the installed build"+ case .recordsUnreadable:+ return "\(name): left the \(build) in \(path): legendary's install records could not be read; Highball looks again when it next opens"+ }+ }++ /// Starts an Epic game's Mac build the way legendary launches it, with the sign-in arguments+ /// Epic's own launcher passes (single use, fetched right before). On the strip, as the GOG+ /// Mac build and the Windows build start: legendary takes seconds to answer, and a second+ /// Play meanwhile finds Highball busy and starts nothing, where it used to start a second+ /// copy. A failure reaches the alert, not only the log. The game runs until nothing runs from+ /// its folder (watchEpicMacGame), a launcher's hand-over included.+ func epicPlayMac(_ item: LibraryItem) {+ guard let app = item.epicAppName else { return }+ if macGameProcesses[item.id] != nil {+ fail(HighballError.failed("\(item.title) is already running."))+ return+ }+ let store = epicStore+ runBusy(String(format: L("Starting %@"), item.title), done: .handedOff) { [self] in+ appendLog("\(item.title): opening the Mac version")+ let info = try await Task.detached { try store.launchInfo(app) }.value+ try Task.checkCancellation()+ let p = Process()+ p.executableURL = info.executable+ p.arguments = info.arguments+ p.currentDirectoryURL = info.workingDirectory+ p.environment = ProcessInfo.processInfo.environment.merging(info.environment) { $1 }+ do { try p.run() } catch {+ throw HighballError.failed(String(format: L("The Mac version of %@ did not start: %@"), item.title, error.localizedDescription))+ }+ macGameProcesses[item.id] = p+ recordPlay(item)+ // The install's folder, else the app legendary's launch runs from.+ let folder = epicMacInstalls[app].map { URL(fileURLWithPath: $0, isDirectory: true) }+ ?? sequence(first: info.executable, next: { $0.pathComponents.count > 1 ? $0.deletingLastPathComponent() : nil })+ .first { $0.pathExtension == "app" }+ watchEpicMacGame(p, item: item, folder: folder)+ }+ }++ /// Once an Epic Mac build quits, as for a GOG one (watchMacGame): the process Highball started+ /// may be a launcher that hands over to the game and exits at once, so its entry in+ /// macGameProcesses, which keeps a second Play from starting another copy, stays until+ /// nothing runs from the game's folder (MacGameWatch). Never the Mac games folder itself,+ /// which holds every other game.+ private func watchEpicMacGame(_ process: Process, item: LibraryItem, folder: URL?) {+ let watched = folder.flatMap { $0.standardizedFileURL.path == GOGStore.macGamesDir.standardizedFileURL.path ? nil : $0 }+ Task.detached { [weak self] in+ if await Self.macGameEnd(of: process, watching: watched) {+ await self?.appendLog("\(item.title): the Mac version handed over to another app, which has now quit too")+ }+ await self?.epicMacGameEnded(item)+ }+ }++ private func epicMacGameEnded(_ item: LibraryItem) { macGameProcesses[item.id] = nil }++ /// Removes an Epic game's Mac build through legendary, so its library stays right.+ func epicUninstallMac(_ item: LibraryItem) {+ guard let app = item.epicAppName, refuseWhileRunning(item) else { return }+ runBusy(String(format: L("Removing the Mac version of %@"), item.title), expected: nil) { [self] in+ try await legendaryUninstall(app)+ await MainActor.run { self.epicRefresh() }+ }+ }++ /// An Epic game the player is asked about before it is removed: nothing tells the files the+ /// game wrote in its install folder from legendary's (no manifest, and installed before+ /// Highball kept a history), so Keep can't copy them. Nothing is removed until they agree.+ struct EpicRemovalWithoutCopy {+ let app: String+ let title: String+ let bottle: Bottle+ }+ var epicRemovalWithoutCopy: EpicRemovalWithoutCopy?++ /// The player agreed to remove the Epic game without a copy of its install folder.+ func epicRemoveWithoutCopy() {+ guard let pending = epicRemovalWithoutCopy else { return }+ epicRemovalWithoutCopy = nil+ appendLog("\(pending.title): removing it without a copy of what it wrote in its folder, as asked")+ epicUninstall(pending.app, title: pending.title, in: pending.bottle, deleteSaves: false, agreed: true)+ }++ /// 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 (EpicSaves.gameFiles), and stops if a copy fails; a later+ /// install is offered them back. When nothing tells the game's files apart, the player is+ /// asked first (epicRemovalWithoutCopy); `agreed` is their go-ahead. `deleteSaves` copies+ /// nothing and also deletes the save folder when it lies inside the environment+ /// (EpicSaves.removeSaves). What follows the uninstall waits for legendary's record of the+ /// game to be gone, not the folder: legendary leaves the folder when the game wrote files in it.+ private func epicUninstall(_ app: String, title: String, in bottle: Bottle, deleteSaves: Bool, agreed: Bool = false) {+ 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+ try checkStopped()+ if !deleteSaves {+ let gameFiles = await Task.detached { saves.gameFiles(app, install: install, prefix: prefix) }.value+ try checkStopped()+ if gameFiles == nil, !agreed {+ epicRemovalWithoutCopy = EpicRemovalWithoutCopy(app: app, title: title, bottle: bottle)+ busyDoneOverride = .handedOff // the question takes over; nothing was removed+ return+ }+ // 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, gameFiles: gameFiles)+ }.value+ try checkStopped() // a detached copy runs on through a Stop: nothing is removed after one+ 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)")+ }+ }+ }+ try checkStopped()+ appendLog("\(title): asking the Epic tools to uninstall it")+ _ = try await Task.detached { try store.uninstall(app, onLine: log) }.value+ // legendary's records unreadable: the folder vanishing is all there is to go by.+ let uninstalled = store.isRecorded(app).map { !$0 } ?? install.map { !FileManager.default.fileExists(atPath: $0.path) } ?? false+ if install != nil, !uninstalled {+ appendLog("\(title): the Epic tools still list it as installed, so no saves were kept or deleted")+ }+ if let install, uninstalled {+ EpicSaves.forgetHistory(app: app, driveC: bottle.driveC)+ if deleteSaves, let saveFolder {+ 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")+ }+ } else if deleteSaves {+ appendLog("\(title): Highball found no save folder for it to delete, so no saves outside the game's folder were deleted")+ }+ // Recorded once legendary's record is gone, so this install is never offered its own saves.+ saves.keep(kept, of: app)+ // What legendary didn't install keeps its folder, which a reinstall there can't use.+ if FileManager.default.fileExists(atPath: install.path) {+ // legendary's own records, read locally and off the main actor; when they can't+ // be read, nothing tells whether another game is inside, so the folder stays.+ let prefix = bottle.url+ let removed = await Task.detached { () -> Bool? in+ guard let records = store.installRecords() else { return nil }+ let others = records.values.filter { !$0.isEmpty }.map { URL(fileURLWithPath: $0) }+ return saves.removeLeftover(install, prefix: prefix, stillInstalled: others)+ }.value+ switch removed {+ case true?: appendLog("\(title): removed the folder the Epic tools left at \(install.path)")+ case false?: appendLog("\(title): the Epic tools left \(install.path), with files they didn't install; Highball leaves it, as it holds more than this game")+ case nil: appendLog("\(title): the Epic tools left \(install.path); Highball couldn't read their install records, so it leaves the folder")+ }+ }+ }+ 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, 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)+ 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/HighballKit/EpicBuildSwitch.swiftindex 55f6d38,0000000..979c682mode 100644,000000..100644--- a/Sources/HighballKit/EpicBuildSwitch.swift+++ b/Sources/HighballKit/EpicBuildSwitch.swift@@@ -1,353 -1,0 +1,342 @@@+import Foundation++/// Replacing an Epic game's installed build with its other one (Windows to Mac, or back).+///+/// legendary keeps one build per game and, for a game it has a record of, always installs that+/// record's platform, so the old record has to go before the new build can be installed. Only+/// the record goes first, kept aside beforehand (EpicStore.saveRecord): the old files stay on disk+/// until the new build is fully in, so a Stop, a failed download, legendary falling back to the+/// old platform, or Highball quitting midway puts the old record back from disk and the game is+/// as it was. The old files are deleted last.+public enum EpicBuildSwitch {+ public struct Steps {+ /// Epic has the new build for this account. Asked before anything changes.+ public var hasNewBuild: () async throws -> Bool+ /// Drops legendary's record of the old build, keeping its files; nil when no build is+ /// installed (a plain install).+ public var dropOldRecord: (() async throws -> Void)?+ public var install: () async throws -> Void+ public var restoreOldRecord: () async throws -> Void+ public var deleteOldFiles: () async throws -> Void++ public init(hasNewBuild: @escaping () async throws -> Bool, dropOldRecord: (() async throws -> Void)?,+ install: @escaping () async throws -> Void, restoreOldRecord: @escaping () async throws -> Void,+ deleteOldFiles: @escaping () async throws -> Void) {+ self.hasNewBuild = hasNewBuild; self.dropOldRecord = dropOldRecord; self.install = install+ self.restoreOldRecord = restoreOldRecord; self.deleteOldFiles = deleteOldFiles+ }+ }++ public enum Failure: Error, Equatable { case noNewBuild }++ /// Runs the steps in order. A Stop before the old record is dropped changes nothing; after+ /// it, the record is put back. The install's error is rethrown once that is done.+ public static func run(_ steps: Steps) async throws {+ guard try await steps.hasNewBuild() else { throw Failure.noNewBuild }+ try Task.checkCancellation()+ guard let drop = steps.dropOldRecord else { try await steps.install(); return }+ try await drop()+ do {+ try Task.checkCancellation()+ try await steps.install()+ } catch {+ try await steps.restoreOldRecord()+ throw error+ }+ try await steps.deleteOldFiles()+ }++ /// Whether an old build's folder may be deleted: strictly inside one of the folders Highball+ /// installs into, never one of them itself or anything outside. Compared with links resolved+ /// and without case, as the Mac's disks are.+ public static func isSafeToDelete(_ folder: URL, roots: [URL]) -> Bool {+ let path = folder.standardizedFileURL.resolvingSymlinksInPath().path.lowercased()+ return roots.contains { root in+ let r = root.standardizedFileURL.resolvingSymlinksInPath().path.lowercased()+ return path.hasPrefix(r.hasSuffix("/") ? r : r + "/") && path.count > r.count + 1+ }+ }+}++// MARK: The old record, kept aside++extension EpicStore {+ /// Where a switch keeps the old build's record while it runs, one folder per game: legendary's+ /// installed.json entries for it and the manifests they name. A folder still there when+ /// Highball opens is a switch that never finished (quit mid-download), and its undo is+ /// completed then (restoreSavedRecord).+ var switchesFolder: URL { paths.home.appending(path: "epic-switch", directoryHint: .isDirectory) }++ private func savedRecordFolder(_ appName: String) -> URL {+ switchesFolder.appending(path: Self.cleanFilename(appName), directoryHint: .isDirectory)+ }++ /// Keeps legendary's record of an installed build aside before a switch drops it: the game's+ /// entry in installed.json, its DLC's (which share its folder, and which legendary's uninstall+ /// drops with it), and the manifest files those entries name. Read from disk, no network.+ public func saveRecord(_ appName: String) throws {+ let installed = try Self.readInstalled(configDir)+ guard let game = installed[appName] as? [String: Any] else {+ throw HighballError.failed("legendary has no record of \(appName) to keep")+ }+ let path = game["install_path"] as? String+ let entries = installed.filter { key, value in+ key == appName || (path != nil && (value as? [String: Any])?["install_path"] as? String == path)+ }+ let folder = savedRecordFolder(appName), fm = FileManager.default+ try? fm.removeItem(at: folder)+ try fm.createDirectory(at: folder.appending(path: "manifests"), withIntermediateDirectories: true)+ for name in entries.compactMap({ Self.manifestNames($0.key, entry: $0.value as? [String: Any] ?? [:]) }).joined() {+ let file = configDir.appending(path: "manifests/\(name)")+ if fm.fileExists(atPath: file.path) { try fm.copyItem(at: file, to: folder.appending(path: "manifests/\(name)")) }+ }+ // Written last: a folder without it was never finished, before anything was dropped.+ try JSONSerialization.data(withJSONObject: entries, options: [.sortedKeys]).write(to: folder.appending(path: "record.json"), options: .atomic)+ }++ /// Puts a kept record back into legendary's installed.json and manifests folder, directly, with+ /// no network and no legendary run, under legendary's own lock on installed.json. Nothing is+ /// written while legendary records the game already (the new build finished, or the old+ /// record was never dropped). The kept copy is then removed. Whether the record went back.+ @discardableResult+ public func restoreSavedRecord(_ appName: String) throws -> Bool {+ let folder = savedRecordFolder(appName), fm = FileManager.default+ guard let data = try? Data(contentsOf: folder.appending(path: "record.json")),+ let entries = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {+ try? fm.removeItem(at: folder)+ return false+ }+ let restored = try Self.withInstalledLock(configDir) { () throws -> Bool in+ // No installed.json is legendary with no games; one that cannot be read is not written over.+ var installed = try Self.readInstalledIfThere(configDir) ?? [:]+ guard installed[appName] == nil else { return false }+ let manifests = configDir.appending(path: "manifests", directoryHint: .isDirectory)+ try fm.createDirectory(at: manifests, withIntermediateDirectories: true)+ for file in (try? fm.contentsOfDirectory(at: folder.appending(path: "manifests"), includingPropertiesForKeys: nil)) ?? [] {+ let target = manifests.appending(path: file.lastPathComponent)+ try? fm.removeItem(at: target)+ try fm.copyItem(at: file, to: target)+ }+ installed.merge(entries) { $1 }+ try JSONSerialization.data(withJSONObject: installed, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])+ .write(to: configDir.appending(path: "installed.json"), options: .atomic)+ return true+ }+ try? fm.removeItem(at: folder)+ return restored+ }++ /// Where the old build of a switch still in flight was installed, from its kept record.+ public func savedInstallPath(_ appName: String) -> String? {+ guard let data = try? Data(contentsOf: savedRecordFolder(appName).appending(path: "record.json")),+ let entries = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil }+ return (entries[appName] as? [String: Any])?["install_path"] as? String+ }++ /// Forgets a kept record once the new build is in.+ public func discardSavedRecord(_ appName: String) {+ try? FileManager.default.removeItem(at: savedRecordFolder(appName))+ }++ /// The games whose switch never finished: a kept record is still there.+ public func switchesInFlight() -> [String] {+ ((try? FileManager.default.contentsOfDirectory(at: switchesFolder, includingPropertiesForKeys: nil)) ?? [])+ .filter { FileManager.default.fileExists(atPath: $0.appending(path: "record.json").path) }+ .map(\.lastPathComponent).sorted()+ }++ /// installed.json, or nil when legendary has none yet. Throws when it is there and cannot be read.+ static func readInstalledIfThere(_ configDir: URL) throws -> [String: Any]? {+ let file = configDir.appending(path: "installed.json")+ guard FileManager.default.fileExists(atPath: file.path) else { return nil }+ return try readInstalled(configDir)+ }++ static func readInstalled(_ configDir: URL) throws -> [String: Any] {+ let data = try Data(contentsOf: configDir.appending(path: "installed.json"))+ guard let installed = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {+ throw HighballError.failed("legendary's installed.json is not a list of games")+ }+ return installed+ }+- /// The names legendary 0.21.0 gives an entry's manifest (LGDLFS._get_manifest_filename): with- /// the platform, or the older form without it, which it falls back to.- static func manifestNames(_ appName: String, entry: [String: Any]) -> [String] {- guard let version = entry["version"] as? String else { return [] }- let platform = entry["platform"] as? String ?? "Windows"- return ["\(appName)_\(platform)_\(version)", "\(appName)_\(version)"].map { cleanFilename($0) + ".manifest" }- }-- /// legendary's clean_filename: the characters a file name cannot hold, dropped.- static func cleanFilename(_ name: String) -> String { name.filter { !"<>:\"/\\|?*".contains($0) } }-+ /// Runs `body` holding legendary's lock on its install data (installed.json.lock, the+ /// filelock flock every legendary takes before it changes installed.json), so a legendary+ /// still running cannot write over what is put back. Throws when one holds it.+ static func withInstalledLock<T>(_ configDir: URL, _ body: () throws -> T) throws -> T {+ try FileManager.default.createDirectory(at: configDir, withIntermediateDirectories: true)+ let fd = open(configDir.appending(path: "installed.json.lock").path, O_RDWR | O_CREAT, 0o644)+ guard fd >= 0 else { throw HighballError.failed("could not open legendary's install lock") }+ defer { close(fd) }+ guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {+ throw HighballError.failed("legendary is running and holds its install data")+ }+ defer { flock(fd, LOCK_UN) }+ return try body()+ }+}++// MARK: Finishing a switch, and the old build's files++extension EpicStore {+ /// What launch found for a switch Highball quit in the middle of (switchesInFlight).+ public enum UnfinishedSwitch: Equatable, Sendable {+ /// legendary had no record of the game: the old build's record went back.+ case restored+ /// legendary records the new build in another folder: the old build's files are to go+ /// (deleteOldBuild), from this folder. The kept record stays until they have.+ case deleteOldBuild(String)+ /// legendary still records the old build where it was (Highball quit before its record+ /// was dropped), or nothing was kept: the kept copy is dropped and nothing else changes.+ case leftAsItWas+ /// installed.json could not be read: nothing was changed, and the next launch tries again.+ case unreadable+ }++ /// Completes a switch Highball quit in the middle of, from legendary's installed.json read+ /// directly (no legendary run). The old files are named for deletion only when legendary+ /// records the game in a different folder than the kept record's, so a build still installed+ /// is never taken for a leftover.+ public func finishSwitch(_ appName: String) throws -> UnfinishedSwitch {+ let installed: [String: Any]+ do { installed = try Self.readInstalledIfThere(configDir) ?? [:] } catch { return .unreadable }+ guard let current = installed[appName] as? [String: Any] else {+ return try restoreSavedRecord(appName) ? .restored : .leftAsItWas+ }+ if let old = savedInstallPath(appName), let now = current["install_path"] as? String,+ !Self.samePath(old, now) {+ return .deleteOldBuild(old)+ }+ discardSavedRecord(appName)+ return .leftAsItWas+ }++ static func samePath(_ a: String, _ b: String) -> Bool {+ func norm(_ p: String) -> String {+ URL(fileURLWithPath: p, isDirectory: true).standardizedFileURL.resolvingSymlinksInPath().path.lowercased()+ }+ return norm(a) == norm(b)+ }++ /// How deleting an old build's files went.+ public enum OldBuildDeletion: Equatable, Sendable {+ /// The files the old build's manifests list were deleted, then the folders left empty.+ /// `failed`, the listed files that were there and could not be deleted.+ case deleted(files: Int, failed: Int)+ /// The folder is not inside one of Highball's game folders: nothing was deleted.+ case outsideGameFolders+ /// legendary could not list the old build's files: nothing was deleted.+ case noFileList(String)+ /// legendary still records the game in that folder (its uninstall didn't drop the record,+ /// another legendary holding its lock): it is the installed build, and nothing was deleted.+ case stillRecorded+ /// legendary's installed.json could not be read, so nothing says the folder is free:+ /// nothing was deleted, and the kept record stays for the next launch.+ case recordsUnreadable+ }++ /// Whether legendary records the game; nil when its installed.json can't be read. Read+ /// locally, no legendary run.+ public func recordsGame(_ appName: String) -> Bool? {+ do { return try Self.readInstalledIfThere(configDir)?[appName] != nil } catch { return nil }+ }++ /// Deletes an old build's files once a switch is done, the way legendary's own uninstall does+ /// (lfs/utils.py delete_filelist): only the files the old build's manifests list, from the+ /// copies the switch kept (saveRecord), read offline by `legendary list-files --manifest`,+ /// then the folders that leaves empty, the build's folder last. Saves, settings and mods the+ /// game wrote beside its files stay. Nothing is deleted outside Highball's game folders+ /// (EpicBuildSwitch.isSafeToDelete) or when the list cannot be had. The kept record goes+ /// afterwards either way.+ public func deleteOldBuild(_ appName: String, at oldPath: String, roots: [URL]) -> OldBuildDeletion {+ // The folder legendary records as the game is the installed build, never an old one.+ let installed: [String: Any]+ do { installed = try Self.readInstalledIfThere(configDir) ?? [:] } catch { return .recordsUnreadable }+ if let now = (installed[appName] as? [String: Any])?["install_path"] as? String, Self.samePath(now, oldPath) {+ return .stillRecorded+ }+ defer { discardSavedRecord(appName) }+ let folder = URL(fileURLWithPath: oldPath, isDirectory: true)+ guard EpicBuildSwitch.isSafeToDelete(folder, roots: roots) else { return .outsideGameFolders }+ let files: [String]+ do { files = try oldBuildFiles(appName) } catch { return .noFileList(error.localizedDescription) }+ let (deleted, failed) = Self.deleteFileList(files, in: folder)+ return .deleted(files: deleted, failed: failed)+ }++ /// The files the kept manifests of a switch's old build list: the game's and those of its DLC+ /// sharing its folder. Throws without the game's own manifest or when legendary fails.+ func oldBuildFiles(_ appName: String) throws -> [String] {+ let folder = savedRecordFolder(appName)+ guard let data = try? Data(contentsOf: folder.appending(path: "record.json")),+ let entries = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {+ throw HighballError.failed("no kept record of \(appName)'s old build")+ }+ func manifest(_ app: String) -> URL? {+ Self.manifestNames(app, entry: entries[app] as? [String: Any] ?? [:])+ .map { folder.appending(path: "manifests/\($0)") }+ .first { FileManager.default.fileExists(atPath: $0.path) }+ }+ guard let own = manifest(appName) else { throw HighballError.failed("the old build's manifest was not kept") }+ var files: [String] = []+ for file in [own] + entries.keys.filter({ $0 != appName }).sorted().compactMap(manifest) {+ files += try Self.manifestFilenames(capture(["list-files", "--manifest", file.path, "--json"]))+ }+ return files+ }++ /// The `filename`s of `legendary list-files --json`.+ static func manifestFilenames(_ json: String) throws -> [String] {+ guard let list = try JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: Any]] else {+ throw HighballError.failed("legendary list-files did not print a list")+ }+ return list.compactMap { $0["filename"] as? String }+ }++ /// legendary's delete_filelist with its delete_root_directory: each listed file is deleted+ /// (found without case, as legendary's case_insensitive_file_search does), then every folder+ /// the list names and the build's folder itself, deepest first, each only when empty. A name+ /// that would leave the folder is skipped. The files deleted and the ones that could not be.+ static func deleteFileList(_ filenames: [String], in folder: URL) -> (deleted: Int, failed: Int) {+ let fm = FileManager.default+ let root = folder.standardizedFileURL.resolvingSymlinksInPath()+ var deleted = 0, failed = 0+ var dirs = Set<String>()+ for name in filenames {+ let parts = name.replacingOccurrences(of: "\\", with: "/").split(separator: "/").map(String.init)+ .filter { $0 != "." }+ guard !parts.isEmpty, !parts.contains("..") else { continue }+ for i in 1..<parts.count { dirs.insert(parts[..<i].joined(separator: "/")) }+ guard let file = findIgnoringCase(parts, in: root) else { continue }+ let parent = file.deletingLastPathComponent().resolvingSymlinksInPath().path.lowercased()+ let base = root.path.lowercased()+ guard parent == base || parent.hasPrefix(base.hasSuffix("/") ? base : base + "/") else { continue }+ // A manifest names files: a folder at that name is someone else's, and stays.+ var isFolder: ObjCBool = false+ if (try? fm.destinationOfSymbolicLink(atPath: file.path)) == nil,+ fm.fileExists(atPath: file.path, isDirectory: &isFolder), isFolder.boolValue { continue }+ do { try fm.removeItem(at: file); deleted += 1 } catch { failed += 1 }+ }+ for dir in dirs.sorted(by: { $0.count > $1.count }) {+ if let url = findIgnoringCase(dir.split(separator: "/").map(String.init), in: root) { rmdir(url.path) }+ }+ rmdir(root.path)+ return (deleted, failed)+ }++ /// A path under `root` matched one name at a time, exactly first, then without case.+ private static func findIgnoringCase(_ parts: [String], in root: URL) -> URL? {+ let fm = FileManager.default+ var url = root+ for part in parts {+ let exact = url.appending(path: part)+ if (try? exact.checkResourceIsReachable()) == true || (try? fm.destinationOfSymbolicLink(atPath: exact.path)) != nil {+ url = exact; continue+ }+ guard let match = (try? fm.contentsOfDirectory(atPath: url.path))?.first(where: { $0.lowercased() == part.lowercased() })+ else { return nil }+ url = url.appending(path: match)+ }+ return url+ }+}diff --cc Sources/HighballKit/EpicStore.swiftindex 13a7c5e,7a91027..b07caa2--- a/Sources/HighballKit/EpicStore.swift+++ b/Sources/HighballKit/EpicStore.swift@@@ -172,12 -170,8 +173,12 @@@ public struct EpicStore: Sendablepublic let install_path: String?/// legendary's record of the installed size, in bytes.public var install_size: Int64? = nil- /// Where the game keeps the saves legendary syncs, once it has synced them.+ /// Where the game keeps the saves legendary syncs, once it has resolved it (EpicSaves).public var save_path: String? = nil+ /// "Windows" or "Mac": which build legendary installed (one per game).+ public var platform: String? = nil++ public var isMac: Bool { platform?.lowercased() == "mac" }}/// Everything legendary has installed, with where. Legendary's install state is global