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/mac-badges' into feat/gog-mac
Gabeec96275b2318
diff --cc Sources/HighballApp/AppState.swiftindex 07c7242,f7b5c24..85a3a07--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@@ -3922,154 -3887,9 +3928,155 @@@ final class AppState}}+ /// Downloads a GOG game's Mac build into the Mac games folder (GOGMac): no environment, no+ /// runtimes, no setup to run. The Windows install, if any, stays as it is.+ func gogInstallMac(_ item: LibraryItem) {+ guard let id = item.gogID else { return }+ runBusy(String(format: L("Installing the Mac version of %@"), item.title), expected: L("a large download; you can leave it running"),+ stop: .cancelTask(label: L("Stop")), cleanup: { [weak self] in self?.gogInstallControl = nil }) { [self] in+ let store = gogStore+ try await store.ensureInstalled()+ stage = L("Asking GOG about the download")+ let info = try await Task.detached { try store.info(id, platform: "osx") }.value+ let language = GOGStore.language(for: info.languages)+ appendLog("\(item.title): GOG Mac build \(info.buildID ?? "?"), language \(language), \(info.diskSize.map { ByteCountFormatter.string(fromByteCount: $0, countStyle: .file) } ?? "size unknown") on disk")+ stage = String(format: L("Downloading %@"), item.title)+ try await gogDownload(title: item.title, command: "gogdl download --platform osx", completed: { store.downloadCompleted(id) }) { control, onLine in+ try store.installMac(id, language: language, control: control, onLine: onLine)+ }+ busyProgress = nil; transferRate = nil+ guard let game = await refreshGOGMacInstalls()[id] else {+ throw HighballError.failed(L("The download finished, but Highball could not find the Mac version in it."))+ }+ appendLog("\(item.title): Mac version installed in \(game.folder.path), built for \(game.arch)")+ }+ }++ /// Mac builds running now, by library id: their process, for the achievement card's+ /// placement and so Play cannot start a second copy.+ var macGameProcesses: [String: Process] = [:]++ /// Whether a game runs now, either build: changing or removing a build then would pull its+ /// files from under it.+ func isRunningNow(_ item: LibraryItem) -> Bool {+ macGameProcesses[item.id] != nil || runningSessions.contains { $0.libraryID == item.id }+ }++ /// True when a change to the game's builds may go ahead; otherwise says why.+ private func refuseWhileRunning(_ item: LibraryItem) -> Bool {+ guard isRunningNow(item) else { return true }+ fail(HighballError.failed(String(format: L("Quit %@ first: it is running."), item.title)))+ return false+ }++ /// Play on Mac would do nothing: the game runs already, or a GOG or Epic Mac build would wait+ /// on the progress strip another task holds (its start runs there).+ func macPlayUnavailable(_ item: LibraryItem) -> Bool {+ isRunningNow(item) || ((item.source == .gog || item.source == .epic) && busy)+ }++ /// Plays a GOG game's Mac build as the Windows one plays: saves down from GOG's cloud first+ /// (GOG's Mac locations, GOGSaves.macLocations), comet beside it for achievements and the+ /// unlock card, and saves back up once it quits. The app runs as itself, no Wine; Highball+ /// starts its executable, with the play task's arguments and working folder as Galaxy passes+ /// them, so it knows when it has quit.+ func gogPlayMac(_ item: LibraryItem) {+ guard let id = item.gogID, let mac = gogMacInstalled[id], let app = mac.app,+ let executable = Bundle(url: app)?.executableURL else {+ fail(HighballError.failed(String(format: L("Highball could not find the Mac version of %@ to open."), item.title)))+ return+ }+ // The entry stays until the game has ended (watchMacGame), a launcher's hand-over included.+ if macGameProcesses[item.id] != nil {+ fail(HighballError.failed("\(item.title) is already running."))+ return+ }+ let game = mac.asInstalledGame+ let store = gogStore+ let useComet = gogSignedIn && gogSettings.cometOff[id] == nil+ let useSaves = gogSignedIn && !gogSettings.cloudSavesOff.contains(id)+ runBusy(String(format: L("Starting %@"), item.title), done: .handedOff) { [self] in+ let saveFolders = useSaves ? await gogMacSaveLocations(game) : []+ for (location, folder) in saveFolders {+ stage = L("Bringing your saves down from GOG")+ try await gogSync(game, title: item.title, location: location, folder: folder, direction: .download, beforePlay: true)+ }+ try Task.checkCancellation()++ var comet: Process?+ let cometLog = paths.logs.appending(path: "\(ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: ""))-comet-\(id).log")+ if useComet {+ stage = L("Starting comet for achievements")+ comet = await gogStartComet(for: game, in: nil, log: cometLog)+ if let comet { watchAchievements(of: game, item: item, bottleName: "", comet: comet, log: cometLog) }+ }++ let process = Process()+ process.executableURL = executable+ let task = game.launchTask(), launch = task.flatMap { GOGStore.launch($0, in: game) }+ process.arguments = launch?.arguments ?? []+ process.currentDirectoryURL = (task?.workingDir ?? "").isEmpty ? app.deletingLastPathComponent() : launch?.workingDirectory+ do { try process.run() } catch {+ GOGComet(store: store).stop(comet)+ throw HighballError.failed(String(format: L("The Mac version of %@ did not start: %@"), item.title, error.localizedDescription))+ }+ macGameProcesses[item.id] = process+ recordPlay(item)+ appendLog("\(item.title): the Mac version is running\(comet != nil ? ", with comet for achievements" : "")")+ watchMacGame(process, item: item, game: game, comet: comet, cometLog: cometLog, saveFolders: saveFolders)+ }+ }++ /// Once the Mac build quits: comet stops, and the saves go back up. The process Highball+ /// started may be a launcher that hands over to the game and exits at once, so the game ends+ /// only once nothing runs from its folder any more (MacGameWatch), as a Windows session+ /// ends only once none of its programs runs.+ private func watchMacGame(_ process: Process, item: LibraryItem, game: GOGStore.InstalledGame, comet: Process?,+ cometLog: URL, saveFolders: [(GOGSaves.Location, URL)]) {+ let store = gogStore+ let folder = game.folder+ Task.detached { [weak self] in+ if await Self.macGameEnd(of: process, watching: folder) {+ await self?.appendLog("\(item.title): the Mac version handed over to another app, which has now quit too")+ }+ GOGComet(store: store).stop(comet)+ await self?.macGameEnded(item: item, game: game, cometRan: comet != nil, cometLog: cometLog, saveFolders: saveFolders)+ }+ }++ /// Waits until a Mac game Highball started has ended: its process has quit (awaited, holding+ /// no thread for the session), and no app from its folder runs any more+ /// (MacGameWatch.waitForHandover). Only apps a player sees count: a crash reporter or helper+ /// left behind would keep the game running, comet up and its saves unsynced until Highball+ /// quits. Whether the game handed over to another app.+ nonisolated private static func macGameEnd(of process: Process, watching folder: URL?) async -> Bool {+ let started = Date()+ await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) in+ let once = OSAllocatedUnfairLock(initialState: false)+ let finish: @Sendable () -> Void = { if once.withLock({ let first = !$0; $0 = true; return first }) { done.resume() } }+ process.terminationHandler = { _ in finish() }+ if !process.isRunning { finish() } // quit before the handler was set+ }+ guard let folder else { return false }+ return await MacGameWatch.waitForHandover(from: folder, ranFor: Date().timeIntervalSince(started)) { folder in+ MacGameWatch.processes(runningFrom: folder).filter { NSRunningApplication(processIdentifier: $0)?.activationPolicy == .regular }+ }+ }++ private func macGameEnded(item: LibraryItem, game: GOGStore.InstalledGame, cometRan: Bool, cometLog: URL,+ saveFolders: [(GOGSaves.Location, URL)]) async {+ macGameProcesses[item.id] = nil+ if cometRan, !GOGComet.gameConnected(log: cometLog) {+ appendLog("\(item.title): the Mac version never reached comet, so no achievements this time")+ }+ for (location, folder) in saveFolders {+ try? await gogSync(game, title: item.title, location: location, folder: folder, direction: .upload, beforePlay: false)+ }+ }+- /// Steam games Steam Cloud keeps saves for (OwnedSteamGame.steamCloud).- var steamCloudAppIDs: Set<Int> = []+ /// Whether Steam Cloud keeps each owned Steam game's saves (OwnedSteamGame.steamCloud), for the+ /// games an environment's Steam has listed; a game not here is one Highball cannot say about.+ var steamCloudByAppID: [Int: Bool] = [:]/// How GOG syncs each GOG game's saves (GOGSaves.CloudSetup), asked once a session per game.@ObservationIgnored private var gogCloudSetups: [String: GOGSaves.CloudSetup] = [:]