Skip to content

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

Play offers an environment already on the engine a game needs, and an environment counts every game installed in it (highball-db#318, highball#264)

Gauthier Piarrette0541f8af4145
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 553fd65..e43aab7 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -249,7 +249,7 @@ final class AppState {
libraryItems = LibraryIndex.build(bottles: bottles, steamByBottle: gamesByBottle,
steamOwnedByBottle: steamOwnedByBottle, macInstalled: macSteamGames,
epicOwned: epicOwned, epicInstalls: epicInstalls,
- plays: libraryPlays)
+ plays: libraryPlays, defaultBottle: defaultBottle?.name)
sortLibraryByDisplayTitle()
if let deferred = deferredPlayLink { resolvePlayLink(deferred.request) }
refreshMacFlags()
@@ -445,7 +445,7 @@ final class AppState {
// used to auto-apply on r5 and launch there, so nobody was ever offered the engine
// the game was verified on (Red Dead's and CS:GO's case).
if let wanted = recipe.engineToOffer(current: engine.manifest, known: Self.knownManifests) {
- pendingEngine = (recipe, bottle, wanted)
+ pendingEngine = (recipe, bottle, wanted, item, environmentFit(for: recipe, besides: bottle, item: item))
return
}
if let missing = recipe.engineUnknown(current: engine.manifest, known: Self.knownManifests) {
@@ -1228,7 +1228,10 @@ final class AppState {
/// about to be installed into an environment on a different Wine build. Nothing downloads
/// or re-runs the Windows setup without asking: the ask offers a new environment on that
/// engine (other programs untouched) or moving this one.
- var pendingEngine: (recipe: HighballKit.Recipe, bottle: Bottle, manifest: EngineManifest)?
+ /// `item` is the game Play was starting, nil when a fix's own button asked. `fit` is an
+ /// environment already on the right engine that the ask offers first, worked out when the
+ /// ask is raised: reading engines from disk inside the alert kept it from ever showing.
+ var pendingEngine: (recipe: HighballKit.Recipe, bottle: Bottle, manifest: EngineManifest, item: LibraryItem?, fit: Bottle?)?
/// The page a player sees after picking another engine on an environment's page (highball#254).
/// Only for a switch the player started; the app's own engine questions stay as they are.
struct EngineTransition: Identifiable {
@@ -1258,15 +1261,25 @@ final class AppState {
var pendingUpdate: (recipe: HighballKit.Recipe, engineID: String, play: (item: LibraryItem, bottle: Bottle, renderer: Renderer?)?)?
/// The ask's first way out: a new environment on the engine the recipe names, the recipe
- /// applied; the engine downloads first when it is not installed.
- func createEnvironment(for recipe: HighballKit.Recipe, on manifest: EngineManifest) {
+ /// applied; the engine downloads first when it is not installed. A new environment starts
+ /// without the game, so for a Steam game the done row's button hands it to that environment's
+ /// Steam (highball-db#318: the row said "installed" and nothing said what came next).
+ func createEnvironment(for recipe: HighballKit.Recipe, on manifest: EngineManifest, item: LibraryItem? = nil) {
pendingEngine = nil
guard !busy else { return }
let name = BottleStore.freeName(recipe.title, taken: Set(bottles.map(\.name)))
let accepted = Set(engines.flatMap { $0.manifest.acceptedLicenses ?? [] })
+ let done: DoneState
+ if let item, item.source == .steam {
+ done = DoneState(title: String(format: L("The %@ environment is ready"), name),
+ ctaTitle: String(format: L("Install %@"), displayTitle(item)),
+ cta: { [weak self] in self?.installSteamGame(item.homed(in: name)) })
+ } else {
+ done = DoneState(title: String(format: L("%@ installed"), recipe.title), ctaTitle: nil, cta: nil)
+ }
runBusy(String(format: L("Creating the %@ environment on %@"), name, GamePageCopy.shortEngineName(manifest)),
expected: L("a download when the engine is new, then a first boot of about 90 seconds"),
- done: DoneState(title: String(format: L("%@ installed"), recipe.title), ctaTitle: nil, cta: nil),
+ done: done,
stop: .cancelTask(label: L("Stop"))) { [self] in
let engine: InstalledEngine
if let installed = engines.first(where: { $0.id == manifest.id }) {
@@ -1296,6 +1309,43 @@ final class AppState {
launch(play.item, in: play.bottle, renderer: play.renderer)
}
+ /// An environment, other than the one Play started from, already on an engine the recipe
+ /// accepts: the one the ask's "New environment" made, or one the player moved there. Offered
+ /// first by the ask, so pressing Play again never makes a second environment (highball-db#318).
+ /// Only for a game Play can reach there: one installed there, or a Steam game its Steam can install.
+ func environmentFit(for recipe: HighballKit.Recipe, besides bottle: Bottle, item: LibraryItem?) -> Bottle? {
+ guard let item else { return nil }
+ let candidates = bottles.filter { b in
+ b.name != bottle.name && !deletingBottles.contains(b.name)
+ && engine(for: b).map { recipe.engineToOffer(current: $0.manifest, known: Self.knownManifests) == nil } == true
+ && (item.otherBottles.contains(b.name) || item.source == .steam)
+ }.map { b in
+ EnvironmentFit.Candidate(name: b.name, holdsGame: item.otherBottles.contains(b.name),
+ hasFix: b.settings.recipes.contains(recipe.id))
+ }
+ return EnvironmentFit.best(candidates).flatMap { c in bottles.first { $0.name == c.name } }
+ }
+
+ /// The ask's way out through an environment that already fits: the fix goes in first when it
+ /// is missing (for Mirror's Edge Catalyst that is the EA app), then the game plays there, or
+ /// that environment's Steam is asked to install it.
+ func useEnvironment(_ env: Bottle, for recipe: HighballKit.Recipe, item: LibraryItem) {
+ pendingEngine = nil
+ let target = item.homed(in: env.name)
+ let next: () -> Void = { [weak self] in
+ guard let self else { return }
+ if target.installed { self.play(target) } else { self.installSteamGame(target) }
+ }
+ if !env.settings.recipes.contains(recipe.id) || !recipe.artifactsPresent(driveC: env.driveC) {
+ applyRecipe(recipe.id, to: env, then: DoneState(
+ title: String(format: L("%@ installed"), recipe.title),
+ ctaTitle: String(format: target.installed ? L("Play %@") : L("Install %@"), displayTitle(item)),
+ cta: next))
+ } else {
+ next()
+ }
+ }
+
/// The ask's second way out: move the environment itself (the Windows setup re-runs, nothing
/// installed is lost), then the done row offers the install.
func moveEnvironment(for recipe: HighballKit.Recipe, bottle: Bottle, to manifest: EngineManifest) {
@@ -1353,7 +1403,7 @@ final class AppState {
func applyRecipe(_ id: String, to bottle: Bottle, then done: DoneState? = nil) {
guard let engine = engine(for: bottle), let recipe = Self.recipe(id) else { return }
if let wanted = recipe.engineToOffer(current: engine.manifest, known: Self.knownManifests) {
- pendingEngine = (recipe, bottle, wanted); return
+ pendingEngine = (recipe, bottle, wanted, nil, nil); return
}
if let missing = recipe.engineUnknown(current: engine.manifest, known: Self.knownManifests) {
pendingUpdate = (recipe, missing, nil); return
diff --git a/Sources/HighballApp/EngineAsk.swift b/Sources/HighballApp/EngineAsk.swift
index c8b1575..816d094 100644
--- a/Sources/HighballApp/EngineAsk.swift
+++ b/Sources/HighballApp/EngineAsk.swift
@@ -23,7 +23,17 @@ extension GamePageCopy {
/// `others` is how many other programs the environment has installed (Steam games and added
/// programs): moving the environment moves them all onto the engine, which a player found out
/// the hard way when an old revision could not show Steam's window (highball#262).
- static func engineAsk(recipe: HighballKit.Recipe, manifest: EngineManifest, installed: Bool, others: Int) -> String {
+ /// `existing` names an environment already on that engine and whether the game is installed
+ /// in it; the ask then offers it first (highball-db#318).
+ static func engineAsk(recipe: HighballKit.Recipe, manifest: EngineManifest, installed: Bool, others: Int,
+ existing: (name: String, holdsGame: Bool)? = nil) -> String {
+ guard let existing else { return engineAskBody(recipe: recipe, manifest: manifest, installed: installed, others: others) }
+ return existing.holdsGame
+ ? String(format: L("'%@' is already on the %@ engine and has the game installed, so it plays there. This environment stays as it is."), existing.name, shortEngineName(manifest))
+ : String(format: L("'%@' is already on the %@ engine. Using it installs the game there, with what it needs, and this environment stays as it is."), existing.name, shortEngineName(manifest))
+ }
+
+ private static func engineAskBody(recipe: HighballKit.Recipe, manifest: EngineManifest, installed: Bool, others: Int) -> String {
let download = installed ? "" : String(format: L(", after a download of about %@"), downloadSize(manifest))
if others == 0 {
return String(format: L("%@ is verified on the %@ engine, and this environment is not on it. Moving this environment switches it there%@ and keeps everything installed; the Windows setup re-runs when needed, a minute or two. A new environment starts empty, so the game has to be installed again."),
diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swift
index 282ddfc..7a7311d 100644
--- a/Sources/HighballApp/GameDetailView.swift
+++ b/Sources/HighballApp/GameDetailView.swift
@@ -362,8 +362,14 @@ struct GameDetailView: View {
Text(bottle.name).font(.callout)
Button(L("Environment settings…")) { showBottleSettings = true }.controlSize(.small)
}
- if !item.otherBottles.isEmpty {
- row(L("Also installed in"), item.otherBottles.joined(separator: ", "))
+ // Another copy plays from its own environment; once played there, the
+ // tile follows it (highball#264).
+ ForEach(item.otherBottles, id: \.self) { other in
+ HStack(alignment: .firstTextBaseline, spacing: 12) {
+ Text(L("Also installed in")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading)
+ Text(other).font(.callout)
+ Button(L("Play there")) { state.play(item.homed(in: other)) }.controlSize(.small)
+ }
}
HStack(alignment: .firstTextBaseline, spacing: 12) {
Text(L("Files")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading)
diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swift
index b2d7f15..e853cae 100644
--- a/Sources/HighballApp/HighballApp.swift
+++ b/Sources/HighballApp/HighballApp.swift
@@ -238,6 +238,30 @@ struct ContentView: View {
state.debugStartEngineTransition = true
}
}
+ // HB_DEBUG_RUN="<environment>|<path to an .exe>" runs it as a drop on the environment
+ // would, so a script can see where its window opens. On an M4 with macOS 27 (2026-10-05)
+ // Notepad on both engines and Steam's sign-in on Wine 11 came to the front by themselves
+ // when Highball started them; Steam's stayed behind only while a macOS prompt held the front.
+ .task {
+ guard let spec = ProcessInfo.processInfo.environment["HB_DEBUG_RUN"],
+ let cut = spec.firstIndex(of: "|") else { return }
+ try? await Task.sleep(for: .seconds(4))
+ guard let bottle = state.bottles.first(where: { $0.name == String(spec[..<cut]) }) else { return }
+ state.runDropped(URL(fileURLWithPath: String(spec[spec.index(after: cut)...])), in: bottle, andPin: false)
+ }
+ // HB_DEBUG_PLAY="<library item id>" presses Play on that tile, so a script can capture
+ // the questions Play asks (the engine ask, highball-db#318).
+ .task {
+ guard let id = ProcessInfo.processInfo.environment["HB_DEBUG_PLAY"] else { return }
+ for _ in 0..<30 {
+ try? await Task.sleep(for: .seconds(1))
+ guard let item = state.libraryItems.first(where: { $0.id == id }) else { continue }
+ state.play(item)
+ debugNote(state.paths.logs, "HB_DEBUG_PLAY \(id) in \(item.bottleName ?? "-"): engine ask \(state.pendingEngine.map { "for \($0.manifest.id)" } ?? "not raised")")
+ return
+ }
+ debugNote(state.paths.logs, "HB_DEBUG_PLAY \(id): no such tile among \(state.libraryItems.count)")
+ }
#endif
.errorAlert(state)
.sheet(isPresented: Binding(get: { state.showErrorDetails }, set: { state.showErrorDetails = $0 })) {
@@ -348,19 +372,27 @@ private extension View {
isPresented: .init(get: { state.pendingEngine != nil }, set: { if !$0 { state.pendingEngine = nil } }),
presenting: state.pendingEngine) { pending in
// With other programs installed here, a new environment is the safe choice and comes
- // first (highball#262); for an environment holding only this game, moving it is.
+ // first (highball#262); for an environment holding only this game, moving it is. An
+ // environment already on that engine comes before both and replaces the move: Play
+ // again after "New environment" must not make a second one (highball-db#318).
let others = state.otherProgramCount(in: pending.bottle, besides: pending.recipe)
- if others > 0 {
- Button(String(format: L("New environment for %@"), pending.recipe.title)) { state.createEnvironment(for: pending.recipe, on: pending.manifest) }
+ if let fit = pending.fit, let item = pending.item {
+ Button(String(format: L("Use '%@'"), fit.name)) { state.useEnvironment(fit, for: pending.recipe, item: item) }
+ Button(String(format: L("New environment for %@"), pending.recipe.title)) { state.createEnvironment(for: pending.recipe, on: pending.manifest, item: pending.item) }
+ Button(L("Not now"), role: .cancel) { state.pendingEngine = nil }
+ } else if others > 0 {
+ Button(String(format: L("New environment for %@"), pending.recipe.title)) { state.createEnvironment(for: pending.recipe, on: pending.manifest, item: pending.item) }
Button(L("Move this environment")) { state.moveEnvironment(for: pending.recipe, bottle: pending.bottle, to: pending.manifest) }
+ Button(L("Not now"), role: .cancel) { state.pendingEngine = nil }
} else {
Button(L("Move this environment")) { state.moveEnvironment(for: pending.recipe, bottle: pending.bottle, to: pending.manifest) }
- Button(String(format: L("New environment for %@"), pending.recipe.title)) { state.createEnvironment(for: pending.recipe, on: pending.manifest) }
+ Button(String(format: L("New environment for %@"), pending.recipe.title)) { state.createEnvironment(for: pending.recipe, on: pending.manifest, item: pending.item) }
+ Button(L("Not now"), role: .cancel) { state.pendingEngine = nil }
}
- Button(L("Not now"), role: .cancel) { state.pendingEngine = nil }
} message: { pending in
Text(GamePageCopy.engineAsk(recipe: pending.recipe, manifest: pending.manifest, installed: state.engines.contains { $0.id == pending.manifest.id },
- others: state.otherProgramCount(in: pending.bottle, besides: pending.recipe)))
+ others: state.otherProgramCount(in: pending.bottle, besides: pending.recipe),
+ existing: pending.fit.map { ($0.name, pending.item?.otherBottles.contains($0.name) == true) }))
}
}
@MainActor func updateAsk(_ state: AppState) -> some View {
@@ -623,3 +655,13 @@ struct ErrorDetailsSheet: View {
.frame(minWidth: 520, minHeight: 320)
}
}
+
+#if DEBUG
+/// One line for a script driving a debug build, in Highball's logs folder.
+@MainActor func debugNote(_ logs: URL, _ line: String) {
+ let url = logs.appending(path: "debug-hooks.txt")
+ let text = "\(Date()) \(line)\n"
+ if let h = try? FileHandle(forWritingTo: url) { h.seekToEndOfFile(); h.write(Data(text.utf8)); try? h.close() }
+ else { try? text.write(to: url, atomically: true, encoding: .utf8) }
+}
+#endif
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index 93b75cd..c314616 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -519,6 +519,12 @@ enum L10n {
// Whole-app review 2026-09-04: environment wording, Settings, game page
"%@ for every game in this environment, whatever the database says.": "%@ pour tous les jeux de cet environnement, quoi que dise la base.",
"%d titles": "%d titres",
+ // An environment that already fits a game's engine, and the windows Highball brings forward (highball-db#318, highball#264)
+ "%d installed": "%d installés",
+ "Play there": "Y jouer",
+ "Use '%@'": "Utiliser « %@ »",
+ "'%@' is already on the %@ engine and has the game installed, so it plays there. This environment stays as it is.": "« %@ » utilise déjà le moteur %@ et le jeu y est installé, il s'y lance donc. Cet environnement reste tel quel.",
+ "'%@' is already on the %@ engine. Using it installs the game there, with what it needs, and this environment stays as it is.": "« %@ » utilise déjà le moteur %@. L'utiliser y installe le jeu, avec ce qu'il lui faut, et cet environnement reste tel quel.",
"Add": "Ajouter",
"Automatic": "Automatique",
"Creating the %@ environment — first boot takes about 90 seconds": "Création de l'environnement %@ — le premier démarrage prend environ 90 secondes",
diff --git a/Sources/HighballApp/SettingsView.swift b/Sources/HighballApp/SettingsView.swift
index 022d8af..15c107a 100644
--- a/Sources/HighballApp/SettingsView.swift
+++ b/Sources/HighballApp/SettingsView.swift
@@ -141,14 +141,19 @@ struct EnvironmentsPane: View {
}
}
+ /// Every game installed in the environment, also one whose tile lives in another (highball#264).
+ private func footprint(_ bottle: Bottle) -> (count: Int, bytes: Int64) {
+ LibraryIndex.footprint(of: bottle.name, items: state.libraryItems, steamGames: state.gamesByBottle[bottle.name] ?? [])
+ }
+
private func sizeText(_ bottle: Bottle) -> String {
- let bytes = state.libraryItems.filter { $0.bottleName == bottle.name }.reduce(Int64(0)) { $0 + $1.sizeOnDisk }
+ let bytes = footprint(bottle).bytes
return bytes > 0 ? ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) : ""
}
private func environmentCard(_ bottle: Bottle) -> some View {
let isSelected = selected?.name == bottle.name
- let titles = state.libraryItems.filter { $0.bottleName == bottle.name }.count
+ let titles = footprint(bottle).count
return Button {
selectedName = bottle.name
} label: {
@@ -166,7 +171,7 @@ struct EnvironmentsPane: View {
}
}
Text([state.engine(for: bottle)?.displayName ?? bottle.settings.engineID,
- String(format: L("%d titles"), titles),
+ String(format: L("%d installed"), titles),
sizeText(bottle)].filter { !$0.isEmpty }.joined(separator: " · "))
.font(.caption.monospacedDigit()).foregroundStyle(.secondary)
}
diff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swift
index 83c5a95..95c241a 100644
--- a/Sources/HighballKit/Library.swift
+++ b/Sources/HighballKit/Library.swift
@@ -47,6 +47,20 @@ public struct LibraryItem: Identifiable, Sendable, Hashable {
/// Playable here in either build: the Windows one in a bottle or the Mac one in Steam for Mac.
public var installedAnywhere: Bool { installed || installedOnMac }
+
+ /// The same game seen from another environment: the library shows one tile per Steam game,
+ /// homed where it was last played (highball#264), and this is how Play reaches a copy in one
+ /// of the others, or how Install hands the game to that environment's Steam. Installed when
+ /// that environment holds a copy.
+ public func homed(in bottle: String) -> LibraryItem {
+ guard bottle != bottleName else { return self }
+ let holds = otherBottles.contains(bottle)
+ let others = (otherBottles.filter { $0 != bottle } + (installed ? [bottleName].compactMap { $0 } : [])).sorted()
+ return LibraryItem(source: source, id: id, title: title, bottleName: bottle, installed: holds,
+ installedOnMac: installedOnMac, steamAppID: steamAppID, epicAppName: epicAppName,
+ pinID: pinID, artworkTall: artworkTall, artworkWide: artworkWide,
+ otherBottles: others, sizeOnDisk: holds ? 0 : sizeOnDisk, lastPlayed: lastPlayed)
+ }
}
public enum LibraryIndex {
@@ -87,10 +101,18 @@ public enum LibraryIndex {
macInstalled: [SteamGame] = [],
epicOwned: [EpicStore.Game],
epicInstalls: [String: String],
- plays: [String: LibraryStore.PlayRecord] = [:]) -> [LibraryItem] {
+ plays: [String: LibraryStore.PlayRecord] = [:],
+ defaultBottle: String? = nil) -> [LibraryItem] {
var items: [LibraryItem] = []
let onMac = Dictionary(macInstalled.map { ($0.appid, $0) }, uniquingKeysWith: { a, _ in a })
- let firstBottle = bottles.map(\.name).min { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }
+ // Where a game with no other reason to live somewhere goes: the default environment first,
+ // then by name. By name alone, a test environment called "Clean" took every owned game
+ // from "Games" (highball#264).
+ func before(_ a: String, _ b: String) -> Bool {
+ if let d = defaultBottle, (a == d) != (b == d) { return a == d }
+ return a.localizedCaseInsensitiveCompare(b) == .orderedAscending
+ }
+ let firstBottle = bottles.map(\.name).min(by: before)
// Steam: group by appid, pick a primary copy, remember the others.
var byAppID: [Int: [(bottle: String, game: SteamGame)]] = [:]
@@ -105,7 +127,7 @@ public enum LibraryIndex {
let primary = copies.min { a, b in
if let lp = lastPlayedBottle, (a.bottle == lp) != (b.bottle == lp) { return a.bottle == lp }
if a.game.isReady != b.game.isReady { return a.game.isReady }
- return a.bottle.localizedCaseInsensitiveCompare(b.bottle) == .orderedAscending
+ return before(a.bottle, b.bottle)
}!
let acfPlayed = (copies.compactMap(\.game.lastPlayed) + [onMac[appid]?.lastPlayed].compactMap { $0 }).max()
let recorded = plays[id]?.lastPlayedAt
@@ -122,9 +144,9 @@ public enum LibraryIndex {
}
// Steam games owned but not installed: one tile each, like Epic's, in the first bottle
- // (by name) whose client lists them, where Install will hand them to Steam.
+ // (the default, then by name) whose client lists them, where Install will hand them to Steam.
var ownedOnly = Set<Int>()
- for bottle in bottles.sorted(by: { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }) {
+ for bottle in bottles.sorted(by: { before($0.name, $1.name) }) {
for game in steamOwnedByBottle[bottle.name] ?? [] where byAppID[game.appid] == nil && !ownedOnly.contains(game.appid) {
ownedOnly.insert(game.appid)
let id = "steam:\(game.appid)"
@@ -174,6 +196,40 @@ public enum LibraryIndex {
return items.sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == .orderedAscending }
}
+
+ /// What an environment holds, for its card in Settings: every Steam game installed in it,
+ /// whether or not the library homes that game's tile there (one tile per game, highball#264),
+ /// plus the programs and Epic games that live in it. Games the account owns but has not
+ /// installed are not in any environment, so they are not counted.
+ public static func footprint(of bottle: String, items: [LibraryItem], steamGames: [SteamGame]) -> (count: Int, bytes: Int64) {
+ let steam = steamGames.filter(\.isReady)
+ let others = items.filter { $0.source != .steam && $0.bottleName == bottle && $0.installed }
+ return (steam.count + others.count,
+ steam.reduce(Int64(0)) { $0 + $1.sizeOnDisk } + others.reduce(Int64(0)) { $0 + $1.sizeOnDisk })
+ }
+}
+
+/// Which existing environment a game that needs another engine should use (highball-db#318).
+/// The engine ask offers the best one before "New environment", so pressing Play again after
+/// making one never makes a second. An environment holding the game comes first, then one
+/// with the game's fix applied, then any other on an engine the fix accepts.
+public enum EnvironmentFit {
+ public struct Candidate: Equatable, Sendable {
+ public let name: String
+ public let holdsGame: Bool
+ public let hasFix: Bool
+ public init(name: String, holdsGame: Bool, hasFix: Bool) {
+ self.name = name; self.holdsGame = holdsGame; self.hasFix = hasFix
+ }
+ }
+
+ /// `candidates` are already on an engine the fix accepts, in the order the app lists them.
+ public static func best(_ candidates: [Candidate]) -> Candidate? {
+ func rank(_ c: Candidate) -> Int { c.holdsGame ? 0 : (c.hasFix ? 1 : 2) }
+ return candidates.enumerated().min { a, b in
+ rank(a.element) != rank(b.element) ? rank(a.element) < rank(b.element) : a.offset < b.offset
+ }?.element
+ }
}
/// Last-played persistence for the Continue shelf. Lives in its own library.json at the
diff --git a/Tests/HighballKitTests/EnvironmentCopiesTests.swift b/Tests/HighballKitTests/EnvironmentCopiesTests.swift
new file mode 100644
index 0000000..f0b051f
--- /dev/null
+++ b/Tests/HighballKitTests/EnvironmentCopiesTests.swift
@@ -0,0 +1,100 @@
+import XCTest
+@testable import HighballKit
+
+/// A game installed in more than one environment (highball#264), and an environment that
+/// already fits a game's engine (highball-db#318).
+final class EnvironmentCopiesTests: XCTestCase {
+ private func bottle(_ name: String) -> Bottle {
+ Bottle(url: URL(fileURLWithPath: "/tmp/hb-copies-tests/bottles/\(name)"),
+ settings: BottleSettings(name: name, engineID: "e"))
+ }
+ private func steam(_ appid: Int, _ name: String, ready: Bool = true, size: Int64 = 10) -> SteamGame {
+ SteamGame(appid: appid, name: name, installdir: name, sizeOnDisk: size, stateFlags: ready ? 4 : 2, lastPlayed: nil)
+ }
+
+ // MARK: Where a shared game lives
+
+ func testTheDefaultEnvironmentHoldsASharedGameBeforeOneSortedEarlierByName() {
+ let clean = bottle("Clean"), games = bottle("Games")
+ let both = ["Clean": [steam(1, "Streets of Rage 4")], "Games": [steam(1, "Streets of Rage 4")]]
+ let byName = LibraryIndex.build(bottles: [clean, games], steamByBottle: both, epicOwned: [], epicInstalls: [:])
+ XCTAssertEqual(byName.first?.bottleName, "Clean", "without a default, the name decides, as before")
+ let items = LibraryIndex.build(bottles: [clean, games], steamByBottle: both, epicOwned: [], epicInstalls: [:],
+ defaultBottle: "Games")
+ XCTAssertEqual(items.first?.bottleName, "Games")
+ XCTAssertEqual(items.first?.otherBottles, ["Clean"])
+ }
+
+ func testOwnedGamesNotInstalledAnywhereGoToTheDefaultEnvironment() {
+ let clean = bottle("Clean"), games = bottle("Games")
+ let owned = [OwnedSteamGame(appid: 9, name: "Hades")]
+ let items = LibraryIndex.build(bottles: [clean, games], steamByBottle: [:],
+ steamOwnedByBottle: ["Clean": owned, "Games": owned],
+ epicOwned: [], epicInstalls: [:], defaultBottle: "Games")
+ XCTAssertEqual(items.first { $0.id == "steam:9" }?.bottleName, "Games")
+ }
+
+ func testThePlayedEnvironmentStillWinsOverTheDefault() {
+ let clean = bottle("Clean"), games = bottle("Games")
+ let both = ["Clean": [steam(1, "Bloody Spell")], "Games": [steam(1, "Bloody Spell")]]
+ let items = LibraryIndex.build(bottles: [clean, games], steamByBottle: both, epicOwned: [], epicInstalls: [:],
+ plays: ["steam:1": .init(lastPlayedAt: Date(), bottle: "Clean")],
+ defaultBottle: "Games")
+ XCTAssertEqual(items.first?.bottleName, "Clean", "a game played from a second environment stays there")
+ }
+
+ // MARK: Counting what an environment holds
+
+ func testAnEnvironmentCountsEveryGameInstalledInItNotJustTheTilesHomedThere() {
+ let clean = bottle("Clean"), games = bottle("Games")
+ let steamByBottle = ["Clean": [steam(1, "A"), steam(2, "B")],
+ "Games": [steam(1, "A"), steam(2, "B"), steam(3, "C", ready: false)]]
+ let items = LibraryIndex.build(bottles: [clean, games], steamByBottle: steamByBottle,
+ steamOwnedByBottle: ["Clean": (10..<130).map { OwnedSteamGame(appid: $0, name: "Owned \($0)") }],
+ epicOwned: [], epicInstalls: [:])
+ // Before: Clean showed 120 titles (owned, not installed) and Games almost none.
+ let c = LibraryIndex.footprint(of: "Clean", items: items, steamGames: steamByBottle["Clean"]!)
+ let g = LibraryIndex.footprint(of: "Games", items: items, steamGames: steamByBottle["Games"]!)
+ XCTAssertEqual(c.count, 2)
+ XCTAssertEqual(g.count, 2, "a half-downloaded game is not installed yet")
+ XCTAssertEqual(c.bytes, 20)
+ }
+
+ func testProgramsCountInTheirOwnEnvironment() {
+ var a = bottle("a")
+ a.settings.pins = [Pin(name: "MyGame", path: "Games/my.exe")]
+ let items = LibraryIndex.build(bottles: [a], steamByBottle: [:], epicOwned: [], epicInstalls: [:])
+ XCTAssertEqual(LibraryIndex.footprint(of: "a", items: items, steamGames: []).count, 1)
+ XCTAssertEqual(LibraryIndex.footprint(of: "b", items: items, steamGames: []).count, 0)
+ }
+
+ // MARK: A copy seen from another environment
+
+ func testAGameHomedInAnotherEnvironmentThatHoldsACopyIsInstalledThere() {
+ let item = LibraryItem(source: .steam, id: "steam:1", title: "A", bottleName: "Games", installed: true,
+ steamAppID: 1, otherBottles: ["Clean", "W11"], sizeOnDisk: 5)
+ let there = item.homed(in: "W11")
+ XCTAssertEqual(there.bottleName, "W11")
+ XCTAssertTrue(there.installed)
+ XCTAssertEqual(there.otherBottles, ["Clean", "Games"])
+ XCTAssertEqual(there.id, item.id, "the same game, so plays and covers follow it")
+ let notThere = item.homed(in: "Fresh")
+ XCTAssertFalse(notThere.installed, "Install hands it to that environment's Steam")
+ XCTAssertEqual(notThere.otherBottles, ["Clean", "Games", "W11"])
+ XCTAssertEqual(item.homed(in: "Games"), item)
+ }
+
+ // MARK: An environment that already fits
+
+ func testTheEnvironmentHoldingTheGameComesFirstThenTheOneWithTheFix() {
+ let any = EnvironmentFit.Candidate(name: "Overwatch 2", holdsGame: false, hasFix: false)
+ let fix = EnvironmentFit.Candidate(name: "Mirror's Edge Catalyst", holdsGame: false, hasFix: true)
+ let game = EnvironmentFit.Candidate(name: "W11", holdsGame: true, hasFix: false)
+ XCTAssertEqual(EnvironmentFit.best([any, fix, game])?.name, "W11")
+ XCTAssertEqual(EnvironmentFit.best([any, fix])?.name, "Mirror's Edge Catalyst")
+ XCTAssertEqual(EnvironmentFit.best([any])?.name, "Overwatch 2")
+ XCTAssertNil(EnvironmentFit.best([]))
+ let first = EnvironmentFit.Candidate(name: "A", holdsGame: false, hasFix: true)
+ XCTAssertEqual(EnvironmentFit.best([first, fix])?.name, "A", "ties keep the app's order")
+ }
+}