Skip to content

Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.

highball play starts a library game by its id and can wait for it to quit, and highball library lists the ids (highball#432)

Gauthier Piarrette17e055eacd43
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 07dd3f0..93b64c6 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -2385,8 +2385,14 @@ final class AppState {
// MARK: Sessions (UX plan 0.6)
/// Games running right now, from their processes. The library shows them and offers Stop;
- /// nothing here blocks the app while a game runs.
- var runningSessions: [GameSession] = []
+ /// nothing here blocks the app while a game runs. Kept in the home as well (RunningGames), so
+ /// `highball play --wait` returns when its game quits (highball#432).
+ var runningSessions: [GameSession] = [] {
+ didSet {
+ let ids = runningSessions.compactMap(\.libraryID)
+ if ids != oldValue.compactMap(\.libraryID) { RunningGames.write(ids, paths: paths) }
+ }
+ }
/// The last session that ended, for the post-play prompt to come.
var lastEndedSession: SessionRecord?
/// A finished session worth asking about: at least a minute of play (a shorter one is a
diff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swift
index 772f99c..db730d0 100644
--- a/Sources/HighballKit/Library.swift
+++ b/Sources/HighballKit/Library.swift
@@ -213,6 +213,34 @@ public enum LibraryIndex {
}
}
+/// The library as `highball library` prints it (highball#432): a game per line, led by the id
+/// `highball play` takes, then the name the player sees, its environment and whether it can be
+/// played. Tab-separated so a frontend's script can cut it; `--json` gives the same entries.
+public enum LibraryListing {
+ public struct Entry: Codable, Equatable, Sendable {
+ public let id: String
+ public let title: String
+ public let source: String
+ public let environment: String?
+ public let installed: Bool
+ public let installedOnMac: Bool
+ }
+
+ /// `title` is the name shown in the app: a custom one (NameStore) or the store's.
+ public static func entry(_ item: LibraryItem, title: String) -> Entry {
+ Entry(id: item.id, title: title, source: item.source.rawValue, environment: item.bottleName,
+ installed: item.installed, installedOnMac: item.installedOnMac)
+ }
+
+ public static func line(_ entry: Entry) -> String {
+ func field(_ text: String) -> String {
+ text.replacingOccurrences(of: "[\t\r\n]+", with: " ", options: .regularExpression)
+ }
+ let state = entry.installed ? "installed" : entry.installedOnMac ? "installed on Mac" : "not installed"
+ return [entry.id, field(entry.title), field(entry.environment ?? "-"), state].joined(separator: "\t")
+ }
+}
+
/// Which existing environment a game that needs another engine should use (highball-db#318).
/// The engine ask offers the best one before "New environment", so pressing Play again after
/// making one never makes a second. An environment holding the game comes first, then one
diff --git a/Sources/HighballKit/PlayLink.swift b/Sources/HighballKit/PlayLink.swift
index 38cc626..e44a8f3 100644
--- a/Sources/HighballKit/PlayLink.swift
+++ b/Sources/HighballKit/PlayLink.swift
@@ -24,6 +24,33 @@ public enum PlayLink {
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 "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 "launcher":
+ guard rest.range(of: "^[a-z0-9-]+$", options: .regularExpression) != nil else { return nil }
+ self = .launcher(id: rest)
+ default:
+ return nil
+ }
+ }
}
public struct Request: Equatable, Sendable {
diff --git a/Sources/HighballKit/Sessions.swift b/Sources/HighballKit/Sessions.swift
index e186b38..36b2870 100644
--- a/Sources/HighballKit/Sessions.swift
+++ b/Sources/HighballKit/Sessions.swift
@@ -92,3 +92,73 @@ public enum SessionWatch {
else { try? data.write(to: file) }
}
}
+
+/// The games the app sees running, by library id, kept in a small file in the home for the command
+/// line: `highball play --wait` returns once its game has quit, so a frontend that starts games
+/// (ES-DE, highball#432) gets control back then, and Highball and Steam stay as they are. The app
+/// rewrites the file at every change; its process id and executable make a file left behind by an
+/// app that is gone read as nothing known, never as a game still running.
+public struct RunningGames: Codable, Sendable, Equatable {
+ public var pid: Int32
+ public var executable: String
+ public var games: [String]
+
+ public init(pid: Int32, executable: String, games: [String]) {
+ self.pid = pid; self.executable = executable; self.games = games
+ }
+
+ public static func file(in paths: HighballPaths) -> URL { paths.home.appending(path: "running.json") }
+
+ /// What the running app writes: its own process and the library ids of its sessions.
+ public static func write(_ games: [String], paths: HighballPaths) {
+ let me = RunningGames(pid: getpid(), executable: Bundle.main.executableURL?.resolvingSymlinksInPath().path ?? "", games: games)
+ try? paths.ensure()
+ if let data = try? JSONEncoder().encode(me) { try? data.write(to: file(in: paths), options: .atomic) }
+ }
+
+ public static func read(paths: HighballPaths) -> RunningGames? {
+ guard let data = try? Data(contentsOf: file(in: paths)) else { return nil }
+ return try? JSONDecoder().decode(RunningGames.self, from: data)
+ }
+
+ /// The library ids running now, or nil when no app that wrote the file is running.
+ public static func current(paths: HighballPaths, isLive: (RunningGames) -> Bool = RunningGames.isLive) -> Set<String>? {
+ guard let state = read(paths: paths), isLive(state) else { return nil }
+ return Set(state.games)
+ }
+
+ /// The writer still runs: its process exists and is the same program, so a process id reused
+ /// after a crash does not count.
+ public static func isLive(_ state: RunningGames) -> Bool {
+ guard state.pid > 0, kill(state.pid, 0) == 0 else { return false }
+ var buffer = [CChar](repeating: 0, count: 4096)
+ guard proc_pidpath(state.pid, &buffer, UInt32(buffer.count)) > 0 else { return false }
+ let path = URL(fileURLWithPath: String(cString: buffer)).resolvingSymlinksInPath().path
+ return state.executable.isEmpty || path == state.executable
+ }
+}
+
+/// How `highball play --wait` follows its game, one look at a time: first until the app lists the
+/// game as running, then until it no longer does or the app has quit. A game that never starts (a
+/// question in the app left unanswered, a launch that failed) stops the wait after `startTimeout`.
+public enum PlayWait {
+ public enum Phase: Equatable, Sendable { case starting, running }
+ public enum Step: Equatable, Sendable {
+ case keepWaiting(Phase)
+ case ended
+ case neverStarted
+ }
+
+ /// `running` is what RunningGames.current read: nil when no Highball app runs.
+ public static func step(_ phase: Phase, id: String, running: Set<String>?, waited: TimeInterval,
+ startTimeout: TimeInterval) -> Step {
+ let listed = running?.contains(id) == true
+ switch phase {
+ case .starting:
+ if listed { return .keepWaiting(.running) }
+ return waited >= startTimeout ? .neverStarted : .keepWaiting(.starting)
+ case .running:
+ return listed ? .keepWaiting(.running) : .ended
+ }
+ }
+}
diff --git a/Sources/highball/main.swift b/Sources/highball/main.swift
index f36254b..7dc51b2 100644
--- a/Sources/highball/main.swift
+++ b/Sources/highball/main.swift
@@ -7,7 +7,7 @@ struct Highball: AsyncParsableCommand {
static 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, Report.self, BugReportCommand.self, Verify.self],
+ subcommands: [Config.self, Engine.self, Bottle.self, Run.self, LibraryCommand.self, Play.self, PinCommand.self, Recipe.self, Tricks.self, Env.self, Epic.self, Report.self, BugReportCommand.self, Verify.self],
defaultSubcommand: nil
)
}
@@ -735,6 +735,127 @@ struct Epic: AsyncParsableCommand {
}
}
+// 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, 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
+/// 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
+ return LibraryIndex.build(bottles: bottles, steamByBottle: steam, steamOwnedByBottle: owned,
+ macInstalled: MacSteam.installedGames(), epicOwned: epicOwned, epicInstalls: epicInstalls,
+ plays: LibraryStore(paths: paths).load(), defaultBottle: home?.name,
+ pinExists: { b, pin in FileManager.default.fileExists(atPath: pin.executableURL(driveC: b.driveC).path) })
+}
+
+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>, 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>.")
+ }
+ 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:
+ 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 --git a/Tests/HighballKitTests/PlayFromCommandLineTests.swift b/Tests/HighballKitTests/PlayFromCommandLineTests.swift
new file mode 100644
index 0000000..8bf004c
--- /dev/null
+++ b/Tests/HighballKitTests/PlayFromCommandLineTests.swift
@@ -0,0 +1,87 @@
+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"),
+ .pin(bottle: "Games", id: uuid), .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")
+ }
+
+ /// 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",
+ "launcher:Steam Client", "launcher:../x", "2420510"] {
+ 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)
+ }
+}