Skip to content

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

fix(steam): refuse config.vdf writes while Steam runs and back up the user's default tool

raymondchins860da9a968b1
diff --git a/app/Sources/BridgeplayApp/Model/SteamDefaultTool.swift b/app/Sources/BridgeplayApp/Model/SteamDefaultTool.swift
index 0d8aeeb..84d8b61 100644
--- a/app/Sources/BridgeplayApp/Model/SteamDefaultTool.swift
+++ b/app/Sources/BridgeplayApp/Model/SteamDefaultTool.swift
@@ -2,7 +2,8 @@ import Foundation
// Steam's default compatibility tool: CompatToolMapping's "0" entry in config.vdf, which
// applies to every app without a mapping of its own. Steam rewrites config.vdf when it quits,
-// so this is only written while Steam is closed.
+// so this is only written while Steam is closed, and refused while it runs. The entry it
+// replaces is kept in a backup, so removing Bridgeplay can put the user's own choice back.
enum SteamDefaultTool {
static let globalPriority = "75"
@@ -10,16 +11,66 @@ enum SteamDefaultTool {
SupportPaths.Steam.userData.appending(path: "config/config.vdf")
}
- static func set(_ tool: String, in file: URL = config) throws {
+ static var backup: URL {
+ SupportPaths.backups.appending(path: "steam-default-tool.json")
+ }
+
+ // The fields of a "0" entry, as raw text between their quotes.
+ struct Mapping: Codable, Equatable, Sendable {
+ var name: String
+ var config: String = ""
+ var priority: String = SteamDefaultTool.globalPriority
+ }
+
+ // What the "0" entry was before Bridgeplay first set it; nil when there was none.
+ struct Backup: Codable, Equatable, Sendable {
+ var previous: Mapping?
+ }
+
+ struct SteamRunning: LocalizedError {
+ var errorDescription: String? {
+ String(localized: "Steam is running, and it rewrites its settings when it quits. Quit Steam, then try again.")
+ }
+ }
+
+ static func set(
+ _ tool: String, in file: URL = config, backup: URL = backup,
+ steamRunning: () -> Bool = { SteamBundle.isRunningForThisUser }
+ ) throws {
+ guard !steamRunning() else { throw SteamRunning() }
guard let text = try? String(contentsOf: file, encoding: .utf8) else {
throw StepFailure(step: step, detail: "Steam has no config.vdf yet. Open Steam once, log in, quit it and run this again.")
}
guard let result = updated(text, tool: tool) else {
throw StepFailure(step: step, detail: "config.vdf has no InstallConfigStore > Software > Valve > Steam section.")
}
- if result != text {
- try result.write(to: file, atomically: true, encoding: .utf8)
+ guard result != text else { return }
+ // A default that is already one of ours is not the user's, so the backup taken when
+ // Bridgeplay first replaced theirs is kept.
+ let previous = current(in: text)
+ if previous.map({ !ToolName.isOurs($0.name) }) ?? true {
+ try FileManager.default.createDirectory(at: backup.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try JSONEncoder().encode(Backup(previous: previous)).write(to: backup, options: .atomic)
}
+ try result.write(to: file, atomically: true, encoding: .utf8)
+ }
+
+ // Puts back what set() replaced when the default is still one of Bridgeplay's tools: the
+ // backed up entry, or no "0" entry at all when there is no backup or there was none.
+ // A default the user has changed since is left alone. Returns whether it wrote.
+ @discardableResult
+ static func restore(
+ in file: URL = config, backup: URL = backup,
+ steamRunning: () -> Bool = { SteamBundle.isRunningForThisUser }
+ ) throws -> Bool {
+ guard let text = try? String(contentsOf: file, encoding: .utf8),
+ let mapping = current(in: text), ToolName.isOurs(mapping.name)
+ else { return false }
+ guard !steamRunning() else { throw SteamRunning() }
+ let saved = (try? Data(contentsOf: backup)).flatMap { try? JSONDecoder().decode(Backup.self, from: $0) }
+ guard let result = replacingDefault(text, with: saved?.previous), result != text else { return false }
+ try WriteRefused.catching(file) { try result.write(to: file, atomically: true, encoding: .utf8) }
+ return true
}
static let step = "Set Steam's default compatibility tool"
@@ -27,21 +78,38 @@ enum SteamDefaultTool {
// Replaces the "0" entry under CompatToolMapping, or adds it (and CompatToolMapping) when
// missing. nil when the file has no Valve > Steam section to put it in.
static func updated(_ text: String, tool: String) -> String? {
+ replacingDefault(text, with: Mapping(name: tool))
+ }
+
+ // The "0" entry under CompatToolMapping, if there is one.
+ static func current(in text: String) -> Mapping? {
+ let lines = text.components(separatedBy: "\n")
+ guard let (zero, close) = defaultEntry(lines) else { return nil }
+ var fields: [String: String] = [:]
+ for line in lines[zero + 1 ..< close] {
+ guard let (key, value, _) = BrandMigration.keyValue(line) else { continue }
+ fields[key.lowercased()] = value
+ }
+ guard let name = fields["name"] else { return nil }
+ return Mapping(name: name, config: fields["config"] ?? "", priority: fields["priority"] ?? globalPriority)
+ }
+
+ // Sets the "0" entry to mapping, or removes it when mapping is nil. nil when the file has
+ // no place for it.
+ static func replacingDefault(_ text: String, with mapping: Mapping?) -> String? {
var lines = text.components(separatedBy: "\n")
- if let mapping = keyLine(lines, "CompatToolMapping", from: 0) {
- let depth = indent(lines[mapping])
- guard let open = openBrace(lines, after: mapping), let close = closeBrace(lines, open: open) else { return nil }
- let entryDepth = depth + 1
- if let zero = (open + 1 ..< close).first(where: {
- indent(lines[$0]) == entryDepth && key(lines[$0]) == "0"
- }), let zeroOpen = openBrace(lines, after: zero), let zeroClose = closeBrace(lines, open: zeroOpen) {
- lines.replaceSubrange(zero ... zeroClose, with: entry(tool, depth: entryDepth))
+ if let section = keyLine(lines, "CompatToolMapping", from: 0) {
+ guard let open = openBrace(lines, after: section), closeBrace(lines, open: open) != nil else { return nil }
+ let replacement = mapping.map { entry($0, depth: indent(lines[section]) + 1) } ?? []
+ if let (zero, zeroClose) = defaultEntry(lines) {
+ lines.replaceSubrange(zero ... zeroClose, with: replacement)
} else {
- lines.insert(contentsOf: entry(tool, depth: entryDepth), at: open + 1)
+ lines.insert(contentsOf: replacement, at: open + 1)
}
return lines.joined(separator: "\n")
}
+ guard let mapping else { return text }
guard let valve = keyLine(lines, "Valve", from: 0),
let steam = keyLine(lines, "Steam", from: valve + 1),
@@ -49,19 +117,32 @@ enum SteamDefaultTool {
else { return nil }
let depth = indent(lines[steam]) + 1
let tabs = String(repeating: "\t", count: depth)
- let block = ["\(tabs)\"CompatToolMapping\"", "\(tabs){"] + entry(tool, depth: depth + 1) + ["\(tabs)}"]
+ let block = ["\(tabs)\"CompatToolMapping\"", "\(tabs){"] + entry(mapping, depth: depth + 1) + ["\(tabs)}"]
lines.insert(contentsOf: block, at: open + 1)
return lines.joined(separator: "\n")
}
- private static func entry(_ tool: String, depth: Int) -> [String] {
+ // The "0" key line and its closing brace, directly under CompatToolMapping.
+ private static func defaultEntry(_ lines: [String]) -> (Int, Int)? {
+ guard let mapping = keyLine(lines, "CompatToolMapping", from: 0),
+ let open = openBrace(lines, after: mapping), let close = closeBrace(lines, open: open)
+ else { return nil }
+ let entryDepth = indent(lines[mapping]) + 1
+ guard let zero = (open + 1 ..< close).first(where: {
+ indent(lines[$0]) == entryDepth && key(lines[$0]) == "0"
+ }), let zeroOpen = openBrace(lines, after: zero), let zeroClose = closeBrace(lines, open: zeroOpen)
+ else { return nil }
+ return (zero, zeroClose)
+ }
+
+ private static func entry(_ mapping: Mapping, depth: Int) -> [String] {
let tabs = String(repeating: "\t", count: depth)
return [
"\(tabs)\"0\"",
"\(tabs){",
- "\(tabs)\t\"name\"\t\t\"\(tool)\"",
- "\(tabs)\t\"config\"\t\t\"\"",
- "\(tabs)\t\"priority\"\t\t\"\(globalPriority)\"",
+ "\(tabs)\t\"name\"\t\t\"\(mapping.name)\"",
+ "\(tabs)\t\"config\"\t\t\"\(mapping.config)\"",
+ "\(tabs)\t\"priority\"\t\t\"\(mapping.priority)\"",
"\(tabs)}",
]
}
diff --git a/app/Sources/BridgeplayApp/SetupAssistant.swift b/app/Sources/BridgeplayApp/SetupAssistant.swift
index 684a4cd..e5908c9 100644
--- a/app/Sources/BridgeplayApp/SetupAssistant.swift
+++ b/app/Sources/BridgeplayApp/SetupAssistant.swift
@@ -258,15 +258,15 @@ final class SetupAssistant {
set("engine", .done)
set("default", .running)
- if SteamBundle.isRunning {
- set("default", .failed(String(localized: "Quit Steam, then press Try Again.")))
- return
- }
+ // pgrep and the config.vdf write stay off the main actor.
do {
if let tool = FreeEngineWinecx.current.runner.tools.first?.name {
- try SteamDefaultTool.set(tool)
+ try await Task.detached(priority: .userInitiated) { try SteamDefaultTool.set(tool) }.value
}
set("default", .done)
+ } catch is SteamDefaultTool.SteamRunning {
+ set("default", .failed(String(localized: "Quit Steam, then press Try Again.")))
+ return
} catch {
set("default", .failed(error.localizedDescription))
return
diff --git a/app/Sources/BridgeplayApp/Support/SetupWinecxCommand.swift b/app/Sources/BridgeplayApp/Support/SetupWinecxCommand.swift
index 083e0f6..b5cd746 100644
--- a/app/Sources/BridgeplayApp/Support/SetupWinecxCommand.swift
+++ b/app/Sources/BridgeplayApp/Support/SetupWinecxCommand.swift
@@ -14,7 +14,7 @@ enum SetupWinecxCommand {
private static func perform() async -> Int32 {
do {
- if SteamBundle.isRunning {
+ if SteamBundle.isRunningForThisUser {
throw StepFailure(step: FreeEngineWinecx.step, detail: "Steam is running. Quit Steam and run this again.")
}
if DeploymentContent.current(version: AppVersion.bundled).blocksInstallation {
@@ -36,7 +36,13 @@ enum SetupWinecxCommand {
?? "Game Porting Toolkit not found; games use DXMT.")
if let tool = FreeEngineWinecx.current.runner.tools.first?.name {
- try SteamDefaultTool.set(tool)
+ do {
+ try SteamDefaultTool.set(tool)
+ } catch is SteamDefaultTool.SteamRunning {
+ // Steam opened while the engine was set up; everything but the default is done.
+ throw StepFailure(step: SteamDefaultTool.step,
+ detail: "WineCX is set up, but Steam opened in the meantime, so its default compatibility tool was not changed. Quit Steam and run this again.")
+ }
say("Steam's default compatibility tool is \(tool).")
}
say("WineCX is set up.")
diff --git a/app/Tests/BridgeplayAppTests/SteamDefaultToolTests.swift b/app/Tests/BridgeplayAppTests/SteamDefaultToolTests.swift
index 2a469f6..ab9f54e 100644
--- a/app/Tests/BridgeplayAppTests/SteamDefaultToolTests.swift
+++ b/app/Tests/BridgeplayAppTests/SteamDefaultToolTests.swift
@@ -63,4 +63,85 @@ struct SteamDefaultToolTests {
func refusesUnknownLayout() {
#expect(SteamDefaultTool.updated("\"InstallConfigStore\"\n{\n}\n", tool: "t") == nil)
}
+
+ // MARK: Writing, backing up and restoring
+
+ private static func config(_ entry: String?) -> String {
+ Self.head + "\n\t\t\t\t\"CompatToolMapping\"\n\t\t\t\t{\n" + (entry.map { $0 + "\n" } ?? "") + "\t\t\t\t}\n" + Self.tail
+ }
+
+ private func files(_ text: String) throws -> (dir: URL, config: URL, backup: URL) {
+ let dir = try scratchDirectory("default-tool")
+ let config = dir.appending(path: "config.vdf")
+ try Data(text.utf8).write(to: config)
+ return (dir, config, dir.appending(path: "backups/steam-default-tool.json"))
+ }
+
+ private func read(_ url: URL) throws -> String { try String(contentsOf: url, encoding: .utf8) }
+
+ @Test("Nothing is written while Steam runs, since Steam rewrites the file when it quits")
+ func refusesWhileSteamRuns() throws {
+ let f = try files(Self.config(Self.entry("GE-Proton9-1")))
+ defer { try? FileManager.default.removeItem(at: f.dir) }
+
+ #expect(throws: SteamDefaultTool.SteamRunning.self) {
+ try SteamDefaultTool.set("bridgeplay-proton-winecx-11.17", in: f.config, backup: f.backup, steamRunning: { true })
+ }
+ #expect(try read(f.config) == Self.config(Self.entry("GE-Proton9-1")))
+ #expect(!FileManager.default.fileExists(atPath: f.backup.path))
+ }
+
+ @Test("The user's own default is backed up and comes back on restore")
+ func backsUpAndRestoresTheUsersDefault() throws {
+ let original = Self.config(Self.entry("GE-Proton9-1"))
+ let f = try files(original)
+ defer { try? FileManager.default.removeItem(at: f.dir) }
+
+ try SteamDefaultTool.set("bridgeplay-proton-winecx-11.17", in: f.config, backup: f.backup, steamRunning: { false })
+ #expect(try read(f.config) == Self.config(Self.entry("bridgeplay-proton-winecx-11.17")))
+ // Setting another of ours keeps the backup of the user's choice, not of ours.
+ try SteamDefaultTool.set("bridgeplay-proton-winecx-11.18", in: f.config, backup: f.backup, steamRunning: { false })
+
+ #expect(try SteamDefaultTool.restore(in: f.config, backup: f.backup, steamRunning: { false }))
+ #expect(try read(f.config) == original)
+ }
+
+ @Test("A default that was not there is removed again on restore")
+ func restoreRemovesADefaultThatWasNotThere() throws {
+ let original = Self.config(nil)
+ let f = try files(original)
+ defer { try? FileManager.default.removeItem(at: f.dir) }
+
+ try SteamDefaultTool.set("bridgeplay-proton", in: f.config, backup: f.backup, steamRunning: { false })
+ #expect(try SteamDefaultTool.restore(in: f.config, backup: f.backup, steamRunning: { false }))
+ #expect(try read(f.config) == original)
+ }
+
+ @Test("Without a backup, a default naming one of our tools is removed")
+ func restoreWithoutBackupRemovesOurs() throws {
+ let f = try files(Self.config(Self.entry("notproton-winecx-11.17")))
+ defer { try? FileManager.default.removeItem(at: f.dir) }
+
+ #expect(try SteamDefaultTool.restore(in: f.config, backup: f.backup, steamRunning: { false }))
+ #expect(try read(f.config) == Self.config(nil))
+ }
+
+ @Test("A default the user chose since is left alone")
+ func restoreLeavesTheUsersNewChoice() throws {
+ let f = try files(Self.config(Self.entry("GE-Proton9-1")))
+ defer { try? FileManager.default.removeItem(at: f.dir) }
+ try FileManager.default.createDirectory(at: f.backup.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try JSONEncoder().encode(SteamDefaultTool.Backup(previous: nil)).write(to: f.backup)
+
+ // Steam running does not matter when there is nothing to put back.
+ #expect(try SteamDefaultTool.restore(in: f.config, backup: f.backup, steamRunning: { true }) == false)
+ #expect(try read(f.config) == Self.config(Self.entry("GE-Proton9-1")))
+ }
+
+ @Test("The default entry is read with its fields")
+ func readsTheDefault() {
+ #expect(SteamDefaultTool.current(in: Self.config(Self.entry("t")))
+ == SteamDefaultTool.Mapping(name: "t", config: "", priority: "75"))
+ #expect(SteamDefaultTool.current(in: Self.config(nil)) == nil)
+ }
}