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
External Mac drives get Windows drive letters of their own, so Steam can offer them for a library. Wine gives a letter only to a volume macOS reports as removable media (mountmgr's diskarb.c), and external SSDs and hard drives report fixed media, so Steam listed none of them and a player with an exFAT drive could not install there (Discord, 2026-10-06). Before a program starts, each mounted external volume is linked to a free letter in the environment's dosdevices, and Wine reports it as a fixed disk, the kind Steam offers. A drive keeps its letter, since Steam records a library by its path: while it is away the link goes and the letter stays reserved, and it comes back the same even in another order. Letters Wine or the player made are left alone, and a volume a letter already reaches gets no second one. Windows lists drives through Wine's mount manager, which reads the links when the environment's server starts, so an idle environment restarts when a letter is added and a busy one shows it after its next start. Checked with Wine on an exFAT disk image: a linked letter listed by wmic as DriveType 3 with the volume's free space, a file written through it, letters released and restored. Seven tests. The launch log notes the letters it links. Also: a restart note no longer replaces the note before it
Gauthier Piarrette1d761b1da71e
diff --git a/Sources/HighballKit/Bottle.swift b/Sources/HighballKit/Bottle.swiftindex 7309e39..af821be 100644--- a/Sources/HighballKit/Bottle.swift+++ b/Sources/HighballKit/Bottle.swift@@ -414,6 +414,9 @@ public struct BottleSettings: Codable, Sendable {/// link. Applied to the prefix by `UserFolders`; the saves go with the environment when it/// is deleted, and the delete confirmation says so.public var keepFilesInside: Bool = false+ /// The drive letters Highball linked to external Mac drives (see `MacDrives`). A drive that is+ /// away keeps its letter here, so it comes back the same and Steam finds its library again.+ public var externalDrives: [MacDrives.Mapping] = []public var environment: [String: String] = [:]/// Variables a game's recipe sets for that one game's launches, keyed by the recipe's id (the/// db row's id). A recipe's environment step used to land in `environment` and reach every@@ -425,7 +428,7 @@ public struct BottleSettings: Codable, Sendable {public var recipes: [String] = []public var created: Date = Date()- enum CodingKeys: String, CodingKey { case formatVersion, name, engineID, renderer, rendererExplicit, windowsVersion, sync, metalHUD, advertiseAVX, dxvkAsync, dlssEnabled, fpsCap, frameGen, frameGenAdaptive, frameGenFlowScale, frameGenPerformance, frameGenForceVsync, commandIsControl, commandIsControlSynced, dpiScale, retinaAt100, dllOverrides, dxvkAppConfig, dllOverridesSynced, engineAppDefaultsSynced, keepFilesInside, environment, gameEnvironment, pins, recipes, created }+ enum CodingKeys: String, CodingKey { case formatVersion, name, engineID, renderer, rendererExplicit, windowsVersion, sync, metalHUD, advertiseAVX, dxvkAsync, dlssEnabled, fpsCap, frameGen, frameGenAdaptive, frameGenFlowScale, frameGenPerformance, frameGenForceVsync, commandIsControl, commandIsControlSynced, dpiScale, retinaAt100, dllOverrides, dxvkAppConfig, dllOverridesSynced, engineAppDefaultsSynced, keepFilesInside, externalDrives, environment, gameEnvironment, pins, recipes, created }/// The variables `gameID`'s recipe scoped to it; empty for a game without any, or with no id.public func environment(forGame gameID: String?) -> [String: String] {@@ -480,6 +483,7 @@ public struct BottleSettings: Codable, Sendable {dllOverridesSynced = try c.decodeIfPresent(String.self, forKey: .dllOverridesSynced)engineAppDefaultsSynced = try c.decodeIfPresent(String.self, forKey: .engineAppDefaultsSynced)keepFilesInside = try c.decodeIfPresent(Bool.self, forKey: .keepFilesInside) ?? false+ externalDrives = try c.decodeIfPresent([MacDrives.Mapping].self, forKey: .externalDrives) ?? []commandIsControl = try c.decodeIfPresent(Bool.self, forKey: .commandIsControl) ?? truecommandIsControlSynced = try c.decodeIfPresent(Bool.self, forKey: .commandIsControlSynced)environment = try c.decodeIfPresent([String: String].self, forKey: .environment) ?? [:]diff --git a/Sources/HighballKit/MacDrives.swift b/Sources/HighballKit/MacDrives.swiftnew file mode 100644index 0000000..819727d--- /dev/null+++ b/Sources/HighballKit/MacDrives.swift@@ -0,0 +1,149 @@+import Foundation++/// External Mac drives as Windows drive letters.+///+/// Wine gives a drive letter only to a volume macOS reports as removable media: its mount+/// manager adds any other volume without one (dlls/mountmgr.sys/diskarb.c). External SSDs and+/// hard drives report fixed media, so a Windows program reached them only through Z:\Volumes,+/// and Steam, which offers drive letters for its libraries, listed none of them (an external+/// exFAT drive, Discord, 2026-10-06). Before a program starts, each mounted external volume is+/// linked to a letter of its own in the environment's dosdevices. Wine reports such a letter as+/// a fixed disk, since the volume is local and not removable media (ntdll's get_device_info,+/// kernelbase's GetDriveTypeW), which is the kind Steam offers.+///+/// A drive keeps its letter, because Steam records a library by its path (D:\SteamLibrary):+/// while the drive is away its link is removed and the letter stays reserved for it, and the+/// same letter comes back when it is plugged in again, even at another mount point. Letters+/// Wine or the player made are never touched, and a volume one of them already reaches gets no+/// second letter.+public enum MacDrives {+ /// A mounted volume: its mount point and an identity that survives a remount.+ public struct Volume: Equatable, Sendable {+ public var path: String+ public var id: String+ public init(path: String, id: String) { self.path = path; self.id = id }+ }++ /// A letter Highball linked to a volume, as recorded in the environment's settings.+ public struct Mapping: Codable, Equatable, Sendable {+ /// Lowercase, without the colon: "d".+ public var letter: String+ public var id: String+ /// Where the link pointed when it was last made.+ public var path: String+ public init(letter: String, id: String, path: String) { self.letter = letter; self.id = id; self.path = path }+ }++ public struct Plan: Equatable, Sendable {+ /// Links to create, or to point at a new mount point.+ public var link: [Mapping] = []+ /// Letters whose link to an absent drive is removed.+ public var unlink: [String] = []+ /// What the settings record afterwards.+ public var mappings: [Mapping] = []+ }++ /// Letters offered, in order. A and B are the floppy letters Windows programs skip, C is the+ /// environment's own drive and Z is the Mac's root.+ static let letters = "defghijklmnopqrstuvwxy".map(String.init)++ /// Pure: the links that give every external volume a letter of its own. `existing` is each+ /// `dosdevices/x:` entry, its letter to the link's target ("" for an entry that is no link).+ public static func plan(volumes: [Volume], existing: [String: String], mappings: [Mapping]) -> Plan {+ func same(_ a: String?, _ b: String) -> Bool { a.map(normalized) == normalized(b) }+ var plan = Plan()+ var kept: [Mapping] = []+ var lettered = Set<String>()+ for m in mappings where !kept.contains(where: { $0.letter == m.letter }) {+ let volume = volumes.first { $0.id == m.id }+ let target = existing[m.letter]+ // Someone else's now (Wine for a removable disk, or the player): forget the record.+ guard target == nil || same(target, m.path) || (volume.map { same(target, $0.path) } ?? false) else { continue }+ if let volume {+ if !same(target, volume.path) { plan.link.append(Mapping(letter: m.letter, id: m.id, path: volume.path)) }+ kept.append(Mapping(letter: m.letter, id: m.id, path: volume.path))+ lettered.insert(m.id)+ } else {+ if target != nil { plan.unlink.append(m.letter) }+ kept.append(m)+ }+ }+ for volume in volumes where !lettered.contains(volume.id) {+ if existing.values.contains(where: { same($0, volume.path) }) { continue }+ guard let letter = letters.first(where: { l in existing[l] == nil && !kept.contains { $0.letter == l } }) else { break }+ let m = Mapping(letter: letter, id: volume.id, path: volume.path)+ plan.link.append(m)+ kept.append(m)+ lettered.insert(volume.id)+ }+ plan.mappings = kept+ return plan+ }++ static func normalized(_ path: String) -> String {+ path.count > 1 && path.hasSuffix("/") ? String(path.dropLast()) : path+ }++ /// Pure: whether a mounted volume is one Wine leaves without a letter and Highball links.+ /// An unknown value (nil) counts against it.+ public static func qualifies(path: String, isLocal: Bool?, isInternal: Bool?, isRemovable: Bool?,+ isBrowsable: Bool?, isRootFileSystem: Bool?) -> Bool {+ path.hasPrefix("/Volumes/") && isLocal == true && isInternal == false && isRemovable == false+ && isBrowsable == true && isRootFileSystem != true+ }++ /// The external volumes mounted now. HB_DEBUG_EXTERNAL_VOLUMES (mount points separated by+ /// colons) adds volumes to treat as external, so the path can be checked without such a drive.+ public static func mountedExternalVolumes() -> [Volume] {+ let keys: Set<URLResourceKey> = [.volumeIsLocalKey, .volumeIsInternalKey, .volumeIsRemovableKey, .volumeIsBrowsableKey,+ .volumeIsRootFileSystemKey, .volumeUUIDStringKey, .volumeNameKey]+ let urls = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: Array(keys), options: [.skipHiddenVolumes]) ?? []+ var volumes: [Volume] = urls.compactMap { url in+ guard let v = try? url.resourceValues(forKeys: keys),+ qualifies(path: url.path, isLocal: v.volumeIsLocal, isInternal: v.volumeIsInternal, isRemovable: v.volumeIsRemovable,+ isBrowsable: v.volumeIsBrowsable, isRootFileSystem: v.volumeIsRootFileSystem) else { return nil }+ return Volume(path: url.path, id: v.volumeUUIDString ?? "name:" + (v.volumeName ?? url.lastPathComponent))+ }+ for path in (ProcessInfo.processInfo.environment["HB_DEBUG_EXTERNAL_VOLUMES"] ?? "").split(separator: ":").map(String.init)+ where !path.isEmpty && !volumes.contains(where: { $0.path == path }) {+ volumes.append(Volume(path: path, id: "debug:" + path))+ }+ return volumes+ }+}++public extension Bottle {+ /// Links the environment's external drives to letters (see `MacDrives`) and records them.+ /// Returns the links made, so a launch can say which letter a drive got.+ @discardableResult+ func syncExternalDrives(volumes: [MacDrives.Volume] = MacDrives.mountedExternalVolumes()) -> [MacDrives.Mapping] {+ let dosdevices = url.appending(path: "dosdevices", directoryHint: .isDirectory)+ let fm = FileManager.default+ guard let names = try? fm.contentsOfDirectory(atPath: dosdevices.path) else { return [] }+ var existing: [String: String] = [:]+ for name in names where name.count == 2 && name.hasSuffix(":") {+ existing[String(name.prefix(1)).lowercased()] = (try? fm.destinationOfSymbolicLink(atPath: dosdevices.appending(path: name).path)) ?? ""+ }+ let plan = MacDrives.plan(volumes: volumes, existing: existing, mappings: settings.externalDrives)+ for letter in plan.unlink {+ let entry = dosdevices.appending(path: "\(letter):").path+ // Removed only while it is still the link this record made.+ guard let target = try? fm.destinationOfSymbolicLink(atPath: entry),+ settings.externalDrives.contains(where: { $0.letter == letter && MacDrives.normalized($0.path) == MacDrives.normalized(target) })+ else { continue }+ try? fm.removeItem(atPath: entry)+ }+ var made: [MacDrives.Mapping] = []+ for m in plan.link {+ let entry = dosdevices.appending(path: "\(m.letter):").path+ if (try? fm.destinationOfSymbolicLink(atPath: entry)) != nil { try? fm.removeItem(atPath: entry) }+ if (try? fm.createSymbolicLink(atPath: entry, withDestinationPath: m.path)) != nil { made.append(m) }+ }+ let recorded = plan.mappings.filter { m in !plan.link.contains(m) || made.contains(m) }+ if recorded != settings.externalDrives, var fresh = try? Bottle.load(url) {+ fresh.settings.externalDrives = recorded+ try? fresh.save()+ }+ return made+ }+}diff --git a/Sources/HighballKit/WineRunner.swift b/Sources/HighballKit/WineRunner.swiftindex 78ddbf3..f23d527 100644--- a/Sources/HighballKit/WineRunner.swift+++ b/Sources/HighballKit/WineRunner.swift@@ -289,9 +289,29 @@ public struct WineRunner: Sendable {await syncEngineAppDefaults()await syncKeyboardRegistry()var note = headerNote+ // External Mac drives get letters of their own, so Steam can offer them for a library.+ // Windows lists drives through Wine's mount manager, which reads the links when the+ // environment's server starts: a letter linked while the server ran stayed unlisted until+ // the next start (measured 2026-10-06 with wmic). So an idle environment restarts, the way+ // a stack mismatch restarts it below, and one running a program is left alone.+ let linked = bottle.syncExternalDrives()+ if !linked.isEmpty {+ var text = "external drives linked: " + linked.map { "\($0.letter.uppercased()): \($0.path)" }.joined(separator: ", ")+ if ProcessTable.liveServer(forPrefix: bottle.url) != nil {+ if ProcessTable.isIdle(prefix: bottle.url) {+ _ = try kill()+ try? await Task.sleep(for: .seconds(2))+ text += "; restarted the idle environment so Windows lists them"+ } else {+ text += "; Windows lists them after the environment's next start, a program is still running"+ }+ }+ onOutput?("note: \(text)")+ note = [note, text].compactMap { $0 }.joined(separator: "; ")+ }if let rebooted = try await rebootIdleEnvironmentIfMismatched(renderer: renderer, extraEnvironment: extraEnvironment) {onOutput?("note: \(rebooted)")- note = [headerNote, rebooted].compactMap { $0 }.joined(separator: "; ")+ note = [note, rebooted].compactMap { $0 }.joined(separator: "; ")}return try await run([executable.path] + arguments, renderer: renderer, extraEnvironment: extraEnvironment, label: executable.lastPathComponent, workingDirectory: workingDirectory, headerNote: note, onOutput: onOutput)}diff --git a/Tests/HighballKitTests/MacDrivesTests.swift b/Tests/HighballKitTests/MacDrivesTests.swiftnew file mode 100644index 0000000..c98e769--- /dev/null+++ b/Tests/HighballKitTests/MacDrivesTests.swift@@ -0,0 +1,106 @@+import XCTest+@testable import HighballKit++/// External Mac drives get Windows drive letters of their own, keep them, and never take one+/// Wine or the player made (Discord, 2026-10-06: Steam listed no external drive).+final class MacDrivesTests: XCTestCase {+ private let base = ["c": "../drive_c", "z": "/"]++ func testANewExternalDriveGetsTheFirstFreeLetter() {+ var existing = base+ existing["d"] = "/Volumes/Installer" // Wine's letter for a mounted disk image+ let plan = MacDrives.plan(volumes: [.init(path: "/Volumes/Games", id: "U1")], existing: existing, mappings: [])+ XCTAssertEqual(plan.link, [.init(letter: "e", id: "U1", path: "/Volumes/Games")])+ XCTAssertEqual(plan.mappings, plan.link)+ XCTAssertEqual(plan.unlink, [])+ }++ func testADriveKeepsItsLetterAndAnUpToDateLinkChangesNothing() {+ var existing = base+ existing["e"] = "/Volumes/Games"+ let mapped = [MacDrives.Mapping(letter: "e", id: "U1", path: "/Volumes/Games")]+ let plan = MacDrives.plan(volumes: [.init(path: "/Volumes/Games", id: "U1")], existing: existing, mappings: mapped)+ XCTAssertEqual(plan, MacDrives.Plan(link: [], unlink: [], mappings: mapped))+ }++ func testAnUnpluggedDriveLosesItsLinkButKeepsItsLetterForWhenItComesBack() {+ var existing = base+ existing["e"] = "/Volumes/Games"+ let mapped = [MacDrives.Mapping(letter: "e", id: "U1", path: "/Volumes/Games")]+ let away = MacDrives.plan(volumes: [.init(path: "/Volumes/Other", id: "U2")], existing: existing, mappings: mapped)+ XCTAssertEqual(away.unlink, ["e"])+ XCTAssertEqual(away.link, [.init(letter: "d", id: "U2", path: "/Volumes/Other")], "another drive does not take the reserved letter")+ XCTAssertEqual(away.mappings.first, mapped[0])+ // Back at another mount point (macOS names it "Games 1" when the name is taken).+ let back = MacDrives.plan(volumes: [.init(path: "/Volumes/Games 1", id: "U1")], existing: base, mappings: mapped)+ XCTAssertEqual(back.link, [.init(letter: "e", id: "U1", path: "/Volumes/Games 1")])+ XCTAssertEqual(back.mappings, back.link)+ }++ func testALetterSomeoneElseNowUsesIsLeftAloneAndTheDriveMovesOn() {+ var existing = base+ existing["e"] = "/Volumes/SomethingElse" // the player pointed E: elsewhere+ let mapped = [MacDrives.Mapping(letter: "e", id: "U1", path: "/Volumes/Games")]+ let plan = MacDrives.plan(volumes: [.init(path: "/Volumes/Games", id: "U1")], existing: existing, mappings: mapped)+ XCTAssertEqual(plan.unlink, [], "not ours to remove")+ XCTAssertEqual(plan.link, [.init(letter: "d", id: "U1", path: "/Volumes/Games")])+ XCTAssertEqual(plan.mappings, plan.link, "the stale record is dropped")+ }++ func testADriveALetterAlreadyReachesGetsNoSecondOne() {+ var existing = base+ existing["k"] = "/Volumes/Games/" // made by hand, with a trailing slash+ let plan = MacDrives.plan(volumes: [.init(path: "/Volumes/Games", id: "U1")], existing: existing, mappings: [])+ XCTAssertEqual(plan, MacDrives.Plan())+ }++ func testOnlyLocalExternalFixedBrowsableVolumesQualify() {+ func q(_ path: String = "/Volumes/Games", local: Bool? = true, inside: Bool? = false, removable: Bool? = false,+ browsable: Bool? = true, root: Bool? = false) -> Bool {+ MacDrives.qualifies(path: path, isLocal: local, isInternal: inside, isRemovable: removable,+ isBrowsable: browsable, isRootFileSystem: root)+ }+ XCTAssertTrue(q(), "an external SSD or hard drive")+ XCTAssertFalse(q(removable: true), "removable media: Wine gives it a letter itself")+ XCTAssertFalse(q(inside: true), "the Mac's own disk")+ XCTAssertFalse(q(inside: nil), "unknown counts against it")+ XCTAssertFalse(q(local: false), "a network share")+ XCTAssertFalse(q(browsable: false), "a hidden system volume")+ XCTAssertFalse(q("/", root: true))+ XCTAssertFalse(q("/System/Volumes/Data"))+ }++ func testTheEnvironmentsLinksFollowTheDrives() throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "hb-drives-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: root) }+ let bottleURL = root.appending(path: "t")+ let dos = bottleURL.appending(path: "dosdevices")+ try FileManager.default.createDirectory(at: dos, withIntermediateDirectories: true)+ try FileManager.default.createSymbolicLink(atPath: dos.appending(path: "c:").path, withDestinationPath: "../drive_c")+ try FileManager.default.createSymbolicLink(atPath: dos.appending(path: "z:").path, withDestinationPath: "/")+ let bottle = Bottle(url: bottleURL, settings: BottleSettings(name: "t", engineID: "e"))+ try bottle.save()+ let drive = root.appending(path: "Games").path, again = root.appending(path: "Games 1").path++ let made = Bottle.loadOrFail(bottleURL).syncExternalDrives(volumes: [.init(path: drive, id: "U1")])+ XCTAssertEqual(made.map(\.letter), ["d"])+ XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: dos.appending(path: "d:").path), drive)+ XCTAssertEqual(Bottle.loadOrFail(bottleURL).settings.externalDrives, [.init(letter: "d", id: "U1", path: drive)], "recorded")+ XCTAssertEqual(Bottle.loadOrFail(bottleURL).syncExternalDrives(volumes: [.init(path: drive, id: "U1")]), [], "a second launch changes nothing")++ XCTAssertEqual(Bottle.loadOrFail(bottleURL).syncExternalDrives(volumes: []), [])+ XCTAssertFalse(FileManager.default.fileExists(atPath: dos.appending(path: "d:").path), "unplugged, the link goes")+ XCTAssertEqual(Bottle.loadOrFail(bottleURL).settings.externalDrives.map(\.letter), ["d"], "and the letter stays reserved")++ XCTAssertEqual(Bottle.loadOrFail(bottleURL).syncExternalDrives(volumes: [.init(path: again, id: "U1")]).map(\.letter), ["d"])+ XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: dos.appending(path: "d:").path), again, "back on D:")+ XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: dos.appending(path: "c:").path), "../drive_c", "C: untouched")+ XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: dos.appending(path: "z:").path), "/", "Z: untouched")+ }+}++private extension Bottle {+ static func loadOrFail(_ url: URL) -> Bottle {+ do { return try Bottle.load(url) } catch { XCTFail("\(error)"); return Bottle(url: url, settings: BottleSettings(name: "t", engineID: "e")) }+ }+}