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
Launches adopt the running wineserver's sync mode; the Steam tile shows a running client
Gauthier Piarretteb1aef3d74ca7
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 823a323..0c27ac8 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -451,6 +451,14 @@ final class AppState {cleanup: { [weak self] in self?.launchingPins.remove(pin.id) }) { [self] inlet runner = WineRunner(paths: paths, engine: engine, bottle: bottle)var extra = [String: String]()+ // A Steam client left running by a game launch answers a new steam.exe by swallowing+ // it (issue #33). Ask it to show its window instead, and leave the wineserver alone:+ // a game may still be running under it.+ if isSteamUI(pin), let shown = try await runner.showRunningSteam(onOutput: { line in Task { @MainActor in self.appendLog(line) } }) {+ await MainActor.run { self.appendLog("Steam was already running; asked it to show its window") }+ if shown.crashedEarly { /* the forward exits at once by design; not a crash */ }+ return+ }if isSteamUI(pin), bottle.settings.sync != SyncMode.none {try? runner.kill() // restart the wineserver so sync=none takes effecttry? await Task.sleep(for: .seconds(2))diff --git a/Sources/HighballKit/Bottle.swift b/Sources/HighballKit/Bottle.swiftindex 176c97b..fa459a5 100644--- a/Sources/HighballKit/Bottle.swift+++ b/Sources/HighballKit/Bottle.swift@@ -82,6 +82,23 @@ public enum WindowsVersion: String, Codable, CaseIterable, Sendable {public enum SyncMode: String, Codable, CaseIterable, Sendable {case none, esync, msync++ /// The mode a Wine environment selects: msync wins, then esync, else none.+ public init(environment env: [String: String]) {+ if env["WINEMSYNC"] == "1" { self = .msync }+ else if env["WINEESYNC"] == "1" { self = .esync }+ else { self = .none }+ }++ /// The two variables that select this mode. Both are always set: Wine treats an unset+ /// WINEMSYNC as on for msync-capable builds, so "off" has to be explicit.+ public var environment: [String: String] {+ switch self {+ case .none: return ["WINEMSYNC": "0", "WINEESYNC": "0"]+ case .esync: return ["WINEMSYNC": "0", "WINEESYNC": "1"]+ case .msync: return ["WINEMSYNC": "1", "WINEESYNC": "0"]+ }+ }}/// A pinned program inside a bottle.diff --git a/Sources/HighballKit/ProcessTable.swift b/Sources/HighballKit/ProcessTable.swiftindex cfefade..84b13e3 100644--- a/Sources/HighballKit/ProcessTable.swift+++ b/Sources/HighballKit/ProcessTable.swift@@ -70,6 +70,55 @@ public enum ProcessTable {}}+ /// Command line and environment of a process we own, from `KERN_PROCARGS2`. Nil when the+ /// kernel refuses (not ours, restricted) or the process is gone. The environment comes back+ /// empty for Apple platform binaries (`/bin/sleep`, `/bin/sh`); Wine's binaries are not+ /// platform binaries, so theirs is readable.+ public static func commandLineAndEnvironment(of pid: pid_t) -> (arguments: [String], environment: [String: String])? {+ var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]+ var size = 0+ guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > MemoryLayout<Int32>.size else { return nil }+ var buf = [UInt8](repeating: 0, count: size)+ guard sysctl(&mib, 3, &buf, &size, nil, 0) == 0 else { return nil }+ let argc = Int(buf.withUnsafeBytes { $0.load(as: Int32.self) })+ let strings = buf[MemoryLayout<Int32>.size...].split(separator: 0, omittingEmptySubsequences: true)+ .map { String(decoding: $0, as: UTF8.self) }+ guard strings.count >= 1 + argc else { return nil }+ // Layout: executable path, argv[0..argc), then the environment.+ let arguments = Array(strings[1..<(1 + argc)])+ var environment: [String: String] = [:]+ for entry in strings.dropFirst(1 + argc) {+ guard let eq = entry.firstIndex(of: "=") else { continue }+ environment[String(entry[..<eq])] = String(entry[entry.index(after: eq)...])+ }+ return (arguments, environment)+ }++ /// The wineserver currently serving a prefix, if one runs: its working directory is the+ /// prefix's server directory.+ public static func liveServer(forPrefix prefix: URL) -> pid_t? {+ guard let server = serverDirectory(forPrefix: prefix).map({ canonical($0.path) }) else { return nil }+ let me = getpid()+ return allPIDs().first { pid in+ guard pid != me, let cwd = workingDirectory(of: pid) else { return false }+ return canonical(cwd) == server+ }+ }++ /// The sync mode a running wineserver was started with, read from its environment. Wine+ /// fixes the mode when the server starts, and a client started with a different one dies at+ /// `msync_init` ("Failed to open msync shared memory file", issue #32). Nil when no server+ /// runs or its environment cannot be read.+ public static func liveServerSync(forPrefix prefix: URL) -> SyncMode? {+ guard let pid = liveServer(forPrefix: prefix),+ let env = commandLineAndEnvironment(of: pid)?.environment,+ // The kernel hides the environment of Apple platform binaries; Wine's server is not+ // one, and Highball always sets both variables, so their absence means "unknown",+ // never "off".+ env["WINEMSYNC"] != nil || env["WINEESYNC"] != nil else { return nil }+ return SyncMode(environment: env)+ }+/// Ends the given processes: SIGTERM, a grace period, then SIGKILL for whatever is left./// Returns the ids that had to be killed the hard way.@discardableResultdiff --git a/Sources/HighballKit/WineRunner.swift b/Sources/HighballKit/WineRunner.swiftindex d2b85c3..5bc5da4 100644--- a/Sources/HighballKit/WineRunner.swift+++ b/Sources/HighballKit/WineRunner.swift@@ -106,7 +106,16 @@ public struct WineRunner: Sendable {// [csgo.exe], issue #21) — refresh it before the spawn. Every renderer but wined3d gets// DXVK's d3d9 attached, so every one of them needs the conf, not just .dxvk.if (renderer ?? bottle.settings.renderer) != .wined3d { try? bottle.writeDxvkConfig() }- let env = try bottle.environment(engine: engine, renderer: renderer, extra: extraEnvironment)+ var env = try bottle.environment(engine: engine, renderer: renderer, extra: extraEnvironment)+ // Wine fixes the sync mode when the prefix's wineserver starts; a process started with a+ // different one dies at msync_init before doing anything (issue #32: a registry write+ // "succeeding" in 0 s while a Steam window, cold-started with sync off, was open). So a+ // launch that joins a running server takes that server's mode, whatever the bottle or+ // the caller asked for; the bottle's setting applies to the next cold start. The header+ // below records the adoption ("bottle asks ...").+ if let live = ProcessTable.liveServerSync(forPrefix: bottle.url), live != SyncMode(environment: env) {+ env.merge(live.environment) { $1 }+ }let stamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: "")let logURL = Self.uniqueLogURL(in: paths.logs, named: "\(stamp)-\(bottle.name)-\(label ?? args.first ?? "wine")")FileManager.default.createFile(atPath: logURL.path, contents: nil)@@ -296,6 +305,33 @@ public struct WineRunner: Sendable {/// ends whatever is still attached to the prefix. Returns the process ids it had to end/// itself, which is normally none (see `ProcessTable` for why it is not always none).@discardableResult+ /// Whether a Steam client already runs in this bottle, by its command line.+ public func steamIsRunning() -> Bool {+ ProcessTable.processes(ofPrefix: bottle.url).contains { pid in+ guard let first = ProcessTable.commandLineAndEnvironment(of: pid)?.arguments.first else { return false }+ return Self.isSteamExecutable(first)+ }+ }++ /// Pure: does a command line's program name end in steam.exe (Windows or Unix separators).+ public static func isSteamExecutable(_ argv0: String) -> Bool {+ argv0.replacingOccurrences(of: "\\", with: "/").lowercased().hasSuffix("/steam.exe")+ }++ /// If a Steam client is already running in the bottle, asks it to show its window and+ /// returns that launch; nil when no client runs (the caller then starts one).+ ///+ /// After a game launch (`steam -silent -applaunch`) the silent client stays up. Starting+ /// steam.exe again then only forwards to that instance and exits: no window, no error,+ /// a dead button (issue #33). `steam://open/main` forwarded the same way makes the running+ /// instance open its window, without restarting the wineserver under a game that may still+ /// be running. Verified 2026-09-03: silent instance, open/main, Steam window up in seconds.+ public func showRunningSteam(onOutput: (@Sendable (String) -> Void)? = nil) async throws -> LaunchResult? {+ guard steamIsRunning() else { return nil }+ let steam = bottle.driveC.appending(path: "Program Files (x86)/Steam/steam.exe")+ return try await start(steam, arguments: ["steam://open/main"], onOutput: onOutput)+ }+public func kill() throws -> [pid_t] {let env = try bottle.environment(engine: engine, renderer: .wined3d)// `-k` fails when no server holds the lock, which is exactly the crashed-server casediff --git a/Sources/highball/main.swift b/Sources/highball/main.swiftindex 4d82c74..be87be2 100644--- a/Sources/highball/main.swift+++ b/Sources/highball/main.swift@@ -328,7 +328,12 @@ struct Run: AsyncParsableCommand {if let renderer { p.renderer = renderer }p.arguments += argumentsif p.path.lowercased().hasSuffix("steam/steam.exe") {- result = try await runner.startResumingKnownSteamCrash(pin: p, onOutput: out ?? { _ in }).result+ if let shown = try await runner.showRunningSteam(onOutput: out) {+ print("Steam is already running in this bottle; asked it to show its window")+ result = shown+ } else {+ result = try await runner.startResumingKnownSteamCrash(pin: p, onOutput: out ?? { _ in }).result+ }} else {result = try await runner.start(pin: p, onOutput: out)}@@ -349,7 +354,15 @@ struct Run: AsyncParsableCommand {result = try await runner.run([program] + arguments, renderer: renderer, label: program, onOutput: out)}print("exit=\(result.exitStatus) after \(Int(result.duration))s — log: \(result.log.path)")- if result.crashedEarly { print("hint: exited within 10 s; try another renderer (--renderer dxmt|d3dmetal|dxvk|wined3d)") }+ if result.crashedEarly {+ // A sync-mode mismatch with the running wineserver kills the process before it does+ // anything (issue #32); it has nothing to do with renderers, so say what it is.+ if let log = try? String(contentsOf: result.log, encoding: .utf8), log.contains("msync_init") || log.contains("esync_init") {+ print("hint: died joining the bottle's running wineserver with a different sync mode; stop the bottle (highball bottle kill \(b.name)) and retry")+ } else {+ print("hint: exited within 10 s; try another renderer (--renderer dxmt|d3dmetal|dxvk|wined3d)")+ }+ }}}diff --git a/Tests/HighballKitTests/RegressionTests.swift b/Tests/HighballKitTests/RegressionTests.swiftindex af46254..9f75a85 100644--- a/Tests/HighballKitTests/RegressionTests.swift+++ b/Tests/HighballKitTests/RegressionTests.swift@@ -629,6 +629,59 @@ extension RegressionTests {"server-\(String(UInt64(st.st_dev), radix: 16))-\(String(st.st_ino, radix: 16))")}+ // Wine fixes the sync mode when a prefix's wineserver starts, and a client started with a+ // different one dies at msync_init before doing anything (issue #32: `bottle set winver`+ // reported ok while a Steam window, cold-started with sync off, was open). A launch now reads+ // the running server's environment and adopts its mode. The reader is exercised on a real+ // process with a known environment; the mode mapping and its inverse are pure.+ func testSyncModeFollowsTheRunningServersEnvironment() throws {+ XCTAssertEqual(SyncMode(environment: ["WINEMSYNC": "1", "WINEESYNC": "0"]), .msync)+ XCTAssertEqual(SyncMode(environment: ["WINEMSYNC": "0", "WINEESYNC": "1"]), .esync)+ XCTAssertEqual(SyncMode(environment: ["WINEMSYNC": "0", "WINEESYNC": "0"]), SyncMode.none)+ XCTAssertEqual(SyncMode(environment: [:]), SyncMode.none, "unset means off for a launch we control")+ for mode in SyncMode.allCases { XCTAssertEqual(SyncMode(environment: mode.environment), mode) }++ // The kernel hides the environment of Apple platform binaries, so the child is an+ // unsigned copy of sleep, which is what a Wine binary looks like to the kernel.+ let dir = FileManager.default.temporaryDirectory.appending(path: "hb-env-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }+ let sleeper = dir.appending(path: "sleeper")+ try FileManager.default.copyItem(at: URL(fileURLWithPath: "/bin/sleep"), to: sleeper)+ let strip = Process(); strip.executableURL = URL(fileURLWithPath: "/usr/bin/codesign")+ strip.arguments = ["--remove-signature", sleeper.path]; try strip.run(); strip.waitUntilExit()+ let p = Process()+ p.executableURL = sleeper; p.arguments = ["30"]+ p.environment = ["WINEMSYNC": "0", "WINEESYNC": "0", "HB_TEST_MARKER": "yes"]+ try p.run(); defer { p.terminate() }+ let read = try XCTUnwrap(ProcessTable.commandLineAndEnvironment(of: p.processIdentifier))+ XCTAssertEqual(read.arguments, [sleeper.path, "30"])+ XCTAssertEqual(read.environment["HB_TEST_MARKER"], "yes")+ XCTAssertEqual(SyncMode(environment: read.environment), SyncMode.none)++ // A platform binary's environment is hidden: the reader must not invent one.+ let platform = Process(); platform.executableURL = URL(fileURLWithPath: "/bin/sleep"); platform.arguments = ["30"]+ platform.environment = ["WINEMSYNC": "1"]; try platform.run(); defer { platform.terminate() }+ let hidden = try XCTUnwrap(ProcessTable.commandLineAndEnvironment(of: platform.processIdentifier))+ XCTAssertNil(hidden.environment["WINEMSYNC"], "platform binaries hide their environment; adoption must treat that as unknown")++ let prefix = FileManager.default.temporaryDirectory.appending(path: "hb-nosrv-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: prefix, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: prefix) }+ XCTAssertNil(ProcessTable.liveServer(forPrefix: prefix), "no wineserver runs for a fresh temp prefix")+ XCTAssertNil(ProcessTable.liveServerSync(forPrefix: prefix))+ }++ // The Steam tile must recognise a running client by its command line, with either path+ // separator, and not mistake helpers for it (issue #33).+ func testSteamExecutableIsRecognisedByCommandLine() {+ XCTAssertTrue(WineRunner.isSteamExecutable(#"C:\Program Files (x86)\Steam\steam.exe"#))+ XCTAssertTrue(WineRunner.isSteamExecutable("/x/drive_c/Program Files (x86)/Steam/Steam.exe"))+ XCTAssertFalse(WineRunner.isSteamExecutable(#"C:\Program Files (x86)\Steam\bin\cef\cef.win64\steamwebhelper.exe"#))+ XCTAssertFalse(WineRunner.isSteamExecutable(#"C:\windows\system32\services.exe"#))+ XCTAssertFalse(WineRunner.isSteamExecutable("steam.exe.bak"))+ }+func testRendererSuggestionCyclesAndNeverSuggestsItself() {for r in Renderer.allCases {XCTAssertNotEqual(Renderer.suggestion(after: r), r)