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
Engine switch: one busy sheet, fresh bottle read, strict source engine, shared prefix refresh
Gauthier Piarrettef96d83289473
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 905935c..a4f43d5 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -44,8 +44,7 @@ final class AppState {// Crash follow-upvar crashSuggestion: CrashSuggestion?- struct CrashSuggestion: Identifiable {- let id = UUID()+ struct CrashSuggestion {let program: String/// The bottle that was actually launched. The alert used to edit `selectedBottle`, which/// `launchGame` never sets — so accepting could rewrite an unrelated bottle, or none.@@ -257,8 +256,9 @@ final class AppState {}/// The engine new bottles get and the sidebar shows: the one the bundled manifest names when- /// it is installed, else the first installed. Without this, an engine update would leave- /// two engines side by side and `engines.first` (alphabetical) would keep picking the old one.+ /// it is installed, else the newest installed (numeric-aware id order). Without this, an+ /// engine update would leave two engines side by side and `engines.first` would keep+ /// picking the old one.var defaultEngine: InstalledEngine? {EngineStore.defaultEngine(installed: engines, bundledID: Self.bundledManifestID)}@@ -315,7 +315,8 @@ final class AppState {}let referenced = Set(try bottleStore.list().map(\.settings.engineID))let installed = try engineStore.installedEngines()- for stale in EngineStore.unreferencedEngines(installed: installed, referencedIDs: referenced, defaultID: fresh.id) {+ let offered = Set(Self.knownManifests.map(\.id))+ for stale in EngineStore.unreferencedEngines(installed: installed, referencedIDs: referenced, defaultID: fresh.id, keep: offered) {try? FileManager.default.removeItem(at: stale.root)await MainActor.run { self.appendLog("old engine \(stale.id) removed (no bottle uses it)") }}@@ -329,32 +330,38 @@ final class AppState {/// first boot only when the Wine build differs (the same rule as an engine update), then the/// per-bottle setup that boot resets. Switching back is the same call the other way.func moveBottle(_ bottle: Bottle, to target: InstalledEngine) {- guard bottle.settings.engineID != target.id, let current = engine(for: bottle) else { return }+ guard bottle.settings.engineID != target.id, !busy else { return }let title = String(format: L("Moving '%@' to %@"), bottle.name, target.id)runBusy(title, expected: L("a minute or two when the Windows setup re-runs"),done: DoneState(title: L("Engine switched"), ctaTitle: nil, cta: nil)) { [self] in- var bottle = bottle- let runnerOld = WineRunner(paths: paths, engine: current, bottle: bottle)+ try await performMove(bottle, to: target)+ }+ }++ /// The move itself, shared by the two entry points and run inside their single busy sheet.+ /// The bottle is re-read from disk right before the write: the caller's copy may be minutes+ /// old (an engine download ran in between) and saving it would revert edits made meanwhile.+ /// The source engine is resolved strictly: when its directory is gone, nothing is known+ /// about the Wine that built the prefix, so the prefix is refreshed.+ private func performMove(_ stale: Bottle, to target: InstalledEngine) async throws {+ guard var bottle = try? bottleStore.get(stale.name) else { throw HighballError.invalid("bottle '\(stale.name)' no longer exists") }+ guard bottle.settings.engineID != target.id else { return }+ let source = try? engineStore.engine(bottle.settings.engineID)+ if let source {+ let runnerOld = WineRunner(paths: paths, engine: source, bottle: bottle)try? runnerOld.kill()try? await Task.sleep(for: .seconds(2))- bottle.settings.engineID = target.id- try bottle.save()- guard EngineManifest.needsPrefixRefresh(from: current.manifest, to: target.manifest) else {- await MainActor.run { self.appendLog("bottle '\(bottle.name)' moved to \(target.id) (same Wine, no prefix refresh needed)") }- return- }- await MainActor.run { self.stage = String(format: L("Refreshing bottle '%@'"), bottle.name) }- let runner = WineRunner(paths: paths, engine: target, bottle: bottle)- let r = try await runner.wineboot()- guard r.exitStatus == 0 else {- throw HighballError.processFailed(command: "wineboot -u", status: r.exitStatus, output: "see \(r.log.path)")- }- try await BottleStore.ensureWoW64(runner: runner, bottle: bottle, log: r.log)- try? await runner.setGpuIdentity()- try? await runner.setServiceTimeout()- try? await runner.setKeyboardMapping(commandIsControl: bottle.settings.commandIsControl)- await MainActor.run { self.appendLog("bottle '\(bottle.name)' moved to \(target.id)") }}+ bottle.settings.engineID = target.id+ try bottle.save()+ guard EngineManifest.needsPrefixRefresh(from: source?.manifest, to: target.manifest) else {+ await MainActor.run { self.appendLog("bottle '\(bottle.name)' moved to \(target.id) (same Wine, no prefix refresh needed)") }+ return+ }+ await MainActor.run { self.stage = String(format: L("Refreshing bottle '%@'"), bottle.name) }+ let runner = WineRunner(paths: paths, engine: target, bottle: bottle)+ try await BottleStore.refreshPrefix(runner: runner, bottle: bottle)+ await MainActor.run { self.appendLog("bottle '\(bottle.name)' moved to \(target.id)") }}/// What to put in front of the user when something throws. Interpolating an NSError dumps@@ -387,6 +394,9 @@ final class AppState {private func runBusy(_ title: String, expected: String? = nil, showLogSheet: Bool = true,done: DoneState? = nil, cleanup: (() -> Void)? = nil,_ work: @escaping () async throws -> Void) {+ // One busy operation at a time: a second call would reset the sheet's state under the+ // first and end it early when the second finishes (found in review, 2026-09-04).+ guard !busy else { return }busy = true; busyTitle = title; stage = ""; stageHint = ""; logLines = []; showLog = showLogSheetbusyStartedAt = Date(); busyExpected = expected; lastOutputAt = nil; doneState = nilTask {@@ -672,15 +682,9 @@ final class AppState {let runner = WineRunner(paths: paths, engine: engine, bottle: bottle)try? runner.kill()try? await Task.sleep(for: .seconds(2))- let r = try await runner.wineboot()- guard r.exitStatus == 0 else {- throw HighballError.processFailed(command: "wineboot -u", status: r.exitStatus, output: "see \(r.log.path)")- }- // Repair is the escape hatch for a bottle whose 32-bit half never got built (#37).- try await BottleStore.ensureWoW64(runner: runner, bottle: bottle, log: r.log)- try? await runner.setGpuIdentity()- try? await runner.setServiceTimeout()- try? await runner.setKeyboardMapping(commandIsControl: bottle.settings.commandIsControl)+ // Repair is the escape hatch for a bottle whose 32-bit half never got built (#37);+ // refreshPrefix carries that check.+ try await BottleStore.refreshPrefix(runner: runner, bottle: bottle)await MainActor.run { self.appendLog("bottle repaired — Windows environment refreshed") }}}@@ -836,19 +840,20 @@ final class AppState {}/// What the bottle's Engine picker lists: installed engines, then known ones to download.- var offeredEngines: [EngineStore.OfferedEngine] {- EngineStore.offeredEngines(installed: engines, known: Self.knownManifests)+ func offeredEngines(for bottle: Bottle) -> [EngineStore.OfferedEngine] {+ EngineStore.offeredEngines(installed: engines, known: Self.knownManifests, current: bottle.settings.engineID)}/// Moves a bottle to an engine by id, installing it first when it is only known from a/// bundled manifest. Licenses accepted on any installed engine carry over.func moveBottle(_ bottle: Bottle, toEngineID id: String) {+ guard !busy else { return }if let installed = engines.first(where: { $0.id == id }) { moveBottle(bottle, to: installed); return }guard let manifest = Self.knownManifests.first(where: { $0.id == id }) else { return }let accepted = Set(engines.flatMap { $0.manifest.acceptedLicenses ?? [] })let title = String(format: L("Downloading engine %@"), manifest.id)runBusy(title, expected: L("usually a few minutes"),- done: DoneState(title: L("Engine installed"), ctaTitle: nil, cta: nil)) { [self] in+ done: DoneState(title: L("Engine switched"), ctaTitle: nil, cta: nil)) { [self] inlet fresh = try await engineStore.install(manifest, accepted: accepted) { name, received, total inTask { @MainActor inlet mb = { (b: Int64) in String(format: "%.0f", Double(b) / 1_048_576) }@@ -856,11 +861,8 @@ final class AppState {else { self.stage = "Downloading \(name) — \(mb(received)) MB" }}}- await MainActor.run {- self.appendLog("engine \(fresh.id) installed")- self.refresh()- self.moveBottle(bottle, to: fresh)- }+ await MainActor.run { self.appendLog("engine \(fresh.id) installed"); self.refresh() }+ try await performMove(bottle, to: fresh)}}diff --git a/Sources/HighballApp/BottleView.swift b/Sources/HighballApp/BottleView.swiftindex 8964df1..8d28ad0 100644--- a/Sources/HighballApp/BottleView.swift+++ b/Sources/HighballApp/BottleView.swift@@ -372,17 +372,21 @@ struct BottleSettingsSheet: View {.font(.caption).foregroundStyle(.secondary)}Section(L("Advanced")) {- let offered = state.offeredEngines+ let offered = state.offeredEngines(for: state.bottles.first { $0.name == bottle.name } ?? bottle)if offered.count > 1 {Picker(L("Engine"), selection: Binding(get: { (state.bottles.first { $0.name == bottle.name } ?? bottle).settings.engineID },set: { newID in- state.moveBottle(state.bottles.first { $0.name == bottle.name } ?? bottle, toEngineID: newID)+ let current = state.bottles.first { $0.name == bottle.name } ?? bottle+ guard newID != current.settings.engineID else { return }+ dismiss() // the move runs in the busy sheet; two sheets on one window do not stack+ state.moveBottle(current, toEngineID: newID)})) {ForEach(offered, id: \.id) { e in- Text(verbatim: e.installed ? e.id : "\(e.id) (\(L("download")))").tag(e.id)+ Text(verbatim: e.missing ? "\(e.id) (\(L("missing")))" : e.installed ? e.id : "\(e.id) (\(L("download")))").tag(e.id)}}+ .disabled(state.busy)Text(L("Bottles never change engine on their own. Switching re-runs the Windows setup when the Wine build differs; switching back is the same step. An engine marked download is fetched first.")).font(.caption).foregroundStyle(.secondary)}diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex e7cc954..8364671 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -236,7 +236,7 @@ struct ContentView: View {}.buttonStyle(.plain).disabled(state.busy)- .help(L("Installs the newer engine this version of Highball ships, moves every bottle to it and refreshes their Windows environment. Only changed components are downloaded."))+ .help(L("Installs the newer engine this version of Highball ships. Bottles on the same Wine build move to it; the others stay on their engine until you switch them in the bottle's settings. Only changed components are downloaded."))}}}diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex e6a8d0d..d5810fe 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -11,7 +11,8 @@ enum L10n {static let fr: [String: String] = [// Sidebar & shell"Update engine": "Mettre à jour le moteur",- "Installs the newer engine this version of Highball ships, moves every bottle to it and refreshes their Windows environment. Only changed components are downloaded.": "Installe le moteur plus récent livré avec cette version de Highball, y déplace chaque bouteille et rafraîchit leur environnement Windows. Seuls les composants modifiés sont téléchargés.",+ "Installs the newer engine this version of Highball ships. Bottles on the same Wine build move to it; the others stay on their engine until you switch them in the bottle's settings. Only changed components are downloaded.": "Installe le moteur plus récent livré avec cette version de Highball. Les bouteilles sur la même version de Wine y passent ; les autres gardent leur moteur jusqu'à ce que vous le changiez dans les réglages de la bouteille. Seuls les composants modifiés sont téléchargés.",+ "missing": "absent","Updating engine to %@": "Mise à jour du moteur vers %@","usually a few minutes": "généralement quelques minutes","Engine updated": "Moteur mis à jour",@@ -177,6 +178,13 @@ enum L10n {"Details": "Détails","Run and add to Programs": "Lancer et ajouter aux programmes","Keep current": "Garder l’actuel",+ "download": "téléchargement",+ "Try engine %@": "Essayer le moteur %@",+ "Moving '%@' to %@": "Déplacement de '%@' vers %@",+ "a minute or two when the Windows setup re-runs": "une minute ou deux si la configuration Windows est relancée",+ "Engine switched": "Moteur changé",+ "Downloading engine %@": "Téléchargement du moteur %@",+ "Bottles never change engine on their own. Switching re-runs the Windows setup when the Wine build differs; switching back is the same step. An engine marked download is fetched first.": "Une bouteille ne change jamais de moteur toute seule. Changer relance la configuration Windows si la version de Wine diffère ; revenir en arrière est la même étape. Un moteur marqué téléchargement est d'abord récupéré.","Accept & enable D3DMetal": "Accepter et activer D3DMetal","Non-commercial use only · no modification · Apple hardware only":"Usage non commercial uniquement · aucune modification · matériel Apple uniquement",diff --git a/Sources/HighballKit/BottleStore.swift b/Sources/HighballKit/BottleStore.swiftindex 7f794cb..3bafe6c 100644--- a/Sources/HighballKit/BottleStore.swift+++ b/Sources/HighballKit/BottleStore.swift@@ -91,6 +91,21 @@ public struct BottleStore: Sendable {return bottle}+ /// Re-runs the Windows first boot on an existing bottle and the per-bottle setup that boot+ /// resets: the 32-bit half check (#37), the GPU identity, the service timeout and the+ /// keyboard mapping. Repair, an engine switch and the CLI's repair all go through here;+ /// bottle creation keeps its own sequence because it also discards a half-built bottle.+ public static func refreshPrefix(runner: WineRunner, bottle: Bottle) async throws {+ let r = try await runner.wineboot()+ guard r.exitStatus == 0 else {+ throw HighballError.processFailed(command: "wineboot -u", status: r.exitStatus, output: "see \(r.log.path)")+ }+ try await ensureWoW64(runner: runner, bottle: bottle, log: r.log)+ try? await runner.setGpuIdentity()+ try? await runner.setServiceTimeout()+ try? await runner.setKeyboardMapping(commandIsControl: bottle.settings.commandIsControl)+ }+/// The 32-bit half of a prefix, and whether it is actually there.////// Wine populates `syswow64` by launching a 32-bit rundll32 for the inf's Wow64Installdiff --git a/Sources/HighballKit/EngineStore.swift b/Sources/HighballKit/EngineStore.swiftindex 8719a54..1e7cdbe 100644--- a/Sources/HighballKit/EngineStore.swift+++ b/Sources/HighballKit/EngineStore.swift@@ -57,11 +57,13 @@ public struct EngineStore: Sendable {?? installed.max { $0.id.compare($1.id, options: .numeric) == .orderedAscending }}- /// Engines nothing references any more: not the default and not the engine of any bottle.+ /// Engines nothing references any more: not the default, not the engine of any bottle, and+ /// not one the app still offers (`keep`: the bundled manifests, so an engine someone+ /// downloaded for rollback survives the next update even with no bottle on it right now)./// An engine update never removes an engine a bottle still runs on; a bottle keeps its/// engine until its owner switches it (per-bottle choice, not migration).- public static func unreferencedEngines(installed: [InstalledEngine], referencedIDs: Set<String>, defaultID: String?) -> [InstalledEngine] {- installed.filter { $0.id != defaultID && !referencedIDs.contains($0.id) }+ public static func unreferencedEngines(installed: [InstalledEngine], referencedIDs: Set<String>, defaultID: String?, keep: Set<String> = []) -> [InstalledEngine] {+ installed.filter { $0.id != defaultID && !referencedIDs.contains($0.id) && !keep.contains($0.id) }}/// The engine to offer when a program fails on `currentID`: the default engine when the@@ -75,20 +77,24 @@ public struct EngineStore: Sendable {/// One row per engine the app can put a bottle on: every installed engine, then every/// bundled manifest that is not installed yet (it downloads when chosen). Newest first- /// within each group, by numeric-aware id order.+ /// within each group, by numeric-aware id order. When the bottle's own engine is in+ /// neither list (its directory is gone), it is appended as a `missing` row so the picker+ /// still shows what the bottle is on instead of a blank selection.public struct OfferedEngine: Equatable, Sendable {public let id: String- public let displayName: Stringpublic let installed: Bool- public init(id: String, displayName: String, installed: Bool) { self.id = id; self.displayName = displayName; self.installed = installed }+ public let missing: Bool+ public init(id: String, installed: Bool, missing: Bool = false) { self.id = id; self.installed = installed; self.missing = missing }}- public static func offeredEngines(installed: [InstalledEngine], known: [EngineManifest]) -> [OfferedEngine] {+ public static func offeredEngines(installed: [InstalledEngine], known: [EngineManifest], current: String? = nil) -> [OfferedEngine] {let newestFirst: (String, String) -> Bool = { $0.compare($1, options: .numeric) == .orderedDescending }- let have = installed.sorted { newestFirst($0.id, $1.id) }.map { OfferedEngine(id: $0.id, displayName: $0.displayName, installed: true) }+ let have = installed.sorted { newestFirst($0.id, $1.id) }.map { OfferedEngine(id: $0.id, installed: true) }let ids = Set(have.map(\.id))let more = known.filter { !ids.contains($0.id) }.sorted { newestFirst($0.id, $1.id) }- .map { OfferedEngine(id: $0.id, displayName: $0.displayName, installed: false) }- return have + more+ .map { OfferedEngine(id: $0.id, installed: false) }+ var rows = have + more+ if let current, !rows.contains(where: { $0.id == current }) { rows.append(OfferedEngine(id: current, installed: false, missing: true)) }+ return rows}public func engine(_ id: String) throws -> InstalledEngine {diff --git a/Sources/HighballKit/Manifest.swift b/Sources/HighballKit/Manifest.swiftindex c544755..506325f 100644--- a/Sources/HighballKit/Manifest.swift+++ b/Sources/HighballKit/Manifest.swift@@ -77,6 +77,13 @@ public struct EngineManifest: Codable, Sendable, Identifiable {return a != b}+ /// Same rule when the bottle's current engine cannot be resolved (its directory is gone):+ /// nothing is known about the Wine that built the prefix, so it is refreshed.+ public static func needsPrefixRefresh(from old: EngineManifest?, to new: EngineManifest) -> Bool {+ guard let old else { return true }+ return needsPrefixRefresh(from: old, to: new)+ }+public var orderedComponents: [(name: String, component: Component)] {components.sorted { a, b inif a.value.isOptional != b.value.isOptional { return !a.value.isOptional }diff --git a/Sources/highball/main.swift b/Sources/highball/main.swiftindex f1830ae..27f6e2d 100644--- a/Sources/highball/main.swift+++ b/Sources/highball/main.swift@@ -197,14 +197,10 @@ struct Bottle: AsyncParsableCommand {let runner = WineRunner(engine: eng, bottle: b)try? runner.kill()try? await Task.sleep(for: .seconds(2))- let r = try await runner.wineboot()- try? await runner.setGpuIdentity()- try? await runner.setServiceTimeout()- try? await runner.setKeyboardMapping(commandIsControl: b.settings.commandIsControl)- // Same 32-bit check the app and bottle creation use (#37): wineboot exits 0 even- // when it skipped building syswow64, so the exit code alone means little.- try await BottleStore.ensureWoW64(runner: runner, bottle: b, log: r.log)- print(r.exitStatus == 0 ? "repaired \(name)" : "wineboot exited with \(r.exitStatus) — see \(r.log.path)")+ // The same sequence the app's Repair and an engine switch use, 32-bit check included+ // (#37): wineboot exits 0 even when it skipped building syswow64.+ try await BottleStore.refreshPrefix(runner: runner, bottle: b)+ print("repaired \(name)")}}diff --git a/Tests/HighballKitTests/RegressionTests.swift b/Tests/HighballKitTests/RegressionTests.swiftindex 955ed48..fe2f33b 100644--- a/Tests/HighballKitTests/RegressionTests.swift+++ b/Tests/HighballKitTests/RegressionTests.swift@@ -858,6 +858,8 @@ extension RegressionTests {"every old engine still has a bottle: nothing is removed")XCTAssertEqual(EngineStore.unreferencedEngines(installed: all, referencedIDs: [], defaultID: r2.id).map(\.id), [r0.id, r1.id])XCTAssertEqual(EngineStore.unreferencedEngines(installed: all, referencedIDs: [], defaultID: nil).map(\.id), all.map(\.id))+ XCTAssertEqual(EngineStore.unreferencedEngines(installed: all, referencedIDs: [], defaultID: r2.id, keep: [r1.id]).map(\.id), [r0.id],+ "an engine the app still offers (bundled manifest) is kept for rollback even with no bottle on it")}// The crash alert's second way out: the default engine when the bottle is not on it, else the@@ -872,6 +874,9 @@ extension RegressionTests {XCTAssertEqual(EngineStore.alternateEngine(for: r1.id, installed: [r1, r2], defaultID: r2.id)?.id, r2.id, "old bottle: offer the default")XCTAssertEqual(EngineStore.alternateEngine(for: r2.id, installed: [r1, r2], defaultID: r2.id)?.id, r1.id, "on the default: offer the previous engine")XCTAssertNil(EngineStore.alternateEngine(for: r1.id, installed: [r1], defaultID: r1.id), "single engine: nothing to offer")+ let r9 = try engine("x64-sikarugir10.0_6-r9"), r10 = try engine("x64-sikarugir10.0_6-r10")+ XCTAssertEqual(EngineStore.alternateEngine(for: r2.id, installed: [r9, r2, r10], defaultID: r2.id)?.id, r10.id,+ "on the default with two others: the newest by numeric order, r10 over r9")}// The Engine picker lists installed engines first, then known manifests to download, newest first.@@ -887,6 +892,10 @@ extension RegressionTests {XCTAssertEqual(offered.map(\.id), ["x64-a-r1", "x64-a-r0", "x64-a-r10", "x64-a-r2"])XCTAssertEqual(offered.map(\.installed), [true, true, false, false])XCTAssertEqual(EngineStore.offeredEngines(installed: [r1], known: [try manifest("x64-a-r1")]).count, 1, "the installed default is not listed twice")+ let withMissing = EngineStore.offeredEngines(installed: [r1], known: [], current: "x64-gone-r0")+ XCTAssertEqual(withMissing.map(\.id), ["x64-a-r1", "x64-gone-r0"], "a bottle on an engine that is gone still sees its own row")+ XCTAssertEqual(withMissing.last?.missing, true)+ XCTAssertEqual(EngineStore.offeredEngines(installed: [r1], known: [], current: r1.id).count, 1, "current engine present: no extra row")}func testDefaultEnginePrefersBundledManifestID() throws {@@ -918,6 +927,8 @@ extension RegressionTests {XCTAssertFalse(EngineManifest.needsPrefixRefresh(from: r0, to: r1), "same Wine: no wineboot")XCTAssertTrue(EngineManifest.needsPrefixRefresh(from: r0, to: r2), "Wine changed: wineboot")XCTAssertTrue(EngineManifest.needsPrefixRefresh(from: try manifest(nil, id: "x"), to: r1), "unknown: be safe, boot")+ XCTAssertTrue(EngineManifest.needsPrefixRefresh(from: nil, to: r1), "source engine gone: boot")+ XCTAssertFalse(EngineManifest.needsPrefixRefresh(from: Optional(r0), to: r1), "the optional overload keeps the same-Wine rule")}// A Play that auto-applies a recipe with environment or renderer steps must restart the