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
Epic Mac: a build switch can be undone until the new build is in
Gabe2057f0b21c11
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 105cb9a..006db9f 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -3383,38 +3383,41 @@ final class AppState {}/// 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. `before`- /// runs first inside the same task (the Windows build's removal when switching to the Mac one).- private func epicDownload(title: String, before: (@MainActor () async throws -> Void)? = nil,+ /// 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,+ 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(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- try await before?()- epicInstallControl = control- let store = epicStore- epicDownloadTotal = nil- let refused = OSAllocatedUnfairLock(initialState: false)- let failure = OSAllocatedUnfairLock<String?>(initialState: nil)- // 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() }- 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)+ // 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() }+ 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() }}}@@ -3444,7 +3447,7 @@ final class AppState {}/// The Windows build is installed and legendary keeps one build per game: switching asks- /// first (the Windows copy is removed, its settings stay).+ /// 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?@@ -3460,65 +3463,93 @@ final class AppState {guard status == 0 else { throw HighballError.processFailed(command: "legendary uninstall", status: status, output: "see the log above") }}- /// Removes an Epic game's Mac build through legendary, then installs the Windows one in the- /// default environment: legendary keeps one build per game.+ /// 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 }) else { return }+ 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}- let removeMac: @MainActor () async throws -> Void = { [self] in- try Task.checkCancellation()- stage = String(format: L("Removing the Mac version of %@"), item.title)- try await legendaryUninstall(app)- if Task.isCancelled { appendLog("\(item.title): the Mac version was removed before Stop; Install downloads the Windows version") }- }- epicDownload(title: "Installing \(game.app_title)", before: removeMac) { store, control, onLine in+ epicDownload(title: "Installing \(game.app_title)",+ wrap: epicBuildSwitch(item, app: app, oldPath: epicMacInstalls[app], oldPlatform: "Mac", hasNewBuild: { true })) { store, control, onLine intry store.install(app, into: bottle, control: control, onLine: onLine)}}- /// Installs an Epic game's Mac build. With the Windows build installed, that one is removed- /// first through legendary, once the player has said yes (pendingEpicMacSwitch). Before- /// anything is removed, 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, after the Windows copy was already gone.+ /// 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 checkThenRemoveWindows: @MainActor () async throws -> Void = { [self] in+ let hasMac: @MainActor () async throws -> Bool = { [self] instage = L("Asking Epic about the Mac version")- let hasMac: Bool?do {- hasMac = try await Task.detached { try store.hasMacBuild(app) }.value+ return try await Task.detached { try store.hasMacBuild(app) }.value} catch {appendLog("\(item.title): legendary info --platform Mac failed: \(error)")- hasMac = nil- }- switch EpicStore.MacInstallStep.after(hasMacBuild: hasMac, replacingWindows: replacingWindows) {- case .couldNotAsk: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."))- case .noMacBuild:- 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."))- case .install:- return- case .removeWindowsThenInstall:- break}- // Stop before this point changes nothing. Once legendary is removing the Windows copy- // it finishes, and a Stop pressed meanwhile is said to have come after it.- try Task.checkCancellation()- stage = String(format: L("Removing the Windows version of %@"), item.title)- try await legendaryUninstall(app)- if Task.isCancelled { appendLog("\(item.title): the Windows version was removed before Stop; Install the Mac version downloads it") }}- epicDownload(title: String(format: L("Installing the Mac version of %@"), item.title), before: checkThenRemoveWindows) { store, control, onLine in+ 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 intry 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 = bottles.map { $0.driveC.appending(path: "Games", directoryHint: .isDirectory) } + [GOGStore.macGamesDir]+ 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,+ dropOldRecord: oldPath.map { _ in { [self] in+ stage = removing+ let status = try await Task.detached { try store.forgetRecordKeepingFiles(app, onLine: log) }.value+ guard status == 0 else { throw HighballError.processFailed(command: "legendary uninstall --keep-files", status: status, output: "see the log above") }+ } },+ install: download,+ restoreOldRecord: { [self] in+ guard let oldPath else { return }+ let status = try await Task.detached { try store.restoreRecord(app, path: oldPath, platform: oldPlatform, onLine: log) }.value+ appendLog(status == 0 ? "\(item.title): the \(oldPlatform) version is back as it was"+ : "\(item.title): could not record the \(oldPlatform) version again (legendary import exited with \(status)); its files are still in \(oldPath)")+ epicRefresh()+ },+ deleteOldFiles: { [self] in+ guard let oldPath else { return }+ let folder = URL(fileURLWithPath: oldPath, isDirectory: true)+ guard EpicBuildSwitch.isSafeToDelete(folder, roots: roots) else {+ appendLog("\(item.title): left the old \(oldPlatform) files in \(oldPath), outside Highball's game folders")+ return+ }+ do { try await Task.detached { try FileManager.default.removeItem(at: folder) }.value } catch {+ appendLog("\(item.title): could not delete the old \(oldPlatform) files in \(oldPath): \(error.localizedDescription)")+ }+ })+ 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."))+ }+ }+ }+/// 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@@ -3573,7 +3604,7 @@ final class AppState {/// Removes an Epic game's Mac build through legendary, so its library stays right.func epicUninstallMac(_ item: LibraryItem) {- guard let app = item.epicAppName else { return }+ guard let app = item.epicAppName, refuseWhileRunning(item) else { return }runBusy(String(format: L("Removing the Mac version of %@"), item.title), expected: nil) { [self] intry await legendaryUninstall(app)await MainActor.run { self.epicRefresh() }diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swiftindex 5ec1f01..fb178e7 100644--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@ -436,13 +436,13 @@ struct GameDetailView: View {}HStack(spacing: 10) {Button(L("Show in Finder")) { NSWorkspace.shared.activateFileViewerSelecting([folder]) }- Button(L("Remove the Mac version…")) { state.pendingEpicMacUninstall = item }.disabled(state.busy)+ Button(L("Remove the Mac version…")) { state.pendingEpicMacUninstall = item }.disabled(state.busy || state.isRunningNow(item))}.controlSize(.small).padding(.top, 2)} else if item.installed {// Epic keeps one build per game: from the Windows one, a switch.HStack(spacing: 8) {- Button(L("Switch to the Mac version…")) { state.installOnMac(item) }.controlSize(.small).disabled(state.busy)+ Button(L("Switch to the Mac version…")) { state.installOnMac(item) }.controlSize(.small).disabled(state.busy || state.isRunningNow(item))estimateText(macEstimate)}.padding(.top, 2)@@ -666,7 +666,7 @@ struct GameDetailView: View {// out is the Windows build, which takes its place.Text(L("This Mac version is 32-bit, which current macOS can't run.")).font(.callout).foregroundStyle(HB.warn)Button(L("Switch to the Windows version…")) { state.pendingEpicWindowsSwitch = item }- .controlSize(.large).disabled(state.busy)+ .controlSize(.large).disabled(state.busy || state.isRunningNow(item))} else if item.source == .epic || item.source == .gog {Button { state.install(item) } label: { primaryActionLabel(L("Install"), symbol: "arrow.down") }.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber).disabled(state.busy)diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex 079247b..e1a35ef 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -527,8 +527,8 @@ private extension View {Text(GamePageCopy.updateAsk(recipe: pending.recipe, engineID: pending.engineID, canPlay: pending.play != nil))}}- /// Epic keeps one build per game: switching to the Mac one removes the Windows one first,- /// and removing the Mac one means downloading it again to play it. A GOG Mac build goes to+ /// Epic keeps one build per game: switching to the Mac one removes the Windows one once the+ /// Mac one is in (EpicBuildSwitch), and removing the Mac one means downloading it again to play it. A GOG Mac build goes to/// the Trash only once the player has seen what goes.@MainActor func macVersionAsks(_ state: AppState) -> some View {self.alert(state.pendingEpicMacSwitch.map { String(format: L("Switch %@ to the Mac version?"), $0.title) } ?? "",@@ -537,7 +537,7 @@ private extension View {Button(L("Switch to the Mac version")) { state.pendingEpicMacSwitch = nil; state.epicInstallMac(item, replacingWindows: true) }Button(L("Cancel"), role: .cancel) { state.pendingEpicMacSwitch = nil }} message: { _ in- Text(L("Epic keeps one version of a game installed at a time, so the Windows version is removed first, then the Mac version downloads. Your Highball settings for the game stay."))+ Text(L("Epic keeps one version of a game installed at a time, so the Mac version downloads and the Windows version is removed once it is in. Stop the download, or should it fail, and the Windows version stays. Your Highball settings for the game stay."))}.alert(state.pendingEpicWindowsSwitch.map { String(format: L("Switch %@ to the Windows version?"), $0.title) } ?? "",isPresented: .init(get: { state.pendingEpicWindowsSwitch != nil }, set: { if !$0 { state.pendingEpicWindowsSwitch = nil } }),@@ -545,7 +545,7 @@ private extension View {Button(L("Switch to the Windows version")) { state.pendingEpicWindowsSwitch = nil; state.epicSwitchToWindows(item) }Button(L("Cancel"), role: .cancel) { state.pendingEpicWindowsSwitch = nil }} message: { _ in- Text(L("Epic keeps one version of a game installed at a time, so the Mac version is removed first, then the Windows version downloads into your environment."))+ Text(L("Epic keeps one version of a game installed at a time, so the Windows version downloads into your environment and the Mac version is removed once it is in. Stop the download, or should it fail, and the Mac version stays."))}.alert(state.pendingEpicMacUninstall.map { String(format: L("Remove the Mac version of %@?"), $0.title) } ?? "",isPresented: .init(get: { state.pendingEpicMacUninstall != nil }, set: { if !$0 { state.pendingEpicMacUninstall = nil } }),diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex 54e5fa3..af1d2d1 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -435,8 +435,8 @@ enum L10n {"Switch to the Windows version…": "Passer à la version Windows…","Switch to the Windows version": "Passer à la version Windows","Switch %@ to the Windows version?": "Passer %@ à la version Windows ?",- "Epic keeps one version of a game installed at a time, so the Mac version is removed first, then the Windows version downloads into your environment.":- "Epic n’installe qu’une version d’un jeu à la fois : la version Mac est d’abord supprimée, puis la version Windows est téléchargée dans votre environnement.",+ "Epic keeps one version of a game installed at a time, so the Windows version downloads into your environment and the Mac version is removed once it is in. Stop the download, or should it fail, and the Mac version stays.":+ "Epic n’installe qu’une version d’un jeu à la fois : la version Windows est téléchargée dans votre environnement, puis la version Mac est supprimée une fois la nouvelle en place. Si vous arrêtez le téléchargement, ou s’il échoue, la version Mac reste.","Highball could not find the Mac version of %@ to open.": "Highball ne trouve pas la version Mac de %@ à ouvrir.","The Mac version of %@ did not start: %@": "La version Mac de %@ n’a pas démarré : %@","Removing the Windows version of %@": "Suppression de la version Windows de %@",@@ -444,8 +444,8 @@ enum L10n {"Switch %@ to the Mac version?": "Passer %@ à la version Mac ?","Switch to the Mac version": "Passer à la version Mac","Switch to the Mac version…": "Passer à la version Mac…",- "Epic keeps one version of a game installed at a time, so the Windows version is removed first, then the Mac version downloads. Your Highball settings for the game stay.":- "Epic n’installe qu’une version d’un jeu à la fois : la version Windows est d’abord supprimée, puis la version Mac est téléchargée. Vos réglages Highball pour ce jeu sont conservés.",+ "Epic keeps one version of a game installed at a time, so the Mac version downloads and the Windows version is removed once it is in. Stop the download, or should it fail, and the Windows version stays. Your Highball settings for the game stay.":+ "Epic n’installe qu’une version d’un jeu à la fois : la version Mac est téléchargée, puis la version Windows est supprimée une fois la nouvelle en place. Si vous arrêtez le téléchargement, ou s’il échoue, la version Windows reste. Vos réglages Highball pour ce jeu sont conservés.","Asking Epic about the Mac version": "Demande des informations sur la version Mac à Epic","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.":"Highball n’a pas pu demander à Epic si une version Mac de ce jeu est disponible au téléchargement, donc rien n’a été modifié. Vérifiez votre connexion, puis réessayez.",diff --git a/Sources/HighballApp/LibraryView.swift b/Sources/HighballApp/LibraryView.swiftindex 626febe..f127273 100644--- a/Sources/HighballApp/LibraryView.swift+++ b/Sources/HighballApp/LibraryView.swift@@ -466,7 +466,7 @@ struct LibraryTile: View {// Epic's goes through legendary, so its library stays right.if item.source == .epic, item.installedOnMac {Button(L("Remove the Mac version…"), role: .destructive) { state.pendingEpicMacUninstall = item }- .disabled(state.busy)+ .disabled(state.busy || state.isRunningNow(item))}}.accessibilityLabel("\(item.title), \(item.source.rawValue)\(item.installedOnMac ? ", " + (item.source == .steam ? L("Installed in Steam for Mac") : L("Mac version installed")) : item.installed ? "" : ", " + L("Not installed"))")diff --git a/Sources/HighballKit/EpicBuildSwitch.swift b/Sources/HighballKit/EpicBuildSwitch.swiftnew file mode 100644index 0000000..f9b2643--- /dev/null+++ b/Sources/HighballKit/EpicBuildSwitch.swift@@ -0,0 +1,58 @@+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: the old files stay on disk until the new build is fully in, so a Stop,+/// a failed download, or legendary falling back to the old platform puts the old record back+/// (`legendary import`) 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+ }+ }+}diff --git a/Sources/HighballKit/EpicStore.swift b/Sources/HighballKit/EpicStore.swiftindex 5e1f05a..03a63c2 100644--- a/Sources/HighballKit/EpicStore.swift+++ b/Sources/HighballKit/EpicStore.swift@@ -40,7 +40,10 @@ public struct EpicStore: Sendable {/// Captures stdout only. Legendary writes its log lines to stderr and JSON to stdout;/// merging them (Shell.capture) breaks JSON parsing.@discardableResult- func capture(_ args: [String]) throws -> String {+ func capture(_ args: [String]) throws -> String { try captureWithLog(args).out }++ /// legendary's output and its log (stderr), where its warnings appear, such as a missing asset.+ func captureWithLog(_ args: [String]) throws -> (out: String, log: String) {let p = Process()p.executableURL = binaryp.arguments = args@@ -57,7 +60,7 @@ public struct EpicStore: Sendable {status: p.terminationStatus,output: String(decoding: errData.suffix(2000), as: UTF8.self))}- return String(decoding: data, as: UTF8.self)+ return (String(decoding: data, as: UTF8.self), String(decoding: errData, as: UTF8.self))}/// Runs legendary streaming each output line (installs are long and progress matters).@@ -212,11 +215,11 @@ public struct EpicStore: Sendable {}/// Installs a game's Mac build into the Mac games folder, beside GOG's (GOGStore.macGamesDir).- /// legendary keeps one install per game, so the Windows one must be removed first, and only- /// once `hasMacBuild` said yes. Should legendary still fall back to the Windows build (its- /// install_platform_fallback, on by default and with no flag to turn it off, makes a missing- /// Mac asset a warning and downloads the Windows build into this folder, outside every- /// environment), it is stopped at that line, before the download, and the install fails.+ /// legendary keeps one install per game, so the Windows one's record must be dropped first+ /// (EpicBuildSwitch), and only once `hasMacBuild` said yes. Should legendary still fall back+ /// to the Windows build (its install_platform_fallback, on by default and with no flag to+ /// turn it off, makes a missing Mac asset a warning and downloads the Windows build into this+ /// folder, outside every environment), it is stopped at that line, before the download, and the install fails.@discardableResultpublic func installMac(_ appName: String, control: LegendaryControl? = nil,onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {@@ -245,32 +248,25 @@ public struct EpicStore: Sendable {/// read from `legendary info --platform Mac`. A catalog listing Mac (Game.listsMac) does not/// promise one.public func hasMacBuild(_ appName: String) throws -> Bool {- let out = try capture(["info", appName, "--json", "--platform", "Mac"])- return Self.listsBuild(Data(out.utf8), platform: "Mac")- }-- /// legendary's `info --json` names a version for each platform the game has an asset for- /// (game.platform_versions, from the asset list its install checks). None for the platform,- /// or output that cannot be read, is no build.- static func listsBuild(_ data: Data, platform: String) -> Bool {- guard let start = data.firstIndex(of: UInt8(ascii: "{")),+ let (out, log) = try captureWithLog(["info", appName, "--json", "--platform", "Mac"])+ return Self.manifest(Data(out.utf8), log: log, platform: "Mac") != nil+ }++ /// The manifest `legendary info --json --platform <platform>` printed, only when it is that+ /// platform's build. With the platform's asset missing, legendary logs "Asset information+ /// for ... is missing", answers offline and prints the installed build's manifest instead (a+ /// Windows one for a Mac question), so the log must hold no such warning and the manifest's+ /// build version must be the one Epic lists for the platform (game.platform_versions, from+ /// the asset list its install checks). Output that cannot be read is no build.+ static func manifest(_ data: Data, log: String, platform: String) -> [String: Any]? {+ guard !log.contains("Asset information for"),+ let start = data.firstIndex(of: UInt8(ascii: "{")),let obj = try? JSONSerialization.jsonObject(with: data[start...]) as? [String: Any],- let game = obj["game"] as? [String: Any],- let versions = game["platform_versions"] as? [String: Any] else { return false }- return versions[platform] != nil- }-- /// What a Mac install does once `hasMacBuild` has answered: nil when it could not ask. Stop- /// with nothing changed unless Epic named a Mac build, and only then remove the Windows build- /// first when switching from it, so a missing build never costs the Windows copy.- public enum MacInstallStep: Equatable, Sendable {- case couldNotAsk, noMacBuild, install, removeWindowsThenInstall-- public static func after(hasMacBuild: Bool?, replacingWindows: Bool) -> MacInstallStep {- guard let hasMacBuild else { return .couldNotAsk }- guard hasMacBuild else { return .noMacBuild }- return replacingWindows ? .removeWindowsThenInstall : .install- }+ let manifest = obj["manifest"] as? [String: Any],+ let versions = (obj["game"] as? [String: Any])?["platform_versions"] as? [String: Any],+ let listed = versions[platform] as? String,+ manifest["build_version"] as? String == listed else { return nil }+ return manifest}/// Installs a game's Windows build into the bottle at drive_c/Games/<folder>.@@ -357,6 +353,24 @@ public struct EpicStore: Sendable {}static func uninstallArguments(appName: String) -> [String] { ["uninstall", appName, "-y"] }+ static func keepFilesUninstallArguments(appName: String) -> [String] { ["uninstall", appName, "-y", "--keep-files", "--skip-uninstaller"] }+ static func importArguments(appName: String, path: String, platform: String) -> [String] {+ ["import", appName, path, "--platform", platform, "--with-dlcs", "--disable-check"]+ }++ /// Drops legendary's record of an install and keeps its files, so a switch to the other build+ /// can be undone (`restoreRecord`) until the new build is in (EpicBuildSwitch).+ @discardableResult+ public func forgetRecordKeepingFiles(_ appName: String, onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ try runStreaming(Self.keepFilesUninstallArguments(appName: appName), onLine: onLine)+ }++ /// Records again an install whose files are still on disk (`legendary import`).+ @discardableResult+ public func restoreRecord(_ appName: String, path: String, platform: String,+ onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ try runStreaming(Self.importArguments(appName: appName, path: path, platform: platform), onLine: onLine)+ }/// Removes a game legendary installed. Legendary owns the Epic install state, so it does the/// deleting and its library stays right; deleting the folder ourselves would leave itdiff --git a/Tests/HighballKitTests/EpicBuildSwitchTests.swift b/Tests/HighballKitTests/EpicBuildSwitchTests.swiftnew file mode 100644index 0000000..2517c4e--- /dev/null+++ b/Tests/HighballKitTests/EpicBuildSwitchTests.swift@@ -0,0 +1,81 @@+import XCTest+@testable import HighballKit++/// Replacing an Epic build: the old one stays recoverable until the new one is in.+final class EpicBuildSwitchTests: XCTestCase {+ final class Log: @unchecked Sendable { var steps: [String] = [] }++ private func steps(_ log: Log, hasNew: Bool = true, replacing: Bool = true,+ install: @escaping () async throws -> Void = {}) -> EpicBuildSwitch.Steps {+ EpicBuildSwitch.Steps(+ hasNewBuild: { log.steps.append("check"); return hasNew },+ dropOldRecord: replacing ? { log.steps.append("drop") } : nil,+ install: { log.steps.append("install"); try await install() },+ restoreOldRecord: { log.steps.append("restore") },+ deleteOldFiles: { log.steps.append("delete") })+ }++ func testTheOldFilesGoOnlyOnceTheNewBuildIsIn() async throws {+ let log = Log()+ try await EpicBuildSwitch.run(steps(log))+ XCTAssertEqual(log.steps, ["check", "drop", "install", "delete"])+ }++ func testNoNewBuildChangesNothing() async {+ let log = Log()+ do { try await EpicBuildSwitch.run(steps(log, hasNew: false)); XCTFail("no new build") } catch {+ XCTAssertEqual(error as? EpicBuildSwitch.Failure, .noNewBuild)+ }+ XCTAssertEqual(log.steps, ["check"])+ }++ /// A failed download, or legendary falling back to the old platform, puts the old record back.+ func testAFailedInstallPutsTheOldBuildBack() async {+ let log = Log()+ struct Boom: Error {}+ do { try await EpicBuildSwitch.run(steps(log, install: { throw Boom() })); XCTFail("failed") } catch { XCTAssertTrue(error is Boom) }+ XCTAssertEqual(log.steps, ["check", "drop", "install", "restore"])+ }++ /// Stop while Epic is asked: nothing is dropped.+ func testStopDuringTheCheckChangesNothing() async {+ let log = Log()+ let started = AsyncStream<Void>.makeStream()+ let task = Task {+ try await EpicBuildSwitch.run(EpicBuildSwitch.Steps(+ hasNewBuild: { log.steps.append("check"); started.continuation.yield(); try? await Task.sleep(for: .milliseconds(200)); return true },+ dropOldRecord: { log.steps.append("drop") }, install: { log.steps.append("install") },+ restoreOldRecord: { log.steps.append("restore") }, deleteOldFiles: { log.steps.append("delete") }))+ }+ for await _ in started.stream { break }+ task.cancel()+ do { try await task.value; XCTFail("stopped") } catch { XCTAssertTrue(error is CancellationError) }+ XCTAssertEqual(log.steps, ["check"])+ }++ /// Stop during the download: the old record is put back.+ func testStopDuringTheDownloadPutsTheOldBuildBack() async {+ let log = Log()+ let task = Task { try await EpicBuildSwitch.run(steps(log, install: { try await Task.sleep(for: .seconds(5)) })) }+ while !log.steps.contains("install") { await Task.yield() }+ task.cancel()+ do { try await task.value; XCTFail("stopped") } catch { XCTAssertTrue(error is CancellationError) }+ XCTAssertEqual(log.steps, ["check", "drop", "install", "restore"])+ }++ func testAPlainInstallHasNothingToDropOrDelete() async throws {+ let log = Log()+ try await EpicBuildSwitch.run(steps(log, replacing: false))+ XCTAssertEqual(log.steps, ["check", "install"])+ }++ func testOnlyAFolderInsideHighballsGameFoldersIsDeleted() {+ let roots = [URL(fileURLWithPath: "/E/drive_c/Games"), URL(fileURLWithPath: "/U/Applications/Highball Games")]+ XCTAssertTrue(EpicBuildSwitch.isSafeToDelete(URL(fileURLWithPath: "/E/drive_c/Games/Gungeon"), roots: roots))+ XCTAssertTrue(EpicBuildSwitch.isSafeToDelete(URL(fileURLWithPath: "/u/applications/highball games/Garlic"), roots: roots))+ XCTAssertFalse(EpicBuildSwitch.isSafeToDelete(URL(fileURLWithPath: "/E/drive_c/Games"), roots: roots))+ XCTAssertFalse(EpicBuildSwitch.isSafeToDelete(URL(fileURLWithPath: "/E/drive_c/Games/"), roots: roots))+ XCTAssertFalse(EpicBuildSwitch.isSafeToDelete(URL(fileURLWithPath: "/E/drive_c/Games2/X"), roots: roots))+ XCTAssertFalse(EpicBuildSwitch.isSafeToDelete(URL(fileURLWithPath: "/U/Applications"), roots: roots))+ }+}diff --git a/Tests/HighballKitTests/StoreMacVersionTests.swift b/Tests/HighballKitTests/StoreMacVersionTests.swiftindex 16eb005..77be7da 100644--- a/Tests/HighballKitTests/StoreMacVersionTests.swift+++ b/Tests/HighballKitTests/StoreMacVersionTests.swift@@ -270,24 +270,27 @@ final class EpicMacBuildTests: XCTestCase {}/// Epic's catalog can list Mac with no Mac asset, and legendary's install then falls back to- /// Windows: the Windows copy is removed only when `info` names a Mac version.- func testAMacBuildIsThereOnlyWhenLegendaryNamesAMacVersion() {- let both = #"[cli] INFO: Getting game metadata... {"game": {"app_name": "Garlic", "platform_versions": {"Windows": "1.0-w", "Mac": "1.0-m"}}, "install": null, "manifest": null}"#- let windowsOnly = #"{"game": {"app_name": "Duck", "platform_versions": {"Windows": "2.0"}}, "install": {"platform": "Windows"}, "manifest": {"disk_size": 5}}"#- XCTAssertTrue(EpicStore.listsBuild(Data(both.utf8), platform: "Mac"))- XCTAssertFalse(EpicStore.listsBuild(Data(windowsOnly.utf8), platform: "Mac"), "a Windows manifest from the install is not a Mac build")- XCTAssertFalse(EpicStore.listsBuild(Data(#"{"game": null, "install": null, "manifest": null}"#.utf8), platform: "Mac"))- XCTAssertFalse(EpicStore.listsBuild(Data("No game information available.".utf8), platform: "Mac"))- }-- /// The Windows copy goes only once Epic named a Mac build, and only when switching from it.- func testTheWindowsCopyGoesOnlyOnceEpicNamedAMacBuild() {- typealias Step = EpicStore.MacInstallStep- XCTAssertEqual(Step.after(hasMacBuild: nil, replacingWindows: true), .couldNotAsk)- XCTAssertEqual(Step.after(hasMacBuild: false, replacingWindows: true), .noMacBuild)- XCTAssertEqual(Step.after(hasMacBuild: false, replacingWindows: false), .noMacBuild)- XCTAssertEqual(Step.after(hasMacBuild: true, replacingWindows: false), .install)- XCTAssertEqual(Step.after(hasMacBuild: true, replacingWindows: true), .removeWindowsThenInstall)+ /// Windows: a Mac build is there only when `info` prints the Mac manifest Epic lists.+ func testAMacBuildIsThereOnlyWhenLegendaryPrintsItsManifest() {+ func mac(_ out: String, log: String = "") -> Bool { EpicStore.manifest(Data(out.utf8), log: log, platform: "Mac") != nil }+ let both = #"[cli] INFO: Getting game metadata... {"game": {"app_name": "Garlic", "platform_versions": {"Windows": "1.0-w", "Mac": "1.0-m"}}, "install": null, "manifest": {"build_version": "1.0-m"}}"#+ let windowsOnly = #"{"game": {"app_name": "Duck", "platform_versions": {"Windows": "2.0"}}, "install": {"platform": "Windows"}, "manifest": {"build_version": "2.0", "disk_size": 5}}"#+ XCTAssertTrue(mac(both))+ XCTAssertFalse(mac(windowsOnly), "a Windows manifest from the install is not a Mac build")+ XCTAssertFalse(mac(#"{"game": null, "install": null, "manifest": null}"#))+ XCTAssertFalse(mac("No game information available."))+ // The Mac asset gone: legendary warns, answers offline and prints the installed Windows+ // build's manifest, with Mac still listed.+ let installedWindows = #"{"game": {"app_name": "Garlic", "platform_versions": {"Windows": "1.0-w", "Mac": "1.0-m"}}, "manifest": {"build_version": "1.0-w"}}"#+ XCTAssertFalse(mac(installedWindows))+ XCTAssertFalse(mac(both, log: #"[Core] WARNING: Asset information for "Garlic" is missing, the game may have been removed from your account."#))+ }++ /// A switch between builds drops only legendary's record first, so it can be put back.+ func testABuildSwitchKeepsTheOldFilesUntilTheNewBuildIsIn() {+ XCTAssertEqual(EpicStore.keepFilesUninstallArguments(appName: "A"), ["uninstall", "A", "-y", "--keep-files", "--skip-uninstaller"])+ XCTAssertEqual(EpicStore.importArguments(appName: "A", path: "/x/A", platform: "Windows"),+ ["import", "A", "/x/A", "--platform", "Windows", "--with-dlcs", "--disable-check"])}func testTheFallBackToWindowsIsSeen() {