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 main into feat/gog-store
Gabea180b5158542
diff --cc Sources/HighballApp/AppState.swiftindex 236b90f,c3be65f..db5b971--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@@ -288,11 -279,10 +290,12 @@@ final class AppStatefunc rebuildLibrary() {customNames = nameStore.names()+ carryOverGOGCoveredPins()libraryItems = LibraryIndex.build(bottles: bottles, steamByBottle: gamesByBottle,- steamOwnedByBottle: steamOwnedByBottle, macInstalled: macSteamGames,+ steamOwnedByBottle: steamOwnedByBottle, macInstalled: includeMacSteam ? macSteamGames : [],epicOwned: epicOwned, epicInstalls: epicInstalls,+ gogGames: gogGames, gogInstalledByBottle: gogInstalledByBottle, gogLaunchChoice: gogSettings.launchChoice,+ battleNetByBottle: battleNetByBottle,plays: libraryPlays, defaultBottle: defaultBottle?.name,pinExists: { bottle, pin in// follows links, so a link to a file that is gone counts as missing@@@ -1988,13 -2052,8 +2093,13 @@@private func findProgramExecutable(for item: LibraryItem) -> URL? {guard let bottleName = item.bottleName, let bottle = bottles.first(where: { $0.name == bottleName }) else { return nil }switch item.source {- case .steam, .epic:+ case .steam, .epic, .battlenet:return programFolder(for: item).flatMap { PEIcon.bestExecutable(in: $0) }+ case .gog:+ // The file Play runs, so the per-program settings (display mode) apply to the game itself.+ guard let game = gogInstalled(item, in: bottle), let task = game.launchTask(choice: gogSettings.launchChoice[game.id]),+ let launch = GOGStore.launch(task, in: game) else { return nil }+ return launch.executablecase .pin:return item.pinID.flatMap { id in bottle.settings.pins.first { $0.id == id } }.map { $0.executableURL(driveC: bottle.driveC) }}@@@ -2013,10 -2072,10 +2118,12 @@@folder = game.installFolder ?? bottle.driveC.appending(path: "Program Files (x86)/Steam/steamapps/common/\(game.installdir)", directoryHint: .isDirectory)case .epic:folder = item.epicAppName.flatMap { epicInstalls[$0] }.map { URL(fileURLWithPath: $0, isDirectory: true) }+ case .gog:+ folder = gogInstalled(item, in: bottle)?.foldercase .pin:folder = item.pinID.flatMap { id in bottle.settings.pins.first { $0.id == id } }.map { $0.executableURL(driveC: bottle.driveC).deletingLastPathComponent() }+ case .battlenet:+ folder = battleNetGame(for: item, in: bottleName)?.folder}guard let folder else { return nil }var isDir: ObjCBool = falsediff --cc Sources/HighballApp/GameDetailView.swiftindex e155163,2aad297..f25ad0a--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@@ -133,66 -133,10 +133,67 @@@ struct GameDetailView: View}}+ /// A GOG game's own settings, one row each like the rest of the page: comet (achievements and+ /// stats), cloud saves, which launch task Play runs, and an update for a game gogdl installed.+ @ViewBuilder private func gogSettings(_ game: GOGStore.InstalledGame) -> some View {+ let cometOff = state.gogSettings.cometOff[game.id]+ HStack(alignment: .top, spacing: 12) {+ Text(L("Achievements")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 2)+ VStack(alignment: .leading, spacing: 4) {+ Toggle(L("Achievements and stats (comet)"), isOn: Binding(+ get: { cometOff == nil }, set: { state.gogSetComet($0, for: game.id) }))+ .toggleStyle(.checkbox).disabled(!state.gogSignedIn)+ Text(cometOff == GOGSettings.crashedWithComet+ ? L("Turned off after the game closed at once with comet running and then started fine without it. Turn it back on to try again.")+ : L("comet stands in for GOG Galaxy while the game runs, so achievements, stats and play time reach your GOG account. If the game won't start with it, Highball starts it again without."))+ .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }+ }+ HStack(alignment: .top, spacing: 12) {+ Text(L("Cloud saves")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 2)+ VStack(alignment: .leading, spacing: 4) {+ Toggle(L("Sync saves with GOG"), isOn: Binding(+ get: { !state.gogSettings.cloudSavesOff.contains(game.id) }, set: { state.gogSetCloudSaves($0, for: game.id) }))+ .toggleStyle(.checkbox).disabled(!state.gogSignedIn)+ Text(L("Saves come down from GOG's cloud before Play and go back up when the game ends. If both copies changed, Highball asks which one wins."))+ .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ if !state.gogSignedIn {+ Button(L("Connect GOG")) { state.showGOGSignIn = true }.controlSize(.small)+ }+ }+ }+ if !game.launchChoices.isEmpty {+ HStack(alignment: .top, spacing: 12) {+ Text(L("Launch option")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 4)+ Picker("", selection: Binding(+ get: { state.gogSettings.launchChoice[game.id] ?? -1 },+ set: { state.gogSetLaunchChoice($0 < 0 ? nil : $0, for: game.id) })) {+ Text(L("GOG's default")).tag(-1)+ ForEach(Array(game.launchChoices.enumerated()), id: \.offset) { index, task in+ Text(verbatim: task.name ?? task.path ?? "").tag(index)+ }+ }.labelsHidden().frame(maxWidth: 360)+ }+ }+ if state.gogStore.hasManifest(game) {+ HStack(alignment: .top, spacing: 12) {+ Text(L("Version")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 2)+ VStack(alignment: .leading, spacing: 4) {+ HStack(spacing: 8) {+ Text(verbatim: game.buildID.map { String(format: L("GOG build %@"), $0) } ?? "GOG").font(.callout)+ Button(L("Update from GOG")) { state.gogUpdate(item) }.controlSize(.small).disabled(state.busy)+ }+ Text(L("Downloads only what changed since this build. Nothing happens when it is already the newest."))+ .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }+ }+ }+ }+private var libraryInfo: some View {VStack(alignment: .leading, spacing: 12) {- row(L("Source"), item.source == .steam ? "Steam" : item.source == .epic ? "Epic Games" : item.source == .gog ? "GOG" : L("Windows program"))+ row(L("Source"), item.source == .steam ? "Steam" : item.source == .epic ? "Epic Games"- : item.source == .battlenet ? "Battle.net" : L("Windows program"))++ : item.source == .gog ? "GOG" : item.source == .battlenet ? "Battle.net" : L("Windows program"))if item.sizeOnDisk > 0 {row(L("Size on disk"), ByteCountFormatter.string(fromByteCount: item.sizeOnDisk, countStyle: .file))}@@@ -550,7 -506,7 +563,7 @@@.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)}}- if item.source == .steam || item.source == .gog {- if item.source == .steam || item.source == .epic {++ if item.source == .steam || item.source == .epic || item.source == .gog {HStack(alignment: .top, spacing: 12) {Text(L("Launch arguments")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 4)VStack(alignment: .leading, spacing: 4) {diff --cc Sources/HighballApp/LibraryView.swiftindex 3ddeb2a,3094de9..387adcf--- a/Sources/HighballApp/LibraryView.swift+++ b/Sources/HighballApp/LibraryView.swift@@@ -122,7 -130,10 +130,11 @@@ struct LibraryView: ViewFilterChip(label: L("All"), on: sourceFilter == nil) { sourceFilter = nil }FilterChip(label: "Steam", on: sourceFilter == .steam) { sourceFilter = .steam }FilterChip(label: "Epic", on: sourceFilter == .epic) { sourceFilter = .epic }+ FilterChip(label: "GOG", on: sourceFilter == .gog) { sourceFilter = .gog }+ // Only once Battle.net has installed something: most libraries never have a game from it.+ if sourceFilter == .battlenet || state.libraryItems.contains(where: { $0.source == .battlenet }) {+ FilterChip(label: "Battle.net", on: sourceFilter == .battlenet) { sourceFilter = .battlenet }+ }FilterChip(label: L("Programs"), on: sourceFilter == .pin) { sourceFilter = .pin }Divider().frame(height: 16)FilterChip(label: L("Installed"), on: installedOnly) { installedOnly.toggle() }@@@ -437,7 -450,7 +461,7 @@@ struct SourceBadge: View/// whole badge lit when Steam for Mac has it installed.var mac: MacSteamBuild? = nilprivate var label: String {- switch source { case .steam: "STEAM"; case .epic: "EPIC"; case .gog: "GOG"; case .pin: "EXE" }- switch source { case .steam: "STEAM"; case .epic: "EPIC"; case .pin: "EXE"; case .battlenet: "BATTLE.NET" }++ switch source { case .steam: "STEAM"; case .epic: "EPIC"; case .gog: "GOG"; case .pin: "EXE"; case .battlenet: "BATTLE.NET" }}private var lit: Bool { mac == .installed }var body: some View {diff --cc Sources/HighballApp/SettingsView.swiftindex ccba5c2,fb354de..3bf9c7f--- a/Sources/HighballApp/SettingsView.swift+++ b/Sources/HighballApp/SettingsView.swift@@@ -282,17 -281,17 +282,28 @@@ struct EnginePane: View.font(.caption).foregroundStyle(.secondary)}.frame(maxWidth: .infinity, alignment: .leading)}+ GroupBox {+ VStack(alignment: .leading, spacing: 6) {+ HStack {+ Toggle(L("Show achievement pop-ups"), isOn: $achievementPopups)+ Spacer()+ Button(L("Preview")) { state.previewAchievementPopup() }.controlSize(.small)+ }+ Text(L("When a GOG game unlocks an achievement, its badge shows in the corner of the screen for a few seconds, with a sound. The game keeps focus."))+ .font(.caption).foregroundStyle(.secondary)+ }.frame(maxWidth: .infinity, alignment: .leading)+ }+ // Only where it means something: a Mac with Steam for Mac, or one where it was turned off.+ if state.steamForMacInstalled || !state.includeMacSteam {+ GroupBox {+ VStack(alignment: .leading, spacing: 6) {+ Toggle(L("Show games from Steam for Mac"), isOn: Binding(get: { state.includeMacSteam },+ set: { state.setIncludeMacSteam($0) }))+ Text(L("Games Steam for Mac installed are listed next to your Windows games, and Play opens their Mac version. Off, the library lists only what Highball's environments hold, and Play uses the Windows version."))+ .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }.frame(maxWidth: .infinity, alignment: .leading)+ }+ }if let update = state.engineUpdate {GroupBox {HStack {diff --cc Sources/HighballKit/Library.swiftindex d0364f4,a33eef9..86c178a--- a/Sources/HighballKit/Library.swift+++ b/Sources/HighballKit/Library.swift@@@ -7,7 -7,7 +7,7 @@@ import ImageI// section; the bottle is a per-game property, never the navigation.public enum LibrarySource: String, Sendable, Codable {- case steam, epic, gog, pin- case steam, epic, pin, battlenet++ case steam, epic, gog, pin, battlenet}/// A playable item in the unified library. Pure value: no Bottle, no GameDBEntry — the app@@@ -16,21 -16,18 +16,23 @@@public struct LibraryItem: Identifiable, Sendable, Hashable {public let source: LibrarySource/// Stable identity, also the persistence key in library.json — never change its shape:- /// "steam:<appid>" | "epic:<app_name>" | "gog:<product id>" | "pin:<bottle>:<uuid>".- /// "steam:<appid>" | "epic:<app_name>" | "pin:<bottle>:<uuid>" | "battlenet:<product code>".++ /// "steam:<appid>" | "epic:<app_name>" | "gog:<product id>" | "pin:<bottle>:<uuid>" | "battlenet:<product code>".public let id: Stringpublic let title: String- /// Where it lives. nil only for an Epic title owned but not installed in any bottle.+ /// 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.public let installedOnMac: Boolpublic let steamAppID: Int?public let epicAppName: String?+ /// GOG's product id, for a game from the GOG account or a GOG install found on disk.+ public let gogID: String?+ /// The Steam app id GOG's database gives the same game: the compatibility database is matched+ /// by it, never Steam itself (`steamAppID` stays nil, so nothing treats the copy as a Steam one).+ public let gogSteamAppID: Int?+ /// Blizzard's product code for a game Battle.net installed (BattleNetGame.productCode).+ public let battleNetProduct: String?public let pinID: UUID?public let artworkTall: URL?public let artworkWide: URL?@@@ -41,12 -38,11 +43,13 @@@public init(source: LibrarySource, id: String, title: String, bottleName: String?,installed: Bool, installedOnMac: Bool = false, steamAppID: Int? = nil, epicAppName: String? = nil,- gogID: String? = nil, gogSteamAppID: Int? = nil, pinID: UUID? = nil, artworkTall: URL? = nil, artworkWide: URL? = nil,- battleNetProduct: String? = nil, pinID: UUID? = nil, artworkTall: URL? = nil, artworkWide: URL? = nil,++ gogID: String? = nil, gogSteamAppID: Int? = nil, battleNetProduct: String? = nil,++ pinID: UUID? = nil, artworkTall: URL? = nil, artworkWide: URL? = nil,otherBottles: [String] = [], sizeOnDisk: Int64 = 0, lastPlayed: Date? = nil) {self.source = source; self.id = id; self.title = title; self.bottleName = bottleNameself.installed = installed; self.installedOnMac = installedOnMac- self.steamAppID = steamAppID; self.epicAppName = epicAppName; self.battleNetProduct = battleNetProduct+ self.steamAppID = steamAppID; self.epicAppName = epicAppName- self.gogID = gogID; self.gogSteamAppID = gogSteamAppID++ self.gogID = gogID; self.gogSteamAppID = gogSteamAppID; self.battleNetProduct = battleNetProductself.pinID = pinID; self.artworkTall = artworkTall; self.artworkWide = artworkWideself.otherBottles = otherBottles; self.sizeOnDisk = sizeOnDisk; self.lastPlayed = lastPlayed}@@@ -64,7 -60,7 +67,8 @@@let others = (otherBottles.filter { $0 != bottle } + (installed ? [bottleName].compactMap { $0 } : [])).sorted()return LibraryItem(source: source, id: id, title: title, bottleName: bottle, installed: holds,installedOnMac: installedOnMac, steamAppID: steamAppID, epicAppName: epicAppName,- gogID: gogID, gogSteamAppID: gogSteamAppID, pinID: pinID, artworkTall: artworkTall, artworkWide: artworkWide,- battleNetProduct: battleNetProduct, pinID: pinID, artworkTall: artworkTall, artworkWide: artworkWide,++ gogID: gogID, gogSteamAppID: gogSteamAppID, battleNetProduct: battleNetProduct,++ pinID: pinID, artworkTall: artworkTall, artworkWide: artworkWide,otherBottles: others, sizeOnDisk: holds ? 0 : sizeOnDisk, lastPlayed: lastPlayed)}}@@@ -233,9 -111,7 +245,10 @@@ public enum LibraryIndexmacInstalled: [SteamGame] = [],epicOwned: [EpicStore.Game],epicInstalls: [String: String],+ gogGames: [GOGStore.Game] = [],+ gogInstalledByBottle: [String: [GOGStore.InstalledGame]] = [:],+ gogLaunchChoice: [String: Int] = [:],+ battleNetByBottle: [String: [BattleNetGame]] = [:],plays: [String: LibraryStore.PlayRecord] = [:],defaultBottle: String? = nil,pinExists: (Bottle, Pin) -> Bool = { _, _ in true }) -> [LibraryItem] {@@@ -319,37 -195,27 +332,58 @@@lastPlayed: plays[id]?.lastPlayedAt))}+ // GOG: one tile per game. Installs are read from disk (GOGStore.installedGames), so a game+ // an offline installer put in an environment is the GOG game too. Several environments+ // holding it: the one it was last played in, then the default, then by name, like Steam.+ var gogCopies: [String: [(bottle: String, game: GOGStore.InstalledGame)]] = [:]+ for bottle in bottles {+ for game in gogInstalledByBottle[bottle.name] ?? [] { gogCopies[game.id, default: []].append((bottle.name, game)) }+ }+ // Programs the GOG tile stands for leave the library (below); their plays show on it.+ let standing = gogCoveredPins(bottles: bottles, gogInstalledByBottle: gogInstalledByBottle, launchChoice: gogLaunchChoice)+ .filter(\.tilePlaysIt)+ let coveredPins = Set(standing.map(\.pinItemID))+ var gogSeen = Set<String>()+ let gogKnown = Dictionary(gogGames.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })+ for id in gogGames.map(\.id) + gogCopies.keys.sorted() where !gogSeen.contains(id) {+ gogSeen.insert(id)+ let itemID = "gog:\(id)"+ let copies = gogCopies[id] ?? []+ let lastPlayedBottle = plays[itemID]?.bottle+ let primary = copies.min { a, b in+ if let lp = lastPlayedBottle, (a.bottle == lp) != (b.bottle == lp) { return a.bottle == lp }+ return before(a.bottle, b.bottle)+ }+ 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,+ 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()))+ }++ // Battle.net: one tile per game like Steam's, homed where it was last played, then in the+ // default environment, then by name; the other environments holding it are remembered.+ var byProduct: [String: [(bottle: String, game: BattleNetGame)]] = [:]+ for bottle in bottles {+ for game in battleNetByBottle[bottle.name] ?? [] { byProduct[game.productCode, default: []].append((bottle.name, game)) }+ }+ for (code, copies) in byProduct {+ let id = "battlenet:\(code)"+ let lastPlayedBottle = plays[id]?.bottle+ let primary = copies.min { a, b in+ if let lp = lastPlayedBottle, (a.bottle == lp) != (b.bottle == lp) { return a.bottle == lp }+ return before(a.bottle, b.bottle)+ }!+ items.append(LibraryItem(+ source: .battlenet, id: id, title: primary.game.title, bottleName: primary.bottle,+ installed: true, battleNetProduct: code, artworkTall: primary.game.boxArt,+ otherBottles: copies.map(\.bottle).filter { $0 != primary.bottle }.sorted(),+ sizeOnDisk: primary.game.sizeOnDisk,+ lastPlayed: [primary.game.lastPlayed, plays[id]?.lastPlayedAt].compactMap { $0 }.max()))+ }+// Custom pins (dropped exes, preinstalled games), no artwork. Installed when the program's// file is there: one on a drive that is unplugged, or deleted since, is not (highball#269,// the Installed filter kept listing them). `pinExists` is the app's check of the disk;diff --cc Sources/HighballKit/PlayLink.swiftindex 5ea181f,a1e76c0..5fc5374--- a/Sources/HighballKit/PlayLink.swift+++ b/Sources/HighballKit/PlayLink.swift@@@ -9,8 -9,9 +9,10 @@@ public enum PlayLinkpublic enum Target: Equatable, Sendable {case steam(appid: Int)case epic(appName: String)+ case gog(id: String)case pin(bottle: String, id: UUID)+ /// A game Battle.net installed, by Blizzard's product code (highball#417, #432).+ case battlenet(product: String)/// A launcher (Steam, Epic, …) by recipe id: `highball://open/launcher/steam`. Opens it,/// installing it first if needed (issue #53: Mac icons for launchers too).case launcher(id: String)@@@ -21,11 -22,46 +23,50 @@@switch self {case let .steam(appid): return "steam:\(appid)"case let .epic(name): return "epic:\(name)"+ case let .gog(id): return "gog:\(id)"case let .pin(bottle, id): return "pin:\(bottle):\(id.uuidString)"+ case let .battlenet(product): return "battlenet:\(product)"case let .launcher(id): return "launcher:\(id)"}}++ /// The target a library id names, the inverse of `libraryID`: what `highball play` takes+ /// (highball#432), so a frontend starts a game by the same id `highball library` lists and+ /// library.json keys everything by. An environment's name may hold a colon, so a program's+ /// id splits at its last one. Anything else is nil.+ public init?(libraryID id: String) {+ guard let colon = id.firstIndex(of: ":") else { return nil }+ let rest = String(id[id.index(after: colon)...])+ guard !rest.isEmpty else { return nil }+ switch id[..<colon] {+ case "steam":+ guard let appid = Int(rest), appid > 0 else { return nil }+ self = .steam(appid: appid)+ case "epic":+ self = .epic(appName: rest)++ case "gog":++ guard rest.allSatisfy(\.isNumber) else { return nil }++ self = .gog(id: rest)+ case "pin":+ guard let last = rest.lastIndex(of: ":") else { return nil }+ let bottle = String(rest[..<last])+ guard !bottle.isEmpty, let uuid = UUID(uuidString: String(rest[rest.index(after: last)...])) else { return nil }+ self = .pin(bottle: bottle, id: uuid)+ case "battlenet":+ guard Self.isProductCode(rest) else { return nil }+ self = .battlenet(product: rest)+ case "launcher":+ guard rest.range(of: "^[a-z0-9-]+$", options: .regularExpression) != nil else { return nil }+ self = .launcher(id: rest)+ default:+ return nil+ }+ }++ /// Blizzard's product codes are short words of letters, digits and underscores (wow_classic).+ static func isProductCode(_ s: String) -> Bool {+ s.range(of: "^[A-Za-z0-9_]+$", options: .regularExpression) != nil+ }}public struct Request: Equatable, Sendable {@@@ -71,8 -106,8 +115,9 @@@switch target {case let .steam(appid): c.path = "/steam/\(appid)"case let .epic(name): c.path = "/epic/\(name)"+ case let .gog(id): c.path = "/gog/\(id)"case let .pin(bottle, id): c.path = "/pin/\(bottle)/\(id.uuidString)"+ case let .battlenet(product): c.path = "/battlenet/\(product)"case let .launcher(id): c.host = "open"; c.path = "/launcher/\(id)"}c.queryItems = [URLQueryItem(name: "t", value: token)]@@@ -82,8 -117,8 +127,9 @@@public static func target(for item: LibraryItem) -> Target? {if let appid = item.steamAppID { return .steam(appid: appid) }if let name = item.epicAppName { return .epic(appName: name) }+ if let id = item.gogID { return .gog(id: id) }if let id = item.pinID, let bottle = item.bottleName { return .pin(bottle: bottle, id: id) }+ if let product = item.battleNetProduct { return .battlenet(product: product) }return nil}diff --cc Sources/HighballKit/Uninstall.swiftindex 8329970,d1a6546..339aaaf--- a/Sources/HighballKit/Uninstall.swift+++ b/Sources/HighballKit/Uninstall.swift@@@ -42,13 -38,12 +42,17 @@@ public enum Uninstallreturn .none(reason: "Highball does not know this game's Epic id, so the Epic tools cannot be asked to remove it.")}return .epic(appName: name)+ case .gog:+ guard let id = item.gogID, item.installed else {+ return .none(reason: "This GOG game is not installed in an environment.")+ }+ return .gog(id: id)case .pin:return .windowsUninstaller+ case .battlenet:+ // Battle.net registers each game with Windows' Add or Remove Programs, pointing at its+ // own uninstaller, which also updates the client's records.+ return .windowsUninstaller}}diff --cc Sources/highball/main.swiftindex 7c9c7d1,31df8a0..d6f2c59--- a/Sources/highball/main.swift+++ b/Sources/highball/main.swift@@@ -7,7 -7,7 +7,7 @@@ struct Highball: AsyncParsableCommandstatic let configuration = CommandConfiguration(commandName: "highball",abstract: "Highball — run Windows games on Apple Silicon. Free, open, engine-agnostic.",- subcommands: [Config.self, Engine.self, Bottle.self, Run.self, PinCommand.self, Recipe.self, Tricks.self, Env.self, Epic.self, GOG.self, Report.self, BugReportCommand.self, Verify.self],- subcommands: [Config.self, Engine.self, Bottle.self, Run.self, LibraryCommand.self, Play.self, QuitCommand.self, PinCommand.self, Recipe.self, Tricks.self, Env.self, Epic.self, Report.self, BugReportCommand.self, Verify.self],++ subcommands: [Config.self, Engine.self, Bottle.self, Run.self, LibraryCommand.self, Play.self, QuitCommand.self, PinCommand.self, Recipe.self, Tricks.self, Env.self, Epic.self, GOG.self, Report.self, BugReportCommand.self, Verify.self],defaultSubcommand: nil)}@@@ -735,157 -735,157 +735,316 @@@ struct Epic: AsyncParsableCommand}}+struct GOG: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "gog",+ abstract: "Install and play GOG games through gogdl, with comet for achievements and gogdl for cloud saves (GOG Galaxy cannot sign in under Wine).",+ subcommands: [Login.self, Auth.self, List.self, Install.self, Launch.self])++ struct Login: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Print the GOG sign-in URL; paste the address it ends on into 'highball gog auth'.")+ func run() async throws {+ try await GOGStore().ensureInstalled()+ print("1. Open: \(GOGStore.loginURL.absoluteString)")+ print("2. Sign in. GOG ends on a mostly blank embed.gog.com page: copy its whole address.")+ print("3. Run: highball gog auth, and paste the address when asked.")+ }+ }++ struct Auth: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Finish sign-in with the address (or the code) the login page ended on; asks for it when not given, which keeps it out of shell history.")+ @Argument var pasted: String?+ func run() async throws {+ let store = GOGStore()+ try await store.ensureInstalled()+ var text = pasted+ if text == nil {+ print("Paste the address GOG's sign-in page ended on: ", terminator: "")+ text = readLine()+ }+ let reading = GOGStore.readSignIn(text ?? "")+ guard case let .code(code) = reading else {+ switch reading {+ case .signInPage: fail("that is the sign-in page itself; log in on it, then paste the address of the page it ends on")+ case .noCode: fail("that GOG address has no code; paste the address shown right after you log in")+ default: fail("no code in that; paste the whole embed.gog.com address")+ }+ }+ try store.authenticate(code: code)+ print("signed in\(store.username.map { " as \($0)" } ?? "")")+ }+ }++ struct List: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "List the account's games, and where each installed one lives.")+ func run() async throws {+ let store = GOGStore()+ try await store.ensureInstalled()+ guard store.isAuthenticated else { fail("not signed in — run 'highball gog login' first") }+ var installed: [String: String] = [:]+ for b in (try? BottleStore().list()) ?? [] {+ for g in GOGStore.installedGames(driveC: b.driveC) { installed[g.id] = b.name }+ }+ for g in try await store.ownedGames() {+ let mark = installed[g.id].map { "[installed: \($0)] " } ?? ""+ print("\(mark)\(g.id)\t\(g.title)")+ }+ }+ }++ struct Install: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Download a game's Windows build into a bottle (drive_c/Games) and run its GOG setup.")+ @Argument var bottle: String+ @Argument(help: "Product id from 'highball gog list'.") var id: String+ func run() async throws {+ let store = GOGStore()+ try await store.ensureInstalled()+ guard store.isAuthenticated else { fail("not signed in — run 'highball gog login' first") }+ let b = try BottleStore().get(bottle)+ let info = try store.info(id)+ let language = GOGStore.language(for: info.languages)+ if !info.dependencies.isEmpty { _ = try? store.downloadRedists(info.dependencies) { print($0) } }+ let status = try store.install(id, into: b, language: language) { line in+ if !line.contains("[PROGRESS]") || line.contains("= Progress:") { print(line) }+ }+ guard status == 0, store.downloadCompleted(id) else { fail("gogdl download did not finish (exit \(status)); run the same command to resume") }+ guard let game = GOGStore.installedGames(driveC: b.driveC).first(where: { $0.id == id }) else { fail("downloaded, but no goggame-\(id).info turned up in \(b.name)") }+ store.keepManifest(for: game)+ let eng = try EngineStore().engine(b.settings.engineID)+ let runner = WineRunner(engine: eng, bottle: b)+ try await store.runSetup(game, language: language, runner: runner,+ onStep: { n, total, label in print("setup \(n)/\(total): \(label)") },+ onFailure: { label, code in print("setup: \(label) ended with code \(code); carrying on") })+ print("installed \(game.title) into \(b.name): \(game.folder.path)")+ }+ }++ struct Launch: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Launch an installed GOG game in a bottle, with comet and cloud saves unless turned off.")+ @Argument var bottle: String+ @Argument var id: String+ @Option var renderer: HighballKit.Renderer?+ @Flag(help: "Run without comet (no achievements).") var noComet = false+ @Flag(help: "Skip the cloud-save sync before and after.") var noSaves = false+ func run() async throws {+ let store = GOGStore()+ let b = try BottleStore().get(bottle)+ guard let game = GOGStore.installedGames(driveC: b.driveC).first(where: { $0.id == id }),+ let task = game.launchTask(choice: GOGSettings.load(store).launchChoice[id]),+ let launch = GOGStore.launch(task, in: game) else { fail("GOG game \(id) is not installed in \(b.name)") }+ let eng = try EngineStore().engine(b.settings.engineID)+ let runner = WineRunner(engine: eng, bottle: b)+ let saves = GOGSaves(store: store)+ let settings = GOGSettings.load(store) // the game page's choices hold here too+ var folders: [(GOGSaves.Location, URL)] = []+ if !noSaves, !settings.cloudSavesOff.contains(id), store.isAuthenticated, let client = saves.clientID(for: game), let locations = try? saves.locations(clientID: client) {+ folders = locations.compactMap { l in GOGSaves.resolve(l.template, game: game, driveC: b.driveC).map { (l, $0) } }+ for (l, f) in folders { print("saves \(l.name) down: \(Self.describe(saves.sync(game, location: l, folder: f, direction: .download)))") }+ }+ var comet: Process?+ if !noComet, settings.cometOff[id] == nil, store.isAuthenticated {+ if let tools = try? await store.ensureComet() { _ = try? await GOGComet.installService(from: tools.service, runner: runner) }+ let log = HighballPaths().logs.appending(path: "comet-\(id).log")+ comet = try? GOGComet(store: store).start(log: log)+ print(comet != nil ? "comet running (log \(log.path))" : "comet did not start; playing without achievements")+ }+ let result: LaunchResult+ do {+ result = try await runner.start(launch.executable, arguments: launch.arguments, renderer: renderer,+ workingDirectory: launch.workingDirectory)+ } catch {+ GOGComet(store: store).stop(comet) // it would hold port 9977 and its copy of the tokens+ throw error+ }+ print("exit=\(result.exitStatus) — log: \(result.log.path)")+ // A launcher task hands over to another program in the folder and exits: the session+ // lasts while any of them runs in this bottle, so comet and the save upload wait for+ // the game itself.+ let markers = game.sessionMarkers(launching: launch.executable)+ var handedOver = false+ for _ in 0..<5 { // the program it hands to can take a moment to appear+ if !SessionWatch.pids(ofPrefix: b.url, markers: markers).isEmpty { handedOver = true; break }+ try await Task.sleep(for: .seconds(2))+ }+ if handedOver {+ print("the game is still running (handed over from \(launch.executable.lastPathComponent)); waiting for it to close")+ while !SessionWatch.pids(ofPrefix: b.url, markers: markers).isEmpty {+ try await Task.sleep(for: .seconds(2))+ }+ }+ GOGComet(store: store).stop(comet)+ for (l, f) in folders { print("saves \(l.name) up: \(Self.describe(saves.sync(game, location: l, folder: f, direction: .upload)))") }+ }++ static func describe(_ outcome: GOGSaves.Outcome) -> String {+ switch outcome {+ case .synced: return "synced"+ case .conflict: return "both copies changed, nothing moved; play from the app to choose which to keep"+ case .failed(let why): return "failed (\(why))"+ }+ }+ }+}++ // MARK: - highball library / play (highball#432)++ /// The library as the app builds it, read from disk: the environments' Steam games, installed and-/// owned, Steam for Mac's installs, Battle.net's installs, the programs added by hand, and with `epic` the Epic account's-/// games, which asks legendary. Not-installed games are homed as the app homes them (AppState's++/// owned, Steam for Mac's installs, Battle.net's installs, the GOG games in the environments, the++/// programs added by hand, and with `epic` the Epic account's games, which asks legendary, and the++/// GOG games' names and covers, which may ask GOG's database. Not-installed games are homed as the app homes them (AppState's+ /// defaultBottle: the Games environment, else the first with Steam, else the first).+ func currentLibrary(paths: HighballPaths, epic: Bool) -> [LibraryItem] {+ let bottles = (try? BottleStore(paths: paths).list()) ?? []+ let steam = Dictionary(bottles.map { ($0.name, SteamLibrary.games(in: $0)) }, uniquingKeysWith: { a, _ in a })+ let owned = Dictionary(bottles.map { ($0.name, SteamOwnedLibrary.games(in: $0)) }, uniquingKeysWith: { a, _ in a })+ var epicOwned: [EpicStore.Game] = [], epicInstalls: [String: String] = [:]+ let store = EpicStore(paths: paths)+ if epic, store.isAuthenticated {+ epicOwned = (try? store.ownedGames()) ?? []+ epicInstalls = EpicStore.installMap((try? store.installedGames()) ?? [])+ }+ let hasSteam = { (b: HighballKit.Bottle) in+ FileManager.default.fileExists(atPath: b.driveC.appending(path: "Program Files (x86)/Steam/steam.exe").path)+ }+ let home = bottles.first { $0.name == "Games" } ?? bottles.first(where: hasSteam) ?? bottles.first+ let battleNet = Dictionary(bottles.map { ($0.name, BattleNetLibrary.games(in: $0)) }, uniquingKeysWith: { a, _ in a })++ // GOG as the app reads it: installs from disk, and the launch choices that decide which++ // programs added by hand its tiles stand for, so both list the same ids.++ let gogStore = GOGStore(paths: paths)++ let gogInstalled = Dictionary(bottles.map { ($0.name, GOGStore.installedGames(driveC: $0.driveC)) }, uniquingKeysWith: { a, _ in a })++ let gogGames = epic ? Set(gogInstalled.values.joined().map(\.id)).sorted().compactMap { gogStore.game($0) } : []+ return LibraryIndex.build(bottles: bottles, steamByBottle: steam, steamOwnedByBottle: owned,+ macInstalled: MacSteam.installedGames(), epicOwned: epicOwned, epicInstalls: epicInstalls,++ gogGames: gogGames, gogInstalledByBottle: gogInstalled,++ gogLaunchChoice: GOGSettings.load(gogStore).launchChoice,+ battleNetByBottle: battleNet,+ plays: LibraryStore(paths: paths).load(), defaultBottle: home?.name,+ pinExists: { b, pin in FileManager.default.fileExists(atPath: pin.executableURL(driveC: b.driveC).path) })+ }++ /// Everything Highball started, ended in one go: what a frontend runs when it closes (highball#432),+ /// since it knows games by id and has no idea which environment holds which. Every environment+ /// with a live Wine server is stopped the way Stop all processes does it, then the app is asked+ /// to quit, as Quit in its menu would. Nothing outside Highball's environments is touched.+ struct QuitCommand: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "quit",+ abstract: "Stop every program running in Highball's environments, Steam included, and quit Highball.",+ discussion: "For frontends such as ES-DE on exit. --keep-app leaves the Highball app open.")+ @Flag(help: "Stop the environments but leave the Highball app running.") var keepApp = false++ func run() async throws {+ let paths = HighballPaths()+ let engines = EngineStore(paths: paths)+ for b in (try? BottleStore(paths: paths).list()) ?? [] where ProcessTable.liveServer(forPrefix: b.url) != nil {+ guard let eng = try? engines.engine(b.settings.engineID) else { continue }+ _ = try? WineRunner(paths: paths, engine: eng, bottle: b).kill()+ print("stopped \(b.name)")+ }+ guard !keepApp else { return }+ let quit = Process()+ quit.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")+ quit.arguments = ["-e", "if application id \"app.highball.Highball\" is running then tell application id \"app.highball.Highball\" to quit"]+ try? quit.run()+ quit.waitUntilExit()+ }+ }++ struct LibraryCommand: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "library",+ abstract: "List the library's games with the ids `highball play` takes.",+ discussion: "One game per line, tab-separated: id, name, environment, and installed, installed on Mac or not installed.")+ @Flag(help: "Only the games that can be played now.") var installed = false+ @Flag(help: "Print JSON instead of lines.") var json = false++ func run() async throws {+ let paths = HighballPaths()+ let names = NameStore(paths: paths).names()+ let entries = currentLibrary(paths: paths, epic: true)+ .filter { !installed || $0.installedAnywhere }+ .map { LibraryListing.entry($0, title: NameStore.name(for: $0.id, in: names) ?? $0.title) }+ .sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == .orderedAscending }+ if json {+ let enc = JSONEncoder(); enc.outputFormatting = [.prettyPrinted, .sortedKeys]+ print(String(decoding: try enc.encode(entries), as: UTF8.self))+ } else {+ for entry in entries { print(LibraryListing.line(entry)) }+ }+ }+ }++ struct Play: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ abstract: "Start a library game through the Highball app, as its Play button does.",+ discussion: """- The id is one `highball library` lists: steam:<appid>, epic:<app name> or \- pin:<environment>:<uuid>, battlenet:<product code>, and launcher:<id> opens a launcher. Highball starts it with \++ The id is one `highball library` lists: steam:<appid>, epic:<app name>, gog:<product id>, \++ pin:<environment>:<uuid> or battlenet:<product code>, and launcher:<id> opens a launcher. Highball starts it with \+ the game's own settings and stays in the background, the way a game's Mac app does. \+ With --wait the command returns once the game has quit, for frontends such as ES-DE, \+ and Highball and Steam keep running. It follows the games Highball runs in its \+ environments, so a game Steam for Mac starts ends the wait only at --start-timeout.+ """)+ @Argument(help: "The game's library id.") var id: String+ @Flag(help: "Return only once the game has quit.") var wait = false+ @Option(help: "With --wait, how many seconds the game has to start before the command gives up.") var startTimeout: Int = 600++ func run() async throws {+ guard let target = PlayLink.Target(libraryID: id) else {- fail("\(id) is not a library id. `highball library` lists them: steam:<appid>, epic:<app name>, pin:<environment>:<uuid>, battlenet:<product code>.")++ fail("\(id) is not a library id. `highball library` lists them: steam:<appid>, epic:<app name>, gog:<product id>, pin:<environment>:<uuid>, battlenet:<product code>.")+ }+ let paths = HighballPaths()+ // A typo fails here and now, not as an alert in the app and a wait that never ends.+ switch target {+ case .launcher:+ break+ case let .epic(name):+ let store = EpicStore(paths: paths)+ guard store.isAuthenticated, EpicStore.installMap((try? store.installedGames()) ?? [])[name] != nil else {+ fail("\(id) is not an installed Epic game in this Highball. `highball library --installed` lists what can be played.")+ }- case .steam, .pin, .battlenet:++ case .steam, .gog, .pin, .battlenet:+ guard currentLibrary(paths: paths, epic: false).contains(where: { $0.id == target.libraryID }) else {+ fail("\(id) is not in this Highball's library. `highball library` lists the ids.")+ }+ }+ // The link the game's Mac app opens, with this install's token, so the app starts it+ // without asking; -g keeps Highball behind the game (MacAppStub.launchScript).+ let url = PlayLink.url(for: target, token: PlayLink.token(in: paths))+ let open = Process()+ open.executableURL = URL(fileURLWithPath: "/usr/bin/open")+ open.arguments = ["-g"] + (enclosingApp().map { ["-a", $0.path] } ?? []) + [url.absoluteString]+ try open.run()+ open.waitUntilExit()+ guard open.terminationStatus == 0 else { fail("macOS could not open the Highball app (open exited with \(open.terminationStatus))") }+ guard wait else { return }+ if case .launcher = target { return } // a launcher is not a game the app follows++ let started = Date()+ var phase = PlayWait.Phase.starting+ while true {+ try await Task.sleep(for: .seconds(2))+ switch PlayWait.step(phase, id: target.libraryID, running: RunningGames.current(paths: paths),+ waited: Date().timeIntervalSince(started), startTimeout: TimeInterval(startTimeout)) {+ case .keepWaiting(let next): phase = next+ case .ended: return+ case .neverStarted: fail("\(id) did not start within \(startTimeout) s. Highball may be asking something in its window.")+ }+ }+ }++ /// The Highball app this command ships in, so it starts games in that app and not in another+ /// copy macOS knows; nil for a build from source, which uses the app registered for highball://.+ private func enclosingApp() -> URL? {+ var url = Bundle.main.executableURL?.resolvingSymlinksInPath()+ while let current = url, current.path != "/" {+ if current.pathExtension == "app" { return current }+ url = current.deletingLastPathComponent()+ }+ return nil+ }+ }+struct BugReportCommand: AsyncParsableCommand {static let configuration = CommandConfiguration(commandName: "bugreport", abstract: "Print a pre-filled GitHub bug-report URL (system info + newest log tail).")func run() async throws {diff --cc Tests/HighballKitTests/PlayFromCommandLineTests.swiftindex 0000000,ee29453..299fa78mode 000000,100644..100644--- a/Tests/HighballKitTests/PlayFromCommandLineTests.swift+++ b/Tests/HighballKitTests/PlayFromCommandLineTests.swift@@@ -1,0 -1,92 +1,92 @@@+ import XCTest+ @testable import HighballKit++ /// Starting a library game from the command line (highball#432): `highball play` takes the ids+ /// `highball library` lists and library.json keys everything by, hands them to the app as the+ /// play link a game's Mac app opens, and with --wait follows the app's running games.+ final class PlayFromCommandLineTests: XCTestCase {+ func testEveryLibraryIdNamesTheTargetItsLinkStarts() {+ let uuid = UUID(uuidString: "B43215E4-3490-4E8A-835B-3668A02B279F")!- let targets: [PlayLink.Target] = [.steam(appid: 2420510), .epic(appName: "Fortnite"),++ let targets: [PlayLink.Target] = [.steam(appid: 2420510), .epic(appName: "Fortnite"), .gog(id: "1207658924"),+ .pin(bottle: "Games", id: uuid), .battlenet(product: "wow_classic"),+ .launcher(id: "ea-app")]+ for target in targets {+ XCTAssertEqual(PlayLink.Target(libraryID: target.libraryID), target, target.libraryID)+ }+ XCTAssertEqual(PlayLink.Target(libraryID: "steam:620")?.libraryID, "steam:620")+ // A Battle.net game's link is the one its Mac app would open (highball#417, #432).+ let link = PlayLink.url(for: .battlenet(product: "pro"), token: "t")+ XCTAssertEqual(link.absoluteString, "highball://play/battlenet/pro?t=t")+ XCTAssertEqual(PlayLink.parse(link)?.target, .battlenet(product: "pro"))+ }++ /// An environment's name may hold a colon or a space; the program's id ends at its uuid.+ func testAProgramIdKeepsItsEnvironmentsWholeName() {+ let uuid = UUID(uuidString: "B43215E4-3490-4E8A-835B-3668A02B279F")!+ XCTAssertEqual(PlayLink.Target(libraryID: "pin:Old games: 1998:\(uuid.uuidString)"), .pin(bottle: "Old games: 1998", id: uuid))+ // A lowercase uuid typed by hand names the same program.+ XCTAssertEqual(PlayLink.Target(libraryID: "pin:Games:\(uuid.uuidString.lowercased())")?.libraryID, "pin:Games:\(uuid.uuidString)")+ // And its link is the one the Mac app for it would open.+ let url = PlayLink.url(for: .pin(bottle: "Old games", id: uuid), token: "t")+ XCTAssertEqual(PlayLink.parse(url)?.target, .pin(bottle: "Old games", id: uuid))+ }++ func testAnythingElseIsNotAnId() {+ for bad in ["", "steam", "steam:", "steam:0", "steam:-3", "steam:abc", "epic:", "pin:Games",- "pin::B43215E4-3490-4E8A-835B-3668A02B279F", "pin:Games:not-a-uuid", "gog:123",++ "pin::B43215E4-3490-4E8A-835B-3668A02B279F", "pin:Games:not-a-uuid", "gog:", "gog:abc",+ "launcher:Steam Client", "launcher:../x", "2420510", "battlenet:", "battlenet:../wow", "battlenet:wow classic"] {+ XCTAssertNil(PlayLink.Target(libraryID: bad), bad)+ }+ }++ func testTheListingLeadsWithTheIdAndStaysOneLinePerGame() {+ let mac = HighballKit.LibraryItem(source: .steam, id: "steam:400", title: "Portal", bottleName: "Games",+ installed: false, installedOnMac: true, steamAppID: 400)+ XCTAssertEqual(LibraryListing.line(LibraryListing.entry(mac, title: "Portal")), "steam:400\tPortal\tGames\tinstalled on Mac")+ let epic = HighballKit.LibraryItem(source: .epic, id: "epic:Duck", title: "Cardpocalypse", bottleName: nil,+ installed: false, epicAppName: "Duck")+ XCTAssertEqual(LibraryListing.line(LibraryListing.entry(epic, title: "Card\tpocalypse\n")), "epic:Duck\tCard pocalypse \t-\tnot installed")+ let game = HighballKit.LibraryItem(source: .steam, id: "steam:620", title: "Portal 2", bottleName: "Games", installed: true)+ XCTAssertEqual(LibraryListing.line(LibraryListing.entry(game, title: "Portal Deux")), "steam:620\tPortal Deux\tGames\tinstalled")+ }++ func testRunningGamesRoundTripAndAGoneAppReadsAsNothingKnown() throws {+ let home = FileManager.default.temporaryDirectory.appending(path: "hb-running-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: home) }+ let paths = HighballPaths(home: home)+ XCTAssertNil(RunningGames.current(paths: paths), "no file, no app")+ RunningGames.write(["steam:620", "epic:Duck"], paths: paths)+ XCTAssertEqual(RunningGames.read(paths: paths)?.pid, getpid())+ XCTAssertEqual(RunningGames.current(paths: paths, isLive: { _ in true }), ["steam:620", "epic:Duck"])+ XCTAssertNil(RunningGames.current(paths: paths, isLive: { _ in false }))+ // The writer here is this test process, which is alive and is the program it wrote down.+ XCTAssertEqual(RunningGames.current(paths: paths), ["steam:620", "epic:Duck"])+ RunningGames.write([], paths: paths)+ XCTAssertEqual(RunningGames.current(paths: paths), [])+ }++ func testOnlyALiveProcessRunningTheSameProgramCounts() throws {+ let me = Bundle.main.executableURL!.resolvingSymlinksInPath().path+ XCTAssertTrue(RunningGames.isLive(RunningGames(pid: getpid(), executable: me, games: [])))+ XCTAssertFalse(RunningGames.isLive(RunningGames(pid: getpid(), executable: "/Applications/Other.app/Contents/MacOS/Other", games: [])),+ "a process id reused by another program")+ XCTAssertFalse(RunningGames.isLive(RunningGames(pid: 0, executable: me, games: [])))+ let gone = Process(); gone.executableURL = URL(fileURLWithPath: "/usr/bin/true")+ try gone.run(); gone.waitUntilExit()+ XCTAssertFalse(RunningGames.isLive(RunningGames(pid: gone.processIdentifier, executable: "/usr/bin/true", games: [])))+ }++ func testTheWaitFollowsTheGameFromStartToQuit() {+ let id = "steam:620"+ // Not listed yet: keep waiting for the start, until the start timeout.+ XCTAssertEqual(PlayWait.step(.starting, id: id, running: nil, waited: 5, startTimeout: 600), .keepWaiting(.starting))+ XCTAssertEqual(PlayWait.step(.starting, id: id, running: ["steam:730"], waited: 5, startTimeout: 600), .keepWaiting(.starting))+ XCTAssertEqual(PlayWait.step(.starting, id: id, running: [], waited: 600, startTimeout: 600), .neverStarted)+ // Listed: running, whatever the time.+ XCTAssertEqual(PlayWait.step(.starting, id: id, running: [id], waited: 900, startTimeout: 600), .keepWaiting(.running))+ XCTAssertEqual(PlayWait.step(.running, id: id, running: [id, "steam:730"], waited: 7200, startTimeout: 600), .keepWaiting(.running))+ // Gone from the list, or the app quit: the game has ended.+ XCTAssertEqual(PlayWait.step(.running, id: id, running: ["steam:730"], waited: 7200, startTimeout: 600), .ended)+ XCTAssertEqual(PlayWait.step(.running, id: id, running: nil, waited: 7200, startTimeout: 600), .ended)+ }+ }