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
GOG Mac versions install and play from Highball
Gabe8682b1667338
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex b699d3c..f387761 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -295,6 +295,7 @@ final class AppState {steamOwnedByBottle: steamOwnedByBottle, macInstalled: includeMacSteam ? macSteamGames : [],epicOwned: epicOwned, epicInstalls: epicInstalls,gogGames: gogGames, gogInstalledByBottle: gogInstalledByBottle, gogLaunchChoice: gogSettings.launchChoice,+ gogMacInstalled: Set(gogMacInstalled.keys),battleNetByBottle: battleNetByBottle,plays: libraryPlays, defaultBottle: defaultBottle?.name,pinExists: { bottle, pin in@@ -386,6 +387,7 @@ final class AppState {/// Starts the native build through Steam for Mac.func playOnMac(_ item: LibraryItem) {+ if item.source == .gog { gogPlayMac(item); return }guard let appid = item.steamAppID else { return }recordPlay(item)_ = openInSteamForMac(URL(string: "steam://run/\(appid)")!)@@ -394,6 +396,7 @@ final class AppState {/// Hands the game to Steam for Mac, whose own dialog asks where to put it; without it, the/// download page for Steam for Mac.func installOnMac(_ item: LibraryItem) {+ if item.source == .gog { gogInstallMac(item); return }guard let appid = item.steamAppID else { return }if !openInSteamForMac(URL(string: "steam://install/\(appid)")!) {NSWorkspace.shared.open(URL(string: "https://store.steampowered.com/about/")!)@@ -426,7 +429,11 @@ final class AppState {/// Play on Mac leads for this item (see MacSteamBuild.leads).func prefersMacBuild(_ item: LibraryItem) -> Bool {- MacSteamBuild.leads(entry: gameDB.entry(for: item), installedOnMac: item.installedOnMac,+ // A GOG Mac build leads once installed, unless it is one macOS no longer runs.+ if item.source == .gog {+ return item.installedOnMac && item.gogID.flatMap { gogMacInstalled[$0] }?.arch != .only32Bit+ }+ return MacSteamBuild.leads(entry: gameDB.entry(for: item), installedOnMac: item.installedOnMac,appInfo: item.steamAppID.flatMap { macAppInfoByAppID[$0] })}@@ -869,6 +876,8 @@ final class AppState {var gogGames: [GOGStore.Game] = []/// What each environment holds, read from the goggame-<id>.info files on disk.var gogInstalledByBottle: [String: [GOGStore.InstalledGame]] = [:]+ /// GOG Mac builds in the Mac games folder, by GOG id (GOGMac).+ var gogMacInstalled: [String: GOGStore.MacInstalledGame] = [:]var gogLoading = falseprivate var gogFetchInFlight = falsevar showGOGSignIn = false@@ -1048,7 +1057,8 @@ final class AppState {}/// The cheap part of `refresh`: installed games only. Runs on every install-record change,- /// so it must not spawn per call beyond legendary's install list, and never touches the+ /// so it must not spawn per call beyond legendary's install list and one off-main scan for+ /// GOG Mac builds (of which only the newest result counts), and never touches the/// directories it watches.func refreshInstalledGames() {refreshSteamInstalls()@@ -2109,6 +2119,17 @@ final class AppState {}}+ /// The native build's place on disk: a GOG Mac build's app, or Steam for Mac's install+ /// folder. Nil when no Mac build is installed.+ func macFolder(for item: LibraryItem) -> URL? {+ guard item.installedOnMac else { return nil }+ switch item.source {+ case .gog: return item.gogID.flatMap { gogMacInstalled[$0] }.map { $0.app ?? $0.folder }+ case .steam: return macSteamGames.first { $0.appid == item.steamAppID }?.installFolder+ default: return nil+ }+ }+/// The game's own folder on disk: Steam's install directory, Epic's install path, or the/// directory a pinned program lives in. What "Show the game's folder" opens (discussion/// #126: mods are folder copies, and the question was where the game is). Nil when the@@ -3510,6 +3531,7 @@ final class AppState {let found = Dictionary(bottles.map { ($0.name, GOGStore.installedGames(driveC: $0.driveC)) }, uniquingKeysWith: { a, _ in a })let store = gogStorefor game in found.values.joined() { store.adoptManifest(for: game) }+ Task { await refreshGOGMacInstalls() }guard found != gogInstalledByBottle else { return }let newIDs = Set(found.values.joined().map(\.id)).subtracting(gogGames.map(\.id))gogInstalledByBottle = found@@ -3518,6 +3540,21 @@ final class AppState {if !newIDs.isEmpty, !gogFetchInFlight { gogRefresh() }}+ @ObservationIgnored private var macScanGeneration = 0++ /// GOG Mac builds in the Mac games folder and the Applications folders, scanned off the main+ /// actor: /Applications holds every app on the Mac.+ private func refreshGOGMacInstalls() async {+ macScanGeneration += 1+ let generation = macScanGeneration+ let mac = await Task.detached { Dictionary(GOGStore.macInstalledGames().map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) }.value+ // Scans overlap (the install watcher fires many times during a download): an older one+ // landing last must not bring back a game moved to the Trash since.+ guard generation == macScanGeneration, mac != gogMacInstalled else { return }+ gogMacInstalled = mac+ rebuildLibrary()+ }+/// The GOG tile a program added by hand plays as (LibraryIndex.gogCoveredPins), if any, with/// what the program runs. Read off the environment's saved pins, so a launch-time mode on/// `pin` does not hide it.@@ -3663,6 +3700,113 @@ 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+ await refreshGOGMacInstalls()+ guard let game = gogMacInstalled[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] = [:]++ /// Plays a GOG game's Mac build as the Windows one plays: saves down from GOG's cloud first+ /// (GOG's Mac locations, or the Windows ones a Mac folder shares, 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 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+ process.currentDirectoryURL = app.deletingLastPathComponent()+ 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, started = Date()+ Task.detached { [weak self] in+ process.waitUntilExit()+ if await MacGameWatch.waitForHandover(from: folder, ranFor: Date().timeIntervalSince(started)) {+ await self?.appendLog("\(item.title): the Mac version handed over to another process, which has now quit too")+ }+ GOGComet(store: store).stop(comet)+ await self?.macGameEnded(item: item, game: game, cometRan: comet != nil, cometLog: cometLog, saveFolders: saveFolders)+ }+ }++ 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> = []@@ -3673,13 +3817,56 @@ final class AppState {func gogCloudSetup(for item: LibraryItem) async -> GOGSaves.CloudSetup? {guard let id = item.gogID else { return nil }if let known = gogCloudSetups[id] { return known }- guard let game = bottles.first(where: { $0.name == item.bottleName }).flatMap({ gogInstalled(item, in: $0) }) else { return nil }+ let windows = bottles.first { $0.name == item.bottleName }.flatMap { gogInstalled(item, in: $0) }+ guard let game = windows ?? gogMacInstalled[id]?.asInstalledGame else { return nil }let saves = GOGSaves(store: gogStore)let setup = await Task.detached { saves.clientID(for: game).flatMap { try? saves.cloudSetup(clientID: $0) } }.valueif let setup { gogCloudSetups[id] = setup }return setup}+ /// The Mac build's cloud-save folders, empty when it has none or GOG cannot say.+ private func gogMacSaveLocations(_ game: GOGStore.InstalledGame) async -> [(GOGSaves.Location, URL)] {+ let saves = GOGSaves(store: gogStore)+ let locations = await Task.detached { () -> [GOGSaves.Location]? in+ guard let client = saves.clientID(for: game) else { return nil }+ return (try? saves.macLocations(clientID: client)) ?? nil+ }.value+ return (locations ?? []).compactMap { location in+ guard let folder = GOGSaves.resolveMac(location.template, installFolder: game.folder) else {+ appendLog("\(game.title): cloud saves at \(location.template) have no folder on this Mac, skipping that one")+ return nil+ }+ appendLog("\(game.title): cloud saves for the Mac version in \(folder.path)")+ return (location, folder)+ }+ }+++ /// A GOG Mac build the player asked to move to the Trash: asked first, with what goes.+ var pendingGOGMacTrash: LibraryItem?++ /// What the Trash takes for a GOG game's Mac build: its app, or the folder holding its info+ /// (GOGStore.MacInstalledGame.folder). Nil when there is none, or when it would be a folder+ /// Mac builds are looked for in, which holds other apps.+ func gogMacTrashTarget(for item: LibraryItem) -> URL? {+ guard let id = item.gogID, let folder = gogMacInstalled[id]?.folder else { return nil }+ let searched = Set(GOGStore.macSearchFolders.map { $0.standardizedFileURL.path })+ return searched.contains(folder.standardizedFileURL.path) ? nil : folder+ }++ /// Moves a GOG game's Mac build to the Trash, where it can still be put back. Only once the+ /// player said yes (pendingGOGMacTrash).+ func gogTrashMac(_ item: LibraryItem) {+ guard let target = gogMacTrashTarget(for: item) else { return }+ NSWorkspace.shared.recycle([target]) { [weak self] _, error in+ Task { @MainActor in+ if let error { self?.appendLog("\(item.title): could not move the Mac version to the Trash: \(error.localizedDescription)") }+ await self?.refreshGOGMacInstalls()+ }+ }+ }+/// Updates a game gogdl installed to GOG's newest build, then runs its setup again.func gogUpdate(_ item: LibraryItem) {guard let bottleName = item.bottleName, let bottle = bottles.first(where: { $0.name == bottleName }),@@ -3832,7 +4019,7 @@ final class AppState {let cometLog = paths.logs.appending(path: "\(ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: ""))-comet-\(game.id).log")if useComet {stage = L("Starting comet for achievements")- comet = await gogStartComet(for: game, in: bottle, engine: engine, log: cometLog)+ comet = await gogStartComet(for: game, in: (bottle, engine), log: cometLog)if let comet { watchAchievements(of: game, item: item, bottleName: bottle.name, comet: comet, log: cometLog) }}if Task.isCancelled {@@ -3912,18 +4099,21 @@ final class AppState {}}- /// comet up and listening, or nil: never an error. The placeholder service it needs is set up- /// once per environment.- private func gogStartComet(for game: GOGStore.InstalledGame, in bottle: Bottle, engine: InstalledEngine, log: URL) async -> Process? {+ /// comet up and listening, or nil: never an error. For a Windows build, the placeholder service+ /// it needs is set up once per environment; a Mac build (`environment` nil) needs none.+ private func gogStartComet(for game: GOGStore.InstalledGame, in environment: (bottle: Bottle, engine: InstalledEngine)?,+ log: URL) async -> Process? {let store = gogStorelet comet = GOGComet(store: store)do {let tools = try await store.ensureComet()- if try await GOGComet.installService(from: tools.service, runner: WineRunner(paths: paths, engine: engine, bottle: bottle)) {- appendLog("\(bottle.name): registered the GalaxyCommunication placeholder comet uses")+ if let environment,+ try await GOGComet.installService(from: tools.service, runner: WineRunner(paths: paths, engine: environment.engine, bottle: environment.bottle)) {+ appendLog("\(environment.bottle.name): registered the GalaxyCommunication placeholder comet uses")}- // Only GOG sessions leave an end action, so none means no game of ours uses a comet.- let noOtherGame = sessionEndActions.isEmpty+ // Only when no game of ours uses a comet: a Windows GOG session leaves an end action, a+ // Mac one its entry in macGameProcesses until it has ended, a hand-over included.+ let noOtherGame = sessionEndActions.isEmpty && macGameProcesses.isEmptylet process = try await Task.detached {if noOtherGame { comet.stopStrays() }return try comet.start(log: log)@@ -3977,9 +4167,12 @@ final class AppState {// The game's window, so the card lands on it: windowed, full screen or borderless.let session = runningSessions.first { $0.libraryID == item.id && $0.bottleName == bottleName }let prefix = bottles.first { $0.name == bottleName }?.url+ let macPID = macGameProcesses[item.id].flatMap { $0.isRunning ? $0.processIdentifier : nil }Task {var window: CGRect?- if let session, let prefix {+ if let macPID {+ window = await Task.detached { Self.largestWindow(of: [macPID]) }.value+ } else if let session, let prefix {window = await Task.detached { Self.largestWindow(of: SessionWatch.pids(ofPrefix: prefix, markers: session.markers)) }.value}AchievementToast.shared.show(achievement, gameWindow: window)@@ -4104,7 +4297,7 @@ final class AppState {guard let self else { return }for item in libraryItems where !item.installed && (item.source == .gog || item.source == .epic) {for mac in [false] + (offersMacVersion(item) && !item.installedOnMac ? [true] : []) where savedEstimate(for: item, mac: mac) == nil {- while busy || !runningSessions.isEmpty {+ while busy || !runningSessions.isEmpty || !macGameProcesses.isEmpty {try? await Task.sleep(for: .seconds(30))if Task.isCancelled { return }}@@ -4119,7 +4312,7 @@ final class AppState {struct InstalledSizes: Equatable {/// The Windows build's folder (or a program's); nil for Steam, whose own record the page shows.var game: Int64?- /// The Mac build's size: Steam for Mac's record.+ /// The Mac build's size: a GOG Mac build's app, Steam for Mac's record.var macGame: Int64?/// The saves Highball knows the place of: GOG's and Epic's cloud-save folders, Steam/// Cloud's own copy for Steam. nil when there is no such place or nothing in it yet.@@ -4139,9 +4332,10 @@ final class AppState {}.valuecase .gog:let windows = bottle.flatMap { gogInstalled(item, in: $0) }+ let mac = item.gogID.flatMap { gogMacInstalled[$0] }let saves = GOGSaves(store: gogStore)return await Task.detached {- var sizes = InstalledSizes(game: windows.flatMap { DiskUsage.bytes(at: $0.folder) })+ var sizes = InstalledSizes(game: windows.flatMap { DiskUsage.bytes(at: $0.folder) }, macGame: mac.flatMap { DiskUsage.bytes(at: $0.folder) })if let windows, let bottle, let client = saves.clientID(for: windows),let locations = (try? saves.locations(clientID: client)) ?? nil {sizes.saves = DiskUsage.bytes(at: locations.compactMap { GOGSaves.resolve($0.template, game: windows, driveC: bottle.driveC) })diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swiftindex dca0897..111489d 100644--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@ -410,6 +410,25 @@ struct GameDetailView: View {Text(gog ? L("GOG lists a Mac build of this game. It runs without Windows or Wine, though some older Mac versions no longer start on current macOS."): L("Epic lists a Mac build of this game. It runs without Windows or Wine, though some older Mac versions no longer start on current macOS.")).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ if gog, let game = item.gogID.flatMap({ state.gogMacInstalled[$0] }) {+ if let note = Self.archNote(game.arch) {+ Text(note).font(.callout).foregroundStyle(game.arch == .only32Bit ? HB.warn : .secondary)+ }+ HStack(spacing: 10) {+ Button(L("Show in Finder")) { NSWorkspace.shared.activateFileViewerSelecting([game.app ?? game.folder]) }+ Button(L("Move the Mac version to the Trash…")) { state.pendingGOGMacTrash = item }.disabled(state.busy)+ }+ .controlSize(.small).padding(.top, 2)+ } else if gog {+ // With the Windows build installed the play row offers that one; the Mac one is here.+ if item.installed {+ HStack(spacing: 8) {+ Button(L("Install the Mac version")) { state.installOnMac(item) }.controlSize(.small).disabled(state.busy)+ estimateText(macEstimate)+ }+ .padding(.top, 2)+ }+ }}Spacer(minLength: 0)}@@ -457,6 +476,10 @@ struct GameDetailView: View {lines.append(line(setup.windows, synced: L("The Windows version's saves sync with GOG's cloud before and after you play."),own: L("The game handles the Windows version's saves; some games sync them with GOG's cloud themselves while comet runs.")))}+ if item.installedOnMac {+ lines.append(line(setup.mac, synced: L("The Mac version's saves sync with GOG's cloud before and after you play."),+ own: L("The game handles the Mac version's saves; some games sync them with GOG's cloud themselves while comet runs.")))+ }return lines}@@ -491,7 +514,7 @@ struct GameDetailView: View {.font(.callout).foregroundStyle(.secondary)Text(L("The game's own sync: some games send their saves to GOG's cloud themselves, through GOG's game kit. With Highball that works while comet runs beside the game, and the game says so when it syncs, as Cyberpunk 2077 does.")).font(.callout).foregroundStyle(.secondary)- let folders = (cloudSetup.map { item.installed ? $0.windows : [] } ?? []).map(\.template)+ let folders = (cloudSetup.map { (item.installed ? $0.windows : []) + (item.installedOnMac ? $0.mac : []) } ?? []).map(\.template)if !folders.isEmpty {Text(L("Folders this game syncs")).font(.caption.weight(.semibold)).padding(.top, 2)ForEach(folders, id: \.self) { Text(verbatim: $0).font(.caption.monospaced()).textSelection(.enabled) }@@ -541,6 +564,16 @@ struct GameDetailView: View {}}+ /// What an installed Mac build's executable says about running here (MacBinaryArch).+ static func archNote(_ arch: MacBinaryArch) -> String? {+ switch arch {+ case .native: L("Built for Apple silicon: runs natively.")+ case .intelOnly: L("Built for Intel Macs: runs through Rosetta.")+ case .only32Bit: L("A 32-bit build, which current macOS can't run. Play the Windows version instead.")+ case .unknown: nil+ }+ }+/// Only when the Windows build is the installed one: otherwise the play row already offers/// the Mac build (Play on Mac, Install on Mac).@ViewBuilder private var macButton: some View {@@ -574,7 +607,8 @@ struct GameDetailView: View {Button(L("Play the Windows version")) { commitTypedArguments(); state.play(item, windowsBuild: true) }.controlSize(.large).disabled(state.busy || blocked)} else {- Text(L("Starts through Steam for Mac.")).font(.callout).foregroundStyle(.secondary)+ Text(item.source == .steam ? L("Starts through Steam for Mac.") : L("Opens the Mac version, without Wine."))+ .font(.callout).foregroundStyle(.secondary)}} else if item.installed {Button { commitTypedArguments(); state.play(item) } label: {@@ -591,6 +625,22 @@ struct GameDetailView: View {: L("Its anti-cheat does not run on macOS.")).font(.callout).foregroundStyle(.secondary)}+ } else if item.source == .gog, item.macListed, !item.installedOnMac {+ // A Mac version is listed: that's the install on offer, the Windows one a click away.+ VStack(alignment: .leading, spacing: 6) {+ VStack(alignment: .leading, spacing: 10) {+ Button { state.installOnMac(item) } label: { primaryActionLabel(L("Install the Mac version"), symbol: "apple.logo") }+ .buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber).disabled(state.busy)+ Text(String(format: L("Goes into %@, outside every environment."), "~/Applications/Highball Games"))+ .font(.callout).foregroundStyle(.secondary)+ estimateText(macEstimate)+ }+ HStack(spacing: 6) {+ Button(L("Install the Windows version instead")) { state.install(item) }+ .buttonStyle(.link).font(.callout).disabled(state.busy)+ estimateText(windowsEstimate)+ }+ }} 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 af8ccb6..2515698 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -250,6 +250,7 @@ struct ContentView: View {.previewMoveAsk(state).macOSAsk(state).uninstallAsk(state)+ .macVersionAsks(state).rendererTrialAsk(state).modesetTrialAsk(state).homeMoveAsk(state)@@ -526,6 +527,24 @@ private extension View {Text(GamePageCopy.updateAsk(recipe: pending.recipe, engineID: pending.engineID, canPlay: pending.play != nil))}}+ /// 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.pendingGOGMacTrash.map { String(format: L("Move the Mac version of %@ to the Trash?"), $0.title) } ?? "",+ isPresented: .init(get: { state.pendingGOGMacTrash != nil }, set: { if !$0 { state.pendingGOGMacTrash = nil } }),+ presenting: state.pendingGOGMacTrash) { item in+ if state.gogMacTrashTarget(for: item) != nil {+ Button(L("Move to the Trash"), role: .destructive) { state.pendingGOGMacTrash = nil; state.gogTrashMac(item) }+ }+ Button(L("Cancel"), role: .cancel) { state.pendingGOGMacTrash = nil }+ } message: { item in+ if let target = state.gogMacTrashTarget(for: item) {+ Text(String(format: L("%@ goes to the Trash, where you can still put it back."), target.path))+ } else {+ Text(L("Highball could not tell which folder is this game's alone, so it leaves the files where they are."))+ }+ }+ }+@MainActor func uninstallAsk(_ state: AppState) -> some View {self.alert(state.pendingUninstall.map { String(format: L("Remove %@?"), $0.item.title) } ?? "",isPresented: .init(get: { state.pendingUninstall != nil }, set: { if !$0 { state.pendingUninstall = nil } }),diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex 9b4c75e..bcefc94 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -403,12 +403,16 @@ enum L10n {"GOG propose une version Mac de ce jeu. Elle se lance sans Windows ni Wine, mais certaines anciennes versions Mac ne démarrent plus sur les macOS récents.","Epic lists a Mac build of this game. It runs without Windows or Wine, though some older Mac versions no longer start on current macOS.":"Epic propose une version Mac de ce jeu. Elle se lance sans Windows ni Wine, mais certaines anciennes versions Mac ne démarrent plus sur les macOS récents.",+ "Mac version installed": "Version Mac installée","How this game's saves sync": "Comment se synchronisent les sauvegardes de ce jeu","Highball could not reach GOG to see how this game saves.": "Highball n’a pas pu joindre GOG pour voir comment ce jeu sauvegarde.","Kept on this Mac: Sync saves with GOG, under Game settings, syncs them.": "Gardées sur ce Mac : Synchroniser avec GOG, dans les réglages du jeu, les synchronise.","The Windows version's saves sync with GOG's cloud before and after you play.": "Les sauvegardes de la version Windows se synchronisent avec le cloud GOG avant et après chaque partie.","The game handles the Windows version's saves; some games sync them with GOG's cloud themselves while comet runs.":"Le jeu gère les sauvegardes de la version Windows ; certains jeux les synchronisent eux-mêmes avec le cloud GOG quand comet tourne.",+ "The Mac version's saves sync with GOG's cloud before and after you play.": "Les sauvegardes de la version Mac se synchronisent avec le cloud GOG avant et après chaque partie.",+ "The game handles the Mac version's saves; some games sync them with GOG's cloud themselves while comet runs.":+ "Le jeu gère les sauvegardes de la version Mac ; certains jeux les synchronisent eux-mêmes avec le cloud GOG quand comet tourne.","How saves sync with GOG": "Comment les sauvegardes se synchronisent avec GOG","GOG syncs saves in one of two ways, chosen per game and per version.": "GOG synchronise les sauvegardes de deux façons, selon le jeu et la version.","Folder sync: GOG names the folders a game saves in, and Highball copies them to and from GOG's cloud before and after you play, as GOG Galaxy does. When both copies changed, Highball asks which one to keep.":@@ -426,6 +430,11 @@ enum L10n {"How Epic's cloud saves work": "Comment fonctionnent les sauvegardes en ligne d’Epic","Epic's launcher syncs a game's saves with Epic's cloud when the game sets a cloud save folder. Highball plays Epic games through legendary, and their saves stay on this Mac.":"Le lanceur d’Epic synchronise les sauvegardes d’un jeu avec le cloud d’Epic quand le jeu définit un dossier de sauvegarde en ligne. Highball lance les jeux Epic par legendary, et leurs sauvegardes restent sur ce Mac.",+ "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é : %@",+ "Show the Windows version in Finder": "Afficher la version Windows dans le Finder",+ "Show the Mac version in Finder": "Afficher la version Mac dans le Finder",+ "Uninstall the Windows version…": "Désinstaller la version Windows…","Size (Windows)": "Taille (Windows)","Size (Mac)": "Taille (Mac)","Size": "Taille",@@ -439,6 +448,23 @@ enum L10n {"Saves": "Sauvegardes","Steam Cloud saves": "Sauvegardes Steam Cloud","Games with a native Mac version, which runs without Wine.": "Les jeux qui ont une version Mac native, qui tourne sans Wine.",+ "Installing the Mac version of %@": "Installation de la version Mac de %@",+ "The download finished, but Highball could not find the Mac version in it.":+ "Le téléchargement est terminé, mais Highball n’y trouve pas la version Mac.",+ "Opens the Mac version, without Wine.": "Ouvre la version Mac, sans Wine.",+ "Install the Mac version": "Installer la version Mac",+ "Goes into %@, outside every environment.": "Va dans %@, en dehors de tout environnement.",+ "Show in Finder": "Afficher dans le Finder",+ "Move the Mac version to the Trash…": "Mettre la version Mac à la corbeille…",+ "Move the Mac version of %@ to the Trash?": "Mettre la version Mac de %@ à la corbeille ?",+ "Move to the Trash": "Mettre à la corbeille",+ "%@ goes to the Trash, where you can still put it back.": "%@ va à la corbeille, d’où vous pouvez encore le récupérer.",+ "Highball could not tell which folder is this game's alone, so it leaves the files where they are.":+ "Highball ne sait pas quel dossier appartient à ce seul jeu, donc il laisse les fichiers où ils sont.",+ "Built for Apple silicon: runs natively.": "Conçue pour Apple silicon : tourne en natif.",+ "Built for Intel Macs: runs through Rosetta.": "Conçue pour les Mac Intel : tourne via Rosetta.",+ "A 32-bit build, which current macOS can't run. Play the Windows version instead.":+ "Une version 32 bits, que les macOS récents ne lancent plus. Jouez plutôt à la version Windows.","Last played": "Dernière partie","Windows program": "Programme Windows","Choose cover image…": "Choisir une image de couverture…",diff --git a/Sources/HighballApp/LibraryView.swift b/Sources/HighballApp/LibraryView.swiftindex 8fecc22..b392f08 100644--- a/Sources/HighballApp/LibraryView.swift+++ b/Sources/HighballApp/LibraryView.swift@@ -306,7 +306,8 @@ struct LibraryTile: View {}.transition(.opacity)}- SourceBadge(source: item.source, mac: state.macSteamBuild(for: item), macListed: item.macListed)+ SourceBadge(source: item.source, mac: state.macSteamBuild(for: item), macListed: item.macListed,+ macInstalled: item.source == .gog && item.installedOnMac).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading).padding(6)if let appid = item.steamAppID, state.session(forAppID: appid) != nil {@@ -429,6 +430,17 @@ struct LibraryTile: View {} else {Button(L("Hide from library")) { state.setHidden(true, for: item) }}+ // Where the files are, without opening the game's page: one entry per installed build.+ if item.installed, let folder = state.programFolder(for: item) {+ Button(item.installedOnMac ? L("Show the Windows version in Finder") : L("Show in Finder")) {+ NSWorkspace.shared.activateFileViewerSelecting([folder])+ }+ }+ if let mac = state.macFolder(for: item) {+ Button(item.installed ? L("Show the Mac version in Finder") : L("Show in Finder")) {+ NSWorkspace.shared.activateFileViewerSelecting([mac])+ }+ }// A program someone added by hand leaves the library from its tile, not only from// the environment's programs list (highball-db#68). Steam and Epic entries follow// their stores' libraries, so they have no such button.@@ -440,13 +452,19 @@ struct LibraryTile: View {}// Removing the game itself, not just the entry: asked for on r/macgaming because// there was nowhere to do it (highball#185).+ if item.installed || (item.source == .gog && item.installedOnMac) { Divider() }if item.installed {- Divider()- Button(L("Uninstall…"), role: .destructive) { state.askUninstall(item) }+ Button(item.installedOnMac ? L("Uninstall the Windows version…") : L("Uninstall…"), role: .destructive) { state.askUninstall(item) }.disabled(state.uninstallWaitsFor(item) != nil)}+ // A GOG Mac build is an app in the Mac games folder: to the Trash, where it can be put back,+ // once the player has seen what goes.+ if item.source == .gog, item.installedOnMac {+ Button(L("Move the Mac version to the Trash…"), role: .destructive) { state.pendingGOGMacTrash = item }+ .disabled(state.busy)+ }}- .accessibilityLabel("\(item.title), \(item.source.rawValue)\(item.installedOnMac ? ", " + L("Installed in Steam for Mac") : item.installed ? "" : ", " + L("Not installed"))")+ .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"))")}private var verdict: (String, Color)? { verdictLabel(entry?.status) }@@ -471,13 +489,15 @@ struct SourceBadge: View {var mac: MacSteamBuild? = nil/// GOG's or Epic's catalog lists a Mac version (LibraryItem.macListed): the logo, unlit.var macListed = false+ /// That Mac version is installed (a GOG Mac build): the badge lit, as for Steam for Mac.+ var macInstalled = falseprivate var label: String {switch source { case .steam: "STEAM"; case .epic: "EPIC"; case .gog: "GOG"; case .pin: "EXE"; case .battlenet: "BATTLE.NET" }}- private var lit: Bool { mac == .installed }+ private var lit: Bool { mac == .installed || macInstalled }var body: some View {HStack(spacing: 3) {- if mac != nil || macListed { Image(systemName: "apple.logo").font(.system(size: 8, weight: .semibold)) }+ if mac != nil || macListed || macInstalled { Image(systemName: "apple.logo").font(.system(size: 8, weight: .semibold)) }Text(label)}.font(.system(size: 8.5, weight: lit ? .bold : .medium).monospaced())@@ -486,7 +506,7 @@ struct SourceBadge: View {.background(RoundedRectangle(cornerRadius: 4).fill(lit ? .white.opacity(0.92) : .black.opacity(0.55))).overlay(RoundedRectangle(cornerRadius: 4).stroke(.white.opacity(lit ? 0 : 0.18), lineWidth: 0.5)).foregroundStyle(lit ? .black : .white.opacity(0.92))- .help(lit ? L("Installed in Steam for Mac") : mac != nil ? L("Native Mac build on Steam")+ .help(macInstalled ? L("Mac version installed") : lit ? L("Installed in Steam for Mac") : mac != nil ? L("Native Mac build on Steam"): macListed ? (source == .gog ? L("GOG lists a Mac version") : L("Epic lists a Mac version")) : "")}}diff --git a/Sources/HighballKit/GOGLibrary.swift b/Sources/HighballKit/GOGLibrary.swiftindex 04de038..e527915 100644--- a/Sources/HighballKit/GOGLibrary.swift+++ b/Sources/HighballKit/GOGLibrary.swift@@ -296,7 +296,7 @@ extension GOGStore {public let dependencies: [String]}- /// `platform` is gogdl's: "windows", or "osx" for a Mac build.+ /// `platform` is gogdl's: "windows", or "osx" for a Mac build (GOGMac).public func info(_ id: String, platform: String = "windows") throws -> DownloadInfo {let out = try capture(["info", id, "--os", platform])guard let start = out.firstIndex(of: "{"),@@ -336,8 +336,9 @@ extension GOGStore {/// gogdl appends the game's own folder name to `--path` for a download, and takes the game's/// folder itself for an update. DLC comes along: what the account owns installs with the game.- static func downloadArguments(id: String, into base: String, support: String, language: String, update: Bool) -> [String] {- [update ? "update" : "download", id, "--platform", "windows", "--path", base,+ static func downloadArguments(id: String, into base: String, support: String, language: String, update: Bool,+ platform: String = "windows") -> [String] {+ [update ? "update" : "download", id, "--platform", platform, "--path", base,"--support", support, "--with-dlcs", "--lang", language]}diff --git a/Sources/HighballKit/GOGMac.swift b/Sources/HighballKit/GOGMac.swiftnew file mode 100644index 0000000..97ce8d9--- /dev/null+++ b/Sources/HighballKit/GOGMac.swift@@ -0,0 +1,218 @@+import Foundation++/// The processors a Mac program is built for, read from its Mach-O header: whether a Mac build+/// runs here natively, through Rosetta, or not at all (32-bit, which macOS stopped running with+/// Catalina). A store's "has a Mac version" says none of this; the downloaded file does.+public enum MacBinaryArch: Equatable, Sendable {+ /// Apple silicon, alone or in a universal build.+ case native+ /// Intel only: runs on Apple silicon through Rosetta.+ case intelOnly+ /// 32-bit only: does not run on current macOS.+ case only32Bit+ case unknown++ /// An app's, from its bundle's executable; a folder is searched for the app inside it.+ public static func ofApp(at url: URL) -> MacBinaryArch {+ let app = url.pathExtension == "app" ? url+ : ((try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil)) ?? []).first { $0.pathExtension == "app" }+ guard let app, let exe = Bundle(url: app)?.executableURL else { return .unknown }+ return read(exe)+ }++ public static func read(_ executable: URL) -> MacBinaryArch {+ guard let handle = try? FileHandle(forReadingFrom: executable) else { return .unknown }+ defer { try? handle.close() }+ guard let head = try? handle.read(upToCount: 4096), head.count >= 8 else { return .unknown }+ func be32(_ offset: Int) -> UInt32 { head[offset..<offset + 4].reduce(0) { $0 << 8 | UInt32($1) } }+ func le32(_ offset: Int) -> UInt32 { head[offset..<offset + 4].reversed().reduce(0) { $0 << 8 | UInt32($1) } }+ let arm64: UInt32 = 0x0100_000C, x86_64: UInt32 = 0x0100_0007+ var cpus: [UInt32] = []+ switch be32(0) {+ case 0xCAFE_BABE, 0xCAFE_BABF: // universal: big-endian list of slices+ let count = Int(be32(4)), stride = be32(0) == 0xCAFE_BABE ? 20 : 32+ for i in 0..<min(count, 16) where 8 + i * stride + 4 <= head.count { cpus.append(be32(8 + i * stride)) }+ default:+ switch le32(0) {+ case 0xFEED_FACF: cpus = [le32(4)] // 64-bit+ case 0xFEED_FACE: return .only32Bit // 32-bit+ default: return .unknown+ }+ }+ if cpus.contains(arm64) { return .native }+ if cpus.contains(x86_64) { return .intelOnly }+ return cpus.isEmpty ? .unknown : .only32Bit+ }+}++extension GOGStore {+ /// A game's Mac build, installed by gogdl outside every environment: no Wine, no bottle.+ public struct MacInstalledGame: Sendable, Equatable {+ public let id: String+ public let title: String+ /// The game's own place on disk, what the Trash takes: its app when goggame-<id>.info+ /// sits inside one, else the folder holding the info (Galaxy's layout). Never the searched+ /// folder around an app, which can hold other apps.+ public let folder: URL+ /// The app to open; nil when the folder holds none Highball can find.+ public let app: URL?+ public let buildID: String?+ /// What the app's executable is built for, read once when the install is found.+ public let arch: MacBinaryArch+ /// The info file's client id, which cloud saves and comet's achievements are keyed by.+ public var clientID: String? = nil+ /// The info file's play tasks, what Galaxy's Play button runs.+ public var tasks: [PlayTask] = []++ /// The same game as the installed-game record the Windows paths take, so the save sync,+ /// comet's achievement lookup and the rest run unchanged. Its folder keeps the Mac build's+ /// sync history apart from a Windows copy's.+ public var asInstalledGame: InstalledGame {+ InstalledGame(id: id, title: title, folder: folder, buildID: buildID, clientID: clientID, dlcIDs: [], tasks: tasks)+ }++ }++ /// Where Mac builds go: an Applications folder Spotlight and Launchpad already look in, the+ /// player's own so nothing asks for an administrator.+ public static var macGamesDir: URL {+ FileManager.default.homeDirectoryForCurrentUser.appending(path: "Applications/Highball Games", directoryHint: .isDirectory)+ }++ /// Downloads a game's Mac build into the Mac games folder.+ @discardableResult+ public func installMac(_ id: String, language: String, control: LegendaryControl? = nil,+ onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ let base = Self.macGamesDir+ try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)+ // As for a Windows install: a manifest after this download is this download's. The+ // Windows install keeps its own copy beside its files (keepManifest), which updates use.+ try? FileManager.default.removeItem(at: manifest(id))+ return try runStreaming(Self.downloadArguments(id: id, into: base.path, support: supportDir(id).path, language: language,+ update: false, platform: "osx"),+ control: control, onLine: onLine)+ }++ /// Where GOG Mac builds are looked for: Highball's own folder first, then the Applications+ /// folders GOG Galaxy for Mac and GOG's Mac installers put games in (Cyberpunk 2077 in+ /// /Applications/Cyberpunk 2077).+ public static var macSearchFolders: [URL] {+ [macGamesDir, URL(fileURLWithPath: "/Applications", isDirectory: true),+ FileManager.default.homeDirectoryForCurrentUser.appending(path: "Applications", directoryHint: .isDirectory)]+ }++ /// Every GOG Mac build in those folders, one per game (the first folder's when two hold it):+ /// an app gogdl put there itself (Samorost 1's Mac build is `Samorost 1.app`, its+ /// goggame-<id>.info in Contents/Resources), or a folder holding the info at its top, in its+ /// own Contents/Resources beside the app (Galaxy's layout), or inside its app. A download in+ /// progress is skipped. Only folder listings: no app is opened to find out.+ public static func macInstalledGames(in bases: [URL] = macSearchFolders) -> [MacInstalledGame] {+ let fm = FileManager.default+ var seen = Set<String>()+ // A searched folder inside another (Highball Games inside ~/Applications) is never a game:+ // read as one, its Trash button would take every game in it.+ let searched = Set(bases.map { $0.standardizedFileURL.path })+ return bases.flatMap { base -> [MacInstalledGame] in+ let folders = (try? fm.contentsOfDirectory(at: base, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles])) ?? []+ return folders.compactMap { folder in+ guard !searched.contains(folder.standardizedFileURL.path),+ (try? folder.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true,+ !fm.fileExists(atPath: folder.appending(path: ".gogdl-resume").path) else { return nil }+ return macInstalledGame(in: folder)+ }+ }+ .filter { seen.insert($0.id).inserted }+ }++ public static func macInstalledGames(in base: URL) -> [MacInstalledGame] { macInstalledGames(in: [base]) }++ static func macInstalledGame(in folder: URL) -> MacInstalledGame? {+ let fm = FileManager.default+ let top = (try? fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []+ let apps = folder.pathExtension == "app" ? [folder]+ : top.filter { $0.pathExtension == "app" }.sorted { $0.lastPathComponent < $1.lastPathComponent }+ let places = (folder.pathExtension == "app" ? [] : [folder, folder.appending(path: "Contents/Resources")])+ + apps.map { $0.appending(path: "Contents/Resources") }+ let infos: [(InfoFile, URL?)] = places.flatMap { place -> [(InfoFile, URL?)] in+ let files = ((try? fm.contentsOfDirectory(at: place, includingPropertiesForKeys: nil)) ?? [])+ .filter { $0.lastPathComponent.hasPrefix("goggame-") && $0.pathExtension == "info" }+ let inApp = place.deletingLastPathComponent().deletingLastPathComponent()+ let app = inApp.pathExtension == "app" ? inApp : nil+ return files.compactMap { file in (try? JSONDecoder().decode(InfoFile.self, from: Data(contentsOf: file))).map { ($0, app) } }+ }+ guard let (base, home) = infos.first(where: { $0.0.rootGameId == nil || $0.0.rootGameId == $0.0.gameId }) else { return nil }+ // The info inside an app makes that app the game's folder, as the folder holding it in+ // its own Contents/Resources is in Galaxy's layout: the searched folder around it may hold+ // other apps (/Applications/Games), and the Trash, sizes and save paths go by this one.+ let own = home ?? folder+ let tasks = base.playTasks ?? []+ // Beside several apps, the one the game's primary play task names (what Galaxy's Play+ // opens), not the first by name; none named, the first.+ let app = home ?? taskApp(tasks, in: own, among: apps) ?? apps.first+ let named = home.map { $0.deletingPathExtension().lastPathComponent } ?? folder.lastPathComponent+ return MacInstalledGame(id: base.gameId, title: base.name ?? named, folder: own,+ app: app, buildID: base.buildId, arch: app.map(MacBinaryArch.ofApp(at:)) ?? .unknown,+ clientID: base.clientId, tasks: tasks)+ }++ /// The app among `apps` that the primary play task (else the first file task) points at or+ /// into, its path read from `folder` as gogdl and Galaxy read it.+ static func taskApp(_ tasks: [PlayTask], in folder: URL, among apps: [URL]) -> URL? {+ guard let path = (tasks.first { $0.isPrimary == true && $0.isFile } ?? tasks.first { $0.isFile })?.path else { return nil }+ let target = resolve(path, in: folder).standardizedFileURL.path+ return apps.first { app in+ let root = app.standardizedFileURL.path+ return target == root || target.hasPrefix(root + "/")+ }+ }+}++/// A Mac game's processes, seen from outside: what tells it is still running once the process+/// Highball started has quit. A launcher that hands over to the game exits at once, so its exit+/// alone is not the game's end.+public enum MacGameWatch {+ /// Whether an executable runs from inside a game's app or folder, by the kernel's path of it.+ /// Pure, so it is tested without processes.+ public static func runs(executable: String, from folder: String) -> Bool {+ let root = folder.hasSuffix("/") ? folder : folder + "/"+ return executable.hasPrefix(root)+ }++ /// The processes running an executable from inside the folder, never Highball itself.+ public static func processes(runningFrom folder: URL) -> [pid_t] {+ let root = ProcessTable.canonical(folder.path)+ let own = getpid()+ return ProcessTable.allPIDs().filter { pid in+ pid != own && executablePath(of: pid).map { runs(executable: $0, from: root) } == true+ }+ }++ /// The executable a process runs, or nil when it cannot be read (not ours, gone).+ static func executablePath(of pid: pid_t) -> String? {+ var buffer = [UInt8](repeating: 0, count: Int(MAXPATHLEN) * 4)+ let length = proc_pidpath(pid, &buffer, UInt32(buffer.count))+ guard length > 0 else { return nil }+ return String(decoding: buffer.prefix(Int(length)), as: UTF8.self)+ }++ /// Once the process Highball started has quit: waits while anything else runs from the+ /// game's folder, and, when that process quit within `quickExit` seconds of starting (a+ /// launcher), up to `grace` seconds for its successor to appear, since one opened through+ /// Launch Services may show up after the launcher is gone. Whether another process ran.+ @discardableResult+ public static func waitForHandover(from folder: URL, ranFor: TimeInterval, quickExit: TimeInterval = 30,+ grace: TimeInterval = 10, interval: TimeInterval = 2,+ running: (URL) -> [pid_t] = MacGameWatch.processes(runningFrom:)) async -> Bool {+ var deadline = Date().addingTimeInterval(ranFor < quickExit ? grace : 0)+ var handedOver = false+ while true {+ if !running(folder).isEmpty {+ handedOver = true+ deadline = Date()+ } else if Date() >= deadline {+ return handedOver+ }+ try? await Task.sleep(for: .seconds(interval))+ }+ }+}diff --git a/Sources/HighballKit/GOGSaves.swift b/Sources/HighballKit/GOGSaves.swiftindex fc45c8d..873bb1c 100644--- a/Sources/HighballKit/GOGSaves.swift+++ b/Sources/HighballKit/GOGSaves.swift@@ -17,6 +17,12 @@ public struct GOGSaves: Sendable {public let name: String/// GOG's template, e.g. "<?SAVED_GAMES?>/Remedy/Control".public let template: String+ /// The system gogdl syncs it as: "windows" for GOG's Windows locations, "osx" for its Mac ones.+ public var os = "windows"++ public init(name: String, template: String, os: String = "windows") {+ self.name = name; self.template = template; self.os = os+ }}/// The client id cloud storage is keyed by: the info file's, else the manifest gogdl kept@@ -60,36 +66,95 @@ public struct GOGSaves: Sendable {return Self.parseLocations(data, clientID: clientID)}- static func parseLocations(_ data: Data, clientID: String) -> [Location]? {+ /// `platform` is GOG's: "Windows", or "MacOS" for the Mac build's own locations.+ static func parseLocations(_ data: Data, clientID: String, platform: String = "Windows") -> [Location]? {guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let windows = (obj["content"] as? [String: Any])?["Windows"] as? [String: Any],- let cloud = windows["cloudStorage"] as? [String: Any], cloud["enabled"] as? Bool == true else { return nil }+ let config = (obj["content"] as? [String: Any])?[platform] as? [String: Any],+ let cloud = config["cloudStorage"] as? [String: Any], cloud["enabled"] as? Bool == true else { return nil }+ let os = platform == "MacOS" ? "osx" : "windows"let list = (cloud["locations"] as? [[String: Any]] ?? []).compactMap { l -> Location? inguard let name = l["name"] as? String, let location = l["location"] as? String else { return nil }- return Location(name: name, template: location)+ return Location(name: name, template: location, os: os)}- return list.isEmpty- ? [Location(name: "__default", template: "<?APPLICATION_DATA_LOCAL?>/GOG.com/Galaxy/Applications/\(clientID)/Storage/Shared/Files")]- : list+ guard list.isEmpty else { return list }+ return platform == "MacOS"+ ? [Location(name: "__default", template: "<?APPLICATION_SUPPORT?>/GOG.com/Galaxy/Applications/\(clientID)/Storage/Shared/Files", os: os)]+ : [Location(name: "__default", template: "<?APPLICATION_DATA_LOCAL?>/GOG.com/Galaxy/Applications/\(clientID)/Storage/Shared/Files")]}// MARK: How a game saves- /// How GOG syncs a game's saves: the folders GOG's file sync copies, empty when it copies- /// none. Such a game saves through the game itself, which may sync its own saves with GOG's- /// cloud through GOG's SDK, unseen here.+ /// How GOG syncs a game's saves, per version: the folders GOG's file sync copies, empty for a+ /// version it copies none of. Such a version saves through the game itself, which may sync+ /// its own saves with GOG's cloud through GOG's SDK (Cyberpunk 2077 on Mac), unseen here.public struct CloudSetup: Sendable, Equatable {public let windows: [Location]+ public let mac: [Location]}- /// The setup, from the remote config GOG publishes per client id.+ /// Both versions' setups, from the one remote config GOG publishes per client id.public func cloudSetup(clientID: String) throws -> CloudSetup {let url = URL(string: "https://remote-config.gog.com/components/galaxy_client/clients/\(clientID)?component_version=2.0.45")!return Self.parseCloudSetup(try GOGStore.fetch(URLRequest(url: url)), clientID: clientID)}static func parseCloudSetup(_ data: Data, clientID: String) -> CloudSetup {- CloudSetup(windows: parseLocations(data, clientID: clientID) ?? [])+ CloudSetup(windows: parseLocations(data, clientID: clientID) ?? [],+ mac: parseLocations(data, clientID: clientID, platform: "MacOS") ?? [])+ }++ // MARK: The Mac build's saves++ /// Where a Mac build's saves sync: GOG's Mac locations, nil when GOG syncs none for the Mac+ /// build. A game that syncs its own saves through GOG's SDK (Cyberpunk 2077 on Mac, through+ /// comet) needs none from Highball, and a file sync beside it would fight it.+ public func macLocations(clientID: String) throws -> [Location]? {+ let url = URL(string: "https://remote-config.gog.com/components/galaxy_client/clients/\(clientID)?component_version=2.0.45")!+ return Self.parseLocations(try GOGStore.fetch(URLRequest(url: url)), clientID: clientID, platform: "MacOS")+ }++ /// A Mac location as a folder, from GOG's Mac variables.+ /// Never a whole known folder (gogdl deletes local files the cloud lacks): not the variable's+ /// own folder, and not one a variable reaches into either (`<?LIBRARY?>/Preferences` is all+ /// of ~/Library/Preferences), see `isSharedFolder`.+ public static func resolveMac(_ template: String, installFolder: URL,+ home: URL = FileManager.default.homeDirectoryForCurrentUser) -> URL? {+ let values: [String: URL] = [+ "INSTALL": installFolder,+ "DOCUMENTS": home.appending(path: "Documents"),+ "APPLICATION_SUPPORT": home.appending(path: "Library/Application Support"),+ "LIBRARY": home.appending(path: "Library"),+ "PREFERENCES": home.appending(path: "Library/Preferences"),+ "CACHES": home.appending(path: "Library/Caches"),+ ]+ var path = template.replacingOccurrences(of: "\\", with: "/")+ guard let open = path.range(of: "<?"), let close = path.range(of: "?>", range: open.upperBound..<path.endIndex),+ open.lowerBound == path.startIndex, let base = values[String(path[open.upperBound..<close.lowerBound])] else { return nil }+ path.removeSubrange(path.startIndex..<close.upperBound)+ guard !path.contains("%"), !path.contains("<?") else { return nil }+ let parts = path.split(separator: "/").map(String.init)+ guard !parts.isEmpty, !parts.contains(where: { $0 == "." || $0 == ".." }) else { return nil }+ let folder = parts.reduce(base) { $0.appending(path: $1) }+ return isSharedFolder(folder, home: home) ? nil : folder+ }++ /// A folder of the home that holds more than one game's files, which a save sync must never+ /// be given whole: the home itself, every folder straight inside it (Documents, Library,+ /// Desktop and the rest), every folder straight inside its Library (Preferences, Application+ /// Support, Caches, Containers, Group Containers, Saved Application State and the rest), and+ /// the top of a synced drive or a container there (iCloud Drive's com~apple~CloudDocs, a+ /// CloudStorage provider's folder, an app's container). A game's own folder sits deeper, as+ /// in ~/Library/Application Support/<studio>/<game>. Compared without case, as the Mac's+ /// disks are.+ static func isSharedFolder(_ folder: URL, home: URL) -> Bool {+ let homeParts = home.standardizedFileURL.pathComponents.map { $0.lowercased() }+ let parts = folder.standardizedFileURL.pathComponents.map { $0.lowercased() }+ guard parts.count >= homeParts.count, Array(parts.prefix(homeParts.count)) == homeParts else { return false }+ let inside = Array(parts.dropFirst(homeParts.count))+ if inside.count <= 1 { return true }+ guard inside[0] == "library" else { return false }+ if inside.count == 2 { return true }+ return inside.count == 3 && ["mobile documents", "cloudstorage", "containers", "group containers"].contains(inside[1])}/// A location as a folder on the Mac, inside the environment. GOG's variables are the Windows@@ -165,7 +230,7 @@ public struct GOGSaves: Sendable {case .forceDownload: flag = "--force-download"case .forceUpload: flag = "--force-upload"}- return ["save-sync", folder.path, id, "--os", "windows", "--ts", timestamp, "--name", location.name, flag]+ return ["save-sync", folder.path, id, "--os", location.os, "--ts", timestamp, "--name", location.name, flag]}/// gogdl's only stdout is the new timestamp, a bare number written without a newline, so ondiff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swiftindex 307c2fc..a36d45c 100644--- a/Sources/HighballKit/Library.swift+++ b/Sources/HighballKit/Library.swift@@ -22,7 +22,8 @@ public struct LibraryItem: Identifiable, Sendable, Hashable {/// Where it lives. nil only for an Epic or GOG title owned but not installed in any bottle.public let bottleName: String?public let installed: Bool- /// Steam for Mac has its native build installed (MacSteam); Play goes there first.+ /// The native build is installed: Steam for Mac's (MacSteam), or for GOG the Mac build gogdl+ /// put in the Mac games folder (GOGStore.macInstalledGames). Play goes there first.public let installedOnMac: Boolpublic let steamAppID: Int?public let epicAppName: String?@@ -260,6 +261,7 @@ public enum LibraryIndex {gogGames: [GOGStore.Game] = [],gogInstalledByBottle: [String: [GOGStore.InstalledGame]] = [:],gogLaunchChoice: [String: Int] = [:],+ gogMacInstalled: Set<String> = [],battleNetByBottle: [String: [BattleNetGame]] = [:],plays: [String: LibraryStore.PlayRecord] = [:],defaultBottle: String? = nil,@@ -369,7 +371,7 @@ public enum LibraryIndex {let meta = gogKnown[id]items.append(LibraryItem(source: .gog, id: itemID, title: meta?.title ?? primary?.game.title ?? id, bottleName: primary?.bottle,- installed: primary != nil, gogID: id, gogSteamAppID: meta?.steamAppID,+ installed: primary != nil, installedOnMac: gogMacInstalled.contains(id), gogID: id, gogSteamAppID: meta?.steamAppID,artworkTall: meta?.artworkTall, artworkWide: meta?.artworkWide,otherBottles: copies.map(\.bottle).filter { $0 != primary?.bottle }.sorted(),lastPlayed: ([itemID] + standing.filter { $0.gogItemID == itemID }.map(\.pinItemID)).compactMap { plays[$0]?.lastPlayedAt }.max(),diff --git a/Tests/HighballKitTests/StoreMacVersionTests.swift b/Tests/HighballKitTests/StoreMacVersionTests.swiftindex abd0243..a5480c4 100644--- a/Tests/HighballKitTests/StoreMacVersionTests.swift+++ b/Tests/HighballKitTests/StoreMacVersionTests.swift@@ -48,3 +48,276 @@ final class StoreMacVersionTests: XCTestCase {}}+/// Installing and finding a GOG game's Mac build (GOGMac).+final class GOGMacBuildTests: XCTestCase {+ private func header(_ bytes: [UInt8]) throws -> URL {+ let file = FileManager.default.temporaryDirectory.appending(path: "macho-\(UUID().uuidString)")+ try Data(bytes + [UInt8](repeating: 0, count: 64)).write(to: file)+ addTeardownBlock { try? FileManager.default.removeItem(at: file) }+ return file+ }++ func testArchitectureIsReadFromTheExecutable() throws {+ // Thin 64-bit (little-endian magic, then cputype).+ XCTAssertEqual(MacBinaryArch.read(try header([0xCF, 0xFA, 0xED, 0xFE, 0x0C, 0x00, 0x00, 0x01])), .native)+ XCTAssertEqual(MacBinaryArch.read(try header([0xCF, 0xFA, 0xED, 0xFE, 0x07, 0x00, 0x00, 0x01])), .intelOnly)+ // Thin 32-bit.+ XCTAssertEqual(MacBinaryArch.read(try header([0xCE, 0xFA, 0xED, 0xFE, 0x07, 0x00, 0x00, 0x00])), .only32Bit)+ // Universal: x86_64 and arm64 slices (big-endian, 20 bytes each).+ let fat: [UInt8] = [0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 2,+ 0x01, 0, 0, 0x07] + [UInt8](repeating: 0, count: 16) ++ [0x01, 0, 0, 0x0C] + [UInt8](repeating: 0, count: 16)+ XCTAssertEqual(MacBinaryArch.read(try header(fat)), .native)+ // Universal with i386 and x86_64 (an old Intel build): Rosetta.+ let oldFat: [UInt8] = [0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 2,+ 0, 0, 0, 0x07] + [UInt8](repeating: 0, count: 16) ++ [0x01, 0, 0, 0x07] + [UInt8](repeating: 0, count: 16)+ XCTAssertEqual(MacBinaryArch.read(try header(oldFat)), .intelOnly)+ XCTAssertEqual(MacBinaryArch.read(try header([0x7F, 0x45, 0x4C, 0x46, 0, 0, 0, 0])), .unknown)+ }++ /// Mac builds keep goggame-<id>.info inside their app; DLC info beside it is not the game.+ func testMacInstallIsFoundByTheInfoInsideItsApp() throws {+ let base = FileManager.default.temporaryDirectory.appending(path: "macgames-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: base) }+ let resources = base.appending(path: "Samorost 1/Samorost 1.app/Contents/Resources")+ try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)+ try #"{"gameId":"2006298293","rootGameId":"2006298293","name":"Samorost 1","buildId":"55"}"#+ .write(to: resources.appending(path: "goggame-2006298293.info"), atomically: true, encoding: .utf8)+ try #"{"gameId":"99","rootGameId":"2006298293","name":"Soundtrack"}"#+ .write(to: resources.appending(path: "goggame-99.info"), atomically: true, encoding: .utf8)+ // Still downloading: skipped.+ let partial = base.appending(path: "Partial")+ try FileManager.default.createDirectory(at: partial, withIntermediateDirectories: true)+ try Data().write(to: partial.appending(path: ".gogdl-resume"))++ let games = GOGStore.macInstalledGames(in: base)+ XCTAssertEqual(games.map(\.id), ["2006298293"])+ XCTAssertEqual(games.first?.app?.lastPathComponent, "Samorost 1.app")+ XCTAssertEqual(games.first?.folder.lastPathComponent, "Samorost 1.app", "the info sits in the app, so the app is the game's folder")+ XCTAssertEqual(games.first?.buildID, "55")+ }++ /// An app among others in a folder of /Applications (/Applications/Games/Foo.app): the game,+ /// and so its Trash, is that app alone, never the folder with the other apps in it.+ func testAppInAFolderOfOtherAppsIsTheGamesFolderAlone() throws {+ let applications = FileManager.default.temporaryDirectory.appending(path: "apps-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: applications) }+ let games = applications.appending(path: "Games")+ let resources = games.appending(path: "Foo.app/Contents/Resources")+ try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: games.appending(path: "Another Game.app/Contents/MacOS"), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: games.appending(path: "Zed.app/Contents/MacOS"), withIntermediateDirectories: true)+ try #"{"gameId":"1207658924","rootGameId":"1207658924"}"#+ .write(to: resources.appending(path: "goggame-1207658924.info"), atomically: true, encoding: .utf8)++ let game = try XCTUnwrap(GOGStore.macInstalledGames(in: applications).first)+ XCTAssertEqual(game.folder.lastPathComponent, "Foo.app")+ XCTAssertEqual(game.folder.deletingLastPathComponent().lastPathComponent, "Games")+ XCTAssertEqual(game.app?.lastPathComponent, "Foo.app")+ XCTAssertEqual(game.title, "Foo", "with no name in the info, the app's, not the folder's")+ }++ /// What gogdl actually made for Samorost 1: the app itself, straight in the Mac games folder.+ func testMacInstallThatIsTheAppItselfIsFound() throws {+ let base = FileManager.default.temporaryDirectory.appending(path: "macgames-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: base) }+ let resources = base.appending(path: "Samorost 1.app/Contents/Resources")+ try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)+ try #"{"gameId":"2006298293","rootGameId":"2006298293","name":"Samorost 1"}"#+ .write(to: resources.appending(path: "goggame-2006298293.info"), atomically: true, encoding: .utf8)+ let game = try XCTUnwrap(GOGStore.macInstalledGames(in: base).first)+ XCTAssertEqual(game.id, "2006298293")+ XCTAssertEqual(game.app?.lastPathComponent, "Samorost 1.app")+ XCTAssertEqual(game.folder.lastPathComponent, "Samorost 1.app")+ }++ /// GOG Galaxy for Mac's layout (Cyberpunk 2077): the info in the folder's own+ /// Contents/Resources, the app beside it; a game in two searched folders counts once.+ func testGalaxyInstallInApplicationsIsFound() throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "apps-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: root) }+ let applications = root.appending(path: "Applications"), own = root.appending(path: "Highball Games")+ let folder = applications.appending(path: "Cyberpunk 2077")+ try FileManager.default.createDirectory(at: folder.appending(path: "Contents/Resources"), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: folder.appending(path: "Cyberpunk2077.app/Contents/MacOS"), withIntermediateDirectories: true)+ try #"{"gameId":"1423049311","rootGameId":"1423049311","name":"Cyberpunk 2077"}"#+ .write(to: folder.appending(path: "Contents/Resources/goggame-1423049311.info"), atomically: true, encoding: .utf8)+ try #"{"gameId":"1256837418","rootGameId":"1423049311","name":"Phantom Liberty"}"#+ .write(to: folder.appending(path: "Contents/Resources/goggame-1256837418.info"), atomically: true, encoding: .utf8)+ try FileManager.default.createDirectory(at: own, withIntermediateDirectories: true)++ let games = GOGStore.macInstalledGames(in: [own, applications, applications])+ XCTAssertEqual(games.map(\.id), ["1423049311"])+ XCTAssertEqual(games.first?.app?.lastPathComponent, "Cyberpunk2077.app")+ XCTAssertEqual(games.first?.folder.lastPathComponent, "Cyberpunk 2077")+ }++ /// A folder with several apps beside its info opens the one the primary play task names, not+ /// the first by name, and the record the save sync and comet read keeps the info's client id+ /// and tasks.+ func testThePrimaryPlayTaskPicksTheAppAndTheRecordKeepsTheInfo() throws {+ let applications = FileManager.default.temporaryDirectory.appending(path: "apps-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: applications) }+ let folder = applications.appending(path: "Some Game")+ for app in ["A Config Tool.app", "Some Game.app"] {+ try FileManager.default.createDirectory(at: folder.appending(path: "\(app)/Contents/MacOS"), withIntermediateDirectories: true)+ }+ try FileManager.default.createDirectory(at: folder.appending(path: "Contents/Resources"), withIntermediateDirectories: true)+ try #"{"gameId":"7","rootGameId":"7","name":"Some Game","clientId":"5150","playTasks":[{"category":"tool","type":"FileTask","path":"A Config Tool.app"},{"category":"game","isPrimary":true,"type":"FileTask","path":"Some Game.app/Contents/MacOS/Some Game"}]}"#+ .write(to: folder.appending(path: "Contents/Resources/goggame-7.info"), atomically: true, encoding: .utf8)++ let game = try XCTUnwrap(GOGStore.macInstalledGames(in: applications).first)+ XCTAssertEqual(game.app?.lastPathComponent, "Some Game.app")+ XCTAssertEqual(game.folder.lastPathComponent, "Some Game")+ XCTAssertEqual(game.asInstalledGame.clientID, "5150")+ XCTAssertEqual(game.asInstalledGame.tasks.count, 2)+ XCTAssertNil(GOGStore.taskApp([], in: folder, among: [folder.appending(path: "Some Game.app")]), "no task, no choice")+ }++ /// gogdl's sizes: the shared files under "*" plus the installed language's (Samorost 1's Mac build).+ func testDownloadSizeAddsTheLanguagesFilesToTheSharedOnes() {+ let obj: [String: Any] = ["languages": ["en-US", "fr-FR"],+ "size": ["*": ["download_size": 44, "disk_size": 38],+ "en-US": ["download_size": 68067216, "disk_size": 95828300],+ "fr-FR": ["download_size": 1, "disk_size": 1]]]+ let info = GOGStore.parseInfo(obj, preferred: ["en-US"])+ XCTAssertEqual(info.downloadSize, 68067260)+ XCTAssertEqual(info.diskSize, 95828338)+ }++ func testMacDownloadAsksGogdlForTheMacBuild() {+ let args = GOGStore.downloadArguments(id: "7", into: "/x", support: "/s", language: "en-US", update: false, platform: "osx")+ XCTAssertEqual(args[0...3], ["download", "7", "--platform", "osx"])+ XCTAssertEqual(GOGStore.downloadArguments(id: "7", into: "/x", support: "/s", language: "en-US", update: false)[3], "windows")+ }+}++/// A GOG Mac build's saves: GOG's Mac locations, when GOG syncs them for the Mac build.+final class GOGMacSavesTests: XCTestCase {+ private func config(windows: String, mac: String) -> Data {+ Data(#"{"content":{"Windows":{"cloudStorage":\#(windows)},"MacOS":{"cloudStorage":\#(mac)}}}"#.utf8)+ }++ func testGOGsOwnMacLocationsSyncAsTheMacBuild() throws {+ let data = config(windows: #"{"enabled":true,"locations":[{"name":"saves","location":"<?SAVED_GAMES?>/X"}]}"#,+ mac: #"{"enabled":true,"locations":[{"name":"saves","location":"<?APPLICATION_SUPPORT?>/X/saves"}]}"#)+ let locations = try XCTUnwrap(GOGSaves.parseLocations(data, clientID: "c", platform: "MacOS"))+ XCTAssertEqual(locations, [GOGSaves.Location(name: "saves", template: "<?APPLICATION_SUPPORT?>/X/saves", os: "osx")])+ }++ /// Cyberpunk 2077 as GOG configures it: Windows syncs, the Mac build does not, as it syncs its+ /// own saves through GOG's SDK. Highball syncs no files for it.+ func testAMacBuildGOGSyncsNoneForHasNone() {+ let data = config(windows: #"{"enabled":true,"locations":[{"name":"saves","location":"<?SAVED_GAMES?>/CD Projekt Red/Cyberpunk 2077"}]}"#,+ mac: #"{"enabled":false,"locations":[]}"#)+ XCTAssertNil(GOGSaves.parseLocations(data, clientID: "c", platform: "MacOS"))+ }++ /// What the game page says comes from both versions' setups at once: Cyberpunk 2077 copies+ /// folders for Windows and saves through the game itself on Mac.+ func testCloudSetupReadsBothVersions() {+ let data = config(windows: #"{"enabled":true,"locations":[{"name":"saves","location":"<?SAVED_GAMES?>/CD Projekt Red/Cyberpunk 2077"}]}"#,+ mac: #"{"enabled":false,"locations":[]}"#)+ let setup = GOGSaves.parseCloudSetup(data, clientID: "c")+ XCTAssertEqual(setup.windows.map(\.name), ["saves"])+ XCTAssertEqual(setup.mac, [])+ }++ func testMacFoldersResolveUnderTheHomeAndNeverAWholeKnownFolder() {+ let home = URL(fileURLWithPath: "/Users/someone"), install = URL(fileURLWithPath: "/Applications/Game")+ XCTAssertEqual(GOGSaves.resolveMac("<?APPLICATION_SUPPORT?>/Studio/Game", installFolder: install, home: home)?.path,+ "/Users/someone/Library/Application Support/Studio/Game")+ XCTAssertEqual(GOGSaves.resolveMac("<?INSTALL?>/saves", installFolder: install, home: home)?.path, "/Applications/Game/saves")+ XCTAssertNil(GOGSaves.resolveMac("<?DOCUMENTS?>", installFolder: install, home: home))+ XCTAssertNil(GOGSaves.resolveMac("<?DOCUMENTS?>/../..", installFolder: install, home: home))+ XCTAssertNil(GOGSaves.resolveMac("<?SOMETHING_NEW?>/x", installFolder: install, home: home))+ // A variable reaching into a known folder names all of it, which gogdl would empty of+ // whatever the cloud lacks.+ for whole in ["<?LIBRARY?>/Preferences", "<?LIBRARY?>/Application Support", "<?LIBRARY?>/Caches",+ "<?LIBRARY?>/Containers", "<?LIBRARY?>/Group Containers", "<?LIBRARY?>/preferences/",+ "<?LIBRARY?>", "<?PREFERENCES?>", "<?APPLICATION_SUPPORT?>", "<?CACHES?>",+ "<?LIBRARY?>/Mobile Documents/com~apple~CloudDocs", "<?LIBRARY?>/CloudStorage/Dropbox",+ "<?LIBRARY?>/Containers/com.studio.game", "<?DOCUMENTS?>/../Desktop"] {+ XCTAssertNil(GOGSaves.resolveMac(whole, installFolder: install, home: home), whole)+ }+ XCTAssertEqual(GOGSaves.resolveMac("<?LIBRARY?>/Preferences/Studio Game", installFolder: install, home: home)?.path,+ "/Users/someone/Library/Preferences/Studio Game")+ XCTAssertEqual(GOGSaves.resolveMac("<?LIBRARY?>/Containers/com.studio.game/Data/Saves", installFolder: install, home: home)?.path,+ "/Users/someone/Library/Containers/com.studio.game/Data/Saves")+ XCTAssertEqual(GOGSaves.resolveMac("<?DOCUMENTS?>/Studio", installFolder: install, home: home)?.path, "/Users/someone/Documents/Studio")+ XCTAssertEqual(GOGSaves.resolveMac("<?INSTALL?>/saves", installFolder: home.appending(path: "Applications/Highball Games/Game.app"), home: home)?.path,+ "/Users/someone/Applications/Highball Games/Game.app/saves")+ }++ func testSyncNamesTheSystemOfTheLocation() {+ let mac = GOGSaves.Location(name: "saves", template: "t", os: "osx")+ let args = GOGSaves.arguments(folder: URL(fileURLWithPath: "/s"), id: "1", location: mac, timestamp: "0", direction: .download)+ XCTAssertEqual(args[3...4], ["--os", "osx"])+ }+}++final class MacBuildDetectionTests: XCTestCase {+ /// A 64-bit universal header (0xCAFEBABF): 32-byte slices.+ func testSixtyFourBitUniversalHeader() throws {+ let file = FileManager.default.temporaryDirectory.appending(path: "fat64-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: file) }+ let slice: (UInt8) -> [UInt8] = { cpu in [0x01, 0, 0, cpu] + [UInt8](repeating: 0, count: 28) }+ try Data([0xCA, 0xFE, 0xBA, 0xBF, 0, 0, 0, 2] + slice(0x07) + slice(0x0C) + [UInt8](repeating: 0, count: 64)).write(to: file)+ XCTAssertEqual(MacBinaryArch.read(file), .native)+ }++ /// Highball Games inside ~/Applications is searched on its own, never read as one game: its+ /// Trash button would take every game in it.+ func testASearchedFolderInsideAnotherIsNotAGame() throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "apps-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: root) }+ let applications = root.appending(path: "Applications"), own = applications.appending(path: "Highball Games")+ let resources = own.appending(path: "Samorost 1.app/Contents/Resources")+ try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)+ try #"{"gameId":"2006298293","rootGameId":"2006298293","name":"Samorost 1"}"#+ .write(to: resources.appending(path: "goggame-2006298293.info"), atomically: true, encoding: .utf8)+ try Data().write(to: own.appending(path: "Samorost 1.app/.gogdl-resume")) // its own pass skips it+ XCTAssertEqual(GOGStore.macInstalledGames(in: [own, applications]).map(\.folder.lastPathComponent), [])+ }+}++/// A Mac game ends once nothing runs from its folder, not when the process Highball started+/// quits: that one may be a launcher handing over to the game.+final class MacGameWatchTests: XCTestCase {+ func testAProcessRunsFromTheFolderOnlyInsideIt() {+ XCTAssertTrue(MacGameWatch.runs(executable: "/Applications/Games/Foo.app/Contents/MacOS/Foo", from: "/Applications/Games/Foo.app"))+ XCTAssertTrue(MacGameWatch.runs(executable: "/Applications/Games/Foo.app/Contents/MacOS/Foo", from: "/Applications/Games/Foo.app/"))+ XCTAssertFalse(MacGameWatch.runs(executable: "/Applications/Games/Foo.app2/Contents/MacOS/Foo", from: "/Applications/Games/Foo.app"))+ XCTAssertFalse(MacGameWatch.runs(executable: "/Applications/Games/Bar.app/Contents/MacOS/Bar", from: "/Applications/Games/Foo.app"))+ }++ func testALauncherThatHandsOverIsFollowedUntilTheGameQuits() async {+ var checks = 0+ let handedOver = await MacGameWatch.waitForHandover(from: URL(fileURLWithPath: "/g"), ranFor: 1, grace: 5, interval: 0.01) { _ in+ checks += 1+ return checks <= 3 ? [42] : []+ }+ XCTAssertTrue(handedOver)+ XCTAssertEqual(checks, 4, "ends at the first look that finds nothing, not after the grace")+ }++ func testAGameThatRanAWhileEndsWithItsProcess() async {+ var checks = 0+ let handedOver = await MacGameWatch.waitForHandover(from: URL(fileURLWithPath: "/g"), ranFor: 600, interval: 0.01) { _ in+ checks += 1+ return []+ }+ XCTAssertFalse(handedOver)+ XCTAssertEqual(checks, 1)+ }++ func testAQuickExitWaitsAMomentForItsSuccessor() async {+ var checks = 0+ let handedOver = await MacGameWatch.waitForHandover(from: URL(fileURLWithPath: "/g"), ranFor: 1, grace: 2, interval: 0.01) { _ in+ checks += 1+ return checks == 5 ? [42] : []+ }+ XCTAssertTrue(handedOver, "a successor that shows up after the launcher quit still counts")+ }+}