Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

fix(prefix): protect saves in rebuilds and refuse Steam changes while a game runs (#1921)

Raymond Chin34b49055b71c
diff --git a/Makefile b/Makefile
index d33d1e2..9cbcac9 100644
--- a/Makefile
+++ b/Makefile
@@ -711,6 +711,7 @@ app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO)
cp -f signatures/macos.arm64/*.json "$(APP_PAYLOAD)/signatures/macos.arm64/"
@rm -rf "$(APP_PAYLOAD)/gamefixes" && mkdir -p "$(APP_PAYLOAD)/gamefixes"
@if ls gamefixes/*.conf >/dev/null 2>&1; then cp -f gamefixes/*.conf "$(APP_PAYLOAD)/gamefixes/"; fi
+ cp -f installer/config/gamecontrollerdb.txt "$(APP_PAYLOAD)/gamecontrollerdb.txt"
@set -e; for spec in $(BRIDGE_FILES); do \
src="$${spec%%:*}"; dst="$(APP_PAYLOAD)/bridge/$${spec##*:}"; \
if [ -f "$$src" ]; then cp -f "$$src" "$$dst"; \
diff --git a/app/Sources/BridgeplayApp/Model/BrandMigration.swift b/app/Sources/BridgeplayApp/Model/BrandMigration.swift
index 5a3abdf..37057a4 100644
--- a/app/Sources/BridgeplayApp/Model/BrandMigration.swift
+++ b/app/Sources/BridgeplayApp/Model/BrandMigration.swift
@@ -58,14 +58,15 @@ struct BrandMigration: Sendable {
var launchOptionsRewritten = 0
var symlinksFixed = 0
var logsRenamed = 0
+ var logsLeft = 0
var filesRewritten = 0
- var backups: URL?
var notes: [String] = []
var description: String {
"Moved NotProton data to Bridgeplay 3.0.0: \(toolsRenamed) compatibility tools renamed, "
+ "\(mappingsRewritten) Steam mappings and \(launchOptionsRewritten) launch options rewritten, "
+ "\(symlinksFixed) symlinks fixed, \(logsRenamed) logs renamed, \(filesRewritten) files rewritten."
+ + (logsLeft == 0 ? "" : " \(logsLeft) logs could not be renamed.")
+ (notes.isEmpty ? "" : " " + notes.joined(separator: " "))
}
}
@@ -106,10 +107,8 @@ struct BrandMigration: Sendable {
try writeMarker(done)
if !done.contains(.backup) {
- summary.backups = try backUpSteamConfig()
+ try backUpSteamConfig()
try record(.backup)
- } else {
- summary.backups = support.appending(path: Self.backupFolder)
}
if !done.contains(.move) {
try moveDirectories(&summary)
@@ -138,7 +137,7 @@ struct BrandMigration: Sendable {
try record(.launchOptions)
}
if !done.contains(.runLogs) {
- summary.logsRenamed += try renameRunLogs()
+ renameRunLogs(&summary)
try record(.runLogs)
}
try record(.done)
@@ -183,7 +182,7 @@ struct BrandMigration: Sendable {
// Copies go into whichever support directory exists now, so they move along in step 2.
// A copy already there is the older one and is kept.
- private func backUpSteamConfig() throws -> URL {
+ private func backUpSteamConfig() throws {
let files = FileManager.default
let backups = markerHome.appending(path: Self.backupFolder)
let root = steamUserData.path(percentEncoded: false)
@@ -196,7 +195,6 @@ struct BrandMigration: Sendable {
try files.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
try files.copyItem(at: source, to: destination)
}
- return support.appending(path: Self.backupFolder)
}
// MARK: Step 2, moving directories
@@ -417,21 +415,24 @@ struct BrandMigration: Sendable {
// Renames steamapps/compatdata/<appid>/notproton-run.log in every library Steam lists.
// One directory listing per library and one stat per game; a library on a volume that
- // is not mounted is skipped.
- private func renameRunLogs() throws -> Int {
- var renamed = 0
+ // is not mounted is skipped. A log this account can't rename, in a library another user
+ // owns, stays under the old name, where PrefixLog still finds it.
+ private func renameRunLogs(_ summary: inout Summary) {
for library in libraries() {
let compatdata = library.appending(path: "steamapps/compatdata")
let games = (try? FileManager.default.contentsOfDirectory(atPath: compatdata.path(percentEncoded: false))) ?? []
for game in games.sorted() {
let folder = compatdata.appending(path: game)
- if try Self.renameIfFree(folder.appending(path: "notproton-run.log"),
- to: folder.appending(path: "bridgeplay-run.log")) {
- renamed += 1
+ do {
+ if try Self.renameIfFree(folder.appending(path: "notproton-run.log"),
+ to: folder.appending(path: "bridgeplay-run.log")) {
+ summary.logsRenamed += 1
+ }
+ } catch {
+ summary.logsLeft += 1
}
}
}
- return renamed
}
// Library roots from steamapps/libraryfolders.vdf, always including Steam's own folder.
diff --git a/app/Sources/BridgeplayApp/Model/GameReport.swift b/app/Sources/BridgeplayApp/Model/GameReport.swift
index ea121ac..4511758 100644
--- a/app/Sources/BridgeplayApp/Model/GameReport.swift
+++ b/app/Sources/BridgeplayApp/Model/GameReport.swift
@@ -145,6 +145,8 @@ enum GameReport {
(#"(?m)^(SteamUser|SteamAppUser|STEAMVIDEOTOKEN|DSB_TOKEN)=.*$"#, "$1=<redacted>"),
(#"\b7656119\d{10}\b"#, "<steamid>"),
(#"\[U:1:\d+\]"#, "[U:1:<redacted>]"),
+ // The account ID, which is the SteamID64 less a constant.
+ (#"(?i)(userdata[/\\]+)\d+"#, "$1<id>"),
(#"[\w.+-]{1,64}@[\w-]{1,63}(\.[\w-]{1,63})+"#, "<email>"),
(#"/Volumes/(?!Preboot/|Macintosh HD/)[^/\n:]+"#, "/Volumes/<drive>"),
// Wine's view of a home folder whose name differs from the account name.
diff --git a/app/Sources/BridgeplayApp/Model/InstallScriptMarkers.swift b/app/Sources/BridgeplayApp/Model/InstallScriptMarkers.swift
index d502e4f..1a2ce14 100644
--- a/app/Sources/BridgeplayApp/Model/InstallScriptMarkers.swift
+++ b/app/Sources/BridgeplayApp/Model/InstallScriptMarkers.swift
@@ -19,7 +19,8 @@ enum InstallScriptMarkers {
var markers: [Marker] = []
var path: [String] = []
var pending: String?
- for raw in text.split(separator: "\n", omittingEmptySubsequences: true) {
+ // isNewline, as "\r\n" is one Character and a CRLF script would read as one line.
+ for raw in text.split(whereSeparator: \.isNewline) {
let line = raw.trimmingCharacters(in: .whitespaces)
if line == "{" {
if let name = pending { path.append(name) }
diff --git a/app/Sources/BridgeplayApp/Model/PlayReports.swift b/app/Sources/BridgeplayApp/Model/PlayReports.swift
index 263d92b..5197f23 100644
--- a/app/Sources/BridgeplayApp/Model/PlayReports.swift
+++ b/app/Sources/BridgeplayApp/Model/PlayReports.swift
@@ -370,7 +370,7 @@ final class PlayReports {
let found = await Task.detached { () -> GameSession? in
let url = PrefixLog.launch.url(for: prefix)
guard let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate,
- let log = try? String(contentsOf: url, encoding: .utf8) else { return nil }
+ let log = PrefixLog.text(of: url) else { return nil }
return GameSession.last(in: log, modified: modified)
}.value
nudges.removeAll { $0.prefix.id == prefix.id }
@@ -414,9 +414,9 @@ final class PlayReports {
let url = PrefixLog.launch.url(for: prefix)
guard let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate,
maxAge.map({ now.timeIntervalSince(modified) < $0 }) ?? true,
- let log = try? String(contentsOf: url, encoding: .utf8),
+ let log = PrefixLog.text(of: url),
let session = GameSession.last(in: log, modified: modified) else { return nil }
- let wineLog = try? String(contentsOf: PrefixLog.wine.url(for: prefix), encoding: .utf8)
+ let wineLog = PrefixLog.text(of: PrefixLog.wine.url(for: prefix))
guard !onlyWorthAsking || session.worthAsking(now: now, wineLog: wineLog) else { return nil }
return Found(prefix: prefix, session: session, log: log, wineLog: wineLog)
}
@@ -459,8 +459,8 @@ final class PlayReports {
let prefix = nudge.prefix, session = nudge.session
Task {
let logs = await Task.detached {
- (try? String(contentsOf: PrefixLog.launch.url(for: prefix), encoding: .utf8),
- try? String(contentsOf: PrefixLog.wine.url(for: prefix), encoding: .utf8))
+ (PrefixLog.text(of: PrefixLog.launch.url(for: prefix)),
+ PrefixLog.text(of: PrefixLog.wine.url(for: prefix)))
}.value
submitAll([(Found(prefix: prefix, session: session, log: logs.0 ?? "", wineLog: logs.1), status)],
source: source, note: note, issue: issue)
diff --git a/app/Sources/BridgeplayApp/Model/PrefixPrompt.swift b/app/Sources/BridgeplayApp/Model/PrefixPrompt.swift
index e682a6c..ebdbf86 100644
--- a/app/Sources/BridgeplayApp/Model/PrefixPrompt.swift
+++ b/app/Sources/BridgeplayApp/Model/PrefixPrompt.swift
@@ -17,19 +17,20 @@ enum PrefixPrompt {
targets.count > 1 ? String(localized: "Delete \(targets.count) Prefixes") : String(localized: "Delete Prefix")
}
- static func deleteMessage(_ targets: [WinePrefix]) -> String {
- guard targets.count > 1 else {
- return sentences([
- String(localized: "This will DELETE the game's prefix."),
- String(localized: "The game SAVE DATA inside the prefix WILL BE LOST."),
- String(localized: "Are you sure you want to do this?"),
- ])
+ // Backups live inside the folder a delete removes, so they go with it.
+ static func deleteMessage(_ targets: [WinePrefix], backups: Int = 0) -> String {
+ var lines = targets.count > 1
+ ? [String(localized: "This will DELETE the prefixes for \(targets.count) games."),
+ String(localized: "The game SAVE DATA inside them WILL BE LOST.")]
+ : [String(localized: "This will DELETE the game's prefix."),
+ String(localized: "The game SAVE DATA inside the prefix WILL BE LOST.")]
+ if backups == 1 {
+ lines.append(String(localized: "Its 1 backup will also be permanently deleted."))
+ } else if backups > 1 {
+ lines.append(String(localized: "All \(backups) backups will also be permanently deleted."))
}
- return sentences([
- String(localized: "This will DELETE the prefixes for \(targets.count) games."),
- String(localized: "The game SAVE DATA inside them WILL BE LOST."),
- String(localized: "Are you sure you want to do this?"),
- ])
+ lines.append(String(localized: "Are you sure you want to do this?"))
+ return sentences(lines)
}
static func rebuildTitle(_ targets: [WinePrefix], for tool: InstalledTool? = nil) -> String {
diff --git a/app/Sources/BridgeplayApp/Model/PrefixRebuild.swift b/app/Sources/BridgeplayApp/Model/PrefixRebuild.swift
index fccec72..23d0eba 100644
--- a/app/Sources/BridgeplayApp/Model/PrefixRebuild.swift
+++ b/app/Sources/BridgeplayApp/Model/PrefixRebuild.swift
@@ -33,14 +33,26 @@ extension PrefixTools {
runner: URL,
flavor: CompatTool.Flavor = .fex,
now: Date = .now,
- keepBackup: Bool = true
+ keepBackup: Bool = true,
+ wineTimeout: DispatchTimeInterval = wineTimeLimit
) throws -> URL? {
- try rebuild(prefix, runner: runner, flavor: flavor, now: now, keepBackup: keepBackup)
+ try rebuild(
+ prefix, runner: runner, flavor: flavor, now: now, keepBackup: keepBackup,
+ wineTimeout: wineTimeout)
}
+ // A wineboot whose wineserver died never exits. Slow runs on a loaded Mac take under a minute.
+ private static let wineTimeLimit: DispatchTimeInterval = .seconds(300)
+
+ // A healthy system.reg is 3.4 MB. A wineboot whose installer was killed exits 0 at 2 MB,
+ // and the next launch does not repair it.
+ // CEILING: a size floor, so an engine with a much smaller registry is refused — a list of late keys would not be.
+ private static let smallestSystemRegistry = 3_000_000
+
private static func rebuild(
_ prefix: WinePrefix, runner: URL, flavor: CompatTool.Flavor,
now: Date, keepBackup: Bool, record: InstalledTool? = nil,
+ wineTimeout: DispatchTimeInterval = wineTimeLimit,
progress: (RebuildPhase) -> Void = { _ in }
) throws -> URL? {
guard let claim = PrefixStore.claim(prefix) else {
@@ -81,7 +93,33 @@ extension PrefixTools {
var environment = environment(prefix: prefix, runner: runner, flavor: flavor)
environment["WINEPREFIX"] = fresh.path(percentEncoded: false)
layOutProfile(in: fresh)
- _ = try Shell.check(loader.path(percentEncoded: false), ["wineboot", "--init"], environment: environment)
+ let server = layout(runner: runner, flavor: flavor).server.path(percentEncoded: false)
+ do {
+ _ = try Shell.check(
+ loader.path(percentEncoded: false), ["wineboot", "--init"],
+ environment: environment, timeout: wineTimeout)
+ } catch {
+ _ = try? Shell.run(server, ["-k"], environment: environment, timeout: .seconds(10))
+ throw error
+ }
+ // The server writes the .reg files as it exits, and would overwrite a carried user.reg.
+ // A runner with no wineserver throws here, and then nothing can still be writing.
+ if let waited = try? Shell.run(server, ["-w"], environment: environment, timeout: wineTimeout),
+ waited.timedOut
+ {
+ _ = try? Shell.run(server, ["-k"], environment: environment, timeout: .seconds(10))
+ throw StepFailure(
+ step: String(localized: "Recreate prefix"),
+ detail: String(localized: "Wine did not finish building the new prefix. The prefix has been left as it was and nothing has been lost.")
+ )
+ }
+ guard builtWhole(fresh) else {
+ AppLog.note("rebuild \(prefix.appID) refused, wineboot left an incomplete prefix")
+ throw StepFailure(
+ step: String(localized: "Recreate prefix"),
+ detail: String(localized: "Wine could not build a complete new prefix. The prefix has been left as it was and nothing has been lost. Try again, or use Set Up Compatibility Tool first.")
+ )
+ }
progress(.copying)
let carry = Carry(from: prefix.pfx, to: fresh)
@@ -122,6 +160,8 @@ extension PrefixTools {
throw error
}
if let record { try writeBuildRecord(record, for: prefix) }
+ // A rebuild answers the crash the run script was tracking.
+ try? fm.removeItem(at: prefix.root.appending(path: "notproton-switch"))
guard parked else { return nil }
guard !discard else {
try? fm.removeItem(at: previous)
@@ -171,6 +211,15 @@ extension PrefixTools {
return slot
}
+ private static func builtWhole(_ fresh: URL) -> Bool {
+ func size(_ name: String) -> Int {
+ let values = try? fresh.appending(path: name).resourceValues(forKeys: [.fileSizeKey])
+ return values?.fileSize ?? 0
+ }
+ return size("system.reg") >= smallestSystemRegistry
+ && size("user.reg") > 0 && size("userdef.reg") > 0
+ }
+
private static func layOutProfile(in fresh: URL) {
let fm = FileManager.default
let users = fresh.appending(path: "drive_c/users")
@@ -248,13 +297,17 @@ private final class Carry {
}
for name in names where !template.contains(name) {
let stray = source.appending(path: name)
- attempt(stray) {
- try fm.copyItem(at: stray, to: destination.appending(path: name))
+ let landing = destination.appending(path: name)
+ // A template folder under another case, on a volume that folds them.
+ if fm.fileExists(atPath: landing.path(percentEncoded: false)) {
+ park(stray, beside: landing)
+ continue
}
+ attempt(stray) { try fm.copyItem(at: stray, to: landing) }
}
}
- // Saves and launchers also live here. Fresh files win; only what the template lacks comes over.
+ // Saves and launchers also live here. Fresh files win, and an old file that differs is parked.
func installedFolders() {
for name in ["Program Files", "Program Files (x86)", "ProgramData"] {
let source = old.appending(path: "drive_c/\(name)")
@@ -275,6 +328,11 @@ private final class Carry {
park(entry, beside: target)
} else if isDirectory.boolValue {
fill(target, from: entry)
+ } else if !fm.contentsEqual(
+ atPath: entry.path(percentEncoded: false),
+ andPath: target.path(percentEncoded: false))
+ {
+ park(entry, beside: target)
}
}
carryLinks(from: source, to: landing)
@@ -302,19 +360,14 @@ private final class Carry {
guard directoryExists(source) else {
if occupied {
- guard !landingIsDirectory.boolValue else {
- park(source, beside: landing)
- return
- }
- guard carried.insert(identity(of: landing)).inserted else {
+ guard !landingIsDirectory.boolValue, !carried.contains(identity(of: landing)) else {
park(source, beside: landing)
return
}
try? fm.removeItem(at: landing)
- } else {
- carried.insert(identity(of: landing))
}
attempt(source) { try fm.copyItem(at: source, to: landing) }
+ carried.insert(identity(of: landing))
return
}
if !occupied {
@@ -343,12 +396,23 @@ private final class Carry {
name = landing.lastPathComponent + " BACKUP \(next)"
next += 1
}
- attempt(source) { try fm.copyItem(at: source, to: parent.appending(path: name)) }
+ let parked = parent.appending(path: name)
+ attempt(source) { try fm.copyItem(at: source, to: parked) }
+ carried.insert(identity(of: parked))
}
+ // realpath gives the name on disk, so the volume's own folding decides which names are one
+ // file, including folds lowercased() misses. Lowercased too: on a volume that keeps names
+ // apart, a false match only parks a copy.
private func identity(of landing: URL) -> String {
- landing.deletingLastPathComponent().resolvingSymlinksInPath()
+ let path = landing.path(percentEncoded: false)
+ var onDisk = landing.deletingLastPathComponent().resolvingSymlinksInPath()
.appending(path: landing.lastPathComponent).path(percentEncoded: false)
+ if let resolved = realpath(path, nil) {
+ onDisk = String(cString: resolved)
+ free(resolved)
+ }
+ return onDisk.precomposedStringWithCanonicalMapping.lowercased()
}
private func isBrokenLink(_ url: URL) -> Bool {
diff --git a/app/Sources/BridgeplayApp/Model/PrefixTools.swift b/app/Sources/BridgeplayApp/Model/PrefixTools.swift
index b47d39c..674a1cf 100644
--- a/app/Sources/BridgeplayApp/Model/PrefixTools.swift
+++ b/app/Sources/BridgeplayApp/Model/PrefixTools.swift
@@ -48,6 +48,12 @@ enum PrefixLog: CaseIterable, Sendable {
return current
}
+ // Games print raw bytes into these logs, and one invalid UTF-8 byte must not cost the
+ // whole file. nil only when it can't be read.
+ static func text(of url: URL) -> String? {
+ (try? Data(contentsOf: url)).map { String(decoding: $0, as: UTF8.self) }
+ }
+
var fileName: String {
switch self {
case .launch: "bridgeplay-run.log"
diff --git a/app/Sources/BridgeplayApp/Model/RunnerInstaller.swift b/app/Sources/BridgeplayApp/Model/RunnerInstaller.swift
index 6b8f4c9..49e4fb8 100644
--- a/app/Sources/BridgeplayApp/Model/RunnerInstaller.swift
+++ b/app/Sources/BridgeplayApp/Model/RunnerInstaller.swift
@@ -248,13 +248,24 @@ enum RunnerInstaller {
static func isRunning(from clone: URL, ps: String = "/bin/ps") -> Bool {
guard let result = try? Shell.run(ps, ["-axww", "-o", "comm="]), result.succeeded
else { return true }
+ // ps prints the resolved path, and a clone can be a link to another drive.
let root = clone.standardizedFileURL.path(percentEncoded: false)
- let prefix = root.hasSuffix("/") ? root : root + "/"
- return result.stdout.split(separator: "\n").contains {
- $0.trimmingCharacters(in: .whitespaces).hasPrefix(prefix)
+ let prefixes = [root, realpath(root, nil).map { defer { free($0) }; return String(cString: $0) }]
+ .compactMap { $0 }
+ .map { $0.hasSuffix("/") ? $0 : $0 + "/" }
+ return result.stdout.split(separator: "\n").contains { line in
+ let command = line.trimmingCharacters(in: .whitespaces)
+ return prefixes.contains { command.hasPrefix($0) }
}
}
+ static func runningBuild(
+ in runners: URL = SupportPaths.runners,
+ running: (URL) -> Bool = { RunnerInstaller.isRunning(from: $0) }
+ ) -> String? {
+ RunnerStore.clonedBuilds(in: runners).first { running(SupportPaths.runnerRoot(forBuild: $0, runners: runners)) }
+ }
+
static func hasClone(forBuild build: String, runners: URL = SupportPaths.runners) -> Bool {
let root = SupportPaths.clonedRoot(forBuild: build, runners: runners)
return FileManager.default.fileExists(
diff --git a/app/Sources/BridgeplayApp/Model/RunnerSetup.swift b/app/Sources/BridgeplayApp/Model/RunnerSetup.swift
index 5be58d2..d0598eb 100644
--- a/app/Sources/BridgeplayApp/Model/RunnerSetup.swift
+++ b/app/Sources/BridgeplayApp/Model/RunnerSetup.swift
@@ -21,7 +21,6 @@ enum RunnerSetup {
}
struct Outcome: Sendable {
- let build: RunnerBuild
let staged: [WineArch]
let installed: RunnerPatcher.Outcome
var toolsChanged = false
@@ -78,7 +77,7 @@ enum RunnerSetup {
let staged = try stage(build, root, bridge)
report(.patching)
- var outcome = Outcome(build: build, staged: staged, installed: try patch(build, root, bridge))
+ var outcome = Outcome(staged: staged, installed: try patch(build, root, bridge))
outcome.toolsChanged = try CompatToolList.sync(
runners: runners, bridge: bridge, file: toolList, compatTools: compatTools
)
diff --git a/app/Sources/BridgeplayApp/Model/SetupChecks.swift b/app/Sources/BridgeplayApp/Model/SetupChecks.swift
index 1d58f44..c1d509e 100644
--- a/app/Sources/BridgeplayApp/Model/SetupChecks.swift
+++ b/app/Sources/BridgeplayApp/Model/SetupChecks.swift
@@ -98,11 +98,61 @@ enum SetupChecks {
// copy in the image has to carry Valve's signature before it reaches /Applications.
static func copySteam(
from volume: URL, to app: URL,
- verify: (URL) throws -> Void = { try SteamRepair.verifyValveSignature($0, step: step) }
+ verify: (URL) throws -> Void = { try SteamRepair.verifyValveSignature($0, step: step) },
+ copy: (URL, URL) throws -> Void = { source, target in
+ try Shell.check("/usr/bin/ditto", [source.path(percentEncoded: false), target.path(percentEncoded: false)])
+ }
) throws {
let mounted = volume.appending(path: "Steam.app")
try verify(mounted)
- try Shell.check("/usr/bin/ditto", [mounted.path(percentEncoded: false), app.path(percentEncoded: false)])
+ // Staged under its own name, so a failed copy never leaves a half-copied Steam.app that
+ // would pass as installed. A Steam.app that appeared meanwhile is kept.
+ let fm = FileManager.default
+ let staged = app.deletingLastPathComponent().appending(path: "\(stagedPrefix)\(UUID().uuidString)")
+ let stale = stages.claim(staged)
+ defer {
+ try? fm.removeItem(at: staged)
+ stages.release(staged)
+ }
+ for leftover in stale {
+ do { try fm.removeItem(at: leftover) }
+ catch { AppLog.note("setup: could not remove \(leftover.lastPathComponent): \(error.localizedDescription)") }
+ }
+ try copy(mounted, staged)
+ do { try fm.moveItem(at: staged, to: app) }
+ catch where isAppBundle(app) {}
+ }
+
+ private static let stagedPrefix = ".Steam.app-"
+ private static let stages = Stages()
+
+ private static func isAppBundle(_ app: URL) -> Bool {
+ var isDirectory: ObjCBool = false
+ let plist = app.appending(path: "Contents/Info.plist").path(percentEncoded: false)
+ return FileManager.default.fileExists(atPath: plist, isDirectory: &isDirectory) && !isDirectory.boolValue
+ }
+
+ // A force quit leaves its staged copy behind. Listed under the lock, so a copy that has
+ // claimed its name is never taken for one, and one that claims later isn't in the list yet.
+ private final class Stages: @unchecked Sendable {
+ private let lock = NSLock()
+ private var inUse: Set<String> = []
+
+ func claim(_ staged: URL) -> [URL] {
+ let folder = staged.deletingLastPathComponent()
+ return lock.withLock {
+ inUse.insert(staged.lastPathComponent)
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path(percentEncoded: false))) ?? []
+ return names.filter { name in
+ name.hasPrefix(stagedPrefix) && !inUse.contains(name)
+ && UUID(uuidString: String(name.dropFirst(stagedPrefix.count))) != nil
+ }.map { folder.appending(path: $0) }
+ }
+ }
+
+ func release(_ staged: URL) {
+ _ = lock.withLock { inUse.remove(staged.lastPathComponent) }
+ }
}
static let step = String(localized: "Install Steam")
diff --git a/app/Sources/BridgeplayApp/Model/SteamBundle.swift b/app/Sources/BridgeplayApp/Model/SteamBundle.swift
index 9fd0610..3c4026f 100644
--- a/app/Sources/BridgeplayApp/Model/SteamBundle.swift
+++ b/app/Sources/BridgeplayApp/Model/SteamBundle.swift
@@ -141,7 +141,8 @@ enum SteamBundle {
onStopping()
func quits(within attempts: Int) -> Bool {
- for _ in 0..<attempts where client.runningHere() {
+ for _ in 0..<attempts {
+ guard client.runningHere() else { return true }
client.pause()
}
return !client.runningHere()
diff --git a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift b/app/Sources/BridgeplayApp/Model/SteamInstaller.swift
index fdba4c1..62bac87 100644
--- a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift
+++ b/app/Sources/BridgeplayApp/Model/SteamInstaller.swift
@@ -38,9 +38,9 @@ struct InstallOutcome: Sendable {
let build: DeploymentContent.Build
let signatureDatabases: Int
let backedUpPlist: Bool
- let bridgeStaged: Int
- // Input access services macOS refused to reset after Steam's signature changed.
- var failedInputResets: [String] = []
+ // Input access services macOS refused to reset after Steam's signature changed. nil when
+ // the signature didn't change, so no reset ran.
+ var failedInputResets: [String]?
}
enum SteamInstaller {
@@ -103,6 +103,7 @@ enum SteamInstaller {
stopClient: ClientStopper = stopTheClient,
register: BundleRegistrar = { SteamBundle.register($0) },
resetInputAccess: () -> [String] = resetInputAccess,
+ onInputReset: ([String]) -> Void = { _ in },
report: @escaping @Sendable (InstallPhase) -> Void = { _ in }
) throws -> InstallOutcome {
report(.checkingPayload)
@@ -166,7 +167,7 @@ enum SteamInstaller {
file: support.appending(path: "tools"), compatTools: compatTools)
report(.stagingBridge)
- let bridgeResult = try BridgePayload.stage(located: bridgeLocated, bridge: bridge)
+ _ = try BridgePayload.stage(located: bridgeLocated, bridge: bridge)
for build in builds {
try patchRunner(build, SupportPaths.clonedRoot(forBuild: build.id, runners: runners), bridge)
}
@@ -183,16 +184,18 @@ enum SteamInstaller {
}
pruneGamefixes(keeping: payload.gamefixes.map(\.lastPathComponent),
in: deployedVersion.deletingLastPathComponent().appending(path: "gamefixes-default"))
+ seedControllerMappings(from: payload.dylib.deletingLastPathComponent(), in: support)
// The shipped defaults now sit in gamefixes-default/, so the user's file keeps only their own.
do {
try GameDefaults.splitShipped(in: support)
} catch {
AppLog.note("game defaults: could not split the shipped defaults out: \(error.localizedDescription)")
}
- try removeStaleFonts(in: fonts, keeping: payload.fonts)
+ // The CJK fonts come from their own download, so they aren't in the payload.
+ try removeStaleFonts(in: fonts, keeping: payload.fonts + CJKFonts.files.keys + CJKFonts.licences)
var backedUp = false
- var failedInputResets: [String] = []
+ var failedInputResets: [String]?
if patching {
report(.settingInsert)
backedUp = try backUpPlist(plist, into: backups)
@@ -221,7 +224,10 @@ enum SteamInstaller {
// cdhash, which every new dylib changes; signed with the local identity it is the
// certificate, so the approval survives updates and is only cleared on a change.
if designatedRequirement(of: app) != priorRequirement {
- failedInputResets = resetInputAccess()
+ let failed = resetInputAccess()
+ failedInputResets = failed
+ // Told now: the reset stays done even if the install throws below.
+ onInputReset(failed)
}
}
@@ -256,7 +262,6 @@ enum SteamInstaller {
build: build,
signatureDatabases: payload.signatures.count,
backedUpPlist: backedUp,
- bridgeStaged: bridgeResult.staged.count,
failedInputResets: failedInputResets
)
}
@@ -297,6 +302,23 @@ enum SteamInstaller {
}
}
+ // The user's own mappings, so an existing file stays. Without one a pad SDL does not know,
+ // such as the GameSir G7 Pro, reaches games in its raw button order.
+ static func seedControllerMappings(from payload: URL, in support: URL) {
+ let fm = FileManager.default
+ let source = payload.appending(path: "gamecontrollerdb.txt")
+ let mappings = support.appending(path: "gamecontrollerdb.txt")
+ guard fm.fileExists(atPath: source.path(percentEncoded: false)),
+ !fm.fileExists(atPath: mappings.path(percentEncoded: false))
+ else { return }
+ do {
+ try fm.createDirectory(at: support, withIntermediateDirectories: true)
+ try fm.copyItem(at: source, to: mappings)
+ } catch {
+ AppLog.note("controllers: could not seed the mappings: \(error.localizedDescription)")
+ }
+ }
+
static func installIfChanged(_ file: DeploymentContent.File) throws {
if try file.matches() { return }
try install(file.source, at: file.destination)
diff --git a/app/Sources/BridgeplayApp/Model/SteamRepair.swift b/app/Sources/BridgeplayApp/Model/SteamRepair.swift
index 1d44a30..931e9f4 100644
--- a/app/Sources/BridgeplayApp/Model/SteamRepair.swift
+++ b/app/Sources/BridgeplayApp/Model/SteamRepair.swift
@@ -30,10 +30,6 @@ enum RepairPhase: Sendable {
struct RepairOutcome: Sendable {
let stoppedClient: Bool
- let bundleVersion: String?
- let clearedInnerInsert: Bool
- let removedUpdateBlocks: [String]
- let removedStaleBackup: Bool
}
enum SteamRepair {
@@ -55,6 +51,7 @@ enum SteamRepair {
try SteamBundle.stopClient(app: app, step: String(localized: "Repair Steam"), onStopping: onStopping)
},
register: SteamInstaller.BundleRegistrar = { SteamBundle.register($0) },
+ runningBuild: @Sendable () -> String? = { RunnerInstaller.runningBuild() },
report: @escaping @Sendable (RepairPhase) -> Void = { _ in }
) async throws -> RepairOutcome {
let manifest = try suppliedManifest ?? ValvePackageManifest.bundled()
@@ -65,11 +62,20 @@ enum SteamRepair {
)
}
+ // Quitting Steam can take a running game with it.
+ func refuseRunningGame() throws {
+ guard let build = runningBuild() else { return }
+ throw StepFailure(step: step, detail: String(localized: "A game or Wine tool is running on build \(build). Quit it before repairing Steam."))
+ }
+ try refuseRunningGame()
+
let staged = try await stage(bundle, bases: manifest.bases, downloads: downloads, report: report)
report(.checking)
try verifyValveSignature(staged)
+ // A game can start during the download.
+ try refuseRunningGame()
let stopped = try stopClient(app) { report(.stoppingClient) }
try modifications.prepare()
@@ -89,24 +95,18 @@ enum SteamRepair {
_ = try modifications.retireIfClean(app)
report(.clearingInsert)
- let clearedInner = try clearInsert(at: innerPlist)
+ _ = try clearInsert(at: innerPlist)
report(.removingUpdateBlock)
- let removed = try UpdateBlock.remove(from: updateBlocks)
+ _ = try UpdateBlock.remove(from: updateBlocks)
report(.registering)
register(app)
- let removedBackup = try removeStaleBackup(from: backups)
+ _ = try removeStaleBackup(from: backups)
report(.finished)
- return RepairOutcome(
- stoppedClient: stopped,
- bundleVersion: version(of: app),
- clearedInnerInsert: clearedInner,
- removedUpdateBlocks: removed,
- removedStaleBackup: removedBackup
- )
+ return RepairOutcome(stoppedClient: stopped)
}
static func stage(
@@ -240,10 +240,4 @@ enum SteamRepair {
}
return removed
}
-
- static func version(of app: URL) -> String? {
- guard let dict = SteamBundle.readInfoPlist(at: app.appending(path: "Contents/Info.plist"))
- else { return nil }
- return dict["CFBundleVersion"] as? String
- }
}
diff --git a/app/Sources/BridgeplayApp/Model/Uninstall.swift b/app/Sources/BridgeplayApp/Model/Uninstall.swift
index 242c2c3..3782297 100644
--- a/app/Sources/BridgeplayApp/Model/Uninstall.swift
+++ b/app/Sources/BridgeplayApp/Model/Uninstall.swift
@@ -19,8 +19,6 @@ enum UninstallPhase: Sendable {
}
struct UninstallOutcome: Sendable {
- let stoppedClient: Bool
- let detached: Bool
let steamInstalled: Bool
let restoredValveSignature: Bool
let removed: [String]
@@ -74,6 +72,7 @@ enum Uninstall {
var steamRunning: @Sendable () -> Bool
// The password of Bridgeplay's signing keychain, kept in the login keychain.
var forgetSigning: @Sendable () -> Void = {}
+ var runningBuild: @Sendable () -> String? = { nil }
static var live: Leftovers {
Leftovers(
@@ -83,7 +82,8 @@ enum Uninstall {
defaultToolBackup: SteamDefaultTool.backup,
files: [SupportPaths.homeDir],
steamRunning: { SteamBundle.isRunningForThisUser },
- forgetSigning: { LocalSigning.forgetPrivateKeychain() })
+ forgetSigning: { LocalSigning.forgetPrivateKeychain() },
+ runningBuild: { RunnerInstaller.runningBuild() })
}
}
@@ -107,13 +107,15 @@ enum Uninstall {
) async throws -> UninstallOutcome {
let lock = try DeploymentContent.acquireInstallationLock(in: lockFolder, steamFolder: nil)
defer { lock.release() }
+ // Quitting Steam can take a running game with it, and its runner is deleted below.
+ if let build = leftovers.runningBuild() {
+ throw StepFailure(step: step, detail: String(localized: "A game or Wine tool is running on build \(build). Quit it before removing Bridgeplay."))
+ }
try modifications.prepare()
let tracked = try modifications.paths()
let targets = Set((tracked + [app]).map { $0.standardizedFileURL.path }).sorted()
.map { URL(filePath: $0, directoryHint: .notDirectory) }
- var stopped = false
var checkedClient = false
- var detached = false
var steamInstalled = false
var restored = true
var missing: [URL] = []
@@ -135,10 +137,10 @@ enum Uninstall {
case .modified: break
}
try modifications.mark(target)
- stopped = try stop(target) { report(.stoppingClient) } || stopped
+ _ = try stop(target) { report(.stoppingClient) }
checkedClient = true
report(.detaching)
- detached = try detach(from: target, innerPlist: innerPlist, updateBlocks: updateBlocks) || detached
+ _ = try detach(from: target, innerPlist: innerPlist, updateBlocks: updateBlocks)
steamInstalled = true
do {
if let repair {
@@ -146,6 +148,7 @@ enum Uninstall {
} else {
_ = try await SteamRepair.run(app: target, innerPlist: innerPlist,
updateBlocks: updateBlocks, modifications: modifications,
+ runningBuild: { nil },
report: { report(.restoring($0)) })
}
} catch { restored = false }
@@ -170,7 +173,7 @@ enum Uninstall {
let bundleLock = try DeploymentContent.acquireSteamLock(for: app, holding: lock)
defer { bundleLock.release() }
do {
- stopped = try stop(app) { report(.stoppingClient) }
+ _ = try stop(app) { report(.stoppingClient) }
} catch is SteamBundle.OpenInAnotherAccount {
// Steam.app is left as it is from here on, and another account's Steam does
// not use this account's files.
@@ -202,8 +205,6 @@ enum Uninstall {
}
report(.finished)
return UninstallOutcome(
- stoppedClient: stopped,
- detached: detached,
steamInstalled: steamInstalled,
restoredValveSignature: restored,
removed: removed,
diff --git a/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings b/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings
index 135d4ad..c50b190 100644
--- a/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings
+++ b/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings
@@ -1020,6 +1020,38 @@
}
}
},
+ "A game or Wine tool is running on build %@. Quit it before removing Bridgeplay." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Un gioco o uno strumento di Wine è in esecuzione sulla build %@. Chiudilo prima di rimuovere Bridgeplay."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "有游戏或 Wine 工具正在使用构建版本 %@。请先退出,再移除 Bridgeplay。"
+ }
+ }
+ }
+ },
+ "A game or Wine tool is running on build %@. Quit it before repairing Steam." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Un gioco o uno strumento di Wine è in esecuzione sulla build %@. Chiudilo prima di riparare Steam."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "有游戏或 Wine 工具正在使用构建版本 %@。请先退出,再修复 Steam。"
+ }
+ }
+ }
+ },
"A game or Wine tool is running on build %@. Quit it before updating Bridgeplay." : {
"localizations" : {
"it" : {
@@ -1468,6 +1500,22 @@
}
}
},
+ "All %lld backups will also be permanently deleted." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Verranno eliminati definitivamente anche tutti i %lld backup."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "全部 %lld 个备份也将被永久删除。"
+ }
+ }
+ }
+ },
"Allow Bridgeplay in App Management" : {
"localizations" : {
"it" : {
@@ -5826,6 +5874,22 @@
}
}
},
+ "Its 1 backup will also be permanently deleted." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Verrà eliminato definitivamente anche il suo backup."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "其 1 个备份也将被永久删除。"
+ }
+ }
+ }
+ },
"Its output was still open when it exited, so none was captured." : {
"localizations" : {
"it" : {
@@ -11733,6 +11797,38 @@
}
}
},
+ "Wine could not build a complete new prefix. The prefix has been left as it was and nothing has been lost. Try again, or use Set Up Compatibility Tool first." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Wine non è riuscito a creare un nuovo prefisso completo. Il prefisso è rimasto com'era e non è andato perso nulla. Riprova, oppure usa prima Set Up Compatibility Tool."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Wine 无法构建完整的新前缀。原前缀保持不变,没有任何数据丢失。请重试,或先使用 Set Up Compatibility Tool。"
+ }
+ }
+ }
+ },
+ "Wine did not finish building the new prefix. The prefix has been left as it was and nothing has been lost." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Wine non ha finito di creare il nuovo prefisso. Il prefisso è rimasto com'era e non è andato perso nulla."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Wine 未能完成新前缀的构建。原前缀保持不变,没有任何数据丢失。"
+ }
+ }
+ }
+ },
"Wine syntax. A game's own conf replaces these; its launch options win per DLL." : {
"localizations" : {
"it" : {
diff --git a/app/Sources/BridgeplayApp/SetupAssistant.swift b/app/Sources/BridgeplayApp/SetupAssistant.swift
index 44d2ce5..88b8321 100644
--- a/app/Sources/BridgeplayApp/SetupAssistant.swift
+++ b/app/Sources/BridgeplayApp/SetupAssistant.swift
@@ -204,6 +204,8 @@ final class SetupAssistant {
// MARK: Graphics
func importGPTK(_ image: URL) async {
+ // A drop can arrive mid-import, and a second import deletes the first one's staging folder.
+ guard !isWorking else { return }
// The toolkit is copied into the support folder, which the 3.0 move has to find untouched.
if let refusal = MigrationLaunch.shared.refusal {
message = refusal
diff --git a/app/Sources/BridgeplayApp/Support/ErrorReport.swift b/app/Sources/BridgeplayApp/Support/ErrorReport.swift
index ab17802..07b656e 100644
--- a/app/Sources/BridgeplayApp/Support/ErrorReport.swift
+++ b/app/Sources/BridgeplayApp/Support/ErrorReport.swift
@@ -24,12 +24,13 @@ enum ErrorReport {
NSWorkspace.shared.activateFileViewerSelecting([AppLog.file])
}
- static func url(_ failure: String, in place: String) -> URL? {
- GitHubIssue.bugReport(
- title: "\(place): \(GitHubIssue.summary(failure))",
- what: "\(place) showed:\n\n\(GameReport.redacted(failure))",
+ static func url(_ failure: String, in place: String, log: URL = AppLog.file) -> URL? {
+ let clean = GameReport.redacted(failure)
+ return GitHubIssue.bugReport(
+ title: "\(place): \(GitHubIssue.summary(clean))",
+ what: "\(place) showed:\n\n\(clean)",
version: ProductVersion.display,
mac: [SetupChecks.chipName, SetupChecks.macOSDisplay].filter { !$0.isEmpty }.joined(separator: ", "),
- logs: GameReport.redacted(GitHubIssue.tail(of: AppLog.file)))
+ logs: GameReport.redacted(GitHubIssue.tail(of: log)))
}
}
diff --git a/app/Sources/BridgeplayApp/Support/GameDefaults.swift b/app/Sources/BridgeplayApp/Support/GameDefaults.swift
index f494c9b..f78c838 100644
--- a/app/Sources/BridgeplayApp/Support/GameDefaults.swift
+++ b/app/Sources/BridgeplayApp/Support/GameDefaults.swift
@@ -138,7 +138,6 @@ enum GameDefaults {
struct Problem: Equatable, Sendable {
var setting: Setting
- var value: String
var reason: String
}
@@ -185,7 +184,7 @@ enum GameDefaults {
let setting = Setting.allCases.first(where: { $0.keys.contains(key) }),
let reason = refusal(value, for: setting)
else { continue }
- found.append(Problem(setting: setting, value: value, reason: reason))
+ found.append(Problem(setting: setting, reason: reason))
}
return found
}
diff --git a/app/Sources/BridgeplayApp/Support/InstallIntoSteamCommand.swift b/app/Sources/BridgeplayApp/Support/InstallIntoSteamCommand.swift
index 36c4fa7..e993a02 100644
--- a/app/Sources/BridgeplayApp/Support/InstallIntoSteamCommand.swift
+++ b/app/Sources/BridgeplayApp/Support/InstallIntoSteamCommand.swift
@@ -34,6 +34,7 @@ enum InstallIntoSteamCommand {
_ = try await ValveFetcher.run { say($0.label) }
}
try SteamInstaller.finish(result)
+ UserDefaults.standard.removeObject(forKey: SteamPatchKeeper.pausedKey)
say("Bridgeplay \(ProductVersion.short) installed into Steam.")
return 0
} catch {
diff --git a/app/Sources/BridgeplayApp/Support/Launch.swift b/app/Sources/BridgeplayApp/Support/Launch.swift
index 8abe650..6d44afa 100644
--- a/app/Sources/BridgeplayApp/Support/Launch.swift
+++ b/app/Sources/BridgeplayApp/Support/Launch.swift
@@ -132,8 +132,6 @@ enum RebuildPrefixCommand {
let kept = try PrefixTools.recreate(
request.prefix, as: request.tool, keepBackup: request.keepBackup,
progress: { report($0.rawValue); observe(name, $0) })
- // A rebuild answers the crash the run script was tracking.
- try? FileManager.default.removeItem(at: request.prefix.root.appending(path: "notproton-switch"))
report(kept != nil ? "done-backup" : "done")
} catch {
report("failed")
diff --git a/app/Sources/BridgeplayApp/Support/RebuildProgressWindow.swift b/app/Sources/BridgeplayApp/Support/RebuildProgressWindow.swift
index e7b2727..1e6c9b2 100644
--- a/app/Sources/BridgeplayApp/Support/RebuildProgressWindow.swift
+++ b/app/Sources/BridgeplayApp/Support/RebuildProgressWindow.swift
@@ -25,10 +25,11 @@ enum RebuildProgressCommand {
}
})
} catch {
+ AppLog.note("rebuild prefix failed: \(error.localizedDescription)")
FileHandle.standardError.write(Data("\(error.localizedDescription)\n".utf8))
code = 1
}
- DispatchQueue.main.async { exit(code) }
+ DispatchQueue.main.async { exit(AppLog.finished(code)) }
}
app.run()
}
diff --git a/app/Sources/BridgeplayApp/Support/Shell.swift b/app/Sources/BridgeplayApp/Support/Shell.swift
index e7a2718..81e7149 100644
--- a/app/Sources/BridgeplayApp/Support/Shell.swift
+++ b/app/Sources/BridgeplayApp/Support/Shell.swift
@@ -7,15 +7,17 @@ struct CommandResult: Sendable {
let stdout: String
let stderr: String
let outputLost: Bool
+ let timedOut: Bool
- init(status: Int32, stdout: String, stderr: String, outputLost: Bool = false) {
+ init(status: Int32, stdout: String, stderr: String, outputLost: Bool = false, timedOut: Bool = false) {
self.status = status
self.stdout = stdout
self.stderr = stderr
self.outputLost = outputLost
+ self.timedOut = timedOut
}
- var succeeded: Bool { status == 0 }
+ var succeeded: Bool { status == 0 && !timedOut }
}
struct CommandFailure: LocalizedError {
@@ -43,7 +45,8 @@ enum Shell {
_ arguments: [String],
environment: [String: String]? = nil,
currentDirectory: URL? = nil,
- drainTimeout: DispatchTimeInterval = outputDrainTimeout
+ drainTimeout: DispatchTimeInterval = outputDrainTimeout,
+ timeout: DispatchTimeInterval? = nil
) throws -> CommandResult {
let process = Process()
process.executableURL = URL(filePath: executable)
@@ -55,6 +58,9 @@ enum Shell {
process.standardOutput = out
process.standardError = err
+ let exited = DispatchSemaphore(value: 0)
+ process.terminationHandler = { _ in exited.signal() }
+
try process.run()
let outBox = DataBox(), errBox = DataBox()
@@ -68,18 +74,29 @@ enum Shell {
}
}
+ var timedOut = false
+ if let timeout, exited.wait(timeout: .now() + timeout) == .timedOut {
+ timedOut = true
+ AppLog.note("\(executable) did not finish in time, stopping it")
+ process.terminate()
+ if exited.wait(timeout: .now() + .seconds(5)) == .timedOut {
+ kill(process.processIdentifier, SIGKILL)
+ }
+ }
process.waitUntilExit()
if group.wait(timeout: .now() + drainTimeout) == .timedOut {
AppLog.note("\(executable) exited but left its output open")
return CommandResult(
- status: process.terminationStatus, stdout: "", stderr: "", outputLost: true)
+ status: process.terminationStatus, stdout: "", stderr: "", outputLost: true,
+ timedOut: timedOut)
}
return CommandResult(
status: process.terminationStatus,
stdout: String(decoding: outBox.data, as: UTF8.self),
- stderr: String(decoding: errBox.data, as: UTF8.self)
+ stderr: String(decoding: errBox.data, as: UTF8.self),
+ timedOut: timedOut
)
}
@@ -89,11 +106,12 @@ enum Shell {
_ arguments: [String],
environment: [String: String]? = nil,
currentDirectory: URL? = nil,
- drainTimeout: DispatchTimeInterval = outputDrainTimeout
+ drainTimeout: DispatchTimeInterval = outputDrainTimeout,
+ timeout: DispatchTimeInterval? = nil
) throws -> String {
let result = try run(
executable, arguments, environment: environment, currentDirectory: currentDirectory,
- drainTimeout: drainTimeout)
+ drainTimeout: drainTimeout, timeout: timeout)
guard result.succeeded else {
let reason = result.stderr.isEmpty ? result.stdout : result.stderr
throw CommandFailure(
diff --git a/app/Sources/BridgeplayApp/SystemStatus.swift b/app/Sources/BridgeplayApp/SystemStatus.swift
index 5d08f6d..4c27f07 100644
--- a/app/Sources/BridgeplayApp/SystemStatus.swift
+++ b/app/Sources/BridgeplayApp/SystemStatus.swift
@@ -631,13 +631,16 @@ final class SystemStatus {
AppLog.note("run refused: install waits for the 3.0 folder move")
return
}
- var failedInputResets: [String]?
await perform(from: InstallPhase.checkingPayload.label) { progress in
let lock = try DeploymentContent.acquireInstallationLock()
defer { lock.release() }
let stopClient = unattended ? SteamInstaller.leaveTheClient : SteamInstaller.stopTheClient
let result = try await Task.detached(priority: .userInitiated) {
+ // Only an install that changed Steam's signature tried a reset, so only it decides.
try SteamInstaller.run(holdingInstallationLock: true, stopClient: stopClient,
+ onInputReset: { failed in
+ Task { @MainActor in self.controllerResetFailures = failed }
+ },
report: { progress($0.label) })
}.value
@@ -675,17 +678,12 @@ final class SystemStatus {
try await Task.detached(priority: .userInitiated) {
try SteamInstaller.finish(result)
}.value
- failedInputResets = result.failedInputResets
return parts.joined(separator: " ")
}
if failure == nil {
UserDefaults.standard.removeObject(forKey: SteamPatchKeeper.pausedKey)
}
- // Only an install that changed Steam's signature tried a reset, so only it decides.
- if let failedInputResets, failure == nil, !failedInputResets.isEmpty || !controllerResetFailures.isEmpty {
- controllerResetFailures = failedInputResets
- }
}
// MARK: Controller permission
diff --git a/app/Sources/BridgeplayApp/Views/PrefixesView.swift b/app/Sources/BridgeplayApp/Views/PrefixesView.swift
index 6fb0510..cf50ed4 100644
--- a/app/Sources/BridgeplayApp/Views/PrefixesView.swift
+++ b/app/Sources/BridgeplayApp/Views/PrefixesView.swift
@@ -74,7 +74,9 @@ struct PrefixesView: View {
Button("Cancel", role: .cancel) { model.pendingConfirmation = nil }
.keyboardShortcut(.defaultAction)
} message: {
- Text(PrefixPrompt.deleteMessage(deleting))
+ Text(PrefixPrompt.deleteMessage(
+ deleting,
+ backups: model.backups.filter { backup in deleting.contains { $0.id == backup.prefix.id } }.count))
}
.confirmationDialog(
PrefixPrompt.rebuildTitle(rebuilding, for: rebuildTool),
diff --git a/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift b/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift
index b33952d..abc818a 100644
--- a/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift
+++ b/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift
@@ -225,7 +225,7 @@ struct SetupAssistantView: View {
}
}
.dropDestination(for: URL.self) { urls, _ in
- guard let url = urls.first(where: { $0.pathExtension.lowercased() == "dmg" }) else { return false }
+ guard !model.isWorking, let url = urls.first(where: { $0.pathExtension.lowercased() == "dmg" }) else { return false }
Task { await model.importGPTK(url) }
return true
}
diff --git a/app/Sources/BridgeplayInstaller/InstallerModel.swift b/app/Sources/BridgeplayInstaller/InstallerModel.swift
index 3b3916e..81a8fd3 100644
--- a/app/Sources/BridgeplayInstaller/InstallerModel.swift
+++ b/app/Sources/BridgeplayInstaller/InstallerModel.swift
@@ -104,13 +104,14 @@ final class InstallerModel {
components = InstallerComponents.needed() ? try await InstallerComponents.latest() : nil
try Task.checkCancellation()
let state = try service.state(for: fetched)
+ isCurrent = state.isCurrent
total = (state.isCurrent ? 0 : fetched.archiveLength) + (components?.length ?? 0)
InstallerLog.write("Release \(fetched.shortVersion), installed \(state.installedVersion ?? "none"), components \(components == nil ? "present" : "needed")")
switch state {
case .notInstalled: installedVersion = nil; stage = .review
case .updateAvailable(_, let current, _): installedVersion = current; stage = .review
case .upToDate(_, let current):
- installedVersion = current; version = current; isCurrent = true
+ installedVersion = current; version = current
stage = components == nil ? .done : .review
}
} catch is CancellationError {
@@ -123,6 +124,7 @@ final class InstallerModel {
operation = Task {
defer { operation = nil }
stage = .downloading
+ settingUp = false
failure = nil
InstallerLog.write("Install \(release.shortVersion) to \(destination.path)")
received = 0
diff --git a/app/Sources/BridgeplayInstaller/InstallerReport.swift b/app/Sources/BridgeplayInstaller/InstallerReport.swift
index 513ce09..193b11e 100644
--- a/app/Sources/BridgeplayInstaller/InstallerReport.swift
+++ b/app/Sources/BridgeplayInstaller/InstallerReport.swift
@@ -4,9 +4,10 @@ import BridgeplayUI
enum InstallerReport {
static func issueURL(failure: String, version: String, installed: String?) -> URL? {
- GitHubIssue.bugReport(
- title: "Installer: \(GitHubIssue.summary(failure))",
- what: "The installer stopped with:\n\n\(failure)",
+ let clean = InstallerLog.redact(failure)
+ return GitHubIssue.bugReport(
+ title: "Installer: \(GitHubIssue.summary(clean))",
+ what: "The installer stopped with:\n\n\(clean)",
version: "Installer, offering \(version)" + (installed.map { ", installed \($0)" } ?? ""),
mac: InstallerLog.system,
logs: InstallerLog.tail())
diff --git a/app/Sources/BridgeplayInstallerCore/ComponentsPlacement.swift b/app/Sources/BridgeplayInstallerCore/ComponentsPlacement.swift
index 0b12c97..e3ed4d9 100644
--- a/app/Sources/BridgeplayInstallerCore/ComponentsPlacement.swift
+++ b/app/Sources/BridgeplayInstallerCore/ComponentsPlacement.swift
@@ -16,6 +16,7 @@ struct ComponentsPlacement {
_ = try? InstallerComponents.run("/usr/bin/defaults", ["delete", "com.bridgeplay.Bridgeplay", "setupAssistantFinished"])
}
var oldConfs = ComponentsPlacement.oldInstallerConfs
+ var log: (String) -> Void = { InstallerLog.write($0) }
static let steamStatus = "Installing Steam from Valve"
static let copyStatus = "Copying the Game Porting Toolkit, DXMT, DXVK and configs"
@@ -114,7 +115,10 @@ struct ComponentsPlacement {
static func hex(_ digest: SHA256.Digest) -> String { digest.map { String(format: "%02x", $0) }.joined() }
private func fail(_ message: String, _ body: () throws -> Void) throws {
- do { try body() } catch { throw InstallerError.componentsFailure(message) }
+ do { try body() } catch {
+ log("\(message) \(error)")
+ throw InstallerError.componentsFailure(message)
+ }
}
}
@@ -137,6 +141,7 @@ enum ValveSteam {
if let meter = InstallerDownloadProgress(curlMeter: line) { download(meter) }
}
} catch {
+ InstallerLog.write("Steam download failed: \(error)")
throw InstallerError.componentsFailure("Steam could not be downloaded. Check the internet connection and try again.")
}
// A UDIF disk image ends with a 512-byte trailer that starts with "koly".
@@ -148,6 +153,7 @@ enum ValveSteam {
try InstallerComponents.run("/usr/bin/hdiutil", ["attach", "-nobrowse", "-readonly", "-noautoopen", "-quiet",
"-mountpoint", mount.path, dmg.path])
} catch {
+ InstallerLog.write("Opening the Steam installer failed: \(error)")
throw InstallerError.componentsFailure("The Steam installer could not be opened.")
}
defer { _ = try? InstallerComponents.run("/usr/bin/hdiutil", ["detach", "-quiet", mount.path]) }
@@ -160,6 +166,7 @@ enum ValveSteam {
do {
try ComponentsPlacement.put(steam, at: applications.appending(path: "Steam.app"), replacing: false)
} catch {
+ InstallerLog.write("Copying Steam failed: \(error)")
throw InstallerError.componentsFailure("Steam could not be copied to Applications.")
}
}
diff --git a/app/Sources/BridgeplayInstallerCore/InstallerLog.swift b/app/Sources/BridgeplayInstallerCore/InstallerLog.swift
index e9b4e15..28bb9d3 100644
--- a/app/Sources/BridgeplayInstallerCore/InstallerLog.swift
+++ b/app/Sources/BridgeplayInstallerCore/InstallerLog.swift
@@ -44,7 +44,7 @@ public enum InstallerLog {
return [sysctl("hw.model"), sysctl("machdep.cpu.brand_string"), version].compactMap { $0 }.joined(separator: ", ")
}
- static func redact(_ text: String) -> String {
+ public static func redact(_ text: String) -> String {
text.replacingOccurrences(of: NSHomeDirectory(), with: "~")
}
diff --git a/app/Tests/BridgeplayAppTests/BrandMigrationTests.swift b/app/Tests/BridgeplayAppTests/BrandMigrationTests.swift
index af8c73b..1ae8d63 100644
--- a/app/Tests/BridgeplayAppTests/BrandMigrationTests.swift
+++ b/app/Tests/BridgeplayAppTests/BrandMigrationTests.swift
@@ -349,6 +349,25 @@ struct BrandMigrationTests {
try expectMigrated(f)
}
+ @Test("A run log that can't be renamed stays put and the move still finishes")
+ func runLogThatCannotBeRenamed() throws {
+ let f = try fixture()
+ defer { try? FileManager.default.removeItem(at: f.root) }
+ let locked = f.runLogGames[1]
+ try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: f.path(locked))
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: f.path(locked)) }
+
+ let summary = try f.migration.run()
+
+ #expect(summary.logsRenamed == 3)
+ #expect(summary.logsLeft == 1)
+ #expect(summary.notes.isEmpty)
+ #expect(try f.read(locked.appending(path: "notproton-run.log")) == "run log\n")
+ #expect(!f.exists(locked.appending(path: "bridgeplay-run.log")))
+ #expect(try f.read(f.support.appending(path: BrandMigration.markerName)).contains("done"))
+ #expect(!f.migration.isNeeded)
+ }
+
@Test("A crash after the move resumes from the marker")
func resumesAfterMove() throws {
let f = try fixture()
diff --git a/app/Tests/BridgeplayAppTests/GameReportTests.swift b/app/Tests/BridgeplayAppTests/GameReportTests.swift
index 4250092..963bb9d 100644
--- a/app/Tests/BridgeplayAppTests/GameReportTests.swift
+++ b/app/Tests/BridgeplayAppTests/GameReportTests.swift
@@ -84,6 +84,20 @@ struct GameReportTests {
#expect(text.contains("~/Library/x.lock"))
}
+ @Test("The account ID in a Steam userdata path is hidden")
+ func userdataPaths() {
+ let raw = #"""
+ C:\Program Files (x86)\Steam\userdata\52345678\1245620\remote\save.dat
+ C:\\Program Files (x86)\\Steam\\userdata\\52345678\\730\\cfg
+ /Users/tester/Library/Application Support/Steam/userdata/52345678/730/local/cfg/config.cfg
+ """#
+ let text = GameReport.redacted(raw, home: "/Users/tester", user: "tester", computerNames: [])
+ #expect(!text.contains("52345678"))
+ #expect(text.contains(#"userdata\<id>\1245620"#))
+ #expect(text.contains(#"userdata\\<id>\\730"#))
+ #expect(text.contains("userdata/<id>/730"))
+ }
+
@Test("A home folder that isn't spelled like this one's is hidden too")
func otherHomes() {
let raw = """
diff --git a/app/Tests/BridgeplayAppTests/GitHubIssueTests.swift b/app/Tests/BridgeplayAppTests/GitHubIssueTests.swift
new file mode 100644
index 0000000..9952253
--- /dev/null
+++ b/app/Tests/BridgeplayAppTests/GitHubIssueTests.swift
@@ -0,0 +1,84 @@
+import BridgeplayUI
+import Foundation
+import Testing
+
+@testable import BridgeplayApp
+
+@Suite("Bug report links")
+struct GitHubIssueTests {
+
+ private func fields(of url: URL) throws -> [String: String] {
+ let items = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems)
+ return items.reduce(into: [:]) { $0[$1.name] = $1.value }
+ }
+
+ @Test("Every field survives the link, whatever it holds")
+ func fieldsRoundTrip() throws {
+ let awkward = "a&b=c+d #e?f\nsecond line"
+ let url = try #require(GitHubIssue.bugReport(
+ title: awkward, what: awkward, version: awkward, mac: awkward, logs: awkward))
+
+ let sent = try fields(of: url)
+
+ #expect(sent["template"] == "bug-report.yml")
+ for name in ["title", "what", "version", "macos", "logs"] {
+ #expect(sent[name] == awkward, "\(name) was changed on the way")
+ }
+ }
+
+ // GitHub drops a prefill whose name is not a field of the form, and says nothing.
+ @Test("Every prefilled field exists in the issue form")
+ func fieldsMatchTheForm() throws {
+ let repo = URL(filePath: #filePath)
+ .deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent()
+ let form = try String(contentsOf: repo.appending(path: ".github/ISSUE_TEMPLATE/bug-report.yml"), encoding: .utf8)
+ let ids = form.split(separator: "\n").compactMap { line -> String? in
+ let trimmed = line.trimmingCharacters(in: .whitespaces)
+ return trimmed.hasPrefix("id: ") ? String(trimmed.dropFirst(4)) : nil
+ }
+ let url = try #require(GitHubIssue.bugReport(title: "t", what: "w", version: "v", mac: "m", logs: "l"))
+
+ let names = Set(try fields(of: url).keys).subtracting(["template", "title"])
+
+ #expect(names == Set(ids))
+ }
+
+ @Test("A title is the failure's first line, cut to 80 characters")
+ func summaryIsOneShortLine() {
+ #expect(GitHubIssue.summary("first\nsecond") == "first")
+ #expect(GitHubIssue.summary(String(repeating: "x", count: 200)) == String(repeating: "x", count: 80))
+ #expect(GitHubIssue.summary("") == "")
+ }
+
+ @Test("The log's tail keeps to its line and size limits")
+ func tailIsCapped() throws {
+ let dir = try scratchDirectory("issue-tail")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let log = dir.appending(path: "app.log")
+ try Data("one\ntwo\nthree\nfour".utf8).write(to: log)
+
+ #expect(GitHubIssue.tail(of: log, lines: 2) == "three\nfour")
+ #expect(GitHubIssue.tail(of: log, lines: 2, maxCharacters: 4) == "four")
+ #expect(GitHubIssue.tail(of: dir.appending(path: "missing.log")) == "")
+ }
+
+ @Test("A failure's home path stays out of the title as well as the body")
+ func failureIsRedactedEverywhere() throws {
+ let dir = try scratchDirectory("error-report")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let log = dir.appending(path: "app.log")
+ try Data("wrote \(NSHomeDirectory())/Library/x\n".utf8).write(to: log)
+ let failure = "Replacing \(NSHomeDirectory())/Library/Application Support/bridgeplay/x failed."
+
+ let url = try #require(ErrorReport.url(failure, in: "Set up Steam", log: log))
+ let sent = try fields(of: url)
+
+ #expect(sent["title"]?.hasPrefix("Set up Steam: Replacing ~/Library") == true)
+ #expect(sent["what"]?.contains("~/Library/Application Support/bridgeplay/x failed.") == true)
+ #expect(sent["logs"]?.contains("wrote ~/Library/x") == true)
+ for value in sent.values {
+ #expect(!value.contains(NSHomeDirectory()))
+ }
+ }
+}
diff --git a/app/Tests/BridgeplayAppTests/InstallScriptMarkersTests.swift b/app/Tests/BridgeplayAppTests/InstallScriptMarkersTests.swift
index a5cdbd8..ebcee4c 100644
--- a/app/Tests/BridgeplayAppTests/InstallScriptMarkersTests.swift
+++ b/app/Tests/BridgeplayAppTests/InstallScriptMarkersTests.swift
@@ -55,6 +55,13 @@ struct InstallScriptMarkersTests {
])
}
+ @Test("A script with Windows line endings gives the same markers")
+ func readsCRLFScript() {
+ let crlf = Self.script.replacingOccurrences(of: "\n", with: "\r\n")
+ #expect(InstallScriptMarkers.markers(inScript: crlf) == InstallScriptMarkers.markers(inScript: Self.script))
+ #expect(InstallScriptMarkers.markers(inScript: crlf).count == 1)
+ }
+
@Test("The marker goes and the game's other settings and keys stay")
func clearsOnlyTheMarker() {
let result = InstallScriptMarkers.clear(
diff --git a/app/Tests/BridgeplayAppTests/PlayReportsTests.swift b/app/Tests/BridgeplayAppTests/PlayReportsTests.swift
index f3d7108..166968d 100644
--- a/app/Tests/BridgeplayAppTests/PlayReportsTests.swift
+++ b/app/Tests/BridgeplayAppTests/PlayReportsTests.swift
@@ -72,6 +72,20 @@ struct PlayReportsTests {
#expect(!session(60, status: 0).worthAsking(now: Date().addingTimeInterval(4 * 86400), wineLog: nil))
}
+ @Test("A Wine log with a byte that isn't UTF-8 still shows the crash")
+ func wineLogWithInvalidByte() throws {
+ let dir = try scratchDirectory("wine-log")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let log = dir.appending(path: "bridgeplay-wine.log")
+ // A game's Shift-JIS output.
+ var bytes = Data("wine: Unhandled page fault on read access\n".utf8)
+ bytes.append(contentsOf: [0x83, 0x51, 0x81, 0x5B, 0x83, 0x80, 0x0A])
+ try bytes.write(to: log)
+
+ #expect(GameSession.wineCrashed(PrefixLog.text(of: log)))
+ #expect(PrefixLog.text(of: dir.appending(path: "missing.log")) == nil)
+ }
+
@Test("The payload carries the machine, launch and redacted logs")
func payload() throws {
let session = GameSession(id: "x", started: Date().addingTimeInterval(-3600), ended: Date(),
diff --git a/app/Tests/BridgeplayAppTests/PrefixPromptTests.swift b/app/Tests/BridgeplayAppTests/PrefixPromptTests.swift
index 67321be..12666da 100644
--- a/app/Tests/BridgeplayAppTests/PrefixPromptTests.swift
+++ b/app/Tests/BridgeplayAppTests/PrefixPromptTests.swift
@@ -55,6 +55,13 @@ struct PrefixPromptTests {
#expect(!both.contains("Agent 64"))
}
+ @Test("Delete warns that the backups inside the prefix go too")
+ func deleteNamesTheBackups() {
+ #expect(PrefixPrompt.deleteMessage([agent], backups: 0) == PrefixPrompt.deleteMessage([agent]))
+ #expect(PrefixPrompt.deleteMessage([agent], backups: 1).contains("Its 1 backup will also be permanently deleted."))
+ #expect(PrefixPrompt.deleteMessage([agent, ikaruga], backups: 3).contains("All 3 backups will also be permanently deleted."))
+ }
+
// Rebuild inits the prefix itself before the dialog closes, so deferring to Steam
// would be describing something that does not happen.
@Test("Rebuild does not claim Steam makes the prefix again")
diff --git a/app/Tests/BridgeplayAppTests/PrefixStoreTests.swift b/app/Tests/BridgeplayAppTests/PrefixStoreTests.swift
index b8b0632..0d367c4 100644
--- a/app/Tests/BridgeplayAppTests/PrefixStoreTests.swift
+++ b/app/Tests/BridgeplayAppTests/PrefixStoreTests.swift
@@ -314,6 +314,9 @@ struct PrefixStoreTests {
try PrefixTools.recreate(prefix, runner: dir.appending(path: "runner"))
}
#expect(rebuild.detail.contains("is running"))
+ let backup = try #require(throws: StepFailure.self) { try PrefixTools.backUp(prefix) }
+ #expect(backup.detail.contains("is running"))
+ #expect(PrefixStore.backups(of: prefix).isEmpty)
#expect(FileManager.default.fileExists(atPath: prefix.pfx.path))
try #require(flock(fd, LOCK_UN) == 0)
#expect(!PrefixStore.isInUse(prefix, root: root))
@@ -387,6 +390,23 @@ struct PrefixStoreTests {
== "save")
}
+ @Test("A backup that can't finish leaves no partial copy to trust")
+ func failedBackUpLeavesNothing() throws {
+ let dir = try scratchDirectory("pfx")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let prefix = try prefix(in: dir)
+ try write("copied first", to: prefix.pfx.appending(path: "a.sav"))
+ let unreadable = prefix.pfx.appending(path: "z.sav")
+ try write("save", to: unreadable)
+ let path = unreadable.path(percentEncoded: false)
+ try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: path)
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: path) }
+
+ #expect(throws: (any Error).self) { try PrefixTools.backUp(prefix) }
+
+ #expect(PrefixStore.backups(of: prefix).isEmpty)
+ }
+
@Test("Backing up refuses a game that has never made a prefix")
func backUpRefusesAMissingPrefix() throws {
let dir = try scratchDirectory("pfx")
@@ -619,6 +639,47 @@ struct PrefixStoreTests {
#expect(PrefixStore.isInUse(prefix, root: root))
}
+ // Delete, Rebuild and Back Up go through claim, and the launch lock is gone once a game is
+ // up, so during play this is the only thing refusing them.
+ @Test("A claim is refused while the server runs or can't be checked, and given when idle")
+ func claimAnswersToTheServer() throws {
+ let (prefix, root, dir) = try prefixWithServerDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PrefixStore.claim(
+ prefix, root: root, lsof: dir.appending(path: "absent").path(percentEncoded: false)) == nil)
+ #expect(PrefixStore.claim(
+ prefix, root: root, lsof: try stubLsof(in: dir, body: "echo trouble >&2; exit 1")) == nil)
+ #expect(PrefixStore.claim(
+ prefix, root: root, lsof: try stubLsof(in: dir, body: "sleep 3 & exit 1"),
+ drainTimeout: .milliseconds(200)) == nil)
+
+ let claim = try #require(PrefixStore.claim(prefix, root: root))
+ claim.release()
+
+ let held = try #require(PrefixStore.serverDirectory(of: prefix, root: root))
+ .appending(path: "socket")
+ try Data("s".utf8).write(to: held)
+ let handle = try FileHandle(forReadingFrom: held)
+ defer { try? handle.close() }
+ #expect(PrefixStore.claim(prefix, root: root) == nil)
+ }
+
+ // A wrong name here reads as "not running" for every game. Wine names the folder after
+ // the prefix's device and inode, in hex.
+ @Test("The server folder is the one Wine makes for the prefix")
+ func serverDirectoryIsWines() throws {
+ let dir = try scratchDirectory("pfx")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let prefix = try prefix(in: dir)
+ var info = stat()
+ try #require(stat(prefix.pfx.path(percentEncoded: false), &info) == 0)
+ let name = String(format: "server-%llx-%llx", UInt64(UInt32(bitPattern: info.st_dev)), UInt64(info.st_ino))
+
+ #expect(PrefixStore.serverDirectory(of: prefix)?.lastPathComponent == name)
+ #expect(PrefixStore.serverRoot.path(percentEncoded: false) == "/tmp/.wine-\(getuid())")
+ }
+
// Every one of these used to answer that the prefix was free, which is the answer that
// deletes a prefix out from under a running game.
@Test("lsof failing to answer is not read as the prefix being free")
diff --git a/app/Tests/BridgeplayAppTests/PrefixToolsTests.swift b/app/Tests/BridgeplayAppTests/PrefixToolsTests.swift
index 9051d43..8d81003 100644
--- a/app/Tests/BridgeplayAppTests/PrefixToolsTests.swift
+++ b/app/Tests/BridgeplayAppTests/PrefixToolsTests.swift
@@ -598,7 +598,8 @@ struct PrefixToolsTests {
printf template > "$WINEPREFIX/drive_c/users/crossover/AppData/wine.ini"
printf template > "$WINEPREFIX/drive_c/users/crossover/AppData/fresh.ini"
printf 'fresh user' > "$WINEPREFIX/user.reg"
- printf 'fresh system' > "$WINEPREFIX/system.reg"
+ { printf 'fresh system'; head -c 3000000 /dev/zero; } > "$WINEPREFIX/system.reg"
+ printf 'fresh userdef' > "$WINEPREFIX/userdef.reg"
ln -s "\(home.path(percentEncoded: false))" "$WINEPREFIX/drive_c/users/crossover/Documents"
\(extra)
\(lock ? "chflags uchg \"$WINEPREFIX\"" : ":")
@@ -684,7 +685,7 @@ struct PrefixToolsTests {
// HKLM does not, so the record of what is installed matches the files that are
// actually there and the next launch reinstalls what went with the old tree.
- #expect(text("system.reg") == "fresh system")
+ #expect(text("system.reg")?.hasPrefix("fresh system") == true)
// Replaced, both the file the arch is read from and what an installer left beside it.
#expect(text("drive_c/windows/system32/ntdll.dll") == "fresh")
@@ -760,6 +761,219 @@ struct PrefixToolsTests {
#expect(text("AppData/LocalLow/other/save.txt") == "theirs")
}
+ @Test("The run script looks for the server in the folder the app does")
+ func runScriptAgreesOnTheServerFolder() throws {
+ #expect(try Self.compatSource().contains(#"/tmp/.wine-$(id -u)/server-$(printf '%x-%x'"#))
+ }
+
+ @Test("A finished rebuild clears the run script's switch record, a failed one keeps it")
+ func rebuildAnswersTheSwitchRecord() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let record = prefix.root.appending(path: "notproton-switch")
+ try Data("1\n2\n0\n".utf8).write(to: record)
+
+ let failing = try fakeRunner(in: dir, home: home, exit: 1)
+ #expect(throws: (any Error).self) { try PrefixTools.recreate(prefix, runner: failing) }
+ #expect(fm.fileExists(atPath: record.path(percentEncoded: false)))
+
+ try PrefixTools.recreate(prefix, runner: try fakeRunner(in: dir, home: home))
+ #expect(!fm.fileExists(atPath: record.path(percentEncoded: false)))
+ }
+
+ // A volume that ignores case sees one file under both names.
+ @Test("Copies whose names differ only by case both survive a rebuild")
+ func rebuildKeepsCopiesThatDifferOnlyByCase() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let users = prefix.pfx.appending(path: "drive_c/users")
+
+ try Data().write(to: dir.appending(path: "Probe"))
+ guard fm.fileExists(atPath: dir.appending(path: "probe").path(percentEncoded: false)) else { return }
+
+ for (path, text) in [("crossover/AppData/Roaming/Save1.sav", "crossover"),
+ ("steamuser/AppData/Roaming/save1.sav", "steamuser"),
+ ("crossover/AppData/Roaming/Slot/Save2.sav", "crossover"),
+ ("steamuser/AppData/Roaming/slot/save2.sav", "steamuser")] {
+ let file = users.appending(path: path)
+ try fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(text.utf8).write(to: file)
+ }
+
+ try PrefixTools.recreate(prefix, runner: runner, keepBackup: false)
+
+ let roaming = users.appending(path: "steamuser/AppData/Roaming")
+ func text(_ path: String) -> String? {
+ try? String(contentsOf: roaming.appending(path: path), encoding: .utf8)
+ }
+ #expect(text("Save1.sav") == "crossover")
+ #expect(text("save1.sav BACKUP") == "steamuser")
+ #expect(text("Slot/Save2.sav") == "crossover")
+ #expect(text("slot BACKUP/save2.sav") == "steamuser")
+ }
+
+ // ς and σ are one name on APFS but not to lowercased().
+ @Test("Names only the volume folds together both survive a rebuild")
+ func rebuildKeepsCopiesTheVolumeFolds() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+
+ try Data().write(to: dir.appending(path: "ς"))
+ guard fm.fileExists(atPath: dir.appending(path: "σ").path(percentEncoded: false)) else { return }
+
+ let users = prefix.pfx.appending(path: "drive_c/users")
+ for (path, text) in [("crossover/AppData/Roaming/ς.sav", "crossover"),
+ ("steamuser/AppData/Roaming/σ.sav", "steamuser")] {
+ let file = users.appending(path: path)
+ try fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(text.utf8).write(to: file)
+ }
+
+ try PrefixTools.recreate(prefix, runner: runner, keepBackup: false)
+
+ let roaming = users.appending(path: "steamuser/AppData/Roaming")
+ let kept = try fm.contentsOfDirectory(at: roaming, includingPropertiesForKeys: nil)
+ .compactMap { try? String(contentsOf: $0, encoding: .utf8) }
+ #expect(kept.sorted() == ["crossover", "steamuser"])
+ }
+
+ @Test("A real name ending in BACKUP does not overwrite a parked copy")
+ func rebuildKeepsARealBackupNameApart() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+
+ let users = prefix.pfx.appending(path: "drive_c/users")
+ for (path, text) in [("crossover/AppData/Roaming/a.sav", "first"),
+ ("steamuser/AppData/Roaming/a.sav", "parked"),
+ ("steamuser/AppData/Roaming/a.sav BACKUP", "real")] {
+ let file = users.appending(path: path)
+ try fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(text.utf8).write(to: file)
+ }
+
+ try PrefixTools.recreate(prefix, runner: runner, keepBackup: false)
+
+ let roaming = users.appending(path: "steamuser/AppData/Roaming")
+ let kept = try fm.contentsOfDirectory(at: roaming, includingPropertiesForKeys: nil)
+ .compactMap { try? String(contentsOf: $0, encoding: .utf8) }
+ #expect(kept.sorted() == ["first", "parked", "real"])
+ }
+
+ @Test("An old file the template replaces is parked unless it is the same")
+ func rebuildParksATemplateCollision() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home, extra: """
+ printf template > "$WINEPREFIX/drive_c/ProgramData/save.ini"
+ printf template > "$WINEPREFIX/drive_c/ProgramData/same.ini"
+ """)
+ let prefix = try usedPrefix(in: dir, home: home)
+
+ let data = prefix.pfx.appending(path: "drive_c/ProgramData")
+ try fm.createDirectory(at: data, withIntermediateDirectories: true)
+ try Data("mine".utf8).write(to: data.appending(path: "save.ini"))
+ try Data("template".utf8).write(to: data.appending(path: "same.ini"))
+
+ try PrefixTools.recreate(prefix, runner: runner, keepBackup: false)
+
+ func text(_ name: String) -> String? {
+ try? String(contentsOf: data.appending(path: name), encoding: .utf8)
+ }
+ #expect(text("save.ini") == "template")
+ #expect(text("save.ini BACKUP") == "mine")
+ #expect(text("same.ini BACKUP") == nil)
+ }
+
+ // A killed installer leaves wineboot exiting 0 with a registry too small to be a prefix.
+ @Test("A wineboot that exits 0 with a partial registry leaves the prefix alone", arguments: [
+ #"printf small > "$WINEPREFIX/system.reg""#,
+ #"rm -f "$WINEPREFIX/userdef.reg""#,
+ ])
+ func rebuildRefusesAPartialPrefix(extra: String) throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home, extra: extra)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let save = prefix.pfx.appending(path: "drive_c/users/steamuser/AppData/Roaming/keep.sav")
+ try fm.createDirectory(at: save.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("save".utf8).write(to: save)
+
+ #expect(throws: StepFailure.self) {
+ try PrefixTools.recreate(prefix, runner: runner, keepBackup: false)
+ }
+ #expect(fm.fileExists(atPath: save.path(percentEncoded: false)))
+ }
+
+ // The server holds no pipe here, as when a rebuild outlasts Shell's drain, and writes user.reg
+ // into the moved folder as a real one does.
+ @Test("A rebuild waits for the server before carrying user.reg")
+ func rebuildWaitsForTheServer() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home, extra: #"""
+ (cd "$WINEPREFIX"; exec >/dev/null 2>&1 </dev/null; sleep 1; printf server > user.reg) &
+ """#)
+ let server = runner.appending(path: "bin/wineserver")
+ try fm.createDirectory(at: server.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("#!/bin/sh\n[ \"$1\" = -w ] && sleep 2\nexit 0\n".utf8).write(to: server)
+ try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: server.path(percentEncoded: false))
+ let prefix = try usedPrefix(in: dir, home: home)
+ try Data("old user".utf8).write(to: prefix.pfx.appending(path: "user.reg"))
+
+ try PrefixTools.recreate(prefix, runner: runner)
+ Thread.sleep(forTimeInterval: 1.5)
+
+ let reg = try String(contentsOf: prefix.pfx.appending(path: "user.reg"), encoding: .utf8)
+ #expect(reg.contains("old user"))
+ }
+
+ @Test("A wineboot that never exits is stopped and the prefix left alone")
+ func rebuildStopsAHungWineboot() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home, extra: "exec sleep 30")
+ let prefix = try usedPrefix(in: dir, home: home)
+ try Data("old user".utf8).write(to: prefix.pfx.appending(path: "user.reg"))
+
+ let start = Date.now
+ #expect(throws: (any Error).self) {
+ try PrefixTools.recreate(prefix, runner: runner, keepBackup: false, wineTimeout: .seconds(1))
+ }
+ #expect(Date.now.timeIntervalSince(start) < 10)
+ #expect(fm.fileExists(atPath: prefix.pfx.appending(path: "user.reg").path(percentEncoded: false)))
+ }
+
// The merge keeps whichever copy the walk reaches first, never the newer date: a cloud
// download is stamped when it arrives. crossover is the profile the game wrote under.
@Test("Which of two profiles' copies survives does not turn on its date")
diff --git a/app/Tests/BridgeplayAppTests/RunnerSwitchTests.swift b/app/Tests/BridgeplayAppTests/RunnerSwitchTests.swift
index 0d8483f..0f34654 100644
--- a/app/Tests/BridgeplayAppTests/RunnerSwitchTests.swift
+++ b/app/Tests/BridgeplayAppTests/RunnerSwitchTests.swift
@@ -722,6 +722,33 @@ struct RunnerRemovalTests {
#expect(RunnerInstaller.isRunning(from: URL(filePath: "/R/x"), ps: "/nonexistent/ps"))
}
+ @Test("A clone linked to another drive reads as running, and its build is named")
+ func readsRunningThroughALink() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: try scratchDirectory("runner-link").path(percentEncoded: false)).resolvingSymlinksInPath()
+ defer { try? fm.removeItem(at: dir) }
+ let real = dir.appending(path: "external/crossover-27")
+ let runners = dir.appending(path: "runners")
+ try fm.createDirectory(at: real, withIntermediateDirectories: true)
+ try fm.createDirectory(at: runners, withIntermediateDirectories: true)
+ let link = runners.appending(path: "crossover-27")
+ try fm.createSymbolicLink(at: link, withDestinationURL: real)
+ let printed = real.path(percentEncoded: false).withCString { path in
+ realpath(path, nil).map { defer { free($0) }; return String(cString: $0) }
+ } ?? ""
+ let ps = dir.appending(path: "ps")
+ try """
+ #!/bin/sh
+ echo "\(printed)/CrossOver/bin/wineserver"
+ """.write(to: ps, atomically: true, encoding: .utf8)
+ try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: ps.path(percentEncoded: false))
+ let path = ps.path(percentEncoded: false)
+
+ #expect(RunnerInstaller.isRunning(from: link, ps: path))
+ #expect(RunnerInstaller.runningBuild(in: runners) { RunnerInstaller.isRunning(from: $0, ps: path) } == "27")
+ #expect(RunnerInstaller.runningBuild(in: runners) { _ in false } == nil)
+ }
+
@Test("Any build can be removed, and its tools and staged copies go with it")
func removesBuild() throws {
let runners = try makeRunners(cloning: [Self.rosetta.id, Self.fex.id])
diff --git a/app/Tests/BridgeplayAppTests/SetupAssistantTests.swift b/app/Tests/BridgeplayAppTests/SetupAssistantTests.swift
index fc5929b..8431cbe 100644
--- a/app/Tests/BridgeplayAppTests/SetupAssistantTests.swift
+++ b/app/Tests/BridgeplayAppTests/SetupAssistantTests.swift
@@ -12,6 +12,16 @@ struct SetupAssistantTests {
return url
}
+ @Test("A disk image dropped during other work is ignored")
+ @MainActor
+ func importWaitsForOtherWork() async {
+ let model = SetupAssistant(preview: .fresh)
+ model.isWorking = true
+ await model.importGPTK(URL(filePath: "/nonexistent/Game_Porting_Toolkit.dmg"))
+ #expect(model.isWorking)
+ #expect(model.message == nil)
+ }
+
@Test("Steam counts as signed in once loginusers.vdf names an account")
func signIn() throws {
let dir = try folder()
@@ -316,6 +326,98 @@ struct SetupAssistantTests {
@Suite("Setup checks")
struct SetupChecksTests {
+ @Test("Steam reaches Applications whole or not at all")
+ func steamCopyIsStaged() throws {
+ let fm = FileManager.default
+ let dir = try scratchDirectory("setup-steam")
+ defer { try? fm.removeItem(at: dir) }
+ let applications = dir.appending(path: "Applications")
+ try fm.createDirectory(at: applications, withIntermediateDirectories: true)
+ let app = applications.appending(path: "Steam.app")
+ let image = dir.appending(path: "image")
+ try fm.createDirectory(at: image.appending(path: "Steam.app/Contents"), withIntermediateDirectories: true)
+ try Data("valve".utf8).write(to: image.appending(path: "Steam.app/Contents/Info.plist"))
+
+ struct DiskFull: Error {}
+ #expect(throws: DiskFull.self) {
+ try SetupChecks.copySteam(from: image, to: app, verify: { _ in }) { _, target in
+ try fm.createDirectory(at: target, withIntermediateDirectories: true)
+ throw DiskFull()
+ }
+ }
+ #expect(try fm.contentsOfDirectory(atPath: applications.path(percentEncoded: false)).isEmpty)
+
+ try SetupChecks.copySteam(from: image, to: app, verify: { _ in })
+ let plist = app.appending(path: "Contents/Info.plist")
+ #expect(try Data(contentsOf: plist) == Data("valve".utf8))
+ #expect(try fm.contentsOfDirectory(atPath: applications.path(percentEncoded: false)) == ["Steam.app"])
+
+ try Data("other".utf8).write(to: plist)
+ try SetupChecks.copySteam(from: image, to: app, verify: { _ in })
+ #expect(try Data(contentsOf: plist) == Data("other".utf8))
+ #expect(try fm.contentsOfDirectory(atPath: applications.path(percentEncoded: false)) == ["Steam.app"])
+ }
+
+ private func steamImage(in dir: URL) throws -> (image: URL, applications: URL) {
+ let fm = FileManager.default
+ let applications = dir.appending(path: "Applications")
+ try fm.createDirectory(at: applications, withIntermediateDirectories: true)
+ let image = dir.appending(path: "image")
+ try fm.createDirectory(at: image.appending(path: "Steam.app/Contents"), withIntermediateDirectories: true)
+ try Data("valve".utf8).write(to: image.appending(path: "Steam.app/Contents/Info.plist"))
+ return (image, applications)
+ }
+
+ @Test("A copy a force quit left is swept, and nothing else with a similar name")
+ func staleStagedCopiesAreSwept() throws {
+ let fm = FileManager.default
+ let dir = try scratchDirectory("setup-steam-stale")
+ defer { try? fm.removeItem(at: dir) }
+ let (image, applications) = try steamImage(in: dir)
+ let stale = ".Steam.app-\(UUID().uuidString)"
+ try fm.createDirectory(at: applications.appending(path: "\(stale)/Contents"), withIntermediateDirectories: true)
+ let kept = [".Steam.app-notes", ".Steam.app-\(UUID().uuidString)x", "Steam.app-\(UUID().uuidString)"]
+ for name in kept { try Data().write(to: applications.appending(path: name)) }
+
+ try SetupChecks.copySteam(from: image, to: applications.appending(path: "Steam.app"), verify: { _ in })
+
+ #expect(try fm.contentsOfDirectory(atPath: applications.path(percentEncoded: false)).sorted()
+ == (kept + ["Steam.app"]).sorted())
+ }
+
+ @Test("A staged copy still being written is not swept by another install")
+ func stagedCopyInUseIsKept() throws {
+ let fm = FileManager.default
+ let dir = try scratchDirectory("setup-steam-in-use")
+ defer { try? fm.removeItem(at: dir) }
+ let (image, applications) = try steamImage(in: dir)
+ let app = applications.appending(path: "Steam.app")
+
+ try SetupChecks.copySteam(from: image, to: app, verify: { _ in }) { source, target in
+ try fm.copyItem(at: source, to: target)
+ try SetupChecks.copySteam(from: image, to: applications.appending(path: "Other.app"), verify: { _ in })
+ #expect(fm.fileExists(atPath: target.path(percentEncoded: false)))
+ }
+
+ #expect(fm.fileExists(atPath: app.appending(path: "Contents/Info.plist").path(percentEncoded: false)))
+ }
+
+ @Test("A plain file at Steam.app is not taken for a Steam that appeared meanwhile")
+ func plainFileIsNotAnInstall() throws {
+ let fm = FileManager.default
+ let dir = try scratchDirectory("setup-steam-file")
+ defer { try? fm.removeItem(at: dir) }
+ let (image, applications) = try steamImage(in: dir)
+ let app = applications.appending(path: "Steam.app")
+
+ #expect(throws: (any Error).self) {
+ try SetupChecks.copySteam(from: image, to: app, verify: { _ in }) { source, target in
+ try fm.copyItem(at: source, to: target)
+ try Data("not a bundle".utf8).write(to: app)
+ }
+ }
+ }
+
@Test("Downloads is not read when a Game Porting Toolkit is already installed")
func downloadsScanGated() {
var scans = 0
diff --git a/app/Tests/BridgeplayAppTests/SteamBundleTests.swift b/app/Tests/BridgeplayAppTests/SteamBundleTests.swift
index 068fae8..ba704aa 100644
--- a/app/Tests/BridgeplayAppTests/SteamBundleTests.swift
+++ b/app/Tests/BridgeplayAppTests/SteamBundleTests.swift
@@ -73,6 +73,7 @@ struct SteamBundleTests {
private let stuck: Bool
private(set) var requests: [Request] = []
private(set) var swept: [String] = []
+ private(set) var hereChecks = 0
init(here: Bool, elsewhere: Bool = false, quitsOn: Request = .exitURL, stuck: Bool = false) {
self.here = here
@@ -91,7 +92,7 @@ struct SteamBundleTests {
var client: SteamBundle.Client {
SteamBundle.Client(
runningAnywhere: { self.lock.withLock { self.here || self.elsewhere } },
- runningHere: { self.lock.withLock { self.here } },
+ runningHere: { self.lock.withLock { self.hereChecks += 1; return self.here } },
askToQuit: { self.receive(.exitURL) },
requestQuit: { self.receive(.quit) },
stuckExiting: { _ in self.stuck },
@@ -108,6 +109,13 @@ struct SteamBundleTests {
app: URL(filePath: "/tmp/Steam.app"), helpers: [], step: "Test", client: steam.client)
}
+ @Test("Each look for Steam starts a process, so it stops as soon as Steam has quit")
+ func stopsLookingOnceQuit() throws {
+ let steam = FakeSteam(here: true)
+ #expect(try stop(steam))
+ #expect(steam.hereChecks == 2)
+ }
+
@Test("A closed Steam is left alone")
func closedSteamIsLeftAlone() throws {
let steam = FakeSteam(here: false)
diff --git a/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift b/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift
index a8c0708..13201fc 100644
--- a/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift
+++ b/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift
@@ -95,6 +95,12 @@ struct SteamInstallerTests {
private var resets = 0
func resetInputAccess() { lock.lock(); resets += 1; lock.unlock() }
var inputAccessResets: Int { lock.lock(); defer { lock.unlock() }; return resets }
+ private var stopRequests = 0
+ func stop() { lock.lock(); stopRequests += 1; lock.unlock() }
+ var stops: Int { lock.lock(); defer { lock.unlock() }; return stopRequests }
+ private var runnerLooks = 0
+ // Which look at the runners this is, from 1.
+ func lookAtRunners() -> Int { lock.lock(); defer { lock.unlock() }; runnerLooks += 1; return runnerLooks }
}
private func install(
@@ -104,7 +110,12 @@ struct SteamInstallerTests {
stopped: Bool = false,
running: Bool = false,
recordBuild: Bool = true,
- verifyRunner: (RunnerBuild, URL) throws -> Void = { _, _ in }
+ refusedResets: [String] = [],
+ runnerIsRunning: (@Sendable (URL) -> Bool)? = nil,
+ stopClient: SteamInstaller.ClientStopper? = nil,
+ verifyRunner: (RunnerBuild, URL) throws -> Void = { _, _ in },
+ register: SteamInstaller.BundleRegistrar? = nil,
+ onInputReset: ([String]) -> Void = { _ in }
) throws -> InstallOutcome {
let outcome = try SteamInstaller.run(
payload: fixture.payload,
@@ -121,12 +132,17 @@ struct SteamInstallerTests {
compatTools: fixture.work.appending(path: "compatibilitytools.d"),
lockFolder: fixture.work,
modifications: fixture.modifications,
- runnerIsRunning: { _ in running },
+ runnerIsRunning: runnerIsRunning ?? { _ in running },
verifyRunner: verifyRunner,
patchRunner: { _, _, _ in },
- stopClient: { _, onStopping in if stopped { onStopping() }; return stopped },
- register: { calls.register($0) },
- resetInputAccess: { calls.resetInputAccess(); return [] }
+ stopClient: stopClient ?? { _, onStopping in
+ calls.stop()
+ if stopped { onStopping() }
+ return stopped
+ },
+ register: register ?? { calls.register($0) },
+ resetInputAccess: { calls.resetInputAccess(); return refusedResets },
+ onInputReset: onInputReset
)
if recordBuild {
try SteamInstaller.finish(outcome, deployedVersion: fixture.deployedVersion, isCurrent: { _ in true })
@@ -148,6 +164,7 @@ struct SteamInstallerTests {
#expect(outcome.backedUpPlist)
#expect(!outcome.stoppedClient)
#expect(calls.inputAccessResets == 1)
+ #expect(outcome.failedInputResets == [])
let files = FileManager.default
#expect(files.fileExists(atPath: fixture.deployedDylib.path(percentEncoded: false)))
@@ -171,6 +188,87 @@ struct SteamInstallerTests {
#expect(calls.registrations == [fixture.app], "the bundle was not re-registered")
}
+ @Test("A reset stays known when the install fails after it")
+ func reportsInputResetBeforeALaterFailure() async throws {
+ let work = try scratchDirectory("install-reset-then-fail")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+ let calls = Calls()
+ let plist = fixture.app.appending(path: "Contents/Info.plist")
+ var told: [String]?
+
+ // Another writer changing the insert trips the check after registering.
+ let failure = try #require(throws: StepFailure.self) {
+ try install(fixture, calls: calls, refusedResets: ["ListenEvent"], register: { _ in
+ guard var dict = SteamBundle.readInfoPlist(at: plist),
+ var env = dict[SteamBundle.environmentKey] as? [String: Any] else { return }
+ env[SteamBundle.insertKey] = "/elsewhere.dylib"
+ dict[SteamBundle.environmentKey] = env
+ try? SteamBundle.writeInfoPlist(dict, at: plist)
+ }, onInputReset: { told = $0 })
+ }
+
+ #expect(failure.detail.contains("different dylib"))
+ #expect(calls.inputAccessResets == 1)
+ #expect(told == ["ListenEvent"])
+ }
+
+ @Test("Only an install that reset input access reports on it")
+ func reportsInputResetsOnlyWhenTheyRan() async throws {
+ let work = try scratchDirectory("install-input-resets")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+ let calls = Calls()
+
+ #expect(try install(fixture, calls: calls, refusedResets: ["ListenEvent"]).failedInputResets == ["ListenEvent"])
+ #expect(try install(fixture, calls: calls).failedInputResets == nil)
+ #expect(calls.inputAccessResets == 1)
+ }
+
+ @Test("A Steam that won't stop is left as it was, and the failure is the stopper's")
+ func stopFailureLeavesSteamAlone() async throws {
+ let work = try scratchDirectory("install-stop-failure")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+ let plist = try Data(contentsOf: fixture.plist)
+
+ #expect(throws: SteamInstaller.ClientStarted.self) {
+ try install(fixture, stopClient: { _, _ in throw SteamInstaller.ClientStarted() })
+ }
+ let refusal = try #require(throws: StepFailure.self) {
+ try install(fixture, stopClient: { _, _ in
+ throw StepFailure(step: "Test", detail: "Steam did not quit.")
+ })
+ }
+
+ #expect(refusal.detail == "Steam did not quit.")
+ #expect(try Data(contentsOf: fixture.plist) == plist)
+ for untouched in [fixture.deployedDylib, fixture.bridge, fixture.deployedVersion, fixture.overlayShim] {
+ #expect(!FileManager.default.fileExists(atPath: untouched.path(percentEncoded: false)))
+ }
+ }
+
+ @Test("Steam is stopped before anything in or beside it changes")
+ func stopsBeforeWriting() async throws {
+ let work = try scratchDirectory("install-stop-order")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+ let calls = Calls()
+ let plist = fixture.plist, dylib = fixture.deployedDylib, bridge = fixture.bridge
+ let original = try Data(contentsOf: plist)
+
+ _ = try install(fixture, stopClient: { _, _ in
+ calls.stop()
+ #expect((try? Data(contentsOf: plist)) == original)
+ #expect(!FileManager.default.fileExists(atPath: dylib.path(percentEncoded: false)))
+ #expect(!FileManager.default.fileExists(atPath: bridge.path(percentEncoded: false)))
+ return true
+ })
+
+ #expect(calls.stops == 1)
+ #expect(FileManager.default.fileExists(atPath: dylib.path(percentEncoded: false)))
+ }
+
@Test("Setting the insert keeps the rest of Valve's environment")
func preservesValveEnvironment() async throws {
let work = try scratchDirectory("install")
@@ -493,19 +591,6 @@ struct SteamInstallerTests {
)
}
- @Test("A payload with nothing in it stops the install before anything is touched")
- func refusesEmptyPayload() async throws {
- let work = try scratchDirectory("install")
- defer { try? FileManager.default.removeItem(at: work) }
- let fixture = try await self.fixture(into: work)
-
- let empty = work.appending(path: "empty-payload")
- try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)
-
- #expect(throws: StepFailure.self) { try InstallPayload.locate(root: empty) }
- #expect(SteamBundle.currentInsert(at: fixture.plist) == nil)
- }
-
@Test("The installer records the package build time rather than the installation time")
func recordsPackageBuild() async throws {
let work = try scratchDirectory("install-record")
@@ -642,6 +727,27 @@ struct SteamInstallerTests {
#expect(left == ["alt", "alt/arial.ttf", "arial.ttf"])
}
+ @Test("An install keeps the CJK fonts it doesn't ship and still drops stale ones")
+ func keepsCJKFonts() async throws {
+ let work = try scratchDirectory("install-cjk-fonts")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+ let seeded = ["msyh.ttf", "source-han-sans/LICENSE.txt", "old.ttf"]
+ for name in seeded {
+ let file = fixture.fonts.appending(path: name)
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("font".utf8).write(to: file)
+ }
+
+ _ = try install(fixture)
+
+ let left = FileManager.default.subpaths(atPath: fixture.fonts.path(percentEncoded: false)) ?? []
+ #expect(left.contains("msyh.ttf"))
+ #expect(left.contains("source-han-sans/LICENSE.txt"))
+ #expect(left.contains("arial.ttf"))
+ #expect(!left.contains("old.ttf"))
+ }
+
@Test("A running game prevents file replacement before Steam is stopped")
func refusesRunningRunner() async throws {
let work = try scratchDirectory("install-running")
@@ -650,10 +756,33 @@ struct SteamInstallerTests {
let runner = SupportPaths.clonedRoot(forBuild: SupportedRunners.all[0].id,
runners: fixture.support.appending(path: "runners"))
try FileManager.default.createDirectory(at: runner.appending(path: "lib/wine"), withIntermediateDirectories: true)
+ let calls = Calls()
+
+ let error = try #require(throws: StepFailure.self) { try install(fixture, calls: calls, running: true) }
+
+ #expect(error.detail.contains("is running"))
+ #expect(calls.stops == 0, "Steam was asked to quit under a running game")
+ #expect(!FileManager.default.fileExists(atPath: fixture.bridge.path))
+ #expect(!FileManager.default.fileExists(atPath: fixture.deployedDylib.path))
+ }
+
+ @Test("A game started while Steam was stopping still blocks the install")
+ func refusesRunnerStartedDuringStop() async throws {
+ let work = try scratchDirectory("install-running-late")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+ let runner = SupportPaths.clonedRoot(forBuild: SupportedRunners.all[0].id,
+ runners: fixture.support.appending(path: "runners"))
+ try FileManager.default.createDirectory(at: runner.appending(path: "lib/wine"), withIntermediateDirectories: true)
+ let calls = Calls()
- let error = try #require(throws: StepFailure.self) { try install(fixture, running: true) }
+ // One clone, so one look per pass: quiet before the stop, running after it.
+ let error = try #require(throws: StepFailure.self) {
+ try install(fixture, calls: calls, runnerIsRunning: { _ in calls.lookAtRunners() > 1 })
+ }
#expect(error.detail.contains("is running"))
+ #expect(calls.stops == 1)
#expect(!FileManager.default.fileExists(atPath: fixture.bridge.path))
#expect(!FileManager.default.fileExists(atPath: fixture.deployedDylib.path))
}
@@ -665,8 +794,10 @@ struct SteamInstallerTests {
let fixture = try await self.fixture(into: work)
let runner = SupportPaths.clonedRoot(forBuild: "99.0.0.12345", runners: fixture.support.appending(path: "runners"))
try FileManager.default.createDirectory(at: runner.appending(path: "lib/wine"), withIntermediateDirectories: true)
- let error = try #require(throws: StepFailure.self) { try install(fixture, running: true) }
+ let calls = Calls()
+ let error = try #require(throws: StepFailure.self) { try install(fixture, calls: calls, running: true) }
#expect(error.detail.contains("99.0.0.12345"))
+ #expect(calls.stops == 0, "Steam was asked to quit under a running game")
#expect(!FileManager.default.fileExists(atPath: fixture.deployedDylib.path))
}
@@ -725,4 +856,27 @@ struct SteamInstallerTests {
#expect(!FileManager.default.fileExists(atPath: DeploymentContent.record(beside: fixture.deployedVersion).path))
#expect(!FileManager.default.fileExists(atPath: fixture.deployedVersion.path))
}
+
+ @Test("An install seeds the controller mappings and leaves the user's own alone")
+ func seedsControllerMappings() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let payload = dir.appending(path: "payload")
+ let support = dir.appending(path: "support")
+ try fm.createDirectory(at: payload, withIntermediateDirectories: true)
+ let mappings = support.appending(path: "gamecontrollerdb.txt")
+
+ SteamInstaller.seedControllerMappings(from: payload, in: support)
+ #expect(!fm.fileExists(atPath: mappings.path(percentEncoded: false)))
+
+ try Data("shipped".utf8).write(to: payload.appending(path: "gamecontrollerdb.txt"))
+ SteamInstaller.seedControllerMappings(from: payload, in: support)
+ #expect(fm.contents(atPath: mappings.path(percentEncoded: false)) == Data("shipped".utf8))
+
+ try Data("mine".utf8).write(to: mappings)
+ SteamInstaller.seedControllerMappings(from: payload, in: support)
+ #expect(fm.contents(atPath: mappings.path(percentEncoded: false)) == Data("mine".utf8))
+ }
+
}
diff --git a/app/Tests/BridgeplayAppTests/SteamRepairTests.swift b/app/Tests/BridgeplayAppTests/SteamRepairTests.swift
index 09f6604..d96b56f 100644
--- a/app/Tests/BridgeplayAppTests/SteamRepairTests.swift
+++ b/app/Tests/BridgeplayAppTests/SteamRepairTests.swift
@@ -27,11 +27,11 @@ struct SteamRepairTests {
#expect(staged.lastPathComponent == "Steam.app")
#expect(throws: Never.self) { try SteamRepair.verifyValveSignature(staged) }
- #expect(SteamRepair.version(of: staged) == "6.1")
// The bundle Valve ships declares LC_ALL and no insert. Everything repair does to
// the inner plist is measured against this, so it is asserted rather than assumed.
let plist = try #require(SteamBundle.readInfoPlist(at: staged.appending(path: "Contents/Info.plist")))
+ #expect(plist["CFBundleVersion"] as? String == "6.1")
let environment = try #require(plist[SteamBundle.environmentKey] as? [String: Any])
#expect(environment[SteamBundle.insertKey] == nil)
#expect(environment["LC_ALL"] as? String == "en_US.UTF-8")
@@ -158,6 +158,148 @@ struct SteamRepairTests {
}
}
+ // A patched Steam in scratch, for the runs below. Every path a repair defaults to is
+ // passed in, since those are the real Steam's.
+ private struct Patched {
+ let work: URL, app: URL, modifications: SteamModifications
+ var marker: URL { SupportPaths.Steam.deployedDylib(inBundle: app) }
+ var isUntouched: Bool { FileManager.default.contents(atPath: marker.path(percentEncoded: false)) == Data("patched".utf8) }
+
+ func repair(manifest: ValvePackageManifest? = nil, downloads: URL,
+ stopClient: @escaping SteamInstaller.ClientStopper,
+ runningBuild: @escaping @Sendable () -> String? = { nil },
+ report: @escaping @Sendable (RepairPhase) -> Void = { _ in }) async throws {
+ _ = try await SteamRepair.run(
+ manifest: manifest, app: app, innerPlist: work.appending(path: "inner.plist"), updateBlocks: [],
+ backups: work.appending(path: "support/backups"), downloads: downloads,
+ modifications: modifications, stopClient: stopClient, register: { _ in },
+ runningBuild: runningBuild, report: report)
+ }
+ }
+
+ private func patched(from stock: URL, in work: URL) throws -> Patched {
+ let app = work.appending(path: "installed/Steam.app")
+ try FileManager.default.createDirectory(at: app.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: stock, to: app)
+ let patched = Patched(work: work, app: app, modifications: SteamModifications(
+ file: work.appending(path: "steam-bundles.json"), legacyRecord: work.appending(path: "support/install-build.json")))
+ try Data("patched".utf8).write(to: patched.marker)
+ try patched.modifications.mark(app)
+ return patched
+ }
+
+ private final class Log: @unchecked Sendable {
+ private let lock = NSLock()
+ private var lines: [String] = []
+ func add(_ line: String) { lock.withLock { lines.append(line) } }
+ var all: [String] { lock.withLock { lines } }
+ }
+
+ @Test("A Steam that won't stop is not replaced")
+ func stopFailureKeepsTheBundle() async throws {
+ let work = try scratchDirectory("repair-stop-failure")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let steam = try patched(from: try await stagedStockBundle(into: work), in: work)
+
+ struct StillRunning: Error {}
+ await #expect(throws: StillRunning.self) {
+ try await steam.repair(downloads: try isolatedValveDownloads(in: work), stopClient: { _, _ in throw StillRunning() })
+ }
+
+ #expect(steam.isUntouched)
+ }
+
+ @Test("A running game stops the repair before anything is downloaded")
+ func runningGameRefusesTheRepair() async throws {
+ let work = try scratchDirectory("repair-running-game")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let steam = try patched(from: try await stagedStockBundle(into: work), in: work)
+ let log = Log()
+
+ let refusal = try await #require(throws: StepFailure.self) {
+ try await steam.repair(downloads: try isolatedValveDownloads(in: work), stopClient: { _, _ in
+ log.add("stopped")
+ return true
+ }, runningBuild: { "27.0.0" }, report: { log.add($0.label) })
+ }
+
+ #expect(refusal.detail.contains("27.0.0"))
+ #expect(log.all.isEmpty)
+ #expect(steam.isUntouched)
+ }
+
+ @Test("A game started during the download stops the repair before Steam is touched")
+ func gameStartedDuringTheDownloadRefusesTheRepair() async throws {
+ let work = try scratchDirectory("repair-game-started")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let steam = try patched(from: try await stagedStockBundle(into: work), in: work)
+ let log = Log()
+
+ await #expect(throws: StepFailure.self) {
+ try await steam.repair(downloads: try isolatedValveDownloads(in: work), stopClient: { _, _ in
+ log.add("stopped")
+ return true
+ }, runningBuild: {
+ log.all.contains(RepairPhase.checking.label) ? "27.0.0" : nil
+ }, report: { log.add($0.label) })
+ }
+
+ #expect(!log.all.contains("stopped"))
+ #expect(steam.isUntouched)
+ }
+
+ @Test("The staged bundle is checked and Steam stopped before the old bundle goes")
+ func stopsBeforeReplacing() async throws {
+ let work = try scratchDirectory("repair-stop-order")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let steam = try patched(from: try await stagedStockBundle(into: work), in: work)
+ let log = Log()
+
+ try await steam.repair(downloads: try isolatedValveDownloads(in: work), stopClient: { _, onStopping in
+ onStopping()
+ #expect(steam.isUntouched)
+ return true
+ }, report: { log.add($0.label) })
+
+ #expect(!steam.isUntouched)
+ let checked = try #require(log.all.firstIndex(of: RepairPhase.checking.label))
+ let stopped = try #require(log.all.firstIndex(of: RepairPhase.stoppingClient.label))
+ #expect(checked < stopped)
+ }
+
+ @Test("A staged bundle Valve didn't sign stops the repair before Steam is touched")
+ func unsignedBundleNeverStopsSteam() async throws {
+ let work = try scratchDirectory("repair-unsigned")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let steam = try patched(from: try await stagedStockBundle(into: work), in: work)
+
+ // Laid out as Valve's package is: a zip holding a tar.gz of the bundle.
+ let host = work.appending(path: "host")
+ let contents = host.appending(path: "Steam.app/Contents")
+ try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true)
+ try Data("<plist/>".utf8).write(to: contents.appending(path: "Info.plist"))
+ let path = host.path(percentEncoded: false)
+ try Shell.check("/usr/bin/tar", ["-czf", path + "/inner.tar.gz", "-C", path, "Steam.app"])
+ try Shell.check("/usr/bin/zip", ["-q", "-j", path + "/package.zip", path + "/inner.tar.gz"])
+ let package = host.appending(path: "package.zip")
+ let manifest = ValvePackageManifest(
+ bases: [host], packages: [], files: [],
+ bundle: ValveBundle(file: "package.zip", sha256: try Digest.sha256(of: package),
+ innerArchive: "inner.tar.gz", bundleName: "Steam.app"))
+ let log = Log()
+
+ let refusal = try await #require(throws: StepFailure.self) {
+ try await steam.repair(manifest: manifest, downloads: work.appending(path: "unsigned-downloads"), stopClient: { _, _ in
+ log.add("stopped")
+ return true
+ })
+ }
+
+ #expect(refusal.detail.contains("does not verify against its own signature"))
+ #expect(log.all.isEmpty)
+ #expect(steam.isUntouched)
+ }
+
@Test("A repaired Steam is not outstanding after its drive disconnects")
func retiresRepairedSteamBeforeDisconnect() async throws {
let work = try scratchDirectory("repair-tracking")
@@ -176,7 +318,7 @@ struct SteamRepairTests {
_ = try await SteamRepair.run(
app: app, innerPlist: work.appending(path: "inner.plist"), updateBlocks: [],
backups: support.appending(path: "backups"), downloads: try isolatedValveDownloads(in: work),
- modifications: modifications, stopClient: { _, _ in false }, register: { _ in })
+ modifications: modifications, stopClient: { _, _ in false }, register: { _ in }, runningBuild: { nil })
#expect(try modifications.paths().isEmpty)
try FileManager.default.moveItem(at: drive, to: work.appending(path: "disconnected"))
@@ -290,8 +432,9 @@ struct SteamRepairTests {
try SteamRepair.replace(destination, with: staged)
#expect(throws: Never.self) { try SteamRepair.verifyValveSignature(destination) }
- #expect(SteamRepair.version(of: destination) == "6.1")
- #expect(SteamBundle.currentInsert(at: destination.appending(path: "Contents/Info.plist")) == nil)
+ let plist = destination.appending(path: "Contents/Info.plist")
+ #expect(SteamBundle.readInfoPlist(at: plist)?["CFBundleVersion"] as? String == "6.1")
+ #expect(SteamBundle.currentInsert(at: plist) == nil)
#expect(
!FileManager.default.fileExists(
atPath: destination.appending(path: "Contents/MacOS/notproton.dylib").path(percentEncoded: false)
diff --git a/app/Tests/BridgeplayAppTests/UninstallTests.swift b/app/Tests/BridgeplayAppTests/UninstallTests.swift
index ff07da5..e9d83a8 100644
--- a/app/Tests/BridgeplayAppTests/UninstallTests.swift
+++ b/app/Tests/BridgeplayAppTests/UninstallTests.swift
@@ -512,16 +512,49 @@ struct UninstallTests {
}
private func remove(_ layout: Layout, app: URL? = nil,
+ leftovers: Uninstall.Leftovers? = nil,
repair: @escaping Uninstall.Repair = { _, _ in },
stop: Uninstall.Stop = { _, _ in false }) async throws -> UninstallOutcome {
try await Uninstall.run(
app: app ?? layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock],
legacyCompat: layout.legacyCompat, compatTools: layout.compatTools,
directories: [layout.support, layout.caches], libraries: [],
- modifications: layout.modifications, lockFolder: layout.root, leftovers: layout.leftovers,
+ modifications: layout.modifications, lockFolder: layout.root, leftovers: leftovers ?? layout.leftovers,
repair: repair, stop: stop)
}
+ @Test("A running game stops the removal before Steam is touched")
+ func refusesWhileAGameRuns() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ var leftovers = layout.leftovers
+ leftovers.runningBuild = { "27.0.0" }
+ let stops = Flag()
+
+ let failure = try await #require(throws: StepFailure.self) {
+ try await remove(layout, leftovers: leftovers, stop: { _, _ in stops.set(); return false })
+ }
+
+ #expect(failure.detail.contains("27.0.0"))
+ #expect(!stops.value)
+ #expect(FileManager.default.fileExists(atPath: layout.support.path))
+ #expect(try SteamModifications.inspect(layout.app) == .modified)
+ }
+
+ @Test("--remove-everything fails while a game runs")
+ func commandRefusesWhileAGameRuns() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ var leftovers = layout.leftovers
+ leftovers.runningBuild = { "27.0.0" }
+ let captured = leftovers
+
+ let exitCode = await RemoveEverythingCommand.perform { _ in try await remove(layout, leftovers: captured) }
+
+ #expect(exitCode == 1)
+ #expect(FileManager.default.fileExists(atPath: layout.support.path))
+ }
+
@Test("Removal cleans both tracked copies when the first drive returns")
func removesReturnedSteamAsWellAsSelectedSteam() async throws {
let layout = try layout()
diff --git a/app/Tests/BridgeplayInstallerCoreTests/ComponentsPlacementTests.swift b/app/Tests/BridgeplayInstallerCoreTests/ComponentsPlacementTests.swift
index edbe0ad..236c6cb 100644
--- a/app/Tests/BridgeplayInstallerCoreTests/ComponentsPlacementTests.swift
+++ b/app/Tests/BridgeplayInstallerCoreTests/ComponentsPlacementTests.swift
@@ -11,6 +11,13 @@ struct ComponentsPlacementTests {
var statuses: [String] = []
}
+ private final class Lines: @unchecked Sendable {
+ private let lock = NSLock()
+ private var lines: [String] = []
+ func add(_ line: String) { lock.withLock { lines.append(line) } }
+ var all: [String] { lock.withLock { lines } }
+ }
+
private struct Fixture {
let root: URL, source: URL, home: URL, applications: URL
var support: URL { home.appending(path: "Library/Application Support/bridgeplay") }
@@ -94,6 +101,27 @@ struct ComponentsPlacementTests {
#expect(!FileManager.default.fileExists(atPath: f.support.appending(path: "gptk").path))
}
+ @Test("A failed copy logs the tool's reason and shows the plain message")
+ func failureReasonIsLogged() throws {
+ let f = try fixture()
+ defer { try? FileManager.default.removeItem(at: f.root) }
+ try FileManager.default.removeItem(at: f.source.appending(path: "gptk"))
+ let lines = Lines()
+ var placement = placement(f, Calls())
+ placement.log = { lines.add($0) }
+
+ let failure = try #require(throws: InstallerError.self) { try placement.place() }
+
+ guard case .componentsFailure(let message) = failure else {
+ Issue.record("Unexpected error: \(failure)")
+ return
+ }
+ #expect(message == "The Game Porting Toolkit could not be copied.")
+ #expect(lines.all.count == 1)
+ #expect(lines.all.first?.hasPrefix(message) == true)
+ #expect(lines.all.first?.contains("ditto") == true)
+ }
+
@Test("An older GPTK is replaced whole, and the user's mappings and edited confs stay")
func update() throws {
let f = try fixture()