Skip to content

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

Per-game Display choice: move a game's window to the display the player picked

Tuan Dinha4eba5b7f3eb
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 8917a41..24dd101 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -154,6 +154,17 @@ final class AppState {
libraryLaunchArgs = libraryStore.launchArguments()
appendLog(args.isEmpty ? "\(item.id): launch arguments cleared" : "\(item.id): launch arguments set to \(ArgumentLine.join(args))")
}
+ /// The display (CoreGraphics UUID) a game's window moves to, by library id.
+ var libraryDisplays: [String: String] = [:]
+ func displayChoice(for item: LibraryItem) -> String? { libraryDisplays[item.id] }
+ func setDisplay(_ uuid: String?, for item: LibraryItem) {
+ guard uuid != displayChoice(for: item) else { return }
+ if uuid != nil { _ = WindowMover.ensureTrusted(prompt: true) }
+ libraryStore.setDisplay(uuid, for: item.id)
+ libraryDisplays = libraryStore.displayChoices()
+ let name = uuid.flatMap { u in Monitor.connected().first { $0.id == u }?.name }
+ appendLog(uuid == nil ? "\(item.id): display back to the main one" : "\(item.id): display set to \(name ?? "a disconnected display")")
+ }
func setRendererOverride(_ renderer: Renderer?, for id: String) {
libraryStore.setRendererOverride(renderer, for: id)
libraryOverrides = libraryStore.rendererOverrides()
@@ -933,6 +944,7 @@ final class AppState {
libraryPlays = libraryStore.load()
libraryOverrides = libraryStore.rendererOverrides()
libraryLaunchArgs = libraryStore.launchArguments()
+ libraryDisplays = libraryStore.displayChoices()
rebuildLibrary()
steamOwnedRefresh()
epicRefresh()
@@ -2093,6 +2105,7 @@ final class AppState {
runningSessions.append(session)
appendLog("\(session.title) is running")
bringForwardWhenItDraws(session)
+ moveToChosenDisplay(session)
if !FunnelLog.records(in: paths.logs).contains(where: { $0.event == .firstGameProcess }) { funnel(.firstGameProcess) }
sessionWatchers[session.id] = Task.detached { [weak self] in
if let prefix = await self?.discordEnvironmentPrefix(for: session),
@@ -2145,6 +2158,39 @@ final class AppState {
}
}
+ /// Moves the game's windows onto the display the player chose on its page (Accessibility API;
+ /// Wine's Mac driver always opens on the main display). Checks once a second for two minutes,
+ /// moving each window once so one the player drags afterwards stays put.
+ private func moveToChosenDisplay(_ session: GameSession) {
+ guard let id = session.libraryID, let uuid = libraryDisplays[id],
+ let prefix = bottles.first(where: { $0.name == session.bottleName })?.url else { return }
+ guard WindowMover.ensureTrusted(prompt: false) else {
+ appendLog("\(session.title): moving to a display needs Accessibility permission for Highball (System Settings > Privacy & Security > Accessibility)")
+ return
+ }
+ // Off the main actor: AX calls can block while the game loads. Only the checks hop back.
+ Task.detached { [weak self] in
+ var handled: [AXUIElement] = []
+ for _ in 0..<120 {
+ try? await Task.sleep(for: .seconds(1))
+ guard let self else { return }
+ let state = await MainActor.run { () -> (running: Bool, monitor: Monitor?) in
+ (self.runningSessions.contains(session), Monitor.connected().first(where: { $0.id == uuid }))
+ }
+ guard state.running else { return }
+ guard let monitor = state.monitor else {
+ await self.appendLog("\(session.title): chosen display is not connected, leaving the window where it opened")
+ return
+ }
+ for pid in SessionWatch.pids(ofPrefix: prefix, markers: session.markers) {
+ for _ in 0..<WindowMover.move(pid: pid, to: monitor.bounds, alreadyMoved: &handled) {
+ await self.appendLog("moved \(session.title) to \(monitor.name)")
+ }
+ }
+ }
+ }
+ }
+
/// Whether the process owns a normal window on screen. Owner and layer come without the
/// screen recording permission, which only window titles need.
private static func hasWindowOnScreen(_ pid: pid_t) -> Bool {
@@ -2304,7 +2350,8 @@ final class AppState {
steamClients.insert(bottle.name) // the poll would take up to 8 s to notice
} else {
beginSession(GameSession(title: pin.name, bottleName: bottle.name, appid: nil, markers: markers,
- renderer: (pin.renderer ?? bottle.settings.renderer).rawValue), processList: box.processList)
+ renderer: (pin.renderer ?? bottle.settings.renderer).rawValue,
+ libraryID: "pin:\(bottle.name):\(pin.id.uuidString)"), processList: box.processList)
}
}
}
@@ -2469,7 +2516,7 @@ final class AppState {
}
guard handedOff else { return }
beginSession(GameSession(title: game.name, bottleName: bottle.name, appid: game.appid, markers: markers,
- renderer: servedRenderer.rawValue, startNotice: entry?.startNotice,
+ renderer: servedRenderer.rawValue, libraryID: "steam:\(game.appid)", startNotice: entry?.startNotice,
startNoticeMinutes: entry?.startNoticeMinutes), processList: box.processList)
}
}
@@ -2749,8 +2796,8 @@ final class AppState {
}
guard handedOff else { return }
beginSession(GameSession(title: game.app_title, bottleName: bottle.name, appid: nil, markers: markers,
- renderer: (renderer ?? bottle.settings.renderer).rawValue, startNotice: row?.startNotice,
- startNoticeMinutes: row?.startNoticeMinutes), processList: box.processList)
+ renderer: (renderer ?? bottle.settings.renderer).rawValue, libraryID: "epic:\(game.app_name)",
+ startNotice: row?.startNotice, startNoticeMinutes: row?.startNoticeMinutes), processList: box.processList)
}
}
diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swift
index 0ad94a4..cdf9029 100644
--- a/Sources/HighballApp/GameDetailView.swift
+++ b/Sources/HighballApp/GameDetailView.swift
@@ -457,6 +457,24 @@ struct GameDetailView: View {
}
}
}
+ let stored = state.displayChoice(for: item) ?? ""
+ let monitors = Monitor.connected()
+ HStack(alignment: .top, spacing: 12) {
+ Text(L("Display")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 4)
+ VStack(alignment: .leading, spacing: 4) {
+ Picker("", selection: Binding(
+ get: { stored },
+ set: { state.setDisplay($0.isEmpty ? nil : $0, for: item) })) {
+ Text(L("Main display")).tag("")
+ ForEach(monitors) { monitor in Text(monitor.name).tag(monitor.id) }
+ if !stored.isEmpty, !monitors.contains(where: { $0.id == stored }) {
+ Text(L("Disconnected display")).tag(stored)
+ }
+ }.labelsHidden().frame(maxWidth: 360)
+ Text(L("Highball moves the game's window here after it opens. Works best for windowed and borderless games. Needs Accessibility permission for Highball."))
+ .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ }
if item.source == .steam {
HStack(alignment: .top, spacing: 12) {
Text(L("Launch arguments")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 4)
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index eae5ef7..e999bf0 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -219,6 +219,9 @@ enum L10n {
"Display mode": "Mode d'affichage",
"Emulate display mode changes": "Émuler les changements de mode d'affichage",
"For a game that opens small, off-centre, or refuses its fullscreen mode. The Mac cannot switch its display for it, so Wine pretends and scales the picture instead. A fix from the database may have set this already.": "Pour un jeu qui s'ouvre en petit, décentré, ou refuse son mode plein écran. Le Mac ne peut pas changer l'affichage pour lui, alors Wine fait comme si et met l'image à l'échelle. Un correctif de la base de données l'a peut-être déjà activé.",
+ "Main display": "Écran principal",
+ "Disconnected display": "Écran déconnecté",
+ "Highball moves the game's window here after it opens. Works best for windowed and borderless games. Needs Accessibility permission for Highball.": "Highball déplace la fenêtre du jeu ici après son ouverture. Fonctionne mieux pour les jeux en fenêtre ou sans bordure. Nécessite l'autorisation Accessibilité pour Highball.",
"Environment's mode": "Mode de l'environnement",
"Use %@ for this game": "Utiliser %@ pour ce jeu",
"Try %@ for %@ next time?": "Essayer %@ pour %@ la prochaine fois ?",
diff --git a/Sources/HighballApp/Monitors.swift b/Sources/HighballApp/Monitors.swift
new file mode 100644
index 0000000..3105ab2
--- /dev/null
+++ b/Sources/HighballApp/Monitors.swift
@@ -0,0 +1,71 @@
+import AppKit
+import ApplicationServices
+import HighballKit
+
+struct Monitor: Identifiable, Equatable {
+ let id: String
+ let name: String
+ let bounds: CGRect
+
+ /// Connected displays; `id` is the CoreGraphics display UUID, stable across reboots and replug.
+ static func connected() -> [Monitor] {
+ NSScreen.screens.compactMap { screen in
+ guard let num = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber,
+ let uuid = CGDisplayCreateUUIDFromDisplayID(num.uint32Value)?.takeRetainedValue(),
+ let str = CFUUIDCreateString(nil, uuid) as String?
+ else { return nil }
+ return Monitor(id: str, name: screen.localizedName, bounds: CGDisplayBounds(num.uint32Value))
+ }
+ }
+}
+
+enum WindowMover {
+ static func ensureTrusted(prompt: Bool) -> Bool {
+ let key = "AXTrustedCheckOptionPrompt" // kAXTrustedCheckOptionPrompt, a non-Sendable global in Swift 6
+ return AXIsProcessTrustedWithOptions([key: prompt] as CFDictionary)
+ }
+
+ /// Moves the process's windows onto `target`. Windows already handled are skipped, so one the
+ /// player drags afterwards is never fought. Returns how many were moved.
+ static func move(pid: pid_t, to target: CGRect, alreadyMoved: inout [AXUIElement]) -> Int {
+ let app = AXUIElementCreateApplication(pid)
+ AXUIElementSetMessagingTimeout(app, 1) // a game busy loading must not stall us for the 6 s default
+ var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &value) == .success,
+ let windows = value as? [AXUIElement]
+ else { return 0 }
+ var moved = 0
+ for window in windows where !alreadyMoved.contains(where: { CFEqual($0, window) }) {
+ guard let size = read(window, kAXSizeAttribute, .cgSize, as: CGSize.self),
+ let pos = read(window, kAXPositionAttribute, .cgPoint, as: CGPoint.self)
+ else { continue }
+ alreadyMoved.append(window)
+ if MonitorPlacement.isOn(CGRect(origin: pos, size: size), target: target) { continue }
+ let frame = MonitorPlacement.frame(for: size, on: target)
+ var newSize = frame.size
+ var newPos = frame.origin
+ if let s = AXValueCreate(.cgSize, &newSize) {
+ AXUIElementSetAttributeValue(window, kAXSizeAttribute as CFString, s)
+ }
+ if let p = AXValueCreate(.cgPoint, &newPos),
+ AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, p) == .success
+ {
+ moved += 1
+ }
+ }
+ return moved
+ }
+
+ private static func read<T>(_ el: AXUIElement, _ attr: String, _ type: AXValueType, as _: T.Type)
+ -> T?
+ {
+ var v: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(el, attr as CFString, &v) == .success, let ax = v,
+ CFGetTypeID(ax) == AXValueGetTypeID()
+ else { return nil }
+ let ptr = UnsafeMutablePointer<T>.allocate(capacity: 1)
+ defer { ptr.deallocate() }
+ guard AXValueGetValue(ax as! AXValue, type, ptr) else { return nil }
+ return ptr.pointee
+ }
+}
diff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swift
index ea03a0d..772f99c 100644
--- a/Sources/HighballKit/Library.swift
+++ b/Sources/HighballKit/Library.swift
@@ -261,6 +261,9 @@ public struct LibraryStore: Sendable {
/// database adds (highball#236: the only ways were Steam's own Launch Options or a program
/// entry). Optional so older files still decode.
var launchArgs: [String: [String]]?
+ /// The display one game's window is moved to after it opens, by library id (display UUID
+ /// string). Optional so older files still decode.
+ var displays: [String: String]?
}
public let paths: HighballPaths
@@ -299,6 +302,18 @@ public struct LibraryStore: Sendable {
if let data = try? JSONEncoder.highball.encode(shape) { try? data.write(to: fileURL, options: .atomic) }
}
+ public func displayChoices() -> [String: String] { loadShape().displays ?? [:] }
+
+ /// Sets, or with nil clears, the display (CoreGraphics UUID string) one game's window moves to.
+ public func setDisplay(_ uuid: String?, for id: String) {
+ var shape = loadShape()
+ var all = shape.displays ?? [:]
+ all[id] = uuid
+ shape.displays = all.isEmpty ? nil : all
+ try? paths.ensure()
+ if let data = try? JSONEncoder.highball.encode(shape) { try? data.write(to: fileURL, options: .atomic) }
+ }
+
private func loadShape() -> FileShape {
guard let data = try? Data(contentsOf: fileURL),
let shape = try? JSONDecoder.highball.decode(FileShape.self, from: data) else { return FileShape() }
@@ -316,13 +331,20 @@ public struct LibraryStore: Sendable {
/// Drops records whose items no longer exist (uninstalled games, deleted pins).
public func prune(validIDs: Set<String>) {
- let whole = loadShape()
- let current = whole.items
- let kept = current.filter { validIDs.contains($0.key) }
+ var whole = loadShape()
+ let keptItems = whole.items.filter { validIDs.contains($0.key) }
let keptOverrides = (whole.overrides ?? [:]).filter { validIDs.contains($0.key) }
- guard kept.count != current.count || keptOverrides.count != (whole.overrides ?? [:]).count else { return }
- let shape = FileShape(items: kept, overrides: keptOverrides.isEmpty ? nil : keptOverrides)
- if let data = try? JSONEncoder.highball.encode(shape) {
+ let keptArgs = (whole.launchArgs ?? [:]).filter { validIDs.contains($0.key) }
+ let keptDisplays = (whole.displays ?? [:]).filter { validIDs.contains($0.key) }
+ guard keptItems.count != whole.items.count
+ || keptOverrides.count != (whole.overrides ?? [:]).count
+ || keptArgs.count != (whole.launchArgs ?? [:]).count
+ || keptDisplays.count != (whole.displays ?? [:]).count else { return }
+ whole.items = keptItems
+ whole.overrides = keptOverrides.isEmpty ? nil : keptOverrides
+ whole.launchArgs = keptArgs.isEmpty ? nil : keptArgs
+ whole.displays = keptDisplays.isEmpty ? nil : keptDisplays
+ if let data = try? JSONEncoder.highball.encode(whole) {
try? data.write(to: fileURL, options: .atomic)
}
}
diff --git a/Sources/HighballKit/MonitorPlacement.swift b/Sources/HighballKit/MonitorPlacement.swift
new file mode 100644
index 0000000..5fed899
--- /dev/null
+++ b/Sources/HighballKit/MonitorPlacement.swift
@@ -0,0 +1,18 @@
+import CoreGraphics
+
+public enum MonitorPlacement {
+ /// Frame for a window of `size` on the display whose bounds (top-left origin, as AX and CGDisplayBounds use) are `target`: shrunk to fit, centred.
+ public static func frame(for size: CGSize, on target: CGRect) -> CGRect {
+ let w = min(size.width, target.width)
+ let h = min(size.height, target.height)
+ return CGRect(
+ x: target.minX + (target.width - w) / 2,
+ y: target.minY + (target.height - h) / 2,
+ width: w, height: h)
+ }
+
+ /// Whether the window's centre is already on `target`.
+ public static func isOn(_ window: CGRect, target: CGRect) -> Bool {
+ target.contains(CGPoint(x: window.midX, y: window.midY))
+ }
+}
diff --git a/Sources/HighballKit/Sessions.swift b/Sources/HighballKit/Sessions.swift
index ca18f49..e186b38 100644
--- a/Sources/HighballKit/Sessions.swift
+++ b/Sources/HighballKit/Sessions.swift
@@ -16,10 +16,11 @@ public struct GameSession: Identifiable, Sendable, Equatable {
/// The row's start notice (GameDBEntry.startNotice) and how long it stays.
public let startNotice: String?
public let startNoticeMinutes: Int
+ public let libraryID: String?
public init(id: UUID = UUID(), title: String, bottleName: String, appid: Int?, markers: [String], started: Date = Date(), renderer: String? = nil,
- startNotice: String? = nil, startNoticeMinutes: Int? = nil) {
+ libraryID: String? = nil, startNotice: String? = nil, startNoticeMinutes: Int? = nil) {
self.id = id; self.title = title; self.bottleName = bottleName; self.appid = appid; self.markers = markers; self.started = started
- self.renderer = renderer
+ self.renderer = renderer; self.libraryID = libraryID
self.startNotice = startNotice.flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 }
self.startNoticeMinutes = startNoticeMinutes ?? 15
}
diff --git a/Tests/HighballKitTests/MonitorPlacementTests.swift b/Tests/HighballKitTests/MonitorPlacementTests.swift
new file mode 100644
index 0000000..4de8857
--- /dev/null
+++ b/Tests/HighballKitTests/MonitorPlacementTests.swift
@@ -0,0 +1,45 @@
+import XCTest
+
+@testable import HighballKit
+
+final class MonitorPlacementTests: XCTestCase {
+ private let lg = CGRect(x: -522, y: 982, width: 2560, height: 1440)
+ private let builtIn = CGRect(x: 0, y: 0, width: 1512, height: 982)
+
+ func testSmallWindowIsCentredOnTarget() {
+ let f = MonitorPlacement.frame(for: CGSize(width: 800, height: 600), on: lg)
+ XCTAssertEqual(f, CGRect(x: 358, y: 1402, width: 800, height: 600))
+ }
+
+ func testOversizedWindowShrinksToTarget() {
+ let f = MonitorPlacement.frame(for: CGSize(width: 3000, height: 2000), on: lg)
+ XCTAssertEqual(f, lg)
+ }
+
+ func testIsOnUsesWindowCentre() {
+ let onBuiltIn = MonitorPlacement.frame(for: CGSize(width: 800, height: 600), on: builtIn)
+ XCTAssertFalse(MonitorPlacement.isOn(onBuiltIn, target: lg))
+ XCTAssertTrue(
+ MonitorPlacement.isOn(
+ MonitorPlacement.frame(for: CGSize(width: 800, height: 600), on: lg), target: lg))
+ }
+
+ func testDisplayChoiceRoundTripsAndPruneKeepsOtherMaps() throws {
+ let tmp = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: tmp) }
+ let store = LibraryStore(paths: HighballPaths(home: tmp))
+ store.setDisplay("U", for: "steam:1")
+ XCTAssertEqual(store.displayChoices(), ["steam:1": "U"])
+ store.setDisplay(nil, for: "steam:1")
+ XCTAssertEqual(store.displayChoices(), [:])
+
+ store.setDisplay("U", for: "steam:1")
+ store.setDisplay("V", for: "steam:2")
+ store.setLaunchArguments(["-w"], for: "steam:1")
+ store.prune(validIDs: ["steam:1"])
+ XCTAssertEqual(store.displayChoices(), ["steam:1": "U"])
+ XCTAssertEqual(store.launchArguments(), ["steam:1": ["-w"]])
+ store.prune(validIDs: [])
+ XCTAssertEqual(store.displayChoices(), [:])
+ }
+}