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
feat: Epic game installs and launches through Legendary (#14)
Gauthier Piarretted30201c44a52
diff --git a/Sources/HighballKit/EpicStore.swift b/Sources/HighballKit/EpicStore.swiftnew file mode 100644index 0000000..d3d89c0--- /dev/null+++ b/Sources/HighballKit/EpicStore.swift@@ -0,0 +1,139 @@+import Foundation++/// Installs and launches Epic Games titles through Legendary (github.com/legendary-gl/legendary),+/// bypassing the Epic launcher's install flow, which cannot pass its permission audit under Wine+/// (issue #14; the launcher audits Windows ACLs Wine does not persist). Legendary is GPL-3 like+/// Highball, maintained by the Heroic team, and authenticates with the user's own Epic account.+public struct EpicStore: Sendable {+ public let paths: HighballPaths+ public init(paths: HighballPaths = HighballPaths()) { self.paths = paths }++ // Pinned like an engine component. Update deliberately, never float.+ static let binaryURL = URL(string: "https://github.com/legendary-gl/legendary/releases/download/0.21.0/legendary_macOS_arm64")!+ static let binarySHA256 = "28f5f7d0eb8c029679d4faaa483ec85888af17a9a75977ae9170c21d8ce3428b"++ /// The page where the user signs into their existing Epic account. It ends by showing an+ /// authorizationCode to paste back into `highball epic auth <code>`.+ public static let loginURL = URL(string: "https://legendary.gl/epiclogin")!++ public var binary: URL { paths.home.appending(path: "tools/legendary", directoryHint: .notDirectory) }+ var configDir: URL { paths.home.appending(path: "legendary", directoryHint: .isDirectory) }++ /// Downloads and verifies the pinned Legendary binary if missing.+ public func ensureInstalled(progress: DownloadProgress? = nil) async throws -> URL {+ if FileManager.default.fileExists(atPath: binary.path) { return binary }+ let component = EngineManifest.Component(kind: "tool", url: Self.binaryURL, sha256: Self.binarySHA256,+ size: 15_270_304, license: nil, optional: nil,+ acceptance: nil, extract: nil, note: nil, version: "0.21.0")+ let file = try await EngineStore(paths: paths).download(component, name: "legendary", progress: progress)+ try FileManager.default.createDirectory(at: binary.deletingLastPathComponent(), withIntermediateDirectories: true)+ try? FileManager.default.removeItem(at: binary)+ try FileManager.default.copyItem(at: file, to: binary)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: binary.path)+ // Checksum-verified above; quarantine would otherwise block the unsigned PyInstaller binary.+ try? Shell.run("/usr/bin/xattr", ["-c", binary.path])+ return binary+ }++ var environment: [String: String] { ["LEGENDARY_CONFIG_PATH": configDir.path] }++ @discardableResult+ func capture(_ args: [String]) throws -> String {+ try Shell.capture(binary.path, args, env: environment)+ }++ /// Runs legendary streaming each output line (installs are long and progress matters).+ @discardableResult+ public func runStreaming(_ args: [String], onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ let p = Process()+ p.executableURL = binary+ p.arguments = args+ p.environment = ProcessInfo.processInfo.environment.merging(environment) { $1 }+ let pipe = Pipe()+ p.standardOutput = pipe+ p.standardError = pipe+ try p.run()+ let reader = pipe.fileHandleForReading+ var buffer = Data()+ while true {+ let chunk = reader.availableData+ if chunk.isEmpty { break }+ buffer.append(chunk)+ while let nl = buffer.firstIndex(of: 0x0A) {+ onLine?(String(decoding: buffer[..<nl], as: UTF8.self))+ buffer.removeSubrange(...nl)+ }+ }+ if !buffer.isEmpty { onLine?(String(decoding: buffer, as: UTF8.self)) }+ p.waitUntilExit()+ return p.terminationStatus+ }++ public var isAuthenticated: Bool {+ FileManager.default.fileExists(atPath: configDir.appending(path: "user.json").path)+ }++ public func authenticate(code: String) throws {+ _ = try capture(["auth", "--disable-webview", "--code", code])+ }++ public func logout() throws { _ = try capture(["auth", "--delete"]) }++ public struct Game: Codable, Sendable {+ public let app_name: String+ public let app_title: String+ }++ /// Games the account owns (Windows builds).+ public func ownedGames() throws -> [Game] {+ let out = try capture(["list", "--platform", "Windows", "--json"])+ return try JSONDecoder().decode([Game].self, from: Data(out.utf8))+ }++ public func installedGames() throws -> [Game] {+ let out = try capture(["list-installed", "--json"])+ return try JSONDecoder().decode([Game].self, from: Data(out.utf8))+ }++ /// Installs a game's Windows build into the bottle at drive_c/Games/<folder>.+ @discardableResult+ public func install(_ appName: String, into bottle: Bottle, onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ let base = bottle.driveC.appending(path: "Games", directoryHint: .isDirectory)+ try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)+ return try runStreaming(["install", appName, "--platform", "Windows",+ "--base-path", base.path, "-y"], onLine: onLine)+ }++ public struct LaunchInfo: Sendable {+ public let executable: URL+ public let arguments: [String]+ public let workingDirectory: URL+ public let environment: [String: String]+ }++ /// Fresh launch parameters. The auth token inside is single use and expires within minutes,+ /// so call this immediately before each launch and never persist the result.+ public func launchInfo(_ appName: String, offline: Bool = false) throws -> LaunchInfo {+ var args = ["launch", appName, "--json", "--skip-version-check"]+ if offline { args.append("--offline") }+ let out = try capture(args)+ guard let start = out.firstIndex(of: "{"),+ let obj = try JSONSerialization.jsonObject(with: Data(out[start...].utf8)) as? [String: Any] else {+ throw HighballError.invalid("unexpected legendary launch output")+ }+ let gameDir = (obj["game_directory"] as? String) ?? ""+ let exe = (obj["game_executable"] as? String) ?? ""+ let workdir = (obj["working_directory"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? gameDir+ let params = ((obj["egl_parameters"] as? [String]) ?? [])+ + ((obj["game_parameters"] as? [String]) ?? [])+ + ((obj["user_parameters"] as? [String]) ?? [])+ let env = (obj["environment"] as? [String: String]) ?? [:]+ guard !gameDir.isEmpty, !exe.isEmpty else {+ throw HighballError.invalid("legendary returned no executable for \(appName)")+ }+ return LaunchInfo(executable: URL(fileURLWithPath: gameDir).appending(path: exe),+ arguments: params,+ workingDirectory: URL(fileURLWithPath: workdir),+ environment: env)+ }+}diff --git a/Sources/HighballKit/WineRunner.swift b/Sources/HighballKit/WineRunner.swiftindex 0abaecb..a857e96 100644--- a/Sources/HighballKit/WineRunner.swift+++ b/Sources/HighballKit/WineRunner.swift@@ -27,6 +27,7 @@ public struct WineRunner: Sendable {renderer: Renderer? = nil,extraEnvironment: [String: String] = [:],label: String? = nil,+ workingDirectory: URL? = nil,onOutput: (@Sendable (String) -> Void)? = nil) async throws -> LaunchResult {try paths.ensure()@@ -43,7 +44,8 @@ public struct WineRunner: Sendable {process.arguments = argsprocess.environment = ProcessInfo.processInfo.environment.merging(env) { $1 }// drive_c only exists after the first wineboot — fall back to the bottle root on fresh prefixes.- process.currentDirectoryURL = FileManager.default.fileExists(atPath: bottle.driveC.path) ? bottle.driveC : bottle.url+ process.currentDirectoryURL = workingDirectory+ ?? (FileManager.default.fileExists(atPath: bottle.driveC.path) ? bottle.driveC : bottle.url)let pipe = Pipe()process.standardOutput = pipeprocess.standardError = pipe@@ -82,8 +84,8 @@ public struct WineRunner: Sendable {/// Runs the executable directly under `wine` (not `start /unix`) so the process stays attached and/// everything it and its children print lands in the log. The call returns when the program exits.@discardableResult- public func start(_ executable: URL, arguments: [String] = [], renderer: Renderer? = nil, extraEnvironment: [String: String] = [:], onOutput: (@Sendable (String) -> Void)? = nil) async throws -> LaunchResult {- try await run([executable.path] + arguments, renderer: renderer, extraEnvironment: extraEnvironment, label: executable.lastPathComponent, onOutput: onOutput)+ public func start(_ executable: URL, arguments: [String] = [], renderer: Renderer? = nil, extraEnvironment: [String: String] = [:], workingDirectory: URL? = nil, onOutput: (@Sendable (String) -> Void)? = nil) async throws -> LaunchResult {+ try await run([executable.path] + arguments, renderer: renderer, extraEnvironment: extraEnvironment, label: executable.lastPathComponent, workingDirectory: workingDirectory, onOutput: onOutput)}/// Runs the pinned program, honouring its own renderer/env/args.diff --git a/Sources/highball/main.swift b/Sources/highball/main.swiftindex 4279afc..a682566 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: [Engine.self, Bottle.self, Run.self, Recipe.self, Tricks.self, Env.self, Report.self, BugReportCommand.self, Verify.self],+ subcommands: [Engine.self, Bottle.self, Run.self, Recipe.self, Tricks.self, Env.self, Epic.self, Report.self, BugReportCommand.self, Verify.self],defaultSubcommand: nil)}@@ -394,6 +394,82 @@ func loadRecipe(_ idOrPath: String) throws -> HighballKit.Recipe {""")}+struct Epic: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ abstract: "Install and launch Epic games through Legendary (bypasses the Epic launcher's broken install flow).",+ subcommands: [Login.self, Auth.self, List.self, Install.self, Launch.self])++ struct Login: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Print the Epic sign-in URL; paste the code it gives you into 'highball epic auth <code>'.")+ func run() async throws {+ let store = EpicStore()+ _ = try await store.ensureInstalled()+ print("1. Open: \(EpicStore.loginURL.absoluteString)")+ print("2. Sign in with your Epic account; the page shows an authorizationCode.")+ print("3. Run: highball epic auth <that code>")+ }+ }++ struct Auth: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Finish sign-in with the code from the login page.")+ @Argument var code: String+ func run() async throws {+ let store = EpicStore()+ _ = try await store.ensureInstalled()+ try store.authenticate(code: code)+ print(store.isAuthenticated ? "signed in" : "sign-in did not complete — try 'highball epic login' again")+ }+ }++ struct List: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "List the account's games (Windows builds).")+ func run() async throws {+ let store = EpicStore()+ _ = try await store.ensureInstalled()+ guard store.isAuthenticated else { fail("not signed in — run 'highball epic login' first") }+ let installed = Set((try? store.installedGames())?.map(\.app_name) ?? [])+ for g in try store.ownedGames().sorted(by: { $0.app_title < $1.app_title }) {+ print("\(installed.contains(g.app_name) ? "[installed] " : "")\(g.app_name)\t\(g.app_title)")+ }+ }+ }++ struct Install: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Install a game's Windows build into a bottle (drive_c/Games).")+ @Argument var bottle: String+ @Argument(help: "App name from 'highball epic list'.") var app: String+ func run() async throws {+ let store = EpicStore()+ _ = try await store.ensureInstalled()+ guard store.isAuthenticated else { fail("not signed in — run 'highball epic login' first") }+ let b = try BottleStore().get(bottle)+ let status = try store.install(app, into: b) { print($0) }+ guard status == 0 else { fail("legendary install exited with \(status)") }+ print("installed \(app) into \(b.name)")+ }+ }++ struct Launch: AsyncParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Launch an installed Epic game in a bottle through Wine.")+ @Argument var bottle: String+ @Argument var app: String+ @Option var renderer: HighballKit.Renderer?+ @Flag(help: "Skip Epic online auth (for games that allow offline play).") var offline = false+ func run() async throws {+ let store = EpicStore()+ _ = try await store.ensureInstalled()+ let b = try BottleStore().get(bottle)+ let eng = try EngineStore().engine(b.settings.engineID)+ let info = try store.launchInfo(app, offline: offline)+ let runner = WineRunner(engine: eng, bottle: b)+ let result = try await runner.start(info.executable, arguments: info.arguments,+ renderer: renderer, extraEnvironment: info.environment,+ workingDirectory: info.workingDirectory)+ print("exit=\(result.exitStatus) — log: \(result.log.path)")+ }+ }+}+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 {