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
four reports answered on the app side: an engine emptied by an antivirus says so and offers itself back (#151, #153), a game the Mac never switched a display mode for is offered the fix that matches rather than another graphics mode (#67, #103), install statistics say what they are (#161), and every launch log records the Mac's output sample rate (#127)
koren631115e49357
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 5b06793..3f926e7 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -136,12 +136,34 @@ final class AppState {appendLog(renderer.map { "\(id): graphics mode set to \($0.rawValue) for this game" } ?? "\(id): graphics mode back to the environment's")}+ /// A game whose last run asked Windows for a fullscreen size this Mac never switched to.+ /// One click tells Wine to pretend the switch happened and scale the game to the screen.+ struct ModesetTrial {+ let itemID: String+ let title: String+ }+ var modesetTrial: ModesetTrial?+ func acceptModesetTrial() {+ defer { modesetTrial = nil }+ guard let trial = modesetTrial, let item = libraryItems.first(where: { $0.id == trial.itemID }) else { return }+ setDisplayModeEmulation(true, for: item)+ }+/// "Had problems" on the post-play row: offer the next mode for this game, then the report.func offerRendererTrial(for record: SessionRecord) {postPlay = nilguard let bottle = bottles.first(where: { $0.name == record.bottle }), let engine = engine(for: bottle),let item = libraryItems.first(where: { $0.steamAppID != nil && $0.steamAppID == record.appid })?? libraryItems.first(where: { $0.title == record.title && $0.bottleName == record.bottle }) else { return }+ // A game that came up in a corner of the screen, with the mouse landing away from what it+ // draws, is not asking for another graphics mode: it asked for a fullscreen size the Mac+ // did not switch to, and every mode behaves the same (highball#67, #103). The log says+ // which of the two happened, so offer the fix that matches rather than a mode to try.+ if displayModeEmulation(for: item) == false, let log = lastLaunchLog(for: item),+ DisplayModeEmulation.looksUnswitched(log: log) {+ modesetTrial = ModesetTrial(itemID: item.id, title: item.title)+ return+ }let current = record.renderer.flatMap(Renderer.init(rawValue:)) ?? rendererOverride(for: item) ?? bottle.settings.rendererlet next = Renderer.suggestion(after: current, d3dmetalAvailable: engine.rendererDir("d3dmetal") != nil,vkd3dAvailable: engine.rendererDir("vkd3d") != nil)@@ -1778,6 +1800,34 @@ final class AppState {}}+ /// Installs an engine again over the copy on disk, for one whose files went missing after it+ /// was installed — an antivirus quarantine emptying parts of Highball's folder, which reaches+ /// the user as Wine failing to find its own DLLs (highball#151, #153). `install` stages a+ /// whole tree and only then replaces the old one, so the id, the bottles on it and their+ /// settings are untouched; accepted licences carry over as they do for an update.+ func reinstallEngine(_ id: String) {+ guard let manifest = manifestForReinstall(id) else {+ fail(HighballError.failed("Highball cannot tell what engine \(id) was made of: its manifest is gone too. Quit Highball, move the engines folder inside ~/Library/Application Support/Highball to the Trash, then open Highball again and it installs its engine fresh.")); return+ }+ let accepted = Set(engines.flatMap { $0.manifest.acceptedLicenses ?? [] })+ runBusy(String(format: L("Installing engine %@ again"), id), expected: L("usually a few minutes"),+ done: DoneState(title: L("Engine installed again"), ctaTitle: nil, cta: nil),+ stop: .cancelTask(label: L("Stop"))) { [self] in+ _ = try await engineStore.install(manifest, accepted: accepted) { name, received, total in+ Task { @MainActor in self.reportDownload(name, received: received, total: total) }+ }+ await MainActor.run { self.appendLog("engine \(id) installed again"); self.refresh() }+ }+ }++ /// What to reinstall engine `id` from: its own manifest, or the bundled one when that file+ /// was taken too and it describes the same engine.+ private func manifestForReinstall(_ id: String) -> EngineManifest? {+ if let m = try? EngineManifest.load(from: paths.engine(id).appending(path: "manifest.json")) { return m }+ guard let url = Self.bundledManifest, let bundled = try? EngineManifest.load(from: url), bundled.id == id else { return nil }+ return bundled+ }+func repairBottle(_ bottle: Bottle) {_repairBottle(bottle, stop: .killBottle(bottle, label: L("Stop")))}diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex 6d3571d..bf8206e 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -204,6 +204,7 @@ struct ContentView: View {.engineAsk(state).updateAsk(state).rendererTrialAsk(state)+ .modesetTrialAsk(state).homeMoveAsk(state).sheet(isPresented: $state.showEpicSignIn) { EpicSignInSheet() }.errorAlert(state)@@ -352,6 +353,20 @@ private extension View {Text(String(format: L("It ran with %@. Another mode often suits a game better on this Mac, and old DirectX 9 games in particular do badly on Wine's own Direct3D. This changes the mode for this game only; the environment keeps its own. Undo it any time under Advanced on the game's page."), GamePageCopy.plainName(trial.current)))}}+ /// The offer that follows a "had problems" on a game whose log shows a fullscreen mode+ /// change the Mac never made (highball#67, #103): the window in the corner, the mouse+ /// landing elsewhere. One click, this game only.+ @MainActor func modesetTrialAsk(_ state: AppState) -> some View {+ self.alert(state.modesetTrial.map { String(format: L("Scale %@ to the screen next time?"), $0.title) } ?? "",+ isPresented: .init(get: { state.modesetTrial != nil }, set: { if !$0 { state.modesetTrial = nil } }),+ presenting: state.modesetTrial) { _ in+ Button(L("Scale it to the screen")) { state.acceptModesetTrial() }+ Button(L("Not now"), role: .cancel) { state.modesetTrial = nil }+ } message: { _ in+ Text(L("Its last run asked Windows for a fullscreen size this Mac did not switch to. That is what leaves a game small in a corner, or with the mouse landing away from what it draws. Highball can have Wine report the change as done and scale the game to the screen instead. This game only; undo it under Advanced on its page."))+ }+ }+@MainActor func homeMoveAsk(_ state: AppState) -> some View {self.alert(state.pendingHome.map { String(format: L("Move Highball's data to %@?"), $0.lastPathComponent) } ?? "",isPresented: .init(get: { state.pendingHome != nil }, set: { if !$0 { state.pendingHome = nil } }),@@ -378,6 +393,7 @@ private extension View {switch r.action {case .retry: retry?()case .repairBottle: if let bottle { state.repairBottle(bottle) } else { retry?() }+ case let .reinstallEngine(id): state.reinstallEngine(id)case .none: break}}diff --git a/Sources/HighballKit/AudioOutput.swift b/Sources/HighballKit/AudioOutput.swiftnew file mode 100644index 0000000..56c0247--- /dev/null+++ b/Sources/HighballKit/AudioOutput.swift@@ -0,0 +1,43 @@+import CoreAudio+import Foundation++/// The Mac's current output sample rate, for the launch header.+///+/// Windows games mix at 48 kHz and Wine hands that to macOS; when the output device runs at+/// 44.1 kHz something has to resample, and that is what people describe as crackling, or as an+/// old speaker about to take a call (highball#127, Counter-Strike 2, on the built-in speakers+/// and on AirPods alike). Nothing here changes a device — a Mac's audio settings are the+/// owner's — it only records the rate the session actually ran at, so a report about sound says+/// which side of that conversion it came from instead of costing three rounds of questions.+public enum AudioOutput {+ /// The default output device's sample rate in Hz, or nil when CoreAudio will not say (no+ /// output device, a sandbox without audio).+ public static func defaultOutputSampleRate() -> Double? {+ var deviceID = AudioDeviceID(0)+ var size = UInt32(MemoryLayout<AudioDeviceID>.size)+ var device = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDefaultOutputDevice,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain)+ guard AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &device, 0, nil, &size, &deviceID) == noErr,+ deviceID != kAudioObjectUnknown else { return nil }+ var rate = Float64(0)+ var rateSize = UInt32(MemoryLayout<Float64>.size)+ var rateAddress = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyNominalSampleRate,+ mScope: kAudioObjectPropertyScopeOutput,+ mElement: kAudioObjectPropertyElementMain)+ guard AudioObjectGetPropertyData(deviceID, &rateAddress, 0, nil, &rateSize, &rate) == noErr, rate > 0 else { return nil }+ return rate+ }++ /// What games mix at, and so the rate that needs no conversion.+ public static let gameSampleRate: Double = 48000++ /// The header line for a rate, or nil when there is nothing to record. Pure, so the wording+ /// is tested without an audio device.+ public static func headerLine(sampleRate: Double?) -> String? {+ guard let rate = sampleRate else { return nil }+ let hz = Int(rate.rounded())+ guard hz != Int(gameSampleRate) else { return "# audio out=\(hz) Hz\n" }+ return "# audio out=\(hz) Hz (games mix at \(Int(gameSampleRate)) Hz, so macOS resamples)\n"+ }+}diff --git a/Sources/HighballKit/DisplayModeEmulation.swift b/Sources/HighballKit/DisplayModeEmulation.swiftindex ec273ff..aeec108 100644--- a/Sources/HighballKit/DisplayModeEmulation.swift+++ b/Sources/HighballKit/DisplayModeEmulation.swift@@ -12,6 +12,27 @@ import Foundationpublic enum DisplayModeEmulation {public static let valueName = "EmulateModeset"+ /// What a fullscreen size the Mac never switched to leaves in a launch log: win32u gives up+ /// on the display it was told to change, once per attempt. The game then draws at the size it+ /// asked for inside a window that stayed the size it was, which is the corner window with the+ /// pointer landing somewhere other than what is drawn — highball#67 (Five Nights at Freddy's)+ /// and #103 (Dead Rising 3) are the same report, and switching graphics modes never moved it.+ public static let unswitchedMarker = "err:system:display_mode_changed"++ /// Whether a launch log shows a game asking for a mode change that never happened. Two+ /// sightings, not one: a lone failure can be a screen waking up or a monitor being plugged+ /// in, while a game that wants a mode the Mac will not give asks again on every attempt.+ public static func looksUnswitched(inLog text: String, atLeast: Int = 2) -> Bool {+ text.split(separator: "\n").filter { $0.contains(unswitchedMarker) }.count >= atLeast+ }++ /// The same question for a log on disk, read head-and-tail so a log of many megabytes — what+ /// a long session leaves — costs a bounded read.+ public static func looksUnswitched(log url: URL, atLeast: Int = 2) -> Bool {+ guard let text = BugReport.boundedText(of: url) else { return false }+ return looksUnswitched(inLog: text, atLeast: atLeast)+ }+/// The per-program key, as `reg add` wants it.public static func key(forExecutable exe: URL) -> String {"HKCU\\Software\\Wine\\AppDefaults\\\(exe.lastPathComponent)\\X11 Driver"diff --git a/Sources/HighballKit/EngineIntegrity.swift b/Sources/HighballKit/EngineIntegrity.swiftnew file mode 100644index 0000000..31e9af0--- /dev/null+++ b/Sources/HighballKit/EngineIntegrity.swift@@ -0,0 +1,65 @@+import Foundation++/// Files that left the engine folder after it was installed.+///+/// Wine prints `err:module:import_dll Library shcore.dll (which is needed by ...) not found`+/// for two unrelated reasons. A program can ask for a DLL it was supposed to ship itself —+/// Steam's `gldriverquery.exe` asks for SDL2.dll on every launch and nothing is wrong — or Wine+/// can fail to find one of its own builtins, which every build of it ships, and that means files+/// are gone from the installed engine. An antivirus quarantine is what that looks like from the+/// inside: highball#151 and #153 both arrived as `exit=53` with five of Wine's own DLLs not+/// found, and both took a round of questions before anyone could say so. The app said+/// "SteamSetup.exe didn't finish. Highball can try again with a fresh copy", which is advice+/// that can never work, because the download was never the problem.+///+/// A name counts only when it is one of Wine's own DLLs AND it really is absent from this+/// engine's lib folders, so a game's missing SDL2.dll stays what it is: the game's business.+public enum EngineIntegrity {+ /// Wine's own DLLs. Every build ships all of these, and nothing installed into a bottle+ /// replaces the copy in the engine's lib folders. Deliberately short: a name here that an+ /// engine legitimately lacks would turn an ordinary failure into a false "engine damaged".+ public static let builtins: Set<String> = [+ "ntdll.dll", "kernel32.dll", "kernelbase.dll", "user32.dll", "gdi32.dll", "advapi32.dll",+ "ole32.dll", "oleaut32.dll", "combase.dll", "shell32.dll", "shlwapi.dll", "shcore.dll",+ "rpcrt4.dll", "msvcrt.dll", "ws2_32.dll", "setupapi.dll", "version.dll", "imm32.dll",+ "comctl32.dll", "comdlg32.dll", "winmm.dll", "win32u.dll", "sechost.dll", "crypt32.dll",+ ]++ /// Where an engine keeps its builtins, 64-bit half first.+ public static func libraryDirectories(engineRoot: URL) -> [URL] {+ ["engine/lib/wine/x86_64-windows", "engine/lib/wine/i386-windows"]+ .map { engineRoot.appending(path: $0, directoryHint: .isDirectory) }+ }++ /// The DLL names in Wine's `Library <name> ... not found` lines, lowercased, in the order+ /// they appeared and without repeats. Pure, so the parsing is tested without a Wine run.+ public static func librariesNotFound(in output: String) -> [String] {+ var seen = Set<String>(), names: [String] = []+ for line in output.split(separator: "\n") where line.contains("import_dll") && line.contains("not found") {+ guard let range = line.range(of: "Library [A-Za-z0-9_.+-]+", options: .regularExpression) else { continue }+ let name = line[range].dropFirst("Library ".count).lowercased()+ guard !name.isEmpty, seen.insert(String(name)).inserted else { continue }+ names.append(String(name))+ }+ return names+ }++ /// Of the DLLs Wine could not find, its own that are absent from this engine on disk.+ /// Empty when the engine is intact, which is the normal answer.+ public static func gone(fromEngineAt root: URL, notFound: [String]) -> [String] {+ let dirs = libraryDirectories(engineRoot: root)+ return notFound.filter { name in+ builtins.contains(name) && !dirs.contains { FileManager.default.fileExists(atPath: $0.appending(path: name).path) }+ }+ }++ /// "shcore.dll, shlwapi.dll and three others", for a sentence.+ public static func list(_ files: [String]) -> String {+ switch files.count {+ case 0: return "Files"+ case 1: return files[0]+ case 2: return "\(files[0]) and \(files[1])"+ default: return "\(files[0]), \(files[1]) and \(files.count - 2) more"+ }+ }+}diff --git a/Sources/HighballKit/EngineStore.swift b/Sources/HighballKit/EngineStore.swiftindex 33a59ad..fdbf24a 100644--- a/Sources/HighballKit/EngineStore.swift+++ b/Sources/HighballKit/EngineStore.swift@@ -6,6 +6,9 @@ public enum HighballError: Error, CustomStringConvertible {case processFailed(command: String, status: Int32, output: String)case missing(String)case invalid(String)+ /// Wine's own DLLs are gone from an installed engine, so nothing Windows can start in it+ /// (highball#151, #153: an antivirus quarantine emptying parts of Highball's folder).+ case engineDamaged(engine: String, files: [String])/// A message already written for the user. Carries no prefix, so it reads as a sentence/// rather than as a category the reader has to decode.case failed(String)@@ -16,6 +19,8 @@ public enum HighballError: Error, CustomStringConvertible {return "checksum mismatch for \(file): expected \(expected), got \(actual)"case let .processFailed(command, status, output):return "\(command) exited with \(status)\n\(output)"+ case let .engineDamaged(engine, files):+ return "engine \(engine) is missing Wine's own \(files.joined(separator: ", "))"case let .missing(what): return "missing: \(what)"case let .invalid(what): return "invalid: \(what)"case let .failed(message): return messagediff --git a/Sources/HighballKit/FunnelLog.swift b/Sources/HighballKit/FunnelLog.swiftindex 7d539f8..97c82da 100644--- a/Sources/HighballKit/FunnelLog.swift+++ b/Sources/HighballKit/FunnelLog.swift@@ -46,7 +46,7 @@ public enum FunnelLog {/// Counts per event plus the failure details, in words a person can check before sending./// Pure: the same records always give the same text.public static func aggregate(_ records: [Record], appVersion: String, macos: String, chip: String) -> String {- var lines = ["Highball \(appVersion), macOS \(macos), \(chip)", ""]+ var lines = ["Highball \(appVersion), macOS \(macos), \(chip)", "", preamble, ""]for event in Event.allCases {let matching = records.filter { $0.event == event }guard !matching.isEmpty else { continue }@@ -57,10 +57,22 @@ public enum FunnelLog {}lines.append(line)}- if lines.count == 2 { lines.append("no events yet") }+ if lines.last == "" { lines.append("no events yet") }+ if !records.contains(where: { $0.event == .downloadFailed || $0.event == .extractFailed }) {+ lines += ["", "Nothing failed on this Mac."]+ }return lines.joined(separator: "\n")}+ /// What the counts are, in the issue itself. Without it the numbers arrive as a wall titled+ /// "Install statistics" that reads like a bug report with the words missing: highball#161 is+ /// one, sent by an install where nothing went wrong, and a passer-by answered it with "n".+ public static let preamble = """+ Install counters from Highball, sent on purpose from its activity strip. This is not a \+ bug report and needs no reply: it counts how often installing Highball and starting a \+ first game get through, so the failures have something to be measured against.+ """+/// The issue that carries the aggregate: the person sees the text before the browser opens.public static func url(aggregate: String) -> URL {var comps = URLComponents(string: "https://github.com/gauthierpiarrette/highball/issues/new")!diff --git a/Sources/HighballKit/Recovery.swift b/Sources/HighballKit/Recovery.swiftindex 5f4d1db..94a546b 100644--- a/Sources/HighballKit/Recovery.swift+++ b/Sources/HighballKit/Recovery.swift@@ -10,6 +10,8 @@ public struct Recovery: Equatable, Sendable {case retry/// Re-run the bottle's Windows setup.case repairBottle+ /// Download and unpack this engine again over the damaged copy.+ case reinstallEngine(String)/// Nothing automatic; the details and a report are the next step.case none}@@ -45,6 +47,14 @@ public struct Recovery: Equatable, Sendable {return Recovery(headline: (error as NSError).localizedDescription, meaning: "")}switch known {+ case let .engineDamaged(engine, files):+ // The files came back as "not found" from inside Wine, so the loader's own words+ // ("could not load ...") are useless here: say where the files went and offer the+ // one thing that brings them back. The exclusion matters more than the download —+ // without it the fresh engine is quarantined again within the hour (#153).+ return Recovery(headline: "Files are missing from Highball's engine.",+ meaning: "\(EngineIntegrity.list(files)) left engine \(engine) after it was installed, so no Windows program can start in it. Antivirus software quarantining Highball's folder is what this looks like from the inside: add ~/Library/Application Support/Highball to its exclusions first, then install the engine again.",+ actionTitle: "Install the engine again", action: .reinstallEngine(engine))case .checksumMismatch:return Recovery(headline: "The download didn't arrive intact.",meaning: "This is usually a network problem. Highball discards the damaged file and downloads it again.",diff --git a/Sources/HighballKit/WineRunner.swift b/Sources/HighballKit/WineRunner.swiftindex b2c7aa0..eea2fb2 100644--- a/Sources/HighballKit/WineRunner.swift+++ b/Sources/HighballKit/WineRunner.swift@@ -82,6 +82,8 @@ public struct WineRunner: Sendable {case .active(let m): out += " frameGen=\(m)x(requested\(env["LSFGM_PACING_MODE"] == "adaptive" ? ", adaptive" : "")\(env["LSFGM_FLOW_SCALE"].map { ", flow \($0)" } ?? "")\(env["LSFGM_PERFORMANCE_MODE"] == "1" ? ", performance" : ""))\n"case .unavailable: out += " frameGen=off(unavailable)\n"}+ // The Mac's output rate: a sound report is unanswerable without it (highball#127).+ if let audio = AudioOutput.headerLine(sampleRate: AudioOutput.defaultOutputSampleRate()) { out += audio }for key in ["WINEDLLPATH_PREPEND", "WINEDLLOVERRIDES", "ROSETTA_ADVERTISE_AVX", "MTL_HUD_ENABLED", "CX_FWD_COMPAT_GL_CTX", "DXVK_CONFIG_FILE", "DXVK_LOG_PATH", "LSFGM_MULTIPLIER", "LSFGM_PACING_MODE", "LSFGM_FLOW_SCALE", "LSFGM_DLL_PATH"] {if let value = env[key] { out += "# \(key)=\(value)\n" }}@@ -174,6 +176,10 @@ public struct WineRunner: Sendable {}let reader = pipe.fileHandleForReading+ // Wine's "Library x.dll ... not found" lines, kept so a failed run can be told apart+ // from an engine whose files are gone (EngineIntegrity, highball#151/#153). Only those+ // lines are kept: the rest of a launch's output can run to megabytes.+ let importFailures = Collector()// The exit code used to be computed and thrown away: a failed install produced a log// shape-identical to a successful one, so user-submitted reports were undiagnosable// (issue #36 cost two research passes to answer). It is now a footer, written below.@@ -195,6 +201,7 @@ public struct WineRunner: Sendable {while let nl = buffer.firstIndex(of: 0x0A) {let line = String(decoding: buffer[..<nl], as: UTF8.self)buffer.removeSubrange(...nl)+ if line.contains("import_dll") { importFailures.append(line) }onOutput?(line)}}@@ -220,6 +227,16 @@ public struct WineRunner: Sendable {try? tail.close()}onOutput?(footer.trimmingCharacters(in: .newlines))+ // A run that failed while Wine could not find its own DLLs is not a failure of what was+ // run: the engine has been emptied out under Highball (an antivirus quarantine is the+ // usual cause), and every launch in it will fail the same way until it is installed+ // again. Say so here, once, rather than leaving each caller to offer "try again with a+ // fresh copy" for a download that was never the problem (highball#151, #153).+ let gone = EngineIntegrity.gone(fromEngineAt: engine.root,+ notFound: EngineIntegrity.librariesNotFound(in: importFailures.lines.joined(separator: "\n")))+ if status != 0, !gone.isEmpty {+ throw HighballError.engineDamaged(engine: engine.id, files: gone)+ }return LaunchResult(exitStatus: status, duration: duration, log: logURL, note: resolved.note)}diff --git a/Tests/HighballKitTests/AudioOutputTests.swift b/Tests/HighballKitTests/AudioOutputTests.swiftnew file mode 100644index 0000000..02a791d--- /dev/null+++ b/Tests/HighballKitTests/AudioOutputTests.swift@@ -0,0 +1,25 @@+import XCTest+@testable import HighballKit++/// highball#127: "the music lags, like old computer speakers" took three rounds to get as far as+/// the Mac's output rate, because no log ever said what it was.+final class AudioOutputTests: XCTestCase {+ func testMatchingRateIsRecordedPlainly() {+ XCTAssertEqual(AudioOutput.headerLine(sampleRate: 48000), "# audio out=48000 Hz\n")+ }++ func testAMismatchSaysWhatItMeans() {+ let line = AudioOutput.headerLine(sampleRate: 44100)+ XCTAssertEqual(line, "# audio out=44100 Hz (games mix at 48000 Hz, so macOS resamples)\n")+ }++ func testNoDeviceAddsNoLine() {+ XCTAssertNil(AudioOutput.headerLine(sampleRate: nil))+ }++ func testTheRateOfThisMacIsPlausibleWhenThereIsOne() {+ guard let rate = AudioOutput.defaultOutputSampleRate() else { return } // CI has no output device+ XCTAssertGreaterThanOrEqual(rate, 8000)+ XCTAssertLessThanOrEqual(rate, 768000)+ }+}diff --git a/Tests/HighballKitTests/DisplayModeEmulationTests.swift b/Tests/HighballKitTests/DisplayModeEmulationTests.swiftindex 644b303..841d048 100644--- a/Tests/HighballKitTests/DisplayModeEmulationTests.swift+++ b/Tests/HighballKitTests/DisplayModeEmulationTests.swift@@ -44,3 +44,34 @@ extension DisplayModeEmulationTests {XCTAssertFalse(DisplayModeEmulation.isOn(in: bottle, executable: URL(fileURLWithPath: "/x/PEAK.exe")))}}++/// highball#67 (Five Nights at Freddy's) and #103 (Dead Rising 3): the game comes up small in a+/// corner and the mouse lands away from what it draws, and every graphics mode does the same,+/// because the fullscreen size it asked for is one the Mac never switched to.+final class UnswitchedDisplayModeTests: XCTestCase {+ private func log(_ attempts: Int) -> String {+ (["# gin x64-sikarugir10.0_6-r3 bottle=Games renderer=dxvk"]+ + (0..<attempts).map { "00d\($0):err:system:display_mode_changed Failed to get primary source current display settings." }+ + ["# exit=0 after 934s"]).joined(separator: "\n")+ }++ func testRepeatedFailedModeChangesAreTheTell() {+ XCTAssertTrue(DisplayModeEmulation.looksUnswitched(inLog: log(3)))+ XCTAssertTrue(DisplayModeEmulation.looksUnswitched(inLog: log(2)))+ }++ func testOneFailureIsNotEnough() {+ // A screen waking up or a monitor being plugged in fails the same read once.+ XCTAssertFalse(DisplayModeEmulation.looksUnswitched(inLog: log(1)))+ }++ func testAnOrdinaryLogSaysNothing() {+ let ordinary = """+ # gin x64-sikarugir10.0_6-r3 bottle=Games renderer=dxmt+ 0164:err:environ:init_peb starting L"C:\\\\Program Files (x86)\\\\Steam\\\\steam.exe" in experimental wow64 mode+ 0138:err:ole:com_get_class_object apartment not initialised+ # exit=0 after 120s+ """+ XCTAssertFalse(DisplayModeEmulation.looksUnswitched(inLog: ordinary))+ }+}diff --git a/Tests/HighballKitTests/EngineIntegrityTests.swift b/Tests/HighballKitTests/EngineIntegrityTests.swiftnew file mode 100644index 0000000..e3cc346--- /dev/null+++ b/Tests/HighballKitTests/EngineIntegrityTests.swift@@ -0,0 +1,81 @@+import XCTest+@testable import HighballKit++/// highball#151 and #153: an antivirus emptied part of ~/Library/Application Support/Highball,+/// and every install then died with "exit=53" and Wine's own DLLs "not found". The app offered+/// "try again with a fresh copy" — a download that was never the problem — and both reports took+/// a round of questions to answer by hand.+final class EngineIntegrityTests: XCTestCase {+ /// The log from #153, as it arrived.+ private let output = """+ 0024:err:environ:init_peb starting L"Z:\\\\Users\\\\yanhee\\\\SteamSetup.exe" in experimental wow64 mode+ 0024:err:module:import_dll Library shcore.dll (which is needed by L"C:\\\\windows\\\\system32\\\\shlwapi.dll") not found+ 0024:err:module:import_dll Library shlwapi.dll (which is needed by L"C:\\\\windows\\\\system32\\\\SHELL32.dll") not found+ 0024:err:module:import_dll Library SHELL32.dll (which is needed by L"Z:\\\\Users\\\\yanhee\\\\SteamSetup.exe") not found+ 0024:err:module:import_dll Library combase.dll (which is needed by L"C:\\\\windows\\\\system32\\\\ole32.dll") not found+ 0024:err:module:import_dll Library ole32.dll (which is needed by L"Z:\\\\Users\\\\yanhee\\\\SteamSetup.exe") not found+ 0024:err:module:loader_init Importing dlls for L"Z:\\\\Users\\\\yanhee\\\\SteamSetup.exe" failed, status c0000135+ """++ func testNamesAreReadOnceEachAndLowercased() {+ XCTAssertEqual(EngineIntegrity.librariesNotFound(in: output),+ ["shcore.dll", "shlwapi.dll", "shell32.dll", "combase.dll", "ole32.dll"])+ }++ func testAGameShippingItsOwnMissingDllIsNotTheEngine() throws {+ // Steam's gldriverquery.exe asks for SDL2.dll on every launch and nothing is wrong+ // (highball#156's log carries it while the engine is intact).+ let steam = """+ 0348:err:module:import_dll Library SDL2.dll (which is needed by L"C:\\\\Program Files (x86)\\\\Steam\\\\bin\\\\gldriverquery.exe") not found+ """+ let root = try engineTree(shipping: ["ole32.dll", "shell32.dll"])+ XCTAssertEqual(EngineIntegrity.librariesNotFound(in: steam), ["sdl2.dll"])+ XCTAssertEqual(EngineIntegrity.gone(fromEngineAt: root, notFound: EngineIntegrity.librariesNotFound(in: steam)), [])+ }++ func testOnlyWineOwnDllsAbsentFromTheEngineCount() throws {+ let root = try engineTree(shipping: ["ole32.dll", "shell32.dll"])+ // shcore/shlwapi/combase are gone from the engine; ole32 and shell32 are still there,+ // so their "not found" lines are the loader's fallout, not more missing files.+ XCTAssertEqual(EngineIntegrity.gone(fromEngineAt: root, notFound: EngineIntegrity.librariesNotFound(in: output)),+ ["shcore.dll", "shlwapi.dll", "combase.dll"])+ }++ func testAnIntactEngineReportsNothing() throws {+ let root = try engineTree(shipping: ["shcore.dll", "shlwapi.dll", "shell32.dll", "combase.dll", "ole32.dll"])+ XCTAssertEqual(EngineIntegrity.gone(fromEngineAt: root, notFound: EngineIntegrity.librariesNotFound(in: output)), [])+ }++ func testThe32BitHalfCountsAsShipping() throws {+ let root = try engineTree(shipping: [], shipping32: ["shcore.dll", "shlwapi.dll", "shell32.dll", "combase.dll", "ole32.dll"])+ XCTAssertEqual(EngineIntegrity.gone(fromEngineAt: root, notFound: EngineIntegrity.librariesNotFound(in: output)), [])+ }++ func testTheAlertNamesTheFilesAndOffersTheEngineBack() {+ let r = Recovery.describe(HighballError.engineDamaged(engine: "x64-sikarugir10.0_6-r3",+ files: ["shcore.dll", "shlwapi.dll", "combase.dll"]))+ XCTAssertEqual(r.action, .reinstallEngine("x64-sikarugir10.0_6-r3"))+ XCTAssertTrue(r.meaning.contains("shcore.dll"), r.meaning)+ XCTAssertTrue(r.meaning.contains("exclusions"), r.meaning)+ // Never the old advice: a fresh download of the installer cannot fix an emptied engine.+ XCTAssertFalse(r.meaning.contains("fresh copy"), r.meaning)+ }++ func testListReadsAsASentence() {+ XCTAssertEqual(EngineIntegrity.list(["a.dll"]), "a.dll")+ XCTAssertEqual(EngineIntegrity.list(["a.dll", "b.dll"]), "a.dll and b.dll")+ XCTAssertEqual(EngineIntegrity.list(["a.dll", "b.dll", "c.dll", "d.dll"]), "a.dll, b.dll and 2 more")+ }++ /// An engine tree holding only the DLLs named.+ private func engineTree(shipping: [String], shipping32: [String] = []) throws -> URL {+ let root = FileManager.default.temporaryDirectory.appending(path: "engine-\(UUID().uuidString)")+ addTeardownBlock { try? FileManager.default.removeItem(at: root) }+ for (dir, names) in [("x86_64-windows", shipping), ("i386-windows", shipping32)] {+ let d = root.appending(path: "engine/lib/wine/\(dir)")+ try FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)+ for name in names { try Data().write(to: d.appending(path: name)) }+ }+ return root+ }+}diff --git a/Tests/HighballKitTests/FunnelLogTests.swift b/Tests/HighballKitTests/FunnelLogTests.swiftindex 0cba526..c23513a 100644--- a/Tests/HighballKitTests/FunnelLogTests.swift+++ b/Tests/HighballKitTests/FunnelLogTests.swift@@ -21,12 +21,31 @@ final class FunnelLogTests: XCTestCase {XCTAssertEqual(text, """Highball 0.7.23, macOS 26.6.2, Apple M1 Pro+ \(FunnelLog.preamble)+install-started: 2download-failed: 1 (URLError -1005 at 164 MB)install-completed: 1session-ended: 1""")- XCTAssertTrue(FunnelLog.aggregate([], appVersion: "x", macos: "y", chip: "z").hasSuffix("no events yet"))+ XCTAssertTrue(FunnelLog.aggregate([], appVersion: "x", macos: "y", chip: "z").contains("no events yet"))+ }++ /// highball#161 arrived as a wall of counters titled "Install statistics", from an install+ /// where nothing had gone wrong, and read as a bug report nobody could act on. The issue now+ /// says what it is and whether anything failed.+ func testTheIssueSaysWhatItIsAndWhetherAnythingFailed() {+ let clean = FunnelLog.aggregate([.init(event: .installStarted), .init(event: .installCompleted),+ .init(event: .firstLaunch), .init(event: .sessionEnded, detail: "540 s")],+ appVersion: "0.9.28", macos: "26.5.2", chip: "Apple M2")+ XCTAssertTrue(clean.contains("not a"), clean)+ XCTAssertTrue(clean.contains("needs no reply"), clean)+ XCTAssertTrue(clean.hasSuffix("Nothing failed on this Mac."), clean)++ let failed = FunnelLog.aggregate([.init(event: .installStarted),+ .init(event: .downloadFailed, detail: "URLError -1005 at 164 MB")],+ appVersion: "0.9.28", macos: "26.5.2", chip: "Apple M2")+ XCTAssertFalse(failed.contains("Nothing failed"), failed)}func testIssueURLCarriesTheAggregate() throws {