Skip to content

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

Let users choose where Steam is installed

Logand972402cd705
diff --git a/Makefile b/Makefile
index 0fa0800..dd0eec0 100644
--- a/Makefile
+++ b/Makefile
@@ -476,8 +476,8 @@ dobby:
-G "Unix Makefiles"
$(MAKE) -C $(DOBBY_DIR) -j$(shell sysctl -n hw.ncpu)
-STEAM_APP := /Applications/Steam.app
-DEPLOY_DST := $(STEAM_APP)/Contents/MacOS/notproton.dylib
+STEAM_APP ?= $$(p=$$(defaults read com.notproton.NotProton steamAppPath 2>/dev/null); printf '%s' "$${p:-/Applications/Steam.app}")
+DEPLOY_DST = $(STEAM_APP)/Contents/MacOS/notproton.dylib
INSTALL_DST := $(SUPPORT_DIR)/notproton.dylib
dylib-install: $(TARGET)
diff --git a/app/Sources/NotProtonApp/Model/DeploymentContent.swift b/app/Sources/NotProtonApp/Model/DeploymentContent.swift
index 5314dcb..c32c5c7 100644
--- a/app/Sources/NotProtonApp/Model/DeploymentContent.swift
+++ b/app/Sources/NotProtonApp/Model/DeploymentContent.swift
@@ -56,12 +56,50 @@ enum DeploymentContent {
versionFile.deletingLastPathComponent().appending(path: "install-build.json")
}
- static func acquireInstallationLock(for app: URL) throws -> Int32 {
- let parent = app.deletingLastPathComponent().path(percentEncoded: false)
- let fd = open(parent, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
+ struct InstallationLock {
+ fileprivate let descriptors: [Int32]
+
+ func release() {
+ descriptors.reversed().forEach(FileLock.release)
+ }
+ }
+
+ static func acquireInstallationLock(
+ in folder: URL = SupportPaths.applicationSupport,
+ steamFolder: URL? = SupportPaths.Steam.app.deletingLastPathComponent()
+ ) throws -> InstallationLock {
+ let own = try lock(folder, required: true)!
+ guard let steamFolder else { return InstallationLock(descriptors: [own]) }
+ do {
+ guard let steam = try lock(steamFolder, required: false, unless: own) else {
+ return InstallationLock(descriptors: [own])
+ }
+ return InstallationLock(descriptors: [own, steam])
+ } catch {
+ FileLock.release(own)
+ throw error
+ }
+ }
+
+ static func acquireSteamLock(for app: URL, holding lock: InstallationLock) throws -> InstallationLock {
+ let descriptor = try self.lock(app.deletingLastPathComponent(), required: false, unless: lock.descriptors.first)
+ return InstallationLock(descriptors: descriptor.map { [$0] } ?? [])
+ }
+
+ private static func lock(_ folder: URL, required: Bool, unless held: Int32? = nil) throws -> Int32? {
+ let parent = folder.path(percentEncoded: false)
+ let fd = open(parent, O_RDONLY | O_DIRECTORY | O_CLOEXEC | (required ? O_NOFOLLOW : 0))
guard fd >= 0 else {
+ if !required, errno == ENOENT || errno == ENOTDIR { return nil }
throw StepFailure(step: SteamInstaller.step, detail: String(localized: "Could not lock the installation at \(parent): \(String(cString: strerror(errno)))."))
}
+ if let held {
+ var mine = stat(), this = stat()
+ if fstat(held, &mine) == 0, fstat(fd, &this) == 0, mine.st_dev == this.st_dev, mine.st_ino == this.st_ino {
+ close(fd)
+ return nil
+ }
+ }
guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
close(fd)
throw StepFailure(step: SteamInstaller.step, detail: String(localized: "Another installation operation is changing files here. Wait for it to finish."))
diff --git a/app/Sources/NotProtonApp/Model/SteamBundle.swift b/app/Sources/NotProtonApp/Model/SteamBundle.swift
index 7f65af1..cf88bd5 100644
--- a/app/Sources/NotProtonApp/Model/SteamBundle.swift
+++ b/app/Sources/NotProtonApp/Model/SteamBundle.swift
@@ -112,7 +112,12 @@ enum SteamBundle {
}
static func sweepPatterns(app: URL, helpers: [URL]) -> [String] {
- ([app] + helpers).map { $0.path(percentEncoded: false) + "/" }
+ ([app] + helpers).map { url in
+ (url.path(percentEncoded: false) + "/").reduce(into: "") { pattern, character in
+ if "\\.^$|?*+()[]{}".contains(character) { pattern.append("\\") }
+ pattern.append(character)
+ }
+ }
}
static func register(_ app: URL = SupportPaths.Steam.app) {
diff --git a/app/Sources/NotProtonApp/Model/SteamInstaller.swift b/app/Sources/NotProtonApp/Model/SteamInstaller.swift
index a942f99..a02a65a 100644
--- a/app/Sources/NotProtonApp/Model/SteamInstaller.swift
+++ b/app/Sources/NotProtonApp/Model/SteamInstaller.swift
@@ -66,6 +66,8 @@ enum SteamInstaller {
backups: URL = SupportPaths.backups,
compatTools: URL = SupportPaths.Steam.compatTools,
holdingInstallationLock: Bool = false,
+ lockFolder: URL = SupportPaths.applicationSupport,
+ modifications: SteamModifications = .shared,
runnerIsRunning: @Sendable (URL) -> Bool = { RunnerInstaller.isRunning(from: $0) },
verifyRunner: (RunnerBuild, URL) throws -> Void = RunnerInstaller.verifyClone,
patchRunner: (RunnerBuild, URL, URL) throws -> Void = { build, root, bridge in
@@ -86,8 +88,9 @@ enum SteamInstaller {
let dylib = app.appending(path: "Contents/MacOS/\(SupportPaths.dylibName)")
try assertBundleIsPresent(app)
try assertInsertIsDeployedOrAbsent(at: plist, dylib: dylib)
- let installationLock = holdingInstallationLock ? -1 : try DeploymentContent.acquireInstallationLock(for: app)
- defer { if installationLock >= 0 { FileLock.release(installationLock) } }
+ let installationLock = holdingInstallationLock
+ ? nil : try DeploymentContent.acquireInstallationLock(in: lockFolder, steamFolder: app.deletingLastPathComponent())
+ defer { installationLock?.release() }
guard let dylibHashes = try MachOBuild.hashesIgnoringSignature(of: payload.dylib) else {
throw StepFailure(step: step, detail: String(localized: "The bundled NotProton dylib is invalid."))
}
@@ -117,6 +120,7 @@ enum SteamInstaller {
for build in builds {
try verifyRunner(build, SupportPaths.clonedRoot(forBuild: build.id, runners: runners))
}
+ try modifications.mark(app)
let patching = try needsPatching(plist: plist, dylib: dylib, shipping: payload.dylib, app: app)
let replacingFiles = try files.contains {
try $0.needsClientStopped && !$0.matches() && FileManager.default.fileExists(atPath: $0.destination.path(percentEncoded: false))
diff --git a/app/Sources/NotProtonApp/Model/SteamModifications.swift b/app/Sources/NotProtonApp/Model/SteamModifications.swift
new file mode 100644
index 0000000..44849fc
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/SteamModifications.swift
@@ -0,0 +1,79 @@
+import Foundation
+
+struct SteamModifications: Sendable {
+ let file: URL
+ let legacyRecord: URL
+
+ static var shared: Self {
+ Self(file: SupportPaths.applicationSupport.appending(path: "notproton-steam-bundles.json"),
+ legacyRecord: DeploymentContent.record(beside: SupportPaths.deployedVersion))
+ }
+
+ enum State: Equatable {
+ case unreachable, absent, clean, modified
+ }
+
+ func paths() throws -> [URL] {
+ do {
+ return try JSONDecoder().decode([String].self, from: Data(contentsOf: file))
+ .map { URL(filePath: $0, directoryHint: .notDirectory) }
+ } catch let error as NSError where error.domain == NSCocoaErrorDomain
+ && [NSFileReadNoSuchFileError, NSFileNoSuchFileError].contains(error.code) {}
+ if try DeploymentContent.readBuild(at: legacyRecord) != nil {
+ return [SupportPaths.Steam.defaultApp]
+ }
+ return []
+ }
+
+ func prepare() throws {
+ try write(paths())
+ }
+
+ func mark(_ app: URL) throws {
+ try write(paths() + [app])
+ }
+
+ @discardableResult
+ func retireIfClean(_ app: URL) throws -> Bool {
+ switch try Self.inspect(app) {
+ case .unreachable, .modified: return false
+ case .absent, .clean:
+ try write(paths().filter { $0.path != app.standardizedFileURL.path })
+ return true
+ }
+ }
+
+ private func write(_ paths: [URL]) throws {
+ let paths = Set(paths.map { $0.standardizedFileURL.path }).sorted()
+ try atomicReplace(file, with: JSONEncoder().encode(paths), step: Uninstall.step)
+ }
+
+ static func inspect(_ app: URL) throws -> State {
+ let files = FileManager.default
+ do {
+ _ = try files.attributesOfItem(atPath: app.path(percentEncoded: false))
+ } catch let error as NSError where error.domain == NSCocoaErrorDomain
+ && [NSFileReadNoSuchFileError, NSFileNoSuchFileError].contains(error.code) {
+ return SupportPaths.Steam.isUnreachable(app) ? .unreachable : .absent
+ }
+ let plist = SupportPaths.Steam.infoPlist(inBundle: app)
+ let data = try Data(contentsOf: plist)
+ let value = try PropertyListSerialization.propertyList(from: data, format: nil)
+ guard let dictionary = value as? [String: Any] else {
+ throw StepFailure(step: Uninstall.step,
+ detail: String(localized: "\(plist.path(percentEncoded: false)) could not be read as a property list."))
+ }
+ let environment = dictionary[SteamBundle.environmentKey] as? [String: Any] ?? [:]
+ let insert = environment[SteamBundle.insertKey] as? String ?? ""
+ let injected = insert.split(separator: ":").contains {
+ URL(filePath: String($0)).lastPathComponent == SupportPaths.dylibName
+ }
+ let dylib = SupportPaths.Steam.deployedDylib(inBundle: app)
+ if injected || environment[SteamBundle.controllerBlockKey] as? String == SteamBundle.controllerBlockValue
+ || files.fileExists(atPath: dylib.path(percentEncoded: false)) {
+ return .modified
+ }
+ let signature = try Shell.run("/usr/bin/codesign", ["--verify", "--strict", app.path(percentEncoded: false)])
+ return signature.succeeded ? .clean : .modified
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/SteamRepair.swift b/app/Sources/NotProtonApp/Model/SteamRepair.swift
index d1696a8..cd916dd 100644
--- a/app/Sources/NotProtonApp/Model/SteamRepair.swift
+++ b/app/Sources/NotProtonApp/Model/SteamRepair.swift
@@ -50,7 +50,12 @@ enum SteamRepair {
updateBlocks: [URL] = UpdateBlock.paths,
backups: URL = SupportPaths.backups,
downloads: URL = SupportPaths.packageDownloads,
- report: @Sendable (RepairPhase) -> Void = { _ in }
+ modifications: SteamModifications = .shared,
+ stopClient: SteamInstaller.ClientStopper = { app, onStopping in
+ try SteamBundle.stopClient(app: app, step: String(localized: "Repair Steam"), onStopping: onStopping)
+ },
+ register: SteamInstaller.BundleRegistrar = { SteamBundle.register($0) },
+ report: @escaping @Sendable (RepairPhase) -> Void = { _ in }
) async throws -> RepairOutcome {
let manifest = try suppliedManifest ?? ValvePackageManifest.bundled()
guard let bundle = manifest.bundle else {
@@ -65,20 +70,12 @@ enum SteamRepair {
report(.checking)
try verifyValveSignature(staged)
- let stopped = try SteamBundle.stopClient(app: app, step: step) { report(.stoppingClient) }
+ let stopped = try stopClient(app) { report(.stoppingClient) }
+ try modifications.prepare()
report(.replacing)
try replace(app, with: staged)
- report(.clearingInsert)
- let clearedInner = try clearInsert(at: innerPlist)
-
- report(.removingUpdateBlock)
- let removed = try UpdateBlock.remove(from: updateBlocks)
-
- report(.registering)
- SteamBundle.register(app)
-
try verifyValveSignature(app)
let plist = app.appending(path: "Contents/Info.plist")
if let insert = SteamBundle.currentInsert(at: plist), !insert.isEmpty {
@@ -89,6 +86,17 @@ enum SteamRepair {
)
}
+ _ = try modifications.retireIfClean(app)
+
+ report(.clearingInsert)
+ let clearedInner = try clearInsert(at: innerPlist)
+
+ report(.removingUpdateBlock)
+ let removed = try UpdateBlock.remove(from: updateBlocks)
+
+ report(.registering)
+ register(app)
+
let removedBackup = try removeStaleBackup(from: backups)
report(.finished)
@@ -178,6 +186,20 @@ enum SteamRepair {
static func replace(_ app: URL, with staged: URL) throws {
let files = FileManager.default
try WriteRefused.catching(app) {
+ var staged = staged
+ let folder = app.deletingLastPathComponent()
+ if volume(of: staged) != volume(of: folder) {
+ let copy = folder.appending(path: ".\(app.lastPathComponent).\(UUID().uuidString)")
+ do {
+ try files.copyItem(at: staged, to: copy)
+ } catch {
+ try? files.removeItem(at: copy)
+ throw error
+ }
+ staged = copy
+ }
+ defer { try? files.removeItem(at: staged) }
+
guard files.fileExists(atPath: app.path(percentEncoded: false)) else {
try files.moveItem(at: staged, to: app)
return
@@ -186,6 +208,10 @@ enum SteamRepair {
}
}
+ private static func volume(of url: URL) -> URL? {
+ try? url.resourceValues(forKeys: [.volumeURLKey]).volume
+ }
+
static func clearInsert(at plist: URL) throws -> Bool {
guard var dict = SteamBundle.readInfoPlist(at: plist),
var environment = dict[SteamBundle.environmentKey] as? [String: Any]
diff --git a/app/Sources/NotProtonApp/Model/Uninstall.swift b/app/Sources/NotProtonApp/Model/Uninstall.swift
index a337a80..d84c0ef 100644
--- a/app/Sources/NotProtonApp/Model/Uninstall.swift
+++ b/app/Sources/NotProtonApp/Model/Uninstall.swift
@@ -1,5 +1,3 @@
-// Self-explanatory I think
-
import Foundation
enum UninstallPhase: Sendable {
@@ -26,16 +24,34 @@ struct UninstallOutcome: Sendable {
let steamInstalled: Bool
let restoredValveSignature: Bool
let removed: [String]
+ var unreachableSteam: [URL] = []
var steamNeedsRedownload: Bool { steamInstalled && !restoredValveSignature }
+
+ var partialRemoval: String? {
+ guard !unreachableSteam.isEmpty else { return nil }
+ return unreachableSteam.map {
+ String(localized: "NotProton has been partially removed, because Steam at \($0.path(percentEncoded: false)) cannot be found. Delete that copy of Steam and reinstall it to fully remove NotProton.")
+ }.joined(separator: "\n\n")
+ }
}
enum Uninstall {
static let step = String(localized: "Remove NotProton")
- typealias Repair = @Sendable (@escaping @Sendable (RepairPhase) -> Void) async throws -> Void
+ static func confirmation(modifications: SteamModifications = .shared) -> String {
+ let missing = ((try? modifications.paths()) ?? []).filter { SupportPaths.Steam.isUnreachable($0) }
+ guard !missing.isEmpty else {
+ return String(localized: "Steam is restored to its unmodified state and NotProton is removed, including the compatibility tool that lives inside the Steam folder. Windows games and Steam Play prefixes are not removed.")
+ }
+ return missing.map {
+ String(localized: "Steam at \($0.path(percentEncoded: false)) isn't connected, so NotProton can't be removed from it. All other NotProton data is removed, except for Windows Games and prefixes.")
+ }.joined(separator: "\n\n")
+ }
+
+ typealias Repair = @Sendable (URL, @escaping @Sendable (RepairPhase) -> Void) async throws -> Void
- typealias Stop = @Sendable (@Sendable () -> Void) throws -> Bool
+ typealias Stop = @Sendable (URL, @Sendable () -> Void) throws -> Bool
static func run(
app: URL = SupportPaths.Steam.app,
@@ -48,25 +64,80 @@ enum Uninstall {
SupportPaths.packageDownloads.deletingLastPathComponent(),
],
libraries: [SteamLibrary] = PrefixStore.libraries(),
+ modifications: SteamModifications = .shared,
+ lockFolder: URL = SupportPaths.applicationSupport,
report: @escaping @Sendable (UninstallPhase) -> Void = { _ in },
- repair: Repair = { report in _ = try await SteamRepair.run(report: report) },
- stop: Stop = { onStopping in try SteamBundle.stopClient(step: step, onStopping: onStopping) }
+ repair: Repair? = nil,
+ stop: Stop = { app, onStopping in try SteamBundle.stopClient(app: app, step: step, onStopping: onStopping) }
) async throws -> UninstallOutcome {
- let stopped = try stop { report(.stoppingClient) }
-
- report(.detaching)
- let detached = try detach(from: app, innerPlist: innerPlist, updateBlocks: updateBlocks)
-
- // Validate if Steam is present before restoring
- let steamInstalled = FileManager.default.fileExists(atPath: app.path(percentEncoded: false))
- var restored = false
- if steamInstalled {
+ let lock = try DeploymentContent.acquireInstallationLock(in: lockFolder, steamFolder: nil)
+ defer { lock.release() }
+ 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] = []
+ var failures: [any Error] = []
+
+ for target in targets {
do {
- try await repair { report(.restoring($0)) }
- restored = true
- } catch {}
+ let bundleLock = try DeploymentContent.acquireSteamLock(for: target, holding: lock)
+ defer { bundleLock.release() }
+ switch try SteamModifications.inspect(target) {
+ case .unreachable:
+ if tracked.contains(target) { missing.append(target) }
+ continue
+ case .absent, .clean:
+ if tracked.contains(target), try !modifications.retireIfClean(target) {
+ throw StepFailure(step: step, detail: String(localized: "Steam could not be fully restored. Please run Repair Steam again."))
+ }
+ continue
+ case .modified: break
+ }
+ try modifications.mark(target)
+ stopped = try stop(target) { report(.stoppingClient) } || stopped
+ checkedClient = true
+ report(.detaching)
+ detached = try detach(from: target, innerPlist: innerPlist, updateBlocks: updateBlocks) || detached
+ steamInstalled = true
+ do {
+ if let repair {
+ try await repair(target) { report(.restoring($0)) }
+ } else {
+ _ = try await SteamRepair.run(app: target, innerPlist: innerPlist,
+ updateBlocks: updateBlocks, modifications: modifications,
+ report: { report(.restoring($0)) })
+ }
+ } catch { restored = false }
+ guard try modifications.retireIfClean(target) else {
+ throw StepFailure(step: step, detail: String(localized: "Steam could not be fully restored. Please run Repair Steam again."))
+ }
+ } catch {
+ if let refusal = error as? WriteRefused {
+ failures.append(refusal)
+ } else {
+ failures.append(StepFailure(step: step,
+ detail: "\(target.path(percentEncoded: false)): \(error.localizedDescription)"))
+ }
+ }
}
+ if failures.count == 1 { throw failures[0] }
+ if !failures.isEmpty {
+ throw StepFailure(step: step, detail: failures.map(\.localizedDescription).joined(separator: "\n"))
+ }
+ if !checkedClient {
+ let bundleLock = try DeploymentContent.acquireSteamLock(for: app, holding: lock)
+ defer { bundleLock.release() }
+ stopped = try stop(app) { report(.stoppingClient) }
+ }
+ _ = try SteamRepair.clearInsert(at: innerPlist)
+ _ = try UpdateBlock.remove(from: updateBlocks)
report(.removing)
var removed = try remove(
legacyCompat: legacyCompat, compatTools: compatTools, directories: directories
@@ -77,14 +148,14 @@ enum Uninstall {
if !templateFailures.isEmpty {
throw StepFailure(step: step, detail: templateFailures.map(\.detail).joined(separator: "\n"))
}
-
report(.finished)
return UninstallOutcome(
stoppedClient: stopped,
detached: detached,
steamInstalled: steamInstalled,
restoredValveSignature: restored,
- removed: removed
+ removed: removed,
+ unreachableSteam: missing
)
}
diff --git a/app/Sources/NotProtonApp/Resources/Localization/Localizable.xcstrings b/app/Sources/NotProtonApp/Resources/Localization/Localizable.xcstrings
index 5cf3349..65cc179 100644
--- a/app/Sources/NotProtonApp/Resources/Localization/Localizable.xcstrings
+++ b/app/Sources/NotProtonApp/Resources/Localization/Localizable.xcstrings
@@ -201,6 +201,16 @@
}
}
},
+ "%@ is not Steam." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 不是 Steam。"
+ }
+ }
+ }
+ },
"%@ is not a Windows program. Pick an exe, msi, bat or cmd file." : {
"localizations" : {
"zh-Hans" : {
@@ -1062,6 +1072,16 @@
}
}
},
+ "Choose" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "选择"
+ }
+ }
+ }
+ },
"Choose a Windows program to run in %@." : {
"localizations" : {
"zh-Hans" : {
@@ -1072,6 +1092,16 @@
}
}
},
+ "Choose…" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "选择…"
+ }
+ }
+ }
+ },
"Cleaning up" : {
"localizations" : {
"zh-Hans" : {
@@ -1735,6 +1765,16 @@
}
}
},
+ "If NotProton is installed there, it will stay installed. Continue anyway?" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "如果 NotProton 安装在那里,它将保持安装状态。仍要继续吗?"
+ }
+ }
+ }
+ },
"Install" : {
"localizations" : {
"zh-Hans" : {
@@ -1975,6 +2015,16 @@
}
}
},
+ "Location" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "位置"
+ }
+ }
+ }
+ },
"Looking for backups" : {
"localizations" : {
"zh-Hans" : {
@@ -2188,6 +2238,16 @@
}
}
},
+ "NotProton cannot use Steam from a folder with a colon in its name." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "NotProton 无法使用名称中含有冒号的文件夹中的 Steam。"
+ }
+ }
+ }
+ },
"NotProton carries no components." : {
"localizations" : {
"zh-Hans" : {
@@ -2228,6 +2288,16 @@
}
}
},
+ "NotProton has been partially removed, because Steam at %@ cannot be found. Delete that copy of Steam and reinstall it to fully remove NotProton." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "NotProton 仅被部分移除,因为找不到位于 %@ 的 Steam。请删除该 Steam 并重新安装,以完全移除 NotProton。"
+ }
+ }
+ }
+ },
"NotProton has been removed." : {
"localizations" : {
"zh-Hans" : {
@@ -2248,6 +2318,16 @@
}
}
},
+ "NotProton is installed in %@. Use Repair Steam to remove it before choosing another copy of Steam." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "NotProton 已安装在 %@ 中。请先使用“修复 Steam”将其移除,再选择另一份 Steam。"
+ }
+ }
+ }
+ },
"NotProton needs the App Management permission." : {
"localizations" : {
"zh-Hans" : {
@@ -2988,6 +3068,16 @@
}
}
},
+ "Select your copy of Steam." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "请选择你的 Steam 应用。"
+ }
+ }
+ }
+ },
"Set Up" : {
"localizations" : {
"zh-Hans" : {
@@ -3141,6 +3231,26 @@
"Steam" : {
"shouldTranslate" : false
},
+ "Steam at %@ isn't connected, so NotProton can't be removed from it. All other NotProton data is removed, except for Windows Games and prefixes." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "位于 %@ 的 Steam 未连接,因此无法从中移除 NotProton。其他所有 NotProton 数据都会被移除,但 Windows 游戏及游戏容器除外。"
+ }
+ }
+ }
+ },
+ "Steam at %@ isn't connected." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "位于 %@ 的 Steam 未连接。"
+ }
+ }
+ }
+ },
"Steam client updates are allowed." : {
"localizations" : {
"zh-Hans" : {
@@ -3841,6 +3951,16 @@
}
}
},
+ "Use a copy of Steam from another folder or drive." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "使用其他文件夹或磁盘中的 Steam。"
+ }
+ }
+ }
+ },
"Use the newer NotProton app to update or repair the installed files." : {
"localizations" : {
"zh-Hans" : {
diff --git a/app/Sources/NotProtonApp/Support/RemoveEverythingCommand.swift b/app/Sources/NotProtonApp/Support/RemoveEverythingCommand.swift
index 3bb21cf..534c34c 100644
--- a/app/Sources/NotProtonApp/Support/RemoveEverythingCommand.swift
+++ b/app/Sources/NotProtonApp/Support/RemoveEverythingCommand.swift
@@ -8,22 +8,22 @@ enum RemoveEverythingCommand {
dispatchMain()
}
- private static func perform() async -> Int32 {
+ static func perform(remove: @Sendable (@escaping @Sendable (UninstallPhase) -> Void) async throws -> UninstallOutcome = {
+ try await Uninstall.run(report: $0)
+ }) async -> Int32 {
do {
- let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)
- defer { FileLock.release(lock) }
let output = Output()
- let result = try await Uninstall.run { phase in
+ let result = try await remove { phase in
if case .restoring(.finished) = phase { return }
output.say(phase.label)
}
output.say(
- result.steamNeedsRedownload
+ result.partialRemoval ?? (result.steamNeedsRedownload
? "NotProton has been removed. Steam could not be restored. "
+ "Reinstall Steam from steampowered.com before using it again."
- : "NotProton has been removed."
+ : "NotProton has been removed.")
)
- return 0
+ return result.partialRemoval == nil ? 0 : 1
} catch {
FileHandle.standardError.write(Data("\(failureMessage(error))\n".utf8))
return 1
diff --git a/app/Sources/NotProtonApp/Support/SupportPaths.swift b/app/Sources/NotProtonApp/Support/SupportPaths.swift
index 32d253f..512eccd 100644
--- a/app/Sources/NotProtonApp/Support/SupportPaths.swift
+++ b/app/Sources/NotProtonApp/Support/SupportPaths.swift
@@ -71,7 +71,15 @@ enum SupportPaths {
static let bridgeCacheFolder = "bridge"
enum Steam {
- static var app: URL { URL(filePath: "/Applications/Steam.app") }
+ static let defaultApp = URL(filePath: "/Applications/Steam.app")
+ static let appPathKey = "steamAppPath"
+
+ static var app: URL {
+ UserDefaults.standard.string(forKey: appPathKey).map { URL(filePath: $0) } ?? defaultApp
+ }
+ static func isUnreachable(_ bundle: URL = app) -> Bool {
+ !FileManager.default.fileExists(atPath: bundle.deletingLastPathComponent().path(percentEncoded: false))
+ }
static var infoPlist: URL { infoPlist(inBundle: app) }
static var executable: URL { app.appending(path: "Contents/MacOS/steam_osx") }
static var deployedDylib: URL { deployedDylib(inBundle: app) }
diff --git a/app/Sources/NotProtonApp/SystemStatus.swift b/app/Sources/NotProtonApp/SystemStatus.swift
index f15e27c..d593318 100644
--- a/app/Sources/NotProtonApp/SystemStatus.swift
+++ b/app/Sources/NotProtonApp/SystemStatus.swift
@@ -241,8 +241,8 @@ final class SystemStatus {
guard let build = pendingRemoval else { return }
pendingRemoval = nil
await perform(from: RunnerInstaller.removeStep) { _ in
- let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)
- defer { FileLock.release(lock) }
+ let lock = try DeploymentContent.acquireInstallationLock()
+ defer { lock.release() }
try await requireUnblockedContent()
let changed = try await Task.detached(priority: .userInitiated) {
try RunnerInstaller.removeClone(forBuild: build)
@@ -284,6 +284,75 @@ final class SystemStatus {
await refresh()
}
+ func chooseSteam() async {
+ let current = SupportPaths.Steam.app
+ let panel = NSOpenPanel()
+ panel.canChooseFiles = true
+ panel.canChooseDirectories = false
+ panel.allowsMultipleSelection = false
+ panel.allowedContentTypes = [.application]
+ panel.prompt = String(localized: "Choose")
+ panel.message = String(localized: "Select your copy of Steam.")
+ panel.directoryURL = current.deletingLastPathComponent()
+
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+ let picked = URL(filePath: url.path)
+
+ clearFailure()
+ outcome = nil
+
+ func same(_ a: URL, _ b: URL) -> Bool {
+ a.standardizedFileURL.path(percentEncoded: false) == b.standardizedFileURL.path(percentEncoded: false)
+ }
+ guard !same(picked, current) else { return }
+ if SupportPaths.Steam.isUnreachable(current) {
+ let alert = NSAlert()
+ alert.messageText = String(localized: "Steam at \(current.path(percentEncoded: false)) isn't connected.")
+ alert.informativeText = String(localized: "If NotProton is installed there, it will stay installed. Continue anyway?")
+ alert.addButton(withTitle: String(localized: "Continue Anyway"))
+ alert.addButton(withTitle: String(localized: "Cancel"))
+ guard alert.runModal() == .alertFirstButtonReturn else { return }
+ }
+ let lock: DeploymentContent.InstallationLock
+ do {
+ lock = try DeploymentContent.acquireInstallationLock()
+ } catch {
+ setFailure(error)
+ return
+ }
+ if let refusal = Self.steamChoiceRefusal(picked, current: current) {
+ lock.release()
+ setFailure(refusal)
+ AppLog.note("steam choice refused: \(picked.path(percentEncoded: false))")
+ return
+ }
+
+ if same(picked, SupportPaths.Steam.defaultApp) {
+ UserDefaults.standard.removeObject(forKey: SupportPaths.Steam.appPathKey)
+ } else {
+ UserDefaults.standard.set(picked.path(percentEncoded: false), forKey: SupportPaths.Steam.appPathKey)
+ }
+ lock.release()
+ AppLog.note("steam chosen: \(picked.path(percentEncoded: false))")
+ await refresh()
+ }
+
+ static func steamChoiceRefusal(
+ _ picked: URL, current: URL, insert: String? = SteamBundle.currentInsert()
+ ) -> String? {
+ guard Bundle(url: picked)?.bundleIdentifier == SteamRepair.valveIdentifier else {
+ return String(localized: "\(picked.lastPathComponent) is not Steam.")
+ }
+ guard !picked.path(percentEncoded: false).contains(":") else {
+ return String(localized: "NotProton cannot use Steam from a folder with a colon in its name.")
+ }
+ let deployed = SupportPaths.Steam.deployedDylib(inBundle: current).path(percentEncoded: false)
+ if let insert, insert.split(separator: ":").contains(Substring(deployed)) {
+ return String(localized: "NotProton is installed in \(current.path(percentEncoded: false)). Use Repair Steam to remove it before choosing another copy of Steam.")
+ }
+ return nil
+ }
+
private func highlight(_ row: CrossOverRow) {
AccessibilityNotification.Announcement(String(localized: "\(row.title) is already listed.")).post()
highlightReset?.cancel()
@@ -348,8 +417,8 @@ final class SystemStatus {
}
await perform(from: RunnerSetup.Phase.cloning.label) { progress in
- let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)
- defer { FileLock.release(lock) }
+ let lock = try DeploymentContent.acquireInstallationLock()
+ defer { lock.release() }
try await requireInstallableContent()
let result = try await Task.detached(priority: .userInitiated) {
try RunnerSetup.run(from: install, replacingExisting: replacingExisting) {
@@ -364,8 +433,8 @@ final class SystemStatus {
func fetchValveBinaries() async {
guard canInstall else { return }
await perform(from: ValveFetcher.Phase.verifying.label) { progress in
- let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)
- defer { FileLock.release(lock) }
+ let lock = try DeploymentContent.acquireInstallationLock()
+ defer { lock.release() }
try await requireInstallableContent()
let result = try await ValveFetcher.run { progress($0.label) }
return result.wroteNothing ? nil : String(localized: "Downloaded missing components.")
@@ -403,8 +472,8 @@ final class SystemStatus {
func installIntoSteam() async {
await perform(from: InstallPhase.checkingPayload.label) { progress in
- let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)
- defer { FileLock.release(lock) }
+ let lock = try DeploymentContent.acquireInstallationLock()
+ defer { lock.release() }
let result = try await Task.detached(priority: .userInitiated) {
try SteamInstaller.run(holdingInstallationLock: true, report: { progress($0.label) })
}.value
@@ -463,9 +532,9 @@ final class SystemStatus {
func repairSteam() async {
await perform(from: RepairPhase.checking.label) { progress in
- let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)
- defer { FileLock.release(lock) }
- let result = try await SteamRepair.run { progress($0.label) }
+ let lock = try DeploymentContent.acquireInstallationLock()
+ defer { lock.release() }
+ let result = try await SteamRepair.run(report: { progress($0.label) })
var parts = [String(localized: "Steam restored to its original state.")]
if result.stoppedClient { parts.append(Self.restartHint) }
@@ -490,10 +559,9 @@ final class SystemStatus {
func removeEverything() async {
await perform(from: UninstallPhase.stoppingClient.label) { progress in
- let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)
- defer { FileLock.release(lock) }
let result = try await Uninstall.run { progress($0.label) }
+ if let partial = result.partialRemoval { return partial }
return result.steamNeedsRedownload
? String(localized: "NotProton has been removed. Steam could not be restored. Reinstall Steam from steampowered.com before using it again.")
: String(localized: "NotProton has been removed.")
@@ -524,9 +592,9 @@ final class SystemStatus {
) async {
let known = runnerSizes
let measured = await Task.detached(priority: .utility) {
- if cleanTemplates, let lock = try? DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app) {
+ if cleanTemplates, let lock = try? DeploymentContent.acquireInstallationLock() {
RunnerInstaller.removeLeftoverRemovals(runners: runners)
- FileLock.release(lock)
+ lock.release()
}
let failures = cleanTemplates
? RunnerInstaller.removeStalePrefixTemplates(runners: runners, libraries: libraries, reportBusy: false) : []
diff --git a/app/Sources/NotProtonApp/Views/StatusView.swift b/app/Sources/NotProtonApp/Views/StatusView.swift
index 51dcac6..6551c60 100644
--- a/app/Sources/NotProtonApp/Views/StatusView.swift
+++ b/app/Sources/NotProtonApp/Views/StatusView.swift
@@ -232,9 +232,7 @@ struct StatusView: View {
}
Button("Cancel", role: .cancel) {}
} message: {
- Text(
- String(localized: "Steam is restored to its unmodified state and NotProton is removed, including the compatibility tool that lives inside the Steam folder. Windows games and Steam Play prefixes are not removed.")
- )
+ Text(Uninstall.confirmation())
}
.confirmationDialog(
CrossOverLicense.notActivatedTitle,
@@ -315,6 +313,15 @@ struct StatusView: View {
}
Section("Steam") {
+ StatusRow(
+ title: String(localized: "Location"),
+ value: SupportPaths.Steam.app.path(percentEncoded: false),
+ action: StatusAction(
+ label: String(localized: "Choose\u{2026}"),
+ help: String(localized: "Use a copy of Steam from another folder or drive."),
+ isEnabled: status.isIdle
+ ) { Task { await status.chooseSteam() } }
+ )
steamRow(snapshot.steam, payload: snapshot.payload)
if snapshot.steamRunning {
StatusRow(
diff --git a/app/Tests/NotProtonAppTests/DeploymentContentTests.swift b/app/Tests/NotProtonAppTests/DeploymentContentTests.swift
index eba51fc..ebf7873 100644
--- a/app/Tests/NotProtonAppTests/DeploymentContentTests.swift
+++ b/app/Tests/NotProtonAppTests/DeploymentContentTests.swift
@@ -178,19 +178,54 @@ struct DeploymentContentTests {
func installationLock() throws {
let root = try scratchDirectory("content-lock")
defer { try? FileManager.default.removeItem(at: root) }
- let app = root.appending(path: "Steam.app")
do {
- let fd = try DeploymentContent.acquireInstallationLock(for: app)
- defer { FileLock.release(fd) }
- #expect(throws: StepFailure.self) { try DeploymentContent.acquireInstallationLock(for: app) }
+ let lock = try DeploymentContent.acquireInstallationLock(in: root, steamFolder: nil)
+ defer { lock.release() }
+ #expect(throws: StepFailure.self) { try DeploymentContent.acquireInstallationLock(in: root, steamFolder: nil) }
let status = try Shell.run("/bin/sh", ["-c", #"exec 9< "$1"; /usr/bin/lockf -s -t 0 9"#, "fixture", root.path]).status
#expect(status == 75)
}
- let next = try DeploymentContent.acquireInstallationLock(for: app)
- FileLock.release(next)
+ let next = try DeploymentContent.acquireInstallationLock(in: root, steamFolder: nil)
+ next.release()
#expect(try FileManager.default.contentsOfDirectory(atPath: root.path).isEmpty)
}
+ @Test("Steam's folder is locked too, so another account on the Mac is kept out")
+ func installationLockCoversSteam() throws {
+ let root = try scratchDirectory("content-lock-steam")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let mine = root.appending(path: "mine"), theirs = root.appending(path: "theirs"), steam = root.appending(path: "Applications")
+ for folder in [mine, theirs, steam] { try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) }
+
+ let lock = try DeploymentContent.acquireInstallationLock(in: mine, steamFolder: steam)
+ #expect(throws: StepFailure.self) { try DeploymentContent.acquireInstallationLock(in: theirs, steamFolder: steam) }
+ lock.release()
+
+ let after = try DeploymentContent.acquireInstallationLock(in: theirs, steamFolder: steam)
+ after.release()
+ }
+
+ @Test("Steam in the same folder as our own lock, directly or through a symlink, is not locked twice")
+ func installationLockSharesAFolder() throws {
+ let root = try scratchDirectory("content-lock-shared")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let link = root.appending(path: "link")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: root)
+
+ try DeploymentContent.acquireInstallationLock(in: root, steamFolder: root).release()
+ try DeploymentContent.acquireInstallationLock(in: root, steamFolder: link).release()
+ }
+
+ @Test("An unplugged Steam drive does not stop the lock from being taken")
+ func installationLockSkipsMissingSteam() throws {
+ let root = try scratchDirectory("content-lock-unplugged")
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let lock = try DeploymentContent.acquireInstallationLock(in: root, steamFolder: URL(filePath: "/Volumes/np-missing-\(UUID().uuidString)"))
+ defer { lock.release() }
+ #expect(throws: StepFailure.self) { try DeploymentContent.acquireInstallationLock(in: root, steamFolder: nil) }
+ }
+
@Test("Missing and changed tool lists are included in the expected installed content")
func includesToolList() throws {
let root = try scratchDirectory("content-tools")
diff --git a/app/Tests/NotProtonAppTests/SteamBundleTests.swift b/app/Tests/NotProtonAppTests/SteamBundleTests.swift
index ae4f95b..36273fc 100644
--- a/app/Tests/NotProtonAppTests/SteamBundleTests.swift
+++ b/app/Tests/NotProtonAppTests/SteamBundleTests.swift
@@ -15,9 +15,9 @@ struct SteamBundleTests {
)
#expect(patterns.count == 2)
- #expect(patterns.contains("/Applications/Steam.app/"))
+ #expect(patterns.contains(#"/Applications/Steam\.app/"#))
#expect(
- patterns.contains { $0.hasSuffix("/Steam.AppBundle/Steam/") },
+ patterns.contains { $0.hasSuffix(#"/Steam\.AppBundle/Steam/"#) },
"the inner bundle, where ipcserver and the helpers actually run, is not swept"
)
}
@@ -31,13 +31,19 @@ struct SteamBundleTests {
)
#expect(patterns.allSatisfy { $0.hasSuffix("/") })
- #expect(patterns == ["/tmp/Some.app/", "/tmp/Inner/"])
+ #expect(patterns == [#"/tmp/Some\.app/"#, "/tmp/Inner/"])
}
@Test("Sweeping nothing is possible, so a test can stop short of killing helpers")
func helpersCanBeEmpty() {
let patterns = SteamBundle.sweepPatterns(app: URL(filePath: "/tmp/A.app"), helpers: [])
- #expect(patterns == ["/tmp/A.app/"])
+ #expect(patterns == [#"/tmp/A\.app/"#])
+ }
+
+ @Test("pkill gets the path with regular expression characters escaped")
+ func patternsAreEscaped() {
+ let patterns = SteamBundle.sweepPatterns(app: URL(filePath: "/Volumes/Games (SSD)+/Steam.app"), helpers: [])
+ #expect(patterns == [#"/Volumes/Games \(SSD\)\+/Steam\.app/"#])
}
private enum Insert {
diff --git a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift b/app/Tests/NotProtonAppTests/SteamInstallerTests.swift
index 397d5b4..0674056 100644
--- a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift
+++ b/app/Tests/NotProtonAppTests/SteamInstallerTests.swift
@@ -14,7 +14,7 @@ struct SteamInstallerTests {
return try await SteamRepair.stage(
bundle,
bases: manifest.bases,
- downloads: SupportPaths.packageDownloads,
+ downloads: try isolatedValveDownloads(in: work),
work: work.appending(path: "staging")
)
}
@@ -71,6 +71,10 @@ struct SteamInstallerTests {
var deployedVersion: URL { support.appending(path: "dylib.version") }
var backups: URL { support.appending(path: "backups") }
var bridge: URL { support.appending(path: "bridge") }
+ var modifications: SteamModifications {
+ SteamModifications(file: work.appending(path: "steam-bundles.json"),
+ legacyRecord: DeploymentContent.record(beside: deployedVersion))
+ }
}
private func fixture(into work: URL) async throws -> Fixture {
@@ -115,6 +119,8 @@ struct SteamInstallerTests {
deployedVersion: fixture.deployedVersion,
backups: fixture.backups,
compatTools: fixture.work.appending(path: "compatibilitytools.d"),
+ lockFolder: fixture.work,
+ modifications: fixture.modifications,
runnerIsRunning: { _ in running },
verifyRunner: verifyRunner,
patchRunner: { _, _, _ in },
@@ -494,6 +500,41 @@ struct SteamInstallerTests {
#expect(build.builtAt == 100)
#expect(build.version == "9.9.9-test")
#expect(build.dylibHashes == (try MachOBuild.hashesIgnoringSignature(of: fixture.payload.dylib)))
+ #expect(try fixture.modifications.paths().map(\.path) == [fixture.app.standardizedFileURL.path])
+ }
+
+ @Test("A failed install records the bundle before copying its dylib")
+ func tracksFailedInstallation() async throws {
+ let work = try scratchDirectory("install-failure-record")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+ try FileManager.default.createDirectory(at: fixture.support, withIntermediateDirectories: true)
+ try Data("blocked".utf8).write(to: fixture.support.appending(path: "signatures"))
+
+ #expect(throws: (any Error).self) { try install(fixture) }
+
+ #expect(FileManager.default.fileExists(atPath: fixture.deployedDylib.path))
+ #expect(try fixture.modifications.paths().map(\.path) == [fixture.app.standardizedFileURL.path])
+ #expect(try DeploymentContent.readBuild(at: DeploymentContent.record(beside: fixture.deployedVersion)) == nil)
+ }
+
+ @Test("Installing another Steam preserves the disconnected installation")
+ func tracksBothInstallations() async throws {
+ let work = try scratchDirectory("install-two-bundles")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let first = try await fixture(into: work)
+ let other = work.appending(path: "other/Steam.app")
+ try FileManager.default.createDirectory(at: other.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: first.app, to: other)
+ let second = Fixture(work: work, app: other, payload: first.payload, support: first.support)
+ _ = try install(first)
+ try FileManager.default.moveItem(at: first.app.deletingLastPathComponent(), to: work.appending(path: "disconnected"))
+
+ _ = try install(second)
+
+ let recorded = Set(try first.modifications.paths().map(\.path))
+ let expected = Set([first.app.standardizedFileURL.path, second.app.standardizedFileURL.path])
+ #expect(recorded == expected)
}
@Test("An older package is refused before any installed files change")
diff --git a/app/Tests/NotProtonAppTests/SteamRepairTests.swift b/app/Tests/NotProtonAppTests/SteamRepairTests.swift
index 4b8f73b..a6a6d26 100644
--- a/app/Tests/NotProtonAppTests/SteamRepairTests.swift
+++ b/app/Tests/NotProtonAppTests/SteamRepairTests.swift
@@ -14,7 +14,7 @@ struct SteamRepairTests {
return try await SteamRepair.stage(
bundle,
bases: manifest.bases,
- downloads: SupportPaths.packageDownloads,
+ downloads: try isolatedValveDownloads(in: work),
work: work.appending(path: "staging")
)
}
@@ -134,6 +134,39 @@ struct SteamRepairTests {
}
}
+ @Test("A repaired Steam is not outstanding after its drive disconnects")
+ func retiresRepairedSteamBeforeDisconnect() async throws {
+ let work = try scratchDirectory("repair-tracking")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let stock = try await stagedStockBundle(into: work)
+ let drive = work.appending(path: "external")
+ let app = drive.appending(path: "Steam.app")
+ let support = work.appending(path: "support")
+ let modifications = SteamModifications(file: work.appending(path: "steam-bundles.json"),
+ legacyRecord: support.appending(path: "install-build.json"))
+ try FileManager.default.createDirectory(at: drive, withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: stock, to: app)
+ try Data("patched".utf8).write(to: SupportPaths.Steam.deployedDylib(inBundle: app))
+ try modifications.mark(app)
+
+ _ = 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 })
+
+ #expect(try modifications.paths().isEmpty)
+ try FileManager.default.moveItem(at: drive, to: work.appending(path: "disconnected"))
+ let result = try await Uninstall.run(
+ app: app, innerPlist: work.appending(path: "inner.plist"), updateBlocks: [],
+ legacyCompat: work.appending(path: "legacycompat"), compatTools: [],
+ directories: [support], libraries: [], modifications: modifications, lockFolder: work,
+ repair: { _, _ in Issue.record("A disconnected repaired copy needs no repair") },
+ stop: { _, _ in false })
+
+ #expect(result.partialRemoval == nil)
+ #expect(!result.steamNeedsRedownload)
+ }
+
// MARK: - The inner plist
@Test("Clearing the insert removes the keys NotProton added and nothing else")
diff --git a/app/Tests/NotProtonAppTests/SystemStatusTests.swift b/app/Tests/NotProtonAppTests/SystemStatusTests.swift
index ac17809..01429b9 100644
--- a/app/Tests/NotProtonAppTests/SystemStatusTests.swift
+++ b/app/Tests/NotProtonAppTests/SystemStatusTests.swift
@@ -557,3 +557,54 @@ struct PerformTests {
#expect(busyDuringRefresh == true)
}
}
+
+@MainActor
+@Suite("Choosing where Steam is")
+struct SteamChoiceTests {
+
+ private func bundle(_ name: String, identifier: String, in root: URL) throws -> URL {
+ let app = root.appending(path: name)
+ try FileManager.default.createDirectory(at: app.appending(path: "Contents"), withIntermediateDirectories: true)
+ try SteamBundle.writeInfoPlist(["CFBundleIdentifier": identifier], at: app.appending(path: "Contents/Info.plist"))
+ return app
+ }
+
+ @Test("Another copy of Steam is accepted while the current one is not patched")
+ func acceptsSteam() throws {
+ let root = try scratchDirectory("steam-choice")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let picked = try bundle("Steam.app", identifier: SteamRepair.valveIdentifier, in: root)
+
+ #expect(SystemStatus.steamChoiceRefusal(picked, current: SupportPaths.Steam.defaultApp, insert: nil) == nil)
+ }
+
+ @Test("An app that is not Steam is refused")
+ func refusesOtherApps() throws {
+ let root = try scratchDirectory("steam-choice")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let picked = try bundle("CrossOver.app", identifier: "com.codeweavers.CrossOver", in: root)
+
+ #expect(SystemStatus.steamChoiceRefusal(picked, current: SupportPaths.Steam.defaultApp, insert: nil) != nil)
+ }
+
+ @Test("A path with a colon is refused, since it would split DYLD_INSERT_LIBRARIES")
+ func refusesColons() throws {
+ let root = try scratchDirectory("steam-choice")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let picked = try bundle("a:b/Steam.app", identifier: SteamRepair.valveIdentifier, in: root)
+
+ #expect(SystemStatus.steamChoiceRefusal(picked, current: SupportPaths.Steam.defaultApp, insert: nil) != nil)
+ }
+
+ @Test("Switching is refused while NotProton is installed in the current copy")
+ func refusesWhilePatched() throws {
+ let root = try scratchDirectory("steam-choice")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let picked = try bundle("Steam.app", identifier: SteamRepair.valveIdentifier, in: root)
+ let current = URL(filePath: "/Applications/Steam.app")
+ let insert = "/other.dylib:" + SupportPaths.Steam.deployedDylib(inBundle: current).path(percentEncoded: false)
+
+ #expect(SystemStatus.steamChoiceRefusal(picked, current: current, insert: insert) != nil)
+ #expect(SystemStatus.steamChoiceRefusal(picked, current: current, insert: "/other.dylib") == nil)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/TestSupport.swift b/app/Tests/NotProtonAppTests/TestSupport.swift
index 5013430..de6f427 100644
--- a/app/Tests/NotProtonAppTests/TestSupport.swift
+++ b/app/Tests/NotProtonAppTests/TestSupport.swift
@@ -1,7 +1,23 @@
import Foundation
+@testable import NotProtonApp
+
func scratchDirectory(_ label: String) throws -> URL {
let url = URL.temporaryDirectory.appending(path: "np-\(label)-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
+
+func isolatedValveDownloads(in work: URL) throws -> URL {
+ let downloads = work.appending(path: "downloads")
+ try FileManager.default.createDirectory(at: downloads, withIntermediateDirectories: true)
+ if let bundle = try ValvePackageManifest.bundled().bundle {
+ let cached = SupportPaths.packageDownloads.appending(path: bundle.file)
+ let destination = downloads.appending(path: bundle.file)
+ if FileManager.default.fileExists(atPath: cached.path),
+ !FileManager.default.fileExists(atPath: destination.path) {
+ try FileManager.default.copyItem(at: cached, to: destination)
+ }
+ }
+ return downloads
+}
diff --git a/app/Tests/NotProtonAppTests/UninstallTests.swift b/app/Tests/NotProtonAppTests/UninstallTests.swift
index bef984b..ac05e7a 100644
--- a/app/Tests/NotProtonAppTests/UninstallTests.swift
+++ b/app/Tests/NotProtonAppTests/UninstallTests.swift
@@ -41,9 +41,13 @@ struct UninstallTests {
var outerPlist: URL { app.appending(path: "Contents/Info.plist") }
var dylib: URL { app.appending(path: "Contents/MacOS/\(SupportPaths.dylibName)") }
+ var modifications: SteamModifications {
+ SteamModifications(file: root.appending(path: "steam-bundles.json"),
+ legacyRecord: support.appending(path: "install-build.json"))
+ }
}
- private func layout(signable: Bool = false) throws -> Layout {
+ private func layout(signable: Bool = true) throws -> Layout {
let files = FileManager.default
let root = URL.temporaryDirectory.appending(path: "np-uninstall-\(UUID().uuidString)")
let app = root.appending(path: "Steam.app")
@@ -216,8 +220,9 @@ struct UninstallTests {
compatTools: layout.compatTools,
directories: [layout.support, layout.caches],
libraries: [],
- repair: { _ in throw Offline() },
- stop: { _ in false }
+ modifications: layout.modifications, lockFolder: layout.root,
+ repair: { _, _ in throw Offline() },
+ stop: { _, _ in false }
)
#expect(outcome.restoredValveSignature == false)
@@ -250,17 +255,83 @@ struct UninstallTests {
compatTools: layout.compatTools,
directories: [layout.support, layout.caches],
libraries: [],
- repair: { _ in repaired.set() },
- stop: { _ in false }
+ modifications: layout.modifications, lockFolder: layout.root,
+ repair: { _, _ in repaired.set() },
+ stop: { _, _ in false }
)
#expect(!repaired.value)
#expect(!outcome.steamInstalled)
#expect(!outcome.steamNeedsRedownload)
+ #expect(outcome.partialRemoval == nil)
#expect(!FileManager.default.fileExists(atPath: layout.app.path(percentEncoded: false)))
#expect(!FileManager.default.fileExists(atPath: layout.support.path(percentEncoded: false)))
}
+ @Test("A removal with Steam's drive unplugged removes the rest and says Steam was left alone")
+ func reportsAnUnpluggedSteam() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ let unplugged = URL(filePath: "/Volumes/np-missing-\(UUID().uuidString)/Steam.app")
+ try layout.modifications.mark(unplugged)
+
+ let outcome = try await Uninstall.run(
+ app: unplugged,
+ innerPlist: layout.innerPlist,
+ updateBlocks: [layout.updateBlock],
+ legacyCompat: layout.legacyCompat,
+ compatTools: layout.compatTools,
+ directories: [layout.support, layout.caches],
+ libraries: [],
+ modifications: layout.modifications, lockFolder: layout.root,
+ repair: { _, _ in },
+ stop: { _, _ in false }
+ )
+
+ #expect(outcome.unreachableSteam == [unplugged])
+ #expect(outcome.partialRemoval?.contains(unplugged.path(percentEncoded: false)) == true)
+ #expect(!FileManager.default.fileExists(atPath: layout.support.path(percentEncoded: false)))
+ }
+
+ @Test("An unplugged Steam that NotProton was never installed into is not reported")
+ func ignoresAnUnpluggedSteamWithoutNotProton() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+
+ let outcome = try await Uninstall.run(
+ app: URL(filePath: "/Volumes/np-missing-\(UUID().uuidString)/Steam.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,
+ repair: { _, _ in },
+ stop: { _, _ in false }
+ )
+
+ #expect(outcome.partialRemoval == nil)
+ }
+
+ @Test("Shipped build records migrate to /Applications once")
+ func readsTheInstalledSteam() throws {
+ let root = try scratchDirectory("installed-steam")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let record = root.appending(path: "install-build.json")
+ let modifications = SteamModifications(file: root.appending(path: "steam-bundles.json"), legacyRecord: record)
+
+ #expect(try modifications.paths().isEmpty)
+ try Data(#"{"version":"1.1.7","builtAt":1}"#.utf8).write(to: record)
+ #expect(try modifications.paths() == [SupportPaths.Steam.defaultApp])
+ try modifications.prepare()
+ try FileManager.default.removeItem(at: record)
+ #expect(try modifications.paths() == [SupportPaths.Steam.defaultApp])
+ try Data(#"{"version":"1.1.7","builtAt":1}"#.utf8).write(to: record)
+ try JSONEncoder().encode([String]()).write(to: modifications.file)
+ #expect(try modifications.paths().isEmpty)
+ }
+
@Test("A restore that fails asks for a redownload")
func asksForARedownloadWhenTheRestoreFails() async throws {
let layout = try layout()
@@ -275,8 +346,9 @@ struct UninstallTests {
compatTools: layout.compatTools,
directories: [layout.support, layout.caches],
libraries: [],
- repair: { _ in throw Offline() },
- stop: { _ in false }
+ modifications: layout.modifications, lockFolder: layout.root,
+ repair: { _, _ in throw Offline() },
+ stop: { _, _ in false }
)
#expect(outcome.steamNeedsRedownload)
@@ -306,12 +378,13 @@ struct UninstallTests {
compatTools: layout.compatTools,
directories: [layout.support, caches],
libraries: [],
- repair: { _ in
+ modifications: layout.modifications, lockFolder: layout.root,
+ repair: { _, _ in
let staged = caches.appending(path: "bundle")
try FileManager.default.createDirectory(at: staged, withIntermediateDirectories: true)
try Data("2.6G of Steam".utf8).write(to: staged.appending(path: "Steam.app"))
},
- stop: { _ in false }
+ stop: { _, _ in false }
)
#expect(outcome.restoredValveSignature)
@@ -334,12 +407,13 @@ struct UninstallTests {
compatTools: layout.compatTools,
directories: [layout.support, layout.caches],
libraries: [],
+ modifications: layout.modifications, lockFolder: layout.root,
report: { log.add($0) },
- repair: { report in
+ repair: { _, report in
report(.checking)
report(.replacing)
},
- stop: { _ in false }
+ stop: { _, _ in false }
)
let restoring = log.all.compactMap { phase -> RepairPhase? in
@@ -376,7 +450,8 @@ struct UninstallTests {
app: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock],
legacyCompat: layout.legacyCompat, compatTools: layout.compatTools,
directories: [layout.support, layout.caches], libraries: [library],
- repair: { _ in }, stop: { _ in false })
+ modifications: layout.modifications, lockFolder: layout.root,
+ repair: { _, _ in }, stop: { _, _ in false })
for template in templates { #expect(!FileManager.default.fileExists(atPath: template.path)) }
#expect(try String(contentsOf: unrelated, encoding: .utf8) == "keep")
@@ -411,7 +486,8 @@ struct UninstallTests {
app: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock],
legacyCompat: layout.legacyCompat, compatTools: layout.compatTools,
directories: [layout.support, layout.caches], libraries: [ours, foreign, real, empty],
- repair: { _ in }, stop: { _ in false })
+ modifications: layout.modifications, lockFolder: layout.root,
+ repair: { _, _ in }, stop: { _, _ in false })
#expect((try? files.destinationOfSymbolicLink(atPath: dll(ours).path(percentEncoded: false))) == nil)
#expect(outcome.removed.filter { $0 == "Steam.dll" }.count == 1)
@@ -422,6 +498,192 @@ struct UninstallTests {
#expect(!files.fileExists(atPath: empty.root.path(percentEncoded: false)))
}
+ private func remove(_ layout: Layout, app: URL? = 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,
+ repair: repair, stop: stop)
+ }
+
+ @Test("Removal cleans both tracked copies when the first drive returns")
+ func removesReturnedSteamAsWellAsSelectedSteam() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ let drive = layout.root.appending(path: "external")
+ let first = drive.appending(path: "Steam.app")
+ let parked = layout.root.appending(path: "disconnected")
+ try FileManager.default.createDirectory(at: drive, withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: layout.app, to: first)
+ try layout.modifications.mark(first)
+ try FileManager.default.moveItem(at: drive, to: parked)
+ try layout.modifications.mark(layout.app)
+ try FileManager.default.moveItem(at: parked, to: drive)
+ let stoppedFirst = Flag()
+ let stoppedSecond = Flag()
+ let otherAccount = layout.root.appending(path: "other-account")
+ try FileManager.default.createDirectory(at: otherAccount, withIntermediateDirectories: true)
+
+ let outcome = try await remove(layout, stop: { target, _ in
+ if target.path == first.standardizedFileURL.path { stoppedFirst.set() }
+ if target.path == layout.app.standardizedFileURL.path { stoppedSecond.set() }
+ #expect(throws: StepFailure.self) {
+ let lock = try DeploymentContent.acquireInstallationLock(
+ in: otherAccount, steamFolder: target.deletingLastPathComponent())
+ lock.release()
+ }
+ return false
+ })
+
+ #expect(stoppedFirst.value && stoppedSecond.value)
+ #expect(outcome.partialRemoval == nil)
+ #expect(try SteamModifications.inspect(first) == .clean)
+ #expect(try SteamModifications.inspect(layout.app) == .clean)
+ #expect(try layout.modifications.paths().isEmpty)
+ }
+
+ @Test("Partial removal stays incomplete on CLI retries after support data is deleted")
+ func partialRemovalSurvivesRetries() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ let first = layout.root.appending(path: "missing-a/Steam.app")
+ let second = layout.root.appending(path: "missing-b/Steam.app")
+ let parkedFirst = layout.root.appending(path: "disconnected-a")
+ let parkedSecond = layout.root.appending(path: "disconnected-b")
+ for (app, parked) in [(first, parkedFirst), (second, parkedSecond)] {
+ try FileManager.default.createDirectory(at: app.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: layout.app, to: app)
+ try FileManager.default.moveItem(at: app.deletingLastPathComponent(), to: parked)
+ }
+ try layout.modifications.mark(first)
+ try layout.modifications.mark(second)
+ try layout.modifications.mark(layout.app)
+
+ for _ in 0..<2 {
+ let exitCode = await RemoveEverythingCommand.perform { _ in
+ let result = try await remove(layout)
+ #expect(Set(result.unreachableSteam) == Set([first, second]))
+ #expect(result.partialRemoval?.contains(first.path) == true)
+ #expect(result.partialRemoval?.contains(second.path) == true)
+ return result
+ }
+ #expect(exitCode == 1)
+ #expect(Set(try layout.modifications.paths()) == Set([first, second]))
+ #expect(!FileManager.default.fileExists(atPath: layout.support.path))
+ }
+ let confirmation = Uninstall.confirmation(modifications: layout.modifications)
+ #expect(confirmation.contains(first.path) && confirmation.contains(second.path))
+
+ try FileManager.default.moveItem(at: parkedFirst, to: first.deletingLastPathComponent())
+ try FileManager.default.moveItem(at: parkedSecond, to: second.deletingLastPathComponent())
+ let exitCode = await RemoveEverythingCommand.perform { _ in try await remove(layout) }
+
+ #expect(exitCode == 0)
+ #expect(try layout.modifications.paths().isEmpty)
+ #expect(try SteamModifications.inspect(first) == .clean)
+ #expect(try SteamModifications.inspect(second) == .clean)
+ }
+
+ @Test("A conservatively recorded clean bundle is retired without repair")
+ func resolvesAnUnpatchedAttempt() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ _ = try Uninstall.detach(from: layout.app, innerPlist: layout.innerPlist, updateBlocks: [])
+ try layout.modifications.mark(layout.app)
+
+ let result = try await remove(layout)
+
+ #expect(result.partialRemoval == nil)
+ #expect(!result.steamNeedsRedownload)
+ #expect(try layout.modifications.paths().isEmpty)
+ }
+
+ @Test("Interrupted detachment stays tracked until Steam's signature is repaired")
+ func recoversInterruptedDetachment() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ try layout.modifications.mark(layout.app)
+ _ = try SteamRepair.clearInsert(at: layout.outerPlist)
+ try FileManager.default.removeItem(at: layout.dylib)
+ #expect(try !verifies(layout.app))
+ let attempted = Flag()
+ struct Offline: Error {}
+
+ let failed = await RemoveEverythingCommand.perform { _ in
+ try await remove(layout, repair: { _, _ in
+ attempted.set()
+ throw Offline()
+ })
+ }
+
+ #expect(failed == 1)
+ #expect(attempted.value)
+ #expect(try layout.modifications.paths().map(\.path) == [layout.app.standardizedFileURL.path])
+ #expect(FileManager.default.fileExists(atPath: layout.support.path))
+
+ let recovered = await RemoveEverythingCommand.perform { _ in
+ try await remove(layout, repair: { app, _ in try SteamInstaller.adHocSign(app) })
+ }
+
+ #expect(recovered == 0)
+ #expect(try verifies(layout.app))
+ #expect(try layout.modifications.paths().isEmpty)
+ }
+
+ @Test("A refused bundle lock preserves that target for a later removal")
+ func preservesLockedTarget() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ let drive = layout.root.appending(path: "external")
+ let app = drive.appending(path: "Steam.app")
+ let otherAccount = layout.root.appending(path: "other-account")
+ for folder in [drive, otherAccount] {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ }
+ try FileManager.default.copyItem(at: layout.app, to: app)
+ try layout.modifications.mark(app)
+ let lock = try DeploymentContent.acquireInstallationLock(in: otherAccount, steamFolder: drive)
+ do {
+ defer { lock.release() }
+ await #expect(throws: StepFailure.self) { try await remove(layout) }
+ #expect(try layout.modifications.paths().map(\.path) == [app.standardizedFileURL.path])
+ #expect(try SteamModifications.inspect(app) == .modified)
+ }
+
+ let result = try await remove(layout)
+ #expect(result.partialRemoval == nil)
+ #expect(try layout.modifications.paths().isEmpty)
+ }
+
+ @Test("Unreadable bundle metadata never clears an outstanding target")
+ func preservesUninspectableTarget() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ try layout.modifications.mark(layout.app)
+ try Data("not a plist".utf8).write(to: layout.outerPlist)
+
+ await #expect(throws: StepFailure.self) { try await remove(layout) }
+
+ #expect(try layout.modifications.paths().map(\.path) == [layout.app.standardizedFileURL.path])
+ }
+
+ @Test("A corrupt path record blocks removal without deleting it")
+ func preservesCorruptRecord() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ try Data("corrupt".utf8).write(to: layout.modifications.file)
+
+ let exitCode = await RemoveEverythingCommand.perform { _ in try await remove(layout) }
+
+ #expect(exitCode == 1)
+ #expect(try String(contentsOf: layout.modifications.file, encoding: .utf8) == "corrupt")
+ #expect(FileManager.default.fileExists(atPath: layout.support.path))
+ #expect(try SteamModifications.inspect(layout.app) == .modified)
+ }
+
@Test("Uninstall reports template cleanup refusal rather than claiming completion")
func reportsTemplateCleanupFailure() async throws {
let layout = try layout()
@@ -440,7 +702,8 @@ struct UninstallTests {
app: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock],
legacyCompat: layout.legacyCompat, compatTools: layout.compatTools,
directories: [layout.support, layout.caches], libraries: [library],
- repair: { _ in }, stop: { _ in false })
+ modifications: layout.modifications, lockFolder: layout.root,
+ repair: { _, _ in }, stop: { _, _ in false })
}
#expect(try String(contentsOf: sentinel, encoding: .utf8) == "keep")
}