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
Stop ends an Epic download, and quitting Highball does too (highball#323). The strip's Stop cancelled a Swift task nothing listened to: the install awaited a detached task blocked on legendary's output, and legendary itself never heard about it, so Stop did nothing however often it was pressed, and the download went on after the app quit, holding legendary's install lock. The next install then failed with "Failed to acquire installed data lock", which legendary reports as success (status 0, checked in its cli.py), so the strip said Done over nothing installed. Now Stop sends what Ctrl-C in a terminal sends, SIGINT to legendary and every process it started (its downloader runs in child processes), which legendary answers by keeping its progress for the next Install ("Downloads are resumable", its own message), then SIGTERM after 10 seconds and SIGKILL after 15 for anything still running, each process checked against its start time so a reused pid is never hit. Quitting the app stops a running Epic install the same way. The lock refusal now fails the install with a message that names the likely cause. New tests, with a shell tree whose background children ignore SIGINT as the escalation's case.
Gauthier Piarrette89f56253c0c7
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex e1d49f5..2637fe8 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -2,6 +2,7 @@ import AppKitimport Foundationimport HighballKitimport Observation+import os/// The three Settings tabs, so a deep link can select one.enum SettingsTab: Hashable { case environments, engine, troubleshooting }@@ -2653,16 +2654,31 @@ final class AppState {}}+ /// The Epic install running now, for the strip's Stop and for quitting the app (highball#323).+ @ObservationIgnored private var epicInstallControl: LegendaryControl?+func epicInstall(_ game: EpicStore.Game, in bottle: Bottle) {+ let control = LegendaryControl()runBusy("Installing \(game.app_title)", expected: L("a large download; you can leave it running"),- stop: .cancelTask(label: L("Stop"))) { [self] in+ stop: .cancelTask(label: L("Stop")), cleanup: { [weak self] in self?.epicInstallControl = nil }) { [self] in+ epicInstallControl = controllet store = epicStoreepicDownloadTotal = nil- let status = try await Task.detached {- try store.install(game.app_name, into: bottle) { line in- Task { @MainActor in self.appendLog(line); self.reportEpicDownload(line) }- }- }.value+ let refused = OSAllocatedUnfairLock(initialState: false)+ // Stop cancels this task, and the cancellation reaches legendary as a Ctrl-C, which+ // keeps the download's progress for the next Install.+ let status = try await withTaskCancellationHandler {+ try await Task.detached {+ try store.install(game.app_name, into: bottle, control: control) { line in+ if EpicStore.refusedForLock(line) { refused.withLock { $0 = true } }+ Task { @MainActor in self.appendLog(line); self.reportEpicDownload(line) }+ }+ }.value+ } onCancel: { control.stop() }+ try Task.checkCancellation()+ if refused.withLock({ $0 }) {+ throw HighballError.failed(L("Another Epic download is still running, and legendary installs one game at a time. If Highball shows none, one started before Highball last quit is still going, so quit legendary in Activity Monitor and press Install again."))+ }guard status == 0 else {throw HighballError.processFailed(command: "epic install", status: status, output: "see the log above")}@@ -2670,6 +2686,10 @@ final class AppState {}}+ /// Quitting the app stops an Epic download the way Stop does, so it never runs on alone,+ /// holding legendary's install lock with nothing on screen to stop it (highball#323).+ func stopEpicInstall() { epicInstallControl?.stop() }+// renderer nil = the bottle's own renderer (the old hardcoded .dxvk default ignored it)./// `throughEpicLauncherStandIn`: a Rockstar game bought on Epic (its recipe requires the/// Rockstar launcher) starts through a stand-in named EpicGamesLauncher.exe placed in thediff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex a44e5bb..6e17063 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -143,6 +143,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {}func applicationWillTerminate(_ notification: Notification) {+ appState?.stopEpicInstall()DiscordPresence.shared.setEnabled(false)DiscordPresence.shared.stop()}diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex cdf2a45..eeb6137 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -523,6 +523,7 @@ enum L10n {"Stop and repair": "Arrêter et réparer","Stopped.": "Arrêté.","Stopped. Nothing already downloaded is lost.": "Arrêté. Rien de déjà téléchargé n'est perdu.",+ "Another Epic download is still running, and legendary installs one game at a time. If Highball shows none, one started before Highball last quit is still going, so quit legendary in Activity Monitor and press Install again.": "Un autre téléchargement Epic est toujours en cours, et legendary installe un jeu à la fois. Si Highball n'en montre aucun, un téléchargement lancé avant la dernière fermeture de Highball continue, alors quittez legendary dans le Moniteur d'activité et appuyez de nouveau sur Installer.","Stopped. Repairing the bottle so nothing half-installed stays behind.": "Arrêté. Réparation de l'environnement pour ne rien laisser à moitié installé.","That usually means the graphics mode doesn't suit it on this Mac. Highball can switch this bottle to %@, or move it to engine %@.": "Cela veut généralement dire que le mode graphique ne lui convient pas sur ce Mac. Highball peut passer cet environnement en %@, ou le déplacer sur le moteur %@.","That usually means the graphics mode doesn't suit it on this Mac. Highball can switch this bottle to %@.": "Cela veut généralement dire que le mode graphique ne lui convient pas sur ce Mac. Highball peut passer cet environnement en %@.",diff --git a/Sources/HighballKit/EpicStore.swift b/Sources/HighballKit/EpicStore.swiftindex 93d0f18..b1b316a 100644--- a/Sources/HighballKit/EpicStore.swift+++ b/Sources/HighballKit/EpicStore.swift@@ -61,8 +61,10 @@ public struct EpicStore: Sendable {}/// Runs legendary streaming each output line (installs are long and progress matters).+ /// `control` lets the caller stop it the way Ctrl-C in a terminal does.@discardableResult- public func runStreaming(_ args: [String], onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ public func runStreaming(_ args: [String], control: LegendaryControl? = nil,+ onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {let p = Process()p.executableURL = binaryp.arguments = args@@ -71,6 +73,7 @@ public struct EpicStore: Sendable {p.standardOutput = pipep.standardError = pipetry p.run()+ control?.started(p)let reader = pipe.fileHandleForReadingvar buffer = Data()while true {@@ -188,10 +191,18 @@ public struct EpicStore: Sendable {/// Installs a game's Windows build into the bottle at drive_c/Games/<folder>.@discardableResult- public func install(_ appName: String, into bottle: Bottle, onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {+ public func install(_ appName: String, into bottle: Bottle, control: LegendaryControl? = nil,+ onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {let base = bottle.driveC.appending(path: "Games", directoryHint: .isDirectory)try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)- return try runStreaming(Self.installArguments(appName: appName, basePath: base.path), onLine: onLine)+ return try runStreaming(Self.installArguments(appName: appName, basePath: base.path), control: control, onLine: onLine)+ }++ /// legendary refuses to start an install while another legendary holds its install lock,+ /// and returns as if it had succeeded, status 0, so the strip said Done over nothing+ /// installed (highball#323, a download from before a restart still running).+ public static func refusedForLock(_ line: String) -> Bool {+ line.contains("Failed to acquire installed data lock")}/// legendary's install log names the download's size before it starts ("Download size:@@ -254,3 +265,75 @@ public struct EpicStore: Sendable {environment: env)}}++/// Stops a running legendary the way Ctrl-C in a terminal does. A terminal signals the whole+/// process group, and legendary's downloader runs in child processes, so SIGINT goes to+/// legendary and everything it started. legendary answers by keeping the download's progress,+/// and the same install picks up from there later ("Downloads are resumable, you can interrupt+/// the download with CTRL-C and resume it using the same command later on", its install+/// output). Whatever is still running after the grace period gets SIGTERM, and SIGKILL half a+/// period later, including a child left behind by a parent that already exited. Each process+/// is signalled only while it is the one seen at Stop, by its start time, so a pid taken over+/// in the meantime is never hit. Before this the strip's Stop cancelled a task nothing was+/// listening to, and the download outlived the app (highball#323).+public final class LegendaryControl: @unchecked Sendable {+ private let lock = NSLock()+ private var process: Process?+ private var stopRequested = false+ /// Seconds between SIGINT and SIGTERM, and SIGKILL at one and a half times that.+ private let grace: TimeInterval++ public init(grace: TimeInterval = 10) { self.grace = grace }++ func started(_ process: Process) {+ let stopNow = lock.withLock { () -> Bool in self.process = process; return stopRequested }+ if stopNow { stop() }+ }++ public func stop() {+ let process = lock.withLock { () -> Process? in stopRequested = true; return self.process }+ guard let process else { return }+ let seen = Self.members(of: process)+ Self.signal(seen, SIGINT)+ DispatchQueue.global().asyncAfter(deadline: .now() + grace) { Self.signal(seen + Self.members(of: process), SIGTERM) }+ DispatchQueue.global().asyncAfter(deadline: .now() + grace * 1.5) { Self.signal(seen + Self.members(of: process), SIGKILL) }+ }++ struct Member: Hashable {+ let pid: pid_t+ let started: UInt64+ }++ /// legendary and every process under it, each with its start time, or none once legendary+ /// itself has exited.+ private static func members(of process: Process) -> [Member] {+ guard process.isRunning else { return [] }+ return tree(process.processIdentifier).compactMap { pid in startTime(pid).map { Member(pid: pid, started: $0) } }+ }++ private static func signal(_ members: [Member], _ signal: Int32) {+ for member in Set(members) where startTime(member.pid) == member.started { kill(member.pid, signal) }+ }++ /// When the process started, in microseconds, or nil when there is no such process.+ static func startTime(_ pid: pid_t) -> UInt64? {+ var info = proc_bsdinfo()+ let size = Int32(MemoryLayout<proc_bsdinfo>.size)+ guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, size) == size else { return nil }+ return info.pbi_start_tvsec &* 1_000_000 &+ info.pbi_start_tvusec+ }++ /// A process and every process under it, parents first.+ static func tree(_ root: pid_t) -> [pid_t] {+ var pids = [root], next = 0+ while next < pids.count {+ let parent = pids[next]; next += 1+ let count = proc_listchildpids(parent, nil, 0)+ guard count > 0 else { continue }+ var children = [pid_t](repeating: 0, count: Int(count) + 8)+ let found = children.withUnsafeMutableBytes { proc_listchildpids(parent, $0.baseAddress, Int32($0.count)) }+ for child in children.prefix(Int(max(found, 0))) where child > 0 && !pids.contains(child) { pids.append(child) }+ }+ return pids+ }+}diff --git a/Tests/HighballKitTests/LegendaryControlTests.swift b/Tests/HighballKitTests/LegendaryControlTests.swiftnew file mode 100644index 0000000..b4e8703--- /dev/null+++ b/Tests/HighballKitTests/LegendaryControlTests.swift@@ -0,0 +1,54 @@+import XCTest+@testable import HighballKit++/// highball#323: the strip's Stop cancelled a task nothing listened to, so an Epic download+/// went on, and outlived the app. Stop now signals legendary and every process it started,+/// the way Ctrl-C in a terminal does, and escalates for whatever is still running.+final class LegendaryControlTests: XCTestCase {+ private func run(_ script: String) throws -> Process {+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/bin/sh")+ p.arguments = ["-c", script]+ try p.run()+ return p+ }++ private func waitUntil(_ seconds: TimeInterval = 5, _ condition: () -> Bool) {+ let deadline = Date().addingTimeInterval(seconds)+ while !condition(), Date() < deadline { usleep(50_000) }+ }++ private func alive(_ pid: pid_t) -> Bool { kill(pid, 0) == 0 }++ func testStopEndsTheProcessAndEverythingUnderIt() throws {+ // A shell's background jobs ignore SIGINT, as a downloader child might not answer it+ // either, so this also covers the escalation to SIGTERM.+ let p = try run("sleep 60 & sleep 60 & wait")+ waitUntil { LegendaryControl.tree(p.processIdentifier).count >= 3 }+ let tree = LegendaryControl.tree(p.processIdentifier)+ XCTAssertEqual(tree.count, 3, "the shell and its two sleeps")+ XCTAssertEqual(tree.first, p.processIdentifier, "parents first")++ let control = LegendaryControl(grace: 0.3)+ control.started(p)+ control.stop()+ waitUntil { !p.isRunning }+ XCTAssertFalse(p.isRunning)+ waitUntil { !tree.dropFirst().contains(where: alive) }+ XCTAssertFalse(tree.dropFirst().contains(where: alive), "no child left running")+ }++ func testAStopBeforeTheStartStopsItAsSoonAsItStarts() throws {+ let control = LegendaryControl(grace: 0.3)+ control.stop()+ let p = try run("exec sleep 60")+ control.started(p)+ waitUntil { !p.isRunning }+ XCTAssertFalse(p.isRunning)+ }++ func testTheLockRefusalIsRecognized() {+ XCTAssertTrue(EpicStore.refusedForLock("[cli] CRITICAL: Failed to acquire installed data lock, only one instance of Legendary may install/import/move applications at a time."))+ XCTAssertFalse(EpicStore.refusedForLock("[cli] INFO: Download size: 95232.19 MiB (Compression savings: 2.1%)"))+ }+}