Skip to content

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

Add support for installing multiple versions of CrossOver

NotProtonNota9c6dc3fa486
diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml
index 4b78d4d..f820073 100644
--- a/.github/workflows/app.yml
+++ b/.github/workflows/app.yml
@@ -100,6 +100,9 @@ jobs:
make -s spawn-env
make -s compatcheck
make -s compatsvc-check
+ make -s launch-shell
+ make -s envcheck
+ make -s buildcheck
- name: Run the Swift tests
run: make -s app-tests
diff --git a/Makefile b/Makefile
index 4a742a7..43e1ad5 100644
--- a/Makefile
+++ b/Makefile
@@ -61,7 +61,7 @@ DEPS := $(OBJS:.o=.d)
tests-list overlay-shim overlay-shim-install overlay-shim-tests \
overlay-shim-bench iconmaker icon \
appinfo helpers-install ntdll-resolve bridge runcheck compatcheck \
- compatsvc-check scriptcheck envcheck launch-shell FORCE
+ compatsvc-check scriptcheck envcheck buildcheck launch-shell FORCE
APP_PAYLOAD := app/Sources/NotProtonApp/Resources/payload
@@ -92,6 +92,10 @@ envcheck:
@if [ ! -f dylib/tests/envcheck.sh ]; then $(call SKIP,envcheck,dylib/tests/envcheck.sh); exit 0; fi; \
sh dylib/tests/envcheck.sh dylib/feats/compat_run.sh
+buildcheck:
+ @if [ ! -f dylib/tests/buildcheck.sh ]; then $(call SKIP,buildcheck,dylib/tests/buildcheck.sh); exit 0; fi; \
+ sh dylib/tests/buildcheck.sh dylib/feats/compat_run.sh
+
# runcheck owns compat_run.sh, whose warnings wait for a change that can move
# the embedded __text baseline
SCRIPTS := $(shell git ls-files '*.sh' 2>/dev/null | grep -v '^dylib/feats/compat_run\.sh$$')
diff --git a/app/Package.swift b/app/Package.swift
index 7b18779..7721f66 100644
--- a/app/Package.swift
+++ b/app/Package.swift
@@ -31,6 +31,8 @@ let package = Package(
.copy("Resources/detour32.bin"),
.copy("Resources/detour32-fex.bin"),
.copy("Resources/detour64-fex.bin"),
+ .copy("Resources/detour2-cx26.bin"),
+ .copy("Resources/detour32-cx26.bin"),
],
swiftSettings: [.swiftLanguageMode(.v6)]
),
diff --git a/app/Sources/NotProtonApp/App.swift b/app/Sources/NotProtonApp/App.swift
index f7b1deb..8a0d5c9 100644
--- a/app/Sources/NotProtonApp/App.swift
+++ b/app/Sources/NotProtonApp/App.swift
@@ -21,6 +21,9 @@ struct NotProtonApp: App {
.environment(prefixes)
.frame(minWidth: 720, minHeight: 460)
.onChange(of: pane) { prefixes.forgetOutcome() }
+ .onChange(of: status.snapshot?.installedRunners.map(\.id)) {
+ if prefixes.hasLoaded { Task { await prefixes.load() } }
+ }
}
.defaultSize(width: 900, height: 760)
.commands { menus }
@@ -120,12 +123,23 @@ struct NotProtonApp: App {
}
.disabled(selectionTargets.isEmpty)
- Button(PrefixPrompt.rebuildButton(selectionTargets)) {
- if !selectionTargets.isEmpty {
- prefixes.pendingConfirmation = .rebuild(selectionTargets)
+ if prefixes.tools.count > 1 {
+ Menu(PrefixPrompt.rebuildButton(selectionTargets)) {
+ ForEach(prefixes.tools) { tool in
+ Button(tool.display) {
+ prefixes.pendingConfirmation = .rebuild(selectionTargets, tool)
+ }
+ }
}
+ .disabled(selectionTargets.isEmpty)
+ } else {
+ Button(PrefixPrompt.rebuildButton(selectionTargets)) {
+ if let tool = prefixes.tools.first, !selectionTargets.isEmpty {
+ prefixes.pendingConfirmation = .rebuild(selectionTargets, tool)
+ }
+ }
+ .disabled(selectionTargets.isEmpty || prefixes.tools.isEmpty)
}
- .disabled(selectionTargets.isEmpty)
Button(PrefixPrompt.deleteButton(selectionTargets)) {
if !selectionTargets.isEmpty {
diff --git a/app/Sources/NotProtonApp/Model/CrossOverRow.swift b/app/Sources/NotProtonApp/Model/CrossOverRow.swift
new file mode 100644
index 0000000..8bf6563
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/CrossOverRow.swift
@@ -0,0 +1,85 @@
+// One row per CrossOver build on the Status pane
+
+import Foundation
+
+struct CrossOverRow: Identifiable, Equatable {
+
+ enum Copy: Equatable {
+ case none
+ case ready
+ case unpatched
+ case damaged
+ case unsupported
+ }
+
+ let buildID: String
+ let install: CrossOverInstall?
+ let copy: Copy
+ let licensed: Bool?
+ let unsupportedVersion: String?
+
+ var id: String { install?.id ?? buildID }
+ var build: RunnerBuild? { SupportedRunners.build(id: buildID) }
+
+ var title: String {
+ if let install { return install.name }
+ return "CrossOver \(SupportedRunners.displayVersion(forID: buildID))"
+ }
+
+ var canSetUp: Bool { install != nil && unsupportedVersion == nil }
+ var isManual: Bool { install?.isManual ?? false }
+
+ static func == (a: CrossOverRow, b: CrossOverRow) -> Bool {
+ a.buildID == b.buildID && a.install?.id == b.install?.id && a.copy == b.copy
+ && a.licensed == b.licensed && a.unsupportedVersion == b.unsupportedVersion
+ }
+
+ static func rows(
+ installs: [CrossOverInstall],
+ licenses: [String: CrossOverLicense.Status],
+ installed: [RunnerBuild],
+ damaged: [String],
+ orphaned: [String],
+ unpatched: String?
+ ) -> [CrossOverRow] {
+ var rows: [CrossOverRow] = []
+ var seen: Set<String> = []
+
+ func copy(of build: String) -> Copy {
+ if build == unpatched { return .unpatched }
+ if installed.contains(where: { $0.id == build }) { return .ready }
+ if damaged.contains(build) { return .damaged }
+ return .none
+ }
+
+ for install in installs {
+ switch install.support {
+ case .supported(let build):
+ guard seen.insert(build.id).inserted else { continue }
+ rows.append(CrossOverRow(
+ buildID: build.id, install: install, copy: copy(of: build.id),
+ licensed: licenses[install.id]?.licensed, unsupportedVersion: nil
+ ))
+ case .unsupportedBuild(let version):
+ rows.append(CrossOverRow(
+ buildID: "", install: install, copy: .none, licensed: nil, unsupportedVersion: version
+ ))
+ case .unreadable:
+ continue
+ }
+ }
+
+ let copies = installed.map(\.id) + damaged
+ for build in copies where seen.insert(build).inserted {
+ rows.append(CrossOverRow(
+ buildID: build, install: nil, copy: copy(of: build), licensed: nil, unsupportedVersion: nil
+ ))
+ }
+ for build in orphaned where seen.insert(build).inserted {
+ rows.append(CrossOverRow(
+ buildID: build, install: nil, copy: .unsupported, licensed: nil, unsupportedVersion: nil
+ ))
+ }
+ return rows
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/CrossOverSource.swift b/app/Sources/NotProtonApp/Model/CrossOverSource.swift
index ade792d..fbf88f4 100644
--- a/app/Sources/NotProtonApp/Model/CrossOverSource.swift
+++ b/app/Sources/NotProtonApp/Model/CrossOverSource.swift
@@ -35,14 +35,38 @@ enum CrossOverSource {
SupportPaths.home.appending(path: "Applications", directoryHint: .isDirectory),
]
- private static let manualKey = "manualCrossOverPath"
+ private static let manualKey = "manualCrossOverPaths"
+ // 1.0/1.0.1 kept a single chosen copy under this key.
+ private static let legacyManualKey = "manualCrossOverPath"
+
+ static func manualBundles(_ defaults: UserDefaults = .standard) -> [URL] {
+ let paths = defaults.stringArray(forKey: manualKey)
+ ?? defaults.string(forKey: legacyManualKey).map { [$0] } ?? []
+ return paths.filter { !$0.isEmpty }.map { URL(filePath: $0, directoryHint: .isDirectory) }
+ }
- static var manualBundle: URL? {
- get {
- guard let path = UserDefaults.standard.string(forKey: manualKey), !path.isEmpty else { return nil }
- return URL(filePath: path, directoryHint: .isDirectory)
- }
- set { UserDefaults.standard.set(newValue?.path(percentEncoded: false), forKey: manualKey) }
+ static func setManualBundles(_ bundles: [URL], _ defaults: UserDefaults = .standard) {
+ defaults.set(bundles.map { $0.path(percentEncoded: false) }, forKey: manualKey)
+ defaults.removeObject(forKey: legacyManualKey)
+ }
+
+ static func addManualBundle(_ bundle: URL, _ defaults: UserDefaults = .standard) {
+ let current = manualBundles(defaults)
+ guard !current.contains(where: { same($0, bundle) }) else { return }
+ setManualBundles(current + [bundle], defaults)
+ }
+
+ static func removeManualBundle(_ bundle: URL, _ defaults: UserDefaults = .standard) {
+ setManualBundles(manualBundles(defaults).filter { !same($0, bundle) }, defaults)
+ }
+
+ static func isSearched(_ bundle: URL) -> Bool {
+ let parent = bundle.standardizedFileURL.deletingLastPathComponent()
+ return searchRoots.contains { same($0, parent) }
+ }
+
+ private static func same(_ a: URL, _ b: URL) -> Bool {
+ a.standardizedFileURL.path(percentEncoded: false) == b.standardizedFileURL.path(percentEncoded: false)
}
// A CrossOver bundle without this directory is bad!
@@ -65,7 +89,7 @@ enum CrossOverSource {
found.append(inspect(bundle: bundle, isManual: isManual))
}
- if let manual = manualBundle { consider(manual, isManual: true) }
+ for manual in manualBundles() where !isSearched(manual) { consider(manual, isManual: true) }
for root in searchRoots {
let entries = (try? fm.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? []
diff --git a/app/Sources/NotProtonApp/Model/NtdllPatcher.swift b/app/Sources/NotProtonApp/Model/NtdllPatcher.swift
index 79634b4..a0ca5aa 100644
--- a/app/Sources/NotProtonApp/Model/NtdllPatcher.swift
+++ b/app/Sources/NotProtonApp/Model/NtdllPatcher.swift
@@ -10,6 +10,11 @@ struct NtdllHook: Sendable {
let stolen: [UInt8]
}
+enum CavePlacement: Sendable {
+ case padding
+ case section
+}
+
struct NtdllPatch: Sendable {
let arch: WineArch
@@ -29,6 +34,8 @@ struct NtdllPatch: Sendable {
let machine: UInt16
let magic: UInt16
let imageBase: UInt64
+
+ var placement: CavePlacement = .padding
}
enum NtdllPatcher {
@@ -36,6 +43,11 @@ enum NtdllPatcher {
static let step = "Patch ntdll"
private static let magicPE32Plus: UInt16 = 0x20b
+ // SECTION_NAME, SECTION_SIZE and SECTION_FLAGS in resolve.py. The patched file is checked
+ // against patchedNtdll, so a value that drifts here makes patching fail.
+ private static let sectionName: [UInt8] = Array(".npdet".utf8) + [0, 0]
+ private static let sectionSize = 0x1000
+ private static let sectionFlags: UInt32 = 0x6000_0020
private static let machineARM64: UInt16 = 0xaa64
@@ -73,6 +85,41 @@ enum NtdllPatcher {
imageBase: 0x7bc0_0000
),
],
+ "26.3.0.39832": [
+ NtdllPatch(
+ arch: .x86_64Windows,
+ payloadResource: "detour2-cx26",
+ payloadSHA256: "e35b834408599c45f30b23a6d2bf38acfa5c3df4d15206617c471e23a4a01bfb",
+ caveRVA: 0xae000,
+ payloadRVA: 0xae000,
+ hooks: [
+ NtdllHook(rva: 0x44972,
+ stolen: [0x48, 0x83, 0xbc, 0x24, 0xf0, 0x00, 0x00, 0x00, 0x00]),
+ ],
+ caveSize: 0x1000,
+ cavePad: 0x00,
+ machine: 0x8664,
+ magic: 0x20b,
+ imageBase: 0x1_7000_0000,
+ placement: .section
+ ),
+ NtdllPatch(
+ arch: .i386Windows,
+ payloadResource: "detour32-cx26",
+ payloadSHA256: "be465bc936cafafae4aa1b4c41f668e08848492d9858c2cf2ad483a9f1ab25e5",
+ caveRVA: 0xaa000,
+ payloadRVA: 0xaa000,
+ hooks: [
+ NtdllHook(rva: 0x43b40, stolen: [0xf6, 0x45, 0xc0, 0x01, 0x75, 0x26]),
+ ],
+ caveSize: 0x1000,
+ cavePad: 0x00,
+ machine: 0x14c,
+ magic: 0x10b,
+ imageBase: 0x7bc0_0000,
+ placement: .section
+ ),
+ ],
// FEX patches
"27.0.0.40921-fex": [
NtdllPatch(
@@ -136,6 +183,9 @@ enum NtdllPatcher {
static func apply(_ patch: NtdllPatch, to image: Data, payload: Data) throws -> Data {
var bytes = [UInt8](image)
try validateHeaders(patch, bytes)
+ if patch.placement == .section {
+ try appendSection(patch, to: &bytes)
+ }
let caveOffset = try fileOffset(of: patch.caveRVA, in: bytes, describing: "cave", patch: patch)
let payloadOffset = try fileOffset(of: patch.payloadRVA, in: bytes, describing: "payload", patch: patch)
@@ -242,6 +292,59 @@ enum NtdllPatcher {
}
+ private static func appendSection(_ patch: NtdllPatch, to bytes: inout [UInt8]) throws {
+ let pe = Int(try u32(bytes, 0x3c))
+ let sections = Int(try u16(bytes, pe + 6))
+ let optional = pe + 24
+ let table = optional + Int(try u16(bytes, pe + 20))
+ let header = table + sections * 40
+ let fileAlignment = Int(try u32(bytes, optional + 36))
+ let imageSize = Int(try u32(bytes, optional + 56))
+ let headersSize = Int(try u32(bytes, optional + 60))
+
+ guard patch.caveSize == sectionSize, imageSize == patch.caveRVA else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll image ends at \(hex(imageSize)), and the detour "
+ + "section was pinned at \(hex(patch.caveRVA))."
+ )
+ }
+ guard header + 40 <= headersSize, bytes[header ..< header + 40].allSatisfy({ $0 == 0 }) else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll has no free section header slot for the detour."
+ )
+ }
+ guard fileAlignment > 0, fileAlignment & (fileAlignment - 1) == 0 else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll file alignment \(hex(fileAlignment)) is not a power of two."
+ )
+ }
+
+ let rawOffset = (bytes.count + fileAlignment - 1) & ~(fileAlignment - 1)
+ // The last zero is NumberOfRelocations and NumberOfLinenumbers, two bytes each.
+ var entry = sectionName
+ for field in [UInt32(sectionSize), UInt32(patch.caveRVA), UInt32(sectionSize), UInt32(rawOffset),
+ 0, 0, 0, sectionFlags] {
+ withUnsafeBytes(of: field.littleEndian) { entry.append(contentsOf: $0) }
+ }
+ bytes.replaceSubrange(header ..< header + 40, with: entry)
+
+ put16(UInt16(sections + 1), at: pe + 6, in: &bytes)
+ put32(UInt32(imageSize + sectionSize), at: optional + 56, in: &bytes)
+ bytes.append(contentsOf: repeatElement(0, count: rawOffset + sectionSize - bytes.count))
+ }
+
+ private static func put16(_ value: UInt16, at offset: Int, in bytes: inout [UInt8]) {
+ bytes[offset] = UInt8(value & 0xff)
+ bytes[offset + 1] = UInt8(value >> 8)
+ }
+
+ private static func put32(_ value: UInt32, at offset: Int, in bytes: inout [UInt8]) {
+ for index in 0 ..< 4 { bytes[offset + index] = UInt8((value >> (8 * UInt32(index))) & 0xff) }
+ }
+
private static func validateHeaders(_ patch: NtdllPatch, _ bytes: [UInt8]) throws {
let pe = Int(try u32(bytes, 0x3c))
guard try u32(bytes, pe) == 0x0000_4550 else {
@@ -443,7 +546,7 @@ enum NtdllPatcher {
var written: [WineArch] = []
for patch in patches(for: build) {
- let destination = stagedCopy(of: patch.arch, in: bridge)
+ let destination = stagedCopy(of: patch.arch, build: build.id, in: bridge)
if Digest.sha256IfPresent(destination) == build.patchedNtdll[patch.arch] { continue }
@@ -452,59 +555,49 @@ enum NtdllPatcher {
written.append(patch.arch)
}
- prune(keeping: patches(for: build).map(\.arch), in: bridge)
+ prune(keeping: patches(for: build).map(\.arch), build: build.id, in: bridge)
return written
}
- static func snapshot(bridge: URL) throws -> [WineArch: Data] {
- var saved: [WineArch: Data] = [:]
-
- for arch in WineArch.allCases {
- let copy = stagedCopy(of: arch, in: bridge)
- guard FileManager.default.fileExists(atPath: copy.path(percentEncoded: false)) else { continue }
+ static func stageInstalled(
+ builds: [RunnerBuild] = RunnerStore.installedBuilds(),
+ runners: URL = SupportPaths.runners,
+ bridge: URL = SupportPaths.bridge
+ ) -> [(build: String, error: any Error)] {
+ var failures: [(build: String, error: any Error)] = []
+ for build in builds {
do {
- saved[arch] = try Data(contentsOf: copy)
+ try stage(build: build, runnerRoot: SupportPaths.clonedRoot(forBuild: build.id, runners: runners),
+ bridge: bridge)
} catch {
- throw StepFailure(
- step: step,
- detail: "\(copy.path(percentEncoded: false)) could not be read. \(error.localizedDescription)"
- )
+ failures.append((build.id, error))
}
}
-
- return saved
+ return failures
}
- static func restore(_ saved: [WineArch: Data], bridge: URL) throws {
- for arch in WineArch.allCases {
- let copy = stagedCopy(of: arch, in: bridge)
-
- if let data = saved[arch] {
- if (try? Data(contentsOf: copy)) != data {
- try atomicReplace(copy, with: data, step: step)
- }
- continue
- }
-
- do {
- try removeStagedCopy(of: arch, in: bridge)
- } catch {
- throw StepFailure(
- step: step,
- detail: "\(copy.path(percentEncoded: false)) could not be removed. \(error.localizedDescription)"
- )
- }
- }
+ static func stagedCopy(of arch: WineArch, build: String, in bridge: URL = SupportPaths.bridge) -> URL {
+ bridge.appending(path: "wine/\(build)/\(arch.rawValue)/ntdll.dll")
}
- private static func stagedCopy(of arch: WineArch, in bridge: URL) -> URL {
- bridge.appending(path: "wine/\(arch.rawValue)/ntdll.dll")
+ // Also clears the wine/<arch> copies 1.0/1.0.1 left behind.
+ static func pruneBuilds(
+ keeping builds: Set<String>, in bridge: URL = SupportPaths.bridge, keepingLegacy: Bool = false
+ ) {
+ let wine = bridge.appending(path: "wine")
+ let fm = FileManager.default
+ let legacy = keepingLegacy ? Set(WineArch.allCases.map(\.rawValue)) : []
+ let entries = (try? fm.contentsOfDirectory(at: wine, includingPropertiesForKeys: nil)) ?? []
+ for entry in entries
+ where !builds.contains(entry.lastPathComponent) && !legacy.contains(entry.lastPathComponent) {
+ try? fm.removeItem(at: entry)
+ }
}
- private static func removeStagedCopy(of arch: WineArch, in bridge: URL) throws {
+ private static func removeStagedCopy(of arch: WineArch, build: String, in bridge: URL) throws {
let fm = FileManager.default
- let copy = stagedCopy(of: arch, in: bridge)
+ let copy = stagedCopy(of: arch, build: build, in: bridge)
if fm.fileExists(atPath: copy.path(percentEncoded: false)) {
try fm.removeItem(at: copy)
@@ -516,9 +609,9 @@ enum NtdllPatcher {
}
}
- private static func prune(keeping arches: [WineArch], in bridge: URL) {
+ private static func prune(keeping arches: [WineArch], build: String, in bridge: URL) {
for arch in WineArch.allCases where !arches.contains(arch) {
- try? removeStagedCopy(of: arch, in: bridge)
+ try? removeStagedCopy(of: arch, build: build, in: bridge)
}
}
diff --git a/app/Sources/NotProtonApp/Model/PayloadState.swift b/app/Sources/NotProtonApp/Model/PayloadState.swift
index e66c30e..a83574e 100644
--- a/app/Sources/NotProtonApp/Model/PayloadState.swift
+++ b/app/Sources/NotProtonApp/Model/PayloadState.swift
@@ -31,7 +31,9 @@ struct PayloadState: Sendable {
enum PayloadInspector {
- static func inspect(bridge: URL = SupportPaths.bridge, build: RunnerBuild? = nil) -> PayloadState {
+ static func inspect(
+ bridge: URL = SupportPaths.bridge, builds: [RunnerBuild] = RunnerStore.installedBuilds()
+ ) -> PayloadState {
let fm = FileManager.default
var expected = 0
@@ -40,7 +42,7 @@ enum PayloadInspector {
do {
let manifest = try PayloadManifest.bundled()
- let entries = manifest.entries.filter { applies($0, to: build) }
+ let entries = manifest.entries.flatMap { expand($0, for: builds) }
expected = entries.count
missing = entries.filter {
!fm.fileExists(atPath: bridge.appending(path: $0.path).path(percentEncoded: false))
@@ -73,13 +75,15 @@ enum PayloadInspector {
)
}
- private static func applies(_ entry: PayloadEntry, to build: RunnerBuild?) -> Bool {
- guard entry.origin == .patched, let build,
+ private static func expand(_ entry: PayloadEntry, for builds: [RunnerBuild]) -> [PayloadEntry] {
+ guard entry.origin == .patched,
let arch = WineArch.allCases.first(where: {
entry.path == "wine/\($0.rawValue)/ntdll.dll"
})
- else { return true }
- return build.patchedNtdll[arch] != nil
+ else { return [entry] }
+ return builds.filter { $0.patchedNtdll[arch] != nil }.map {
+ PayloadEntry(origin: .patched, path: "wine/\($0.id)/\(arch.rawValue)/ntdll.dll")
+ }
}
static func newestSignatureDatabase(in directory: URL = SupportPaths.signatures) -> String? {
diff --git a/app/Sources/NotProtonApp/Model/PrefixPrompt.swift b/app/Sources/NotProtonApp/Model/PrefixPrompt.swift
index 115785a..88ba45b 100644
--- a/app/Sources/NotProtonApp/Model/PrefixPrompt.swift
+++ b/app/Sources/NotProtonApp/Model/PrefixPrompt.swift
@@ -32,11 +32,12 @@ enum PrefixPrompt {
])
}
- static func rebuildTitle(_ targets: [WinePrefix]) -> String {
+ static func rebuildTitle(_ targets: [WinePrefix], for tool: InstalledTool? = nil) -> String {
+ let with = tool.map { " with \($0.display)" } ?? ""
switch targets.count {
- case 0: "Rebuild prefix?"
- case 1: "Rebuild the prefix for \(targets[0].title)?"
- default: "Rebuild \(targets.count) prefixes?"
+ case 0: return "Rebuild prefix\(with)?"
+ case 1: return "Rebuild the prefix for \(targets[0].title)\(with)?"
+ default: return "Rebuild \(targets.count) prefixes\(with)?"
}
}
diff --git a/app/Sources/NotProtonApp/Model/PrefixRebuild.swift b/app/Sources/NotProtonApp/Model/PrefixRebuild.swift
index 4efde42..6dba9a2 100644
--- a/app/Sources/NotProtonApp/Model/PrefixRebuild.swift
+++ b/app/Sources/NotProtonApp/Model/PrefixRebuild.swift
@@ -6,7 +6,24 @@ extension PrefixTools {
@discardableResult
static func recreate(
_ prefix: WinePrefix,
- runner: URL = SupportPaths.currentRunner,
+ as tool: InstalledTool,
+ runners: URL = SupportPaths.runners,
+ now: Date = .now,
+ keepBackup: Bool = true
+ ) throws -> URL? {
+ let kept = try recreate(
+ prefix, runner: SupportPaths.clonedRoot(forBuild: tool.build, runners: runners),
+ flavor: tool.tool.flavor, now: now, keepBackup: keepBackup
+ )
+ try writeBuildRecord(tool, for: prefix)
+ return kept
+ }
+
+ @discardableResult
+ static func recreate(
+ _ prefix: WinePrefix,
+ runner: URL,
+ flavor: CompatTool.Flavor = .fex,
now: Date = .now,
keepBackup: Bool = true
) throws -> URL? {
@@ -29,7 +46,7 @@ extension PrefixTools {
)
}
- let loader = loader(runner: runner)
+ let loader = loader(runner: runner, flavor: flavor)
guard FileManager.default.isExecutableFile(atPath: loader.path(percentEncoded: false)) else {
throw StepFailure(
step: "Recreate prefix",
@@ -46,7 +63,7 @@ extension PrefixTools {
defer { try? fm.removeItem(at: fresh) }
try fm.createDirectory(at: fresh, withIntermediateDirectories: true)
- var environment = environment(prefix: prefix, runner: runner)
+ 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)
diff --git a/app/Sources/NotProtonApp/Model/PrefixTools.swift b/app/Sources/NotProtonApp/Model/PrefixTools.swift
index 13d4a2f..10dd2bb 100644
--- a/app/Sources/NotProtonApp/Model/PrefixTools.swift
+++ b/app/Sources/NotProtonApp/Model/PrefixTools.swift
@@ -19,21 +19,96 @@ enum WineTool: String, CaseIterable, Sendable {
}
}
+struct PrefixBuildRecord: Sendable, Equatable {
+ let build: String
+ let display: String?
+}
+
enum PrefixTools {
+ static let buildRecordName = "notproton-build"
+
+ static func buildRecord(of prefix: WinePrefix) -> PrefixBuildRecord? {
+ let file = prefix.root.appending(path: buildRecordName)
+ guard let text = try? String(contentsOf: file, encoding: .utf8) else { return nil }
+ let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
+ .map { $0.trimmingCharacters(in: .whitespaces) }
+ guard let build = lines.first, !build.isEmpty else { return nil }
+ let display = lines.dropFirst().first.flatMap { $0.isEmpty ? nil : $0 }
+ return PrefixBuildRecord(build: build, display: display)
+ }
+
+ static func lastBuild(of prefix: WinePrefix, runners: URL = SupportPaths.runners) -> PrefixBuildRecord? {
+ if let record = buildRecord(of: prefix) { return record }
+ let file = prefix.pfx.appending(path: ".update-timestamp")
+ guard let text = try? String(contentsOf: file, encoding: .utf8),
+ let field = text.split(whereSeparator: \.isWhitespace).first,
+ let updated = Int(field)
+ else { return nil }
+ for build in RunnerStore.clonedBuilds(in: runners) {
+ let inf = SupportPaths.clonedRoot(forBuild: build, runners: runners)
+ .appending(path: "share/wine/wine.inf")
+ let modified = (try? FileManager.default.attributesOfItem(
+ atPath: inf.path(percentEncoded: false))[.modificationDate]) as? Date
+ if let modified, Int(modified.timeIntervalSince1970) == updated {
+ return PrefixBuildRecord(build: build, display: nil)
+ }
+ }
+ return PrefixBuildRecord(build: "", display: "another version of CrossOver")
+ }
+
+ static func writeBuildRecord(_ tool: InstalledTool, for prefix: WinePrefix) throws {
+ let file = prefix.root.appending(path: buildRecordName)
+ try atomicReplace(file, with: Data("\(tool.build)\n\(tool.display)\n".utf8), step: "Record prefix build")
+ }
+
+ static func tool(
+ for prefix: WinePrefix, among tools: [InstalledTool] = CompatToolList.installed(),
+ runners: URL = SupportPaths.runners
+ ) -> InstalledTool? {
+ let arch = PrefixStore.arch(of: prefix)
+ func byArch(_ candidates: [InstalledTool]) -> InstalledTool? {
+ guard let arch else { return candidates.first }
+ return candidates.first { $0.tool.prefixArch == arch }
+ }
+ guard let record = lastBuild(of: prefix, runners: runners) else { return byArch(tools) }
+ let served = tools.filter { $0.build == record.build }
+ if let named = served.first(where: { $0.display == record.display }),
+ arch == nil || named.tool.prefixArch == arch {
+ return named
+ }
+ return byArch(served)
+ }
+
+ static func resolvedTool(
+ step: String, for prefix: WinePrefix, among tools: [InstalledTool] = CompatToolList.installed()
+ ) throws -> InstalledTool {
+ if let found = tool(for: prefix, among: tools) { return found }
+ if let record = lastBuild(of: prefix) {
+ throw StepFailure(
+ step: step,
+ detail: "\(prefix.title) was last run by \(record.display ?? "build \(record.build)"), "
+ + "which is no longer set up. Rebuild the prefix first."
+ )
+ }
+ throw StepFailure(step: step, detail: "No compatibility tool is set up.")
+ }
+
static func syncBackend(prefix: WinePrefix) -> String {
let marker = prefix.root.appending(path: "notproton-msync")
let recorded = try? String(contentsOf: marker, encoding: .utf8)
return recorded?.trimmingCharacters(in: .whitespacesAndNewlines) == "1" ? "1" : "0"
}
- static func environment(prefix: WinePrefix, runner: URL = SupportPaths.currentRunner) -> [String: String] {
+ static func environment(
+ prefix: WinePrefix, runner: URL, flavor: CompatTool.Flavor = .fex
+ ) -> [String: String] {
let root = runner.path(percentEncoded: false)
var environment = ProcessInfo.processInfo.environment
environment["CX_ROOT"] = root
environment["CX_HOME"] = SupportPaths.applicationSupport
.appending(path: "CrossOver").path(percentEncoded: false)
- let wine = layout(runner: runner)
+ let wine = layout(runner: runner, flavor: flavor)
environment["WINELOADER"] = wine.loader.path(percentEncoded: false)
environment["WINESERVER"] = wine.server.path(percentEncoded: false)
environment["WINEDLLPATH"] = "\(root)/lib/wine/x86_64-windows:"
@@ -44,8 +119,8 @@ enum PrefixTools {
return environment
}
- static func loader(runner: URL = SupportPaths.currentRunner) -> URL {
- layout(runner: runner).loader
+ static func loader(runner: URL, flavor: CompatTool.Flavor = .fex) -> URL {
+ layout(runner: runner, flavor: flavor).loader
}
struct WineLayout {
@@ -54,7 +129,7 @@ enum PrefixTools {
let unixDir: URL
}
- static func layout(runner: URL = SupportPaths.currentRunner) -> WineLayout {
+ static func layout(runner: URL, flavor: CompatTool.Flavor = .fex) -> WineLayout {
let fm = FileManager.default
let hosted = runner.appending(path: "CrossOver-Hosted Application")
func executable(_ url: URL) -> Bool {
@@ -64,7 +139,7 @@ enum PrefixTools {
let arm = runner.appending(path: "lib/wine/aarch64-unix")
let armLoader = arm.appending(path: "wine.app/Contents/MacOS/wine")
let armServer = hosted.appending(path: "wineserver-arm64")
- if executable(armLoader), executable(armServer) {
+ if flavor == .fex, executable(armLoader), executable(armServer) {
return WineLayout(loader: armLoader, server: armServer, unixDir: arm)
}
@@ -77,8 +152,10 @@ enum PrefixTools {
)
}
- private static func readyLoader(step: String, prefix: WinePrefix, runner: URL) throws -> URL {
- let loader = loader(runner: runner)
+ private static func readyLoader(
+ step: String, prefix: WinePrefix, runner: URL, flavor: CompatTool.Flavor
+ ) throws -> URL {
+ let loader = loader(runner: runner, flavor: flavor)
guard FileManager.default.isExecutableFile(atPath: loader.path(percentEncoded: false)) else {
throw StepFailure(
step: step,
@@ -95,22 +172,43 @@ enum PrefixTools {
return loader
}
- static func launch(_ tool: WineTool, in prefix: WinePrefix, runner: URL = SupportPaths.currentRunner) throws {
- let loader = try readyLoader(step: "Open \(tool.label)", prefix: prefix, runner: runner)
+ static func launch(_ tool: WineTool, in prefix: WinePrefix) throws {
+ let chosen = try resolvedTool(step: "Open \(tool.label)", for: prefix)
+ try launch(
+ tool, in: prefix, runner: SupportPaths.clonedRoot(forBuild: chosen.build),
+ flavor: chosen.tool.flavor
+ )
+ }
+
+ static func launch(
+ _ tool: WineTool, in prefix: WinePrefix, runner: URL, flavor: CompatTool.Flavor = .fex
+ ) throws {
+ let loader = try readyLoader(
+ step: "Open \(tool.label)", prefix: prefix, runner: runner, flavor: flavor
+ )
try Shell.detach(
loader.path(percentEncoded: false),
[tool.rawValue],
- environment: environment(prefix: prefix, runner: runner)
+ environment: environment(prefix: prefix, runner: runner, flavor: flavor)
+ )
+ }
+
+ static func run(_ executable: URL, in prefix: WinePrefix) throws {
+ let chosen = try resolvedTool(step: "Run \(executable.lastPathComponent)", for: prefix)
+ try run(
+ executable, in: prefix, runner: SupportPaths.clonedRoot(forBuild: chosen.build),
+ flavor: chosen.tool.flavor
)
}
static func run(
_ executable: URL,
in prefix: WinePrefix,
- runner: URL = SupportPaths.currentRunner
+ runner: URL,
+ flavor: CompatTool.Flavor = .fex
) throws {
let step = "Run \(executable.lastPathComponent)"
- let loader = try readyLoader(step: step, prefix: prefix, runner: runner)
+ let loader = try readyLoader(step: step, prefix: prefix, runner: runner, flavor: flavor)
guard FileManager.default.fileExists(atPath: executable.path(percentEncoded: false)) else {
throw StepFailure(step: step, detail: "No file at \(executable.path(percentEncoded: false)).")
}
@@ -125,7 +223,7 @@ enum PrefixTools {
try Shell.detach(
loader.path(percentEncoded: false),
arguments,
- environment: environment(prefix: prefix, runner: runner),
+ environment: environment(prefix: prefix, runner: runner, flavor: flavor),
currentDirectory: executable.deletingLastPathComponent()
)
}
@@ -174,8 +272,4 @@ enum PrefixTools {
try FileManager.default.removeItem(at: prefix.root)
}
}
-
- static func prefixArch(runner: URL = SupportPaths.currentRunner) -> PrefixArch {
- layout(runner: runner).unixDir.lastPathComponent == "aarch64-unix" ? .arm64 : .x86_64
- }
}
diff --git a/app/Sources/NotProtonApp/Model/RunnerInstaller.swift b/app/Sources/NotProtonApp/Model/RunnerInstaller.swift
index 993494f..324f8ef 100644
--- a/app/Sources/NotProtonApp/Model/RunnerInstaller.swift
+++ b/app/Sources/NotProtonApp/Model/RunnerInstaller.swift
@@ -43,21 +43,44 @@ enum RunnerInstaller {
static let removeStep = "Remove build"
- static func removeClone(forBuild build: String, runners: URL = SupportPaths.runners) throws {
+ @discardableResult
+ static func removeClone(
+ forBuild build: String,
+ runners: URL = SupportPaths.runners,
+ bridge: URL = SupportPaths.bridge,
+ toolList: URL = SupportPaths.toolList,
+ compatTools: URL = SupportPaths.Steam.compatTools,
+ running: (URL) -> Bool = { RunnerInstaller.isRunning(from: $0) }
+ ) throws -> Bool {
let target = SupportPaths.runnerRoot(forBuild: build, runners: runners)
let path = target.path(percentEncoded: false)
guard FileManager.default.fileExists(atPath: path) else {
throw StepFailure(step: removeStep, detail: "Build \(build) is not set up.")
}
- guard RunnerStore.currentBuild(runners: runners) != build else {
+ guard !running(target) else {
throw StepFailure(
step: removeStep,
- detail: "Build \(build) is the active build. Switch to another build first."
+ detail: "A game or Wine tool is still running on build \(build). Quit it first."
)
}
try WriteRefused.catching(path) { try FileManager.default.removeItem(at: target) }
+ return try CompatToolList.sync(
+ runners: runners, bridge: bridge, file: toolList, compatTools: compatTools
+ )
+ }
+
+ // Wine keeps a wineserver running inside the clone, so a process running from there is a
+ // live session.
+ 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 }
+ 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)
+ }
}
static func hasClone(forBuild build: String, runners: URL = SupportPaths.runners) -> Bool {
@@ -113,22 +136,4 @@ enum RunnerInstaller {
try CrossOverSource.verifyPatchInputs(root: root, build: build)
}
-
- static func pointCurrent(atBuild build: String, runners: URL = SupportPaths.runners) throws {
- let fm = FileManager.default
- let relative = "crossover-\(build)/CrossOver"
- let staging = runners.appending(path: ".current.new")
-
- try? fm.removeItem(at: staging)
- try fm.createSymbolicLink(
- atPath: staging.path(percentEncoded: false), withDestinationPath: relative
- )
-
- let current = runners.appending(path: "current").path(percentEncoded: false)
- if rename(staging.path(percentEncoded: false), current) != 0 {
- let reason = String(cString: strerror(errno))
- try? fm.removeItem(at: staging)
- throw StepFailure(step: step, detail: "Could not point the compatibility tool at \(relative). \(reason)")
- }
- }
}
diff --git a/app/Sources/NotProtonApp/Model/RunnerPatcher.swift b/app/Sources/NotProtonApp/Model/RunnerPatcher.swift
index fb8e022..cd3c8c0 100644
--- a/app/Sources/NotProtonApp/Model/RunnerPatcher.swift
+++ b/app/Sources/NotProtonApp/Model/RunnerPatcher.swift
@@ -98,7 +98,7 @@ enum RunnerPatcher {
for arch in WineArch.allCases {
guard let expected = build.patchedNtdll[arch] else { continue }
- let staged = bridge.appending(path: "wine/\(arch.rawValue)/ntdll.dll")
+ let staged = NtdllPatcher.stagedCopy(of: arch, build: build.id, in: bridge)
guard Digest.sha256IfPresent(staged) == expected else {
throw StepFailure(
diff --git a/app/Sources/NotProtonApp/Model/RunnerSetup.swift b/app/Sources/NotProtonApp/Model/RunnerSetup.swift
index 4e765de..19244e1 100644
--- a/app/Sources/NotProtonApp/Model/RunnerSetup.swift
+++ b/app/Sources/NotProtonApp/Model/RunnerSetup.swift
@@ -24,8 +24,9 @@ enum RunnerSetup {
let build: RunnerBuild
let staged: [WineArch]
let installed: RunnerPatcher.Outcome
+ var toolsChanged = false
- var stagedNothing: Bool { staged.isEmpty && installed.wroteNothing }
+ var stagedNothing: Bool { staged.isEmpty && installed.wroteNothing && !toolsChanged }
}
static func run(
@@ -37,15 +38,17 @@ enum RunnerSetup {
report(.cloning)
let build = try RunnerInstaller.clone(from: install, replacingExisting: replacingExisting)
- return try activate(build, report: report)
+ return try prepare(build, report: report)
}
- static let switchStep = "Switch compatibility tool"
+ static let prepareStep = "Set up compatibility tool"
- static func activate(
+ static func prepare(
_ build: RunnerBuild,
runners: URL = SupportPaths.runners,
bridge: URL = SupportPaths.bridge,
+ toolList: URL = SupportPaths.toolList,
+ compatTools: URL = SupportPaths.Steam.compatTools,
license: (URL) -> CrossOverLicense.Status = { CrossOverLicense.check(crossOverRoot: $0) },
verify: (RunnerBuild, URL) throws -> Void = RunnerInstaller.verifyClone,
stage: (RunnerBuild, URL, URL) throws -> [WineArch] = {
@@ -58,7 +61,7 @@ enum RunnerSetup {
) throws -> Outcome {
guard RunnerInstaller.hasClone(forBuild: build.id, runners: runners) else {
throw StepFailure(
- step: switchStep, detail: "Build \(build.displayVersion) has not been set up."
+ step: prepareStep, detail: "Build \(build.displayVersion) has not been set up."
)
}
@@ -69,29 +72,17 @@ enum RunnerSetup {
}
try verify(build, root)
- let saved = try NtdllPatcher.snapshot(bridge: bridge)
- do {
- report(.staging)
- let staged = try stage(build, root, bridge)
+ report(.staging)
+ let staged = try stage(build, root, bridge)
- report(.patching)
- let installed = try patch(build, root, bridge)
- try RunnerInstaller.pointCurrent(atBuild: build.id, runners: runners)
+ report(.patching)
+ var outcome = Outcome(build: build, staged: staged, installed: try patch(build, root, bridge))
+ outcome.toolsChanged = try CompatToolList.sync(
+ runners: runners, bridge: bridge, file: toolList, compatTools: compatTools
+ )
- report(.finished)
- return Outcome(build: build, staged: staged, installed: installed)
- } catch {
- do {
- try NtdllPatcher.restore(saved, bridge: bridge)
- } catch let restorationError {
- throw StepFailure(
- step: switchStep,
- detail: "\(error.localizedDescription) Restoring the previous build also failed: "
- + restorationError.localizedDescription
- )
- }
- throw error
- }
+ report(.finished)
+ return outcome
}
}
diff --git a/app/Sources/NotProtonApp/Model/RunnerStore.swift b/app/Sources/NotProtonApp/Model/RunnerStore.swift
index d8d2ee7..e9c60e3 100644
--- a/app/Sources/NotProtonApp/Model/RunnerStore.swift
+++ b/app/Sources/NotProtonApp/Model/RunnerStore.swift
@@ -4,15 +4,14 @@ import Foundation
enum RunnerState: Sendable, Equatable {
case none
- case cloned(build: String, supported: Bool)
- case bundleShaped(build: String)
+ case ready(builds: [String])
case unpatched(build: String, problems: [String])
- case broken(detail: String)
- var buildIdentifier: String? {
+ var builds: [String] {
switch self {
- case .cloned(let build, _), .bundleShaped(let build), .unpatched(let build, _): build
- case .none, .broken: nil
+ case .none: []
+ case .ready(let builds): builds
+ case .unpatched(let build, _): [build]
}
}
}
@@ -25,51 +24,14 @@ enum RunnerStore {
RunnerPatcher.verify(build: $0, root: $1)
}
) -> RunnerState {
- let fm = FileManager.default
- let current = runners.appending(path: "current")
- let currentPath = current.path(percentEncoded: false)
-
- guard let attributes = try? fm.attributesOfItem(atPath: currentPath),
- attributes[.type] as? FileAttributeType == .typeSymbolicLink
- else {
- if fm.fileExists(atPath: currentPath) {
- return .broken(detail: "runners/current is not a symlink.")
- }
- return .none
- }
-
- guard let target = try? fm.destinationOfSymbolicLink(atPath: currentPath) else {
- return .broken(detail: "runners/current cannot be read.")
- }
-
- let resolved = current.deletingLastPathComponent().appending(path: target).standardizedFileURL
- guard fm.fileExists(atPath: resolved.appending(path: "lib/wine").path(percentEncoded: false)) else {
- return .broken(detail: "runners/current points at \(target), which has no lib/wine.")
- }
-
- guard let build = buildIdentifier(inPath: target) else {
- return .broken(detail: "runners/current points at \(target), which has no recognisable build.")
- }
-
- if target.split(separator: "/").contains(where: { $0.hasSuffix(".app") }) {
- return .bundleShaped(build: build)
- }
+ let installed = installedBuilds(in: runners)
+ guard !installed.isEmpty else { return .none }
- guard let supported = SupportedRunners.build(id: build) else {
- return .cloned(build: build, supported: false)
+ for build in installed {
+ let problems = verify(build, SupportPaths.clonedRoot(forBuild: build.id, runners: runners))
+ if !problems.isEmpty { return .unpatched(build: build.id, problems: problems) }
}
-
- let problems = verify(supported, resolved)
- guard problems.isEmpty else { return .unpatched(build: build, problems: problems) }
-
- return .cloned(build: build, supported: true)
- }
-
- static func buildIdentifier(inPath path: String) -> String? {
- for component in path.split(separator: "/") where component.hasPrefix("crossover-") {
- return String(component.dropFirst("crossover-".count))
- }
- return nil
+ return .ready(builds: installed.map(\.id))
}
static func clonedBuilds(in runners: URL = SupportPaths.runners) -> [String] {
@@ -112,15 +74,95 @@ enum RunnerStore {
return total
}
- static func currentBuild(runners: URL = SupportPaths.runners) -> String? {
- let current = runners.appending(path: "current").path(percentEncoded: false)
- return (try? FileManager.default.destinationOfSymbolicLink(atPath: current))
- .flatMap(buildIdentifier(inPath:))
- }
-
static func installedBuilds(in runners: URL = SupportPaths.runners) -> [RunnerBuild] {
clonedBuilds(in: runners)
.compactMap(SupportedRunners.build(id:))
.filter { RunnerInstaller.hasClone(forBuild: $0.id, runners: runners) }
}
}
+
+enum CompatToolList {
+
+ static func contents(_ tools: [InstalledTool]) -> String {
+ tools.map { "\($0.name)\t\($0.build)\t\($0.tool.flavor.rawValue)\t\($0.display)\n" }.joined()
+ }
+
+ static func installed(
+ runners: URL = SupportPaths.runners, file: URL = SupportPaths.toolList
+ ) -> [InstalledTool] {
+ resolved(runners: runners, file: file).tools
+ }
+
+ // legacyHolder reads runners/current, so this has to run before prune deletes that symlink.
+ private static func resolved(
+ runners: URL, file: URL
+ ) -> (builds: [RunnerBuild], listed: String?, tools: [InstalledTool]) {
+ let builds = RunnerStore.installedBuilds(in: runners)
+ let listed = try? String(contentsOf: file, encoding: .utf8)
+ let holder = legacyHolder(builds: builds, listed: listed, runners: runners)
+ return (builds, listed, SupportedRunners.tools(for: builds, legacy: holder))
+ }
+
+ // 1.0/1.0.1 used the single 'notproton' tool name and wrote no tool list, so the
+ // runners/current symlink is the record of which version of CrossOver was deployed.
+ static func legacyHolder(
+ builds: [RunnerBuild], listed: String?, runners: URL = SupportPaths.runners
+ ) -> SupportedRunners.LegacyHolder {
+ let ids = Set(builds.map(\.id))
+ let rows = (listed ?? "").split(separator: "\n").map { $0.split(separator: "\t").map(String.init) }
+ .filter { $0.count > 1 && ids.contains($0[1]) && SupportedRunners.legacyHolders.contains($0[1]) }
+ if let held = rows.first(where: { $0[0] == SupportedRunners.legacyToolName }) {
+ return .build(held[1])
+ }
+ if !rows.isEmpty { return .nobody }
+ let link = runners.appending(path: "current").path(percentEncoded: false)
+ if let target = try? FileManager.default.destinationOfSymbolicLink(atPath: link),
+ let id = target.split(separator: "/").first(where: { $0.hasPrefix("crossover-") })
+ .map({ String($0.dropFirst("crossover-".count)) }),
+ ids.contains(id), SupportedRunners.legacyHolders.contains(id) {
+ return .build(id)
+ }
+ return .preferred
+ }
+
+ // Returns true when the list file changed.
+ @discardableResult
+ static func sync(
+ runners: URL = SupportPaths.runners,
+ bridge: URL = SupportPaths.bridge,
+ file: URL = SupportPaths.toolList,
+ compatTools: URL = SupportPaths.Steam.compatTools
+ ) throws -> Bool {
+ let (builds, listed, tools) = resolved(runners: runners, file: file)
+ prune(keeping: Set(builds.map(\.id)), runners: runners, bridge: bridge, compatTools: compatTools)
+
+ let text = contents(tools)
+ if listed == text || (listed == nil && text.isEmpty) { return false }
+ try FileManager.default.createDirectory(
+ at: file.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+ try atomicReplace(file, with: Data(text.utf8), step: "Update compatibility tools")
+ return true
+ }
+
+ private static func prune(
+ keeping ids: Set<String>, runners: URL, bridge: URL, compatTools: URL
+ ) {
+ let legacyInUse = legacyLayoutInUse(compatTools: compatTools)
+ NtdllPatcher.pruneBuilds(keeping: ids, in: bridge, keepingLegacy: legacyInUse)
+ guard !legacyInUse else { return }
+ let legacy = runners.appending(path: "current").path(percentEncoded: false)
+ if (try? FileManager.default.destinationOfSymbolicLink(atPath: legacy)) != nil {
+ try? FileManager.default.removeItem(atPath: legacy)
+ }
+ }
+
+ // Old run scripts read runners/current and bridge/wine/<arch>. Steam keeps running them
+ // until it restarts, so those paths have to keep working until then.
+ static func legacyLayoutInUse(compatTools: URL = SupportPaths.Steam.compatTools) -> Bool {
+ SupportPaths.Steam.notprotonTools(in: compatTools).contains { tool in
+ let run = try? String(contentsOf: tool.appending(path: "run"), encoding: .utf8)
+ return run?.contains("/runners/current") == true
+ }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/SupportedRunner.swift b/app/Sources/NotProtonApp/Model/SupportedRunner.swift
index 07eb551..deaf3d7 100644
--- a/app/Sources/NotProtonApp/Model/SupportedRunner.swift
+++ b/app/Sources/NotProtonApp/Model/SupportedRunner.swift
@@ -28,6 +28,8 @@ struct RunnerBuild: Sendable, Equatable, Identifiable {
let cleanNtdll: [WineArch: String]
let patchedNtdll: [WineArch: String]
+ var tools: [CompatTool] = []
+
var id: String { flavor.map { "\(bundleVersion)-\($0)" } ?? bundleVersion }
var flavorName: String { flavor?.uppercased() ?? "Rosetta" }
@@ -35,9 +37,89 @@ struct RunnerBuild: Sendable, Equatable, Identifiable {
var displayVersion: String { "\(releaseVersion) \(flavorName)" }
}
+struct CompatTool: Sendable, Hashable, Identifiable {
+ enum Flavor: String, Sendable {
+ case fex
+ case rosetta
+ }
+
+ let name: String
+ let flavor: Flavor
+ let display: String
+
+ var id: String { name }
+
+ var prefixArch: PrefixArch { flavor == .fex ? .arm64 : .x86_64 }
+}
+
+struct InstalledTool: Sendable, Hashable, Identifiable {
+ let tool: CompatTool
+ let build: String
+
+ var id: String { tool.name }
+ var name: String { tool.name }
+ var display: String { tool.display }
+}
+
enum SupportedRunners {
+ // First entry is what windows-only games get when Steam has no mapping.
+ static let toolPreference = [
+ legacyToolName, "notproton-fex", "notproton-fex-rosetta", "notproton-preview", "notproton-26.3",
+ ]
+
+ static let legacyToolName = "notproton"
+
+ // The only builds that can own the 'notproton' tool name.
+ static let legacyHolders = ["27.0.0.40921-fex", "27.0.0.40921"]
+
+ enum LegacyHolder: Equatable, Sendable {
+ case preferred
+ case build(String)
+ case nobody
+ }
+
+ static func tools(for builds: [RunnerBuild], legacy: LegacyHolder = .preferred) -> [InstalledTool] {
+ let installed = Set(builds.map(\.id))
+ let holder: String? = switch legacy {
+ case .preferred: legacyHolders.first(where: installed.contains)
+ case .build(let id): id
+ case .nobody: nil
+ }
+ let served = all.filter { installed.contains($0.id) }.flatMap { build in
+ build.tools.enumerated().map { index, tool in
+ let name = build.id == holder && index == 0 ? legacyToolName : tool.name
+ return InstalledTool(
+ tool: CompatTool(name: name, flavor: tool.flavor, display: tool.display), build: build.id
+ )
+ }
+ }
+ func rank(_ tool: InstalledTool) -> Int {
+ toolPreference.firstIndex(of: tool.name) ?? toolPreference.count
+ }
+ return served.enumerated()
+ .sorted { (rank($0.element), $0.offset) < (rank($1.element), $1.offset) }
+ .map(\.element)
+ }
+
static let all: [RunnerBuild] = [
+ RunnerBuild(
+ bundleVersion: "26.3.0.39832",
+ releaseVersion: "26.3",
+ flavor: nil,
+ loaderSHA256: "b5edb0444b5b25ba0aa5091be1cba11680130895c338cc8044101bce98802a63",
+ cleanNtdll: [
+ .x86_64Windows: "6dff64c00793ce92124f1316985c63783f539f26b392975c70f57637458d2387",
+ .i386Windows: "2c60ee6b00dd13b7f6cb11017778a041ba6a321eaea194f1fa0dca7eab8403e2",
+ ],
+ patchedNtdll: [
+ .x86_64Windows: "c0e21a9a5250f0a97c08d3c3e1798566255387213e2553b1e555264fb9ded97e",
+ .i386Windows: "e641d7b2e81ee13877823494679ba2d87e0d61b8a87e8a1ce92b4fe73631ae74",
+ ],
+ tools: [
+ CompatTool(name: "notproton-26.3", flavor: .rosetta, display: "CrossOver 26.3"),
+ ]
+ ),
RunnerBuild(
bundleVersion: "27.0.0.40921",
releaseVersion: "20260821",
@@ -50,6 +132,9 @@ enum SupportedRunners {
patchedNtdll: [
.x86_64Windows: "b6a98622fb8f7e6a998bc038f442b17d257da3df5e9e135f0c35f7bbc46ea5d6",
.i386Windows: "25bfde1f50ee96485763968ef10b9d9ad35e38214232f17ebdc009b098af44a0",
+ ],
+ tools: [
+ CompatTool(name: "notproton-preview", flavor: .rosetta, display: "CrossOver Preview (Rosetta-only version)"),
]
),
RunnerBuild(
@@ -66,6 +151,10 @@ enum SupportedRunners {
.x86_64Windows: "fa8cd8fe7c4c19effade92d55b00fa946b630ab13cbb6721076848238c1dcf6a",
.i386Windows: "e799ea02418294588ee353a90b967358be316a3044ff9515b28aa1ce07e63981",
.aarch64Windows: "f40810193a5ef2520774288f354a8604f5ba91828315f643b3ee6688b873dc3f",
+ ],
+ tools: [
+ CompatTool(name: "notproton-fex", flavor: .fex, display: "CrossOver Preview (FEX)"),
+ CompatTool(name: "notproton-fex-rosetta", flavor: .rosetta, display: "CrossOver Preview (Rosetta)"),
]
),
]
diff --git a/app/Sources/NotProtonApp/Model/Uninstall.swift b/app/Sources/NotProtonApp/Model/Uninstall.swift
index 5272a4a..fd6d916 100644
--- a/app/Sources/NotProtonApp/Model/Uninstall.swift
+++ b/app/Sources/NotProtonApp/Model/Uninstall.swift
@@ -39,7 +39,7 @@ enum Uninstall {
innerPlist: URL = SupportPaths.Steam.innerInfoPlist,
updateBlocks: [URL] = UpdateBlock.paths,
legacyCompat: URL = SupportPaths.Steam.legacyCompat,
- compatTool: URL = SupportPaths.Steam.compatTool,
+ compatTools: [URL] = SupportPaths.Steam.notprotonTools(),
directories: [URL] = [
SupportPaths.support,
SupportPaths.packageDownloads.deletingLastPathComponent(),
@@ -63,7 +63,7 @@ enum Uninstall {
report(.removing)
let removed = try remove(
- legacyCompat: legacyCompat, compatTool: compatTool, directories: directories
+ legacyCompat: legacyCompat, compatTools: compatTools, directories: directories
)
report(.finished)
@@ -106,11 +106,11 @@ enum Uninstall {
return true
}
- static func remove(legacyCompat: URL, compatTool: URL, directories: [URL]) throws -> [String] {
+ static func remove(legacyCompat: URL, compatTools: [URL], directories: [URL]) throws -> [String] {
let files = FileManager.default
var removed: [String] = []
- for target in [legacyCompat, compatTool] + directories {
+ for target in [legacyCompat] + compatTools + directories {
let path = target.path(percentEncoded: false)
guard files.fileExists(atPath: path) else { continue }
try WriteRefused.catching(path) { try files.removeItem(at: target) }
diff --git a/app/Sources/NotProtonApp/PrefixesModel.swift b/app/Sources/NotProtonApp/PrefixesModel.swift
index 2efd311..914ad17 100644
--- a/app/Sources/NotProtonApp/PrefixesModel.swift
+++ b/app/Sources/NotProtonApp/PrefixesModel.swift
@@ -11,12 +11,20 @@ final class PrefixesModel {
private(set) var prefixes: [WinePrefix] = []
private(set) var usage: [String: PrefixUsage] = [:]
private(set) var isLoading = false
- private(set) var arch: [String: PrefixArch] = [:]
- private(set) var expectedArch: PrefixArch = .arm64
+ private(set) var records: [String: PrefixBuildRecord] = [:]
+ private(set) var tools: [InstalledTool] = []
- func isForeign(_ prefix: WinePrefix) -> Bool {
- guard let built = arch[prefix.id] else { return false }
- return built != expectedArch
+ private(set) var stale: Set<String> = []
+
+ // True when no installed compatibility tool matches the version of CrossOver that last
+ // booted the prefix.
+ func isStale(_ prefix: WinePrefix) -> Bool {
+ stale.contains(prefix.id)
+ }
+
+ func lastTool(_ prefix: WinePrefix) -> String? {
+ guard let record = records[prefix.id] else { return nil }
+ return record.display ?? SupportedRunners.displayVersion(forID: record.build)
}
private(set) var hasLoaded = false
@@ -38,7 +46,7 @@ final class PrefixesModel {
enum Confirmation: Equatable {
case delete([WinePrefix])
- case rebuild([WinePrefix])
+ case rebuild([WinePrefix], InstalledTool)
case backUp([WinePrefix])
case deleteBackups([PrefixBackup])
}
@@ -53,22 +61,22 @@ final class PrefixesModel {
}
private let libraries: @Sendable () -> [SteamLibrary]
- private let runnerArch: @Sendable () -> PrefixArch
- private let rebuild: @Sendable (WinePrefix, Bool) throws -> URL?
+ private let installedTools: @Sendable () -> [InstalledTool]
+ private let rebuild: @Sendable (WinePrefix, InstalledTool, Bool) throws -> URL?
private let makeBackup: @Sendable (WinePrefix) throws -> URL
init(
libraries: @escaping @Sendable () -> [SteamLibrary] = { PrefixStore.libraries() },
- runnerArch: @escaping @Sendable () -> PrefixArch = { PrefixTools.prefixArch() },
- rebuild: @escaping @Sendable (WinePrefix, Bool) throws -> URL? = {
- try PrefixTools.recreate($0, keepBackup: $1)
+ installedTools: @escaping @Sendable () -> [InstalledTool] = { CompatToolList.installed() },
+ rebuild: @escaping @Sendable (WinePrefix, InstalledTool, Bool) throws -> URL? = {
+ try PrefixTools.recreate($0, as: $1, keepBackup: $2)
},
makeBackup: @escaping @Sendable (WinePrefix) throws -> URL = {
try PrefixTools.backUp($0)
}
) {
self.libraries = libraries
- self.runnerArch = runnerArch
+ self.installedTools = installedTools
self.rebuild = rebuild
self.makeBackup = makeBackup
}
@@ -85,11 +93,17 @@ final class PrefixesModel {
guard run == loadGeneration else { return }
prefixes = found
usage = [:]
- expectedArch = runnerArch()
- arch = await Task.detached {
- found.reduce(into: [String: PrefixArch]()) { built, prefix in
- if let found = PrefixStore.arch(of: prefix) { built[prefix.id] = found }
+ let listTools = installedTools
+ (tools, records, stale) = await Task.detached {
+ let tools = listTools()
+ var records: [String: PrefixBuildRecord] = [:]
+ var stale = Set<String>()
+ for prefix in found {
+ guard let record = PrefixTools.lastBuild(of: prefix) else { continue }
+ records[prefix.id] = record
+ if PrefixTools.tool(for: prefix, among: tools) == nil { stale.insert(prefix.id) }
}
+ return (tools, records, stale)
}.value
guard run == loadGeneration else { return }
selection = selection.filter { id in found.contains { $0.id == id } }
@@ -143,9 +157,16 @@ final class PrefixesModel {
}
}
- func recreate(_ targets: [WinePrefix], keepBackup: Bool = true) async {
+ @discardableResult
+ func confirmRebuild(keepBackup: Bool = true) -> Task<Void, Never>? {
+ guard case .rebuild(let targets, let tool) = pendingConfirmation else { return nil }
+ pendingConfirmation = nil
+ return Task { await recreate(targets, as: tool, keepBackup: keepBackup) }
+ }
+
+ func recreate(_ targets: [WinePrefix], as tool: InstalledTool, keepBackup: Bool = true) async {
let make = rebuild
- await eachInTurn(targets, { try make($0, keepBackup) }) { rebuilt in
+ await eachInTurn(targets, { try make($0, tool, keepBackup) }) { rebuilt in
let kept = rebuilt.compactMap(\.made)
if rebuilt.count == 1 {
let title = rebuilt[0].prefix.title
diff --git a/app/Sources/NotProtonApp/Resources/detour2-cx26.bin b/app/Sources/NotProtonApp/Resources/detour2-cx26.bin
new file mode 100755
index 0000000..c5ac7a3
Binary files /dev/null and b/app/Sources/NotProtonApp/Resources/detour2-cx26.bin differ
diff --git a/app/Sources/NotProtonApp/Resources/detour32-cx26.bin b/app/Sources/NotProtonApp/Resources/detour32-cx26.bin
new file mode 100755
index 0000000..86eafd5
Binary files /dev/null and b/app/Sources/NotProtonApp/Resources/detour32-cx26.bin differ
diff --git a/app/Sources/NotProtonApp/Support/AppLog.swift b/app/Sources/NotProtonApp/Support/AppLog.swift
index 5a71a9a..cc378f9 100644
--- a/app/Sources/NotProtonApp/Support/AppLog.swift
+++ b/app/Sources/NotProtonApp/Support/AppLog.swift
@@ -75,11 +75,9 @@ enum AppLog {
private static func describe(_ runner: RunnerState) -> String {
switch runner {
case .none: "not set up"
- case .cloned(let build, let supported): "cloned \(build) supported=\(supported)"
- case .bundleShaped(let build): "cloned \(build) in an .app"
+ case .ready(let builds): "ready \(builds.joined(separator: ", "))"
case .unpatched(let build, let problems):
"cloned \(build) unpatched: \(problems.joined(separator: ", "))"
- case .broken(let detail): "broken: \(detail)"
}
}
diff --git a/app/Sources/NotProtonApp/Support/SupportPaths.swift b/app/Sources/NotProtonApp/Support/SupportPaths.swift
index d6adbc4..c7724f9 100644
--- a/app/Sources/NotProtonApp/Support/SupportPaths.swift
+++ b/app/Sources/NotProtonApp/Support/SupportPaths.swift
@@ -39,7 +39,7 @@ enum SupportPaths {
static var deployedVersion: URL { support.appending(path: "dylib.version") }
- static var currentRunner: URL { runners.appending(path: "current") }
+ static var toolList: URL { support.appending(path: "tools") }
static func runnerRoot(forBuild build: String, runners: URL = SupportPaths.runners) -> URL {
runners.appending(path: "crossover-\(build)")
@@ -81,8 +81,13 @@ enum SupportPaths {
static var innerConfigFile: URL { innerClient.appending(path: "steam.cfg") }
static var legacyCompat: URL { innerClient.appending(path: "legacycompat") }
- static var compatTool: URL {
- userData.appending(path: "compatibilitytools.d/notproton")
+ static var compatTools: URL { userData.appending(path: "compatibilitytools.d") }
+
+ static func notprotonTools(in directory: URL = compatTools) -> [URL] {
+ let entries = (try? FileManager.default.contentsOfDirectory(
+ at: directory, includingPropertiesForKeys: nil
+ )) ?? []
+ return entries.filter { $0.lastPathComponent.hasPrefix("notproton") }
}
static var libraryFoldersVDF: URL { userData.appending(path: "steamapps/libraryfolders.vdf") }
diff --git a/app/Sources/NotProtonApp/SystemStatus.swift b/app/Sources/NotProtonApp/SystemStatus.swift
index 19cf1e5..13c2b12 100644
--- a/app/Sources/NotProtonApp/SystemStatus.swift
+++ b/app/Sources/NotProtonApp/SystemStatus.swift
@@ -33,6 +33,7 @@ struct StatusSnapshot: Sendable {
}
let runner = RunnerStore.state()
+ let installed = RunnerStore.installedBuilds()
return StatusSnapshot(
steam: SteamBundle.deployment(bundledVersion: bundledVersion),
@@ -41,10 +42,8 @@ struct StatusSnapshot: Sendable {
crossOver: installs,
crossOverLicense: licenses,
runner: runner,
- payload: PayloadInspector.inspect(
- build: runner.buildIdentifier.flatMap(SupportedRunners.build(id:))
- ),
- installedRunners: RunnerStore.installedBuilds(),
+ payload: PayloadInspector.inspect(builds: installed),
+ installedRunners: installed,
orphanedRunners: RunnerStore.orphanedClones(),
damagedRunners: RunnerStore.damagedClones()
)
@@ -133,48 +132,34 @@ final class SystemStatus {
snapshot?.crossOver.filter(\.isUsable) ?? []
}
- var crossOverRowsOfferSetUp: Bool {
- let usable = usableCrossOvers
- guard usable.count > 1 else { return false }
- let installed = snapshot?.installedRunners ?? []
- return usable.contains { install in
- if case .supported(let build) = install.support { return !installed.contains(build) }
- return false
- }
- }
-
- struct AvailableBuild: Identifiable {
- let install: CrossOverInstall
- let build: RunnerBuild
-
- var id: String { build.id }
+ var crossOverRows: [CrossOverRow] {
+ guard let snapshot else { return [] }
+ var unpatched: String?
+ if case .unpatched(let build, _) = snapshot.runner { unpatched = build }
+ return CrossOverRow.rows(
+ installs: snapshot.crossOver,
+ licenses: snapshot.crossOverLicense,
+ installed: snapshot.installedRunners,
+ damaged: snapshot.damagedRunners,
+ orphaned: snapshot.orphanedRunners,
+ unpatched: unpatched
+ )
}
var repairSource: CrossOverInstall? {
- let current = snapshot?.runner.buildIdentifier
- return usableCrossOvers.first { install in
- if case .supported(let build) = install.support { return build.id == current }
- return false
+ let builds = snapshot?.runner.builds ?? []
+ for wanted in builds {
+ let found = usableCrossOvers.first { install in
+ if case .supported(let build) = install.support { return build.id == wanted }
+ return false
+ }
+ if let found { return found }
}
+ return nil
}
var setupSource: CrossOverInstall? { repairSource ?? usableCrossOver }
- var setupSourceIsDeployed: Bool {
- guard case .supported(let build)? = setupSource?.support else { return false }
- return snapshot?.installedRunners.contains(build) ?? false
- }
-
- var availableBuilds: [AvailableBuild] {
- let installed = snapshot?.installedRunners ?? []
- guard !installed.isEmpty else { return [] }
- return usableCrossOvers.compactMap { install in
- guard case .supported(let build) = install.support,
- !installed.contains(build) else { return nil }
- return AvailableBuild(install: install, build: build)
- }
- }
-
func checkLicense(for chosen: CrossOverInstall? = nil) async -> CrossOverLicense.Status? {
guard let install = chosen ?? usableCrossOver else { return nil }
let status = await Task.detached(priority: .userInitiated) {
@@ -248,34 +233,21 @@ final class SystemStatus {
guard let build = pendingRemoval else { return }
pendingRemoval = nil
await perform(from: RunnerInstaller.removeStep) { _ in
- try await Task.detached(priority: .userInitiated) {
+ let changed = try await Task.detached(priority: .userInitiated) {
try RunnerInstaller.removeClone(forBuild: build)
}.value
- return "Removed build \(SupportedRunners.displayVersion(forID: build))."
+ let removed = "Removed build \(SupportedRunners.displayVersion(forID: build))."
+ return changed && SteamBundle.isRunning ? "\(removed) \(Self.toolsRestartHint)" : removed
}
}
- func switchRunner(to build: RunnerBuild) async {
- guard isIdle else { return }
- guard build.id != snapshot?.runner.buildIdentifier else { return }
- await perform(from: RunnerSetup.Phase.staging.label) { progress in
- let result = try await Task.detached(priority: .userInitiated) {
- try RunnerSetup.activate(build, report: { progress($0.label) })
- }.value
- return "Now using build \(result.build.displayVersion)."
- }
- }
-
- var chosenCrossOver: URL? { CrossOverSource.manualBundle }
-
- // Lets the user pick a copy of CrossOver the search did not find/auto-select
- func chooseCrossOver() async {
+ func addCrossOver() async {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
panel.allowedContentTypes = [.application]
- panel.prompt = "Choose"
+ panel.prompt = "Add"
panel.message = "Select a copy of CrossOver."
panel.directoryURL = URL(filePath: "/Applications", directoryHint: .isDirectory)
@@ -290,21 +262,31 @@ final class SystemStatus {
return
}
- CrossOverSource.manualBundle = picked
- AppLog.note("crossOver choice: \(picked.path(percentEncoded: false))")
+ let found = snapshot?.crossOver.contains {
+ $0.bundle.standardizedFileURL == picked.standardizedFileURL
+ } ?? false
+ if !found {
+ CrossOverSource.addManualBundle(picked)
+ AppLog.note("crossOver added: \(picked.path(percentEncoded: false))")
+ }
await refresh()
}
- func clearCrossOverChoice() async {
+ func removeFromList(_ install: CrossOverInstall) async {
+ guard isIdle else { return }
clearFailure()
outcome = nil
- CrossOverSource.manualBundle = nil
- AppLog.note("crossOver choice cleared")
+ CrossOverSource.removeManualBundle(install.bundle)
+ AppLog.note("crossOver removed from list: \(install.id)")
await refresh()
}
+ private static let toolsRestartHint = "Restart Steam to update its list of compatibility tools."
+
private func runnerOutcome(_ result: RunnerSetup.Outcome) -> String {
- result.stagedNothing ? "Compatibility tool is already set up." : "Compatibility tool ready."
+ if result.stagedNothing { return "Compatibility tool is already set up." }
+ guard result.toolsChanged, SteamBundle.isRunning else { return "Compatibility tool ready." }
+ return "Compatibility tool ready. \(Self.toolsRestartHint)"
}
func perform(
@@ -442,7 +424,15 @@ final class SystemStatus {
let version = AppVersion.bundled
let captured = await Task.detached(priority: .userInitiated) {
- StatusSnapshot.capture(bundledVersion: version)
+ do {
+ if try CompatToolList.sync() { AppLog.note("tool list rewritten") }
+ } catch {
+ AppLog.note("tool list not written: \(error.localizedDescription)")
+ }
+ for failure in NtdllPatcher.stageInstalled() {
+ AppLog.note("ntdll for \(failure.build) not staged: \(failure.error.localizedDescription)")
+ }
+ return StatusSnapshot.capture(bundledVersion: version)
}.value
snapshot = captured
AppLog.note(captured)
diff --git a/app/Sources/NotProtonApp/Views/PrefixesView.swift b/app/Sources/NotProtonApp/Views/PrefixesView.swift
index 4867eed..c2c766d 100644
--- a/app/Sources/NotProtonApp/Views/PrefixesView.swift
+++ b/app/Sources/NotProtonApp/Views/PrefixesView.swift
@@ -73,20 +73,16 @@ struct PrefixesView: View {
Text(PrefixPrompt.deleteMessage(deleting))
}
.confirmationDialog(
- PrefixPrompt.rebuildTitle(rebuilding),
+ PrefixPrompt.rebuildTitle(rebuilding, for: rebuildTool),
isPresented: asking(.rebuild),
titleVisibility: .visible
) {
Button(PrefixPrompt.rebuildWithBackupButton(rebuilding)) {
- let targets = rebuilding
- model.pendingConfirmation = nil
- Task { await model.recreate(targets) }
+ model.confirmRebuild()
}
.keyboardShortcut(.defaultAction)
Button(PrefixPrompt.rebuildWithoutBackupButton(rebuilding)) {
- let targets = rebuilding
- model.pendingConfirmation = nil
- Task { await model.recreate(targets, keepBackup: false) }
+ model.confirmRebuild(keepBackup: false)
}
Button("Cancel", role: .cancel) { model.pendingConfirmation = nil }
} message: {
@@ -119,10 +115,15 @@ struct PrefixesView: View {
}
private var rebuilding: [WinePrefix] {
- if case .rebuild(let targets) = model.pendingConfirmation { return targets }
+ if case .rebuild(let targets, _) = model.pendingConfirmation { return targets }
return []
}
+ private var rebuildTool: InstalledTool? {
+ if case .rebuild(_, let tool) = model.pendingConfirmation { return tool }
+ return nil
+ }
+
private var backingUp: [WinePrefix] {
if case .backUp(let targets) = model.pendingConfirmation { return targets }
return []
@@ -131,7 +132,7 @@ struct PrefixesView: View {
private func isAsking(_ question: Question) -> Bool {
switch (question, model.pendingConfirmation) {
case (.delete, .delete): true
- case (.rebuild, .rebuild): true
+ case (.rebuild, .rebuild(_, _)): true
case (.backUp, .backUp): true
default: false
}
@@ -177,6 +178,10 @@ struct PrefixesView: View {
TextWidth.widest(model.prefixes.map(\.library.displayName)) ?? 120
}
+ private var toolWidth: CGFloat {
+ TextWidth.widest(model.prefixes.compactMap(model.lastTool)) ?? 60
+ }
+
private var lastUsedWidth: CGFloat {
TextWidth.widest(model.prefixes.map(lastUsed)) ?? 110
}
@@ -184,7 +189,7 @@ struct PrefixesView: View {
private var gameWidth: CGFloat {
let widths = model.prefixes.map { prefix -> CGFloat in
var width = TextWidth.of(prefix.title)
- if model.isForeign(prefix) { width += 22 }
+ if model.isStale(prefix) { width += 22 }
if prefix.name == nil {
width += TextWidth.of("No longer installed", size: NSFont.smallSystemFontSize) + 6
}
@@ -199,18 +204,20 @@ struct PrefixesView: View {
return Table(model.prefixes, selection: $model.selection) {
TableColumn("Game") { prefix in
HStack(spacing: 6) {
- if model.isForeign(prefix) {
- Button {
- model.pendingConfirmation = .rebuild([prefix])
+ if model.isStale(prefix) {
+ Menu {
+ rebuildChoices([prefix])
} label: {
Image(systemName: "exclamationmark.circle.fill")
.foregroundStyle(.tint)
}
- .buttonStyle(.borderless)
- .disabled(model.isBusy)
+ .menuStyle(.borderlessButton)
+ .menuIndicator(.hidden)
+ .fixedSize()
+ .disabled(model.isBusy || model.tools.isEmpty)
.help(
- "Built by a different compatibility tool, so the game cannot start. "
- + "Click to rebuild the prefix."
+ "Last run by a build that is no longer set up, so the game cannot "
+ + "start. Click to rebuild the prefix."
)
.accessibilityLabel("Needs rebuilding")
}
@@ -227,6 +234,16 @@ struct PrefixesView: View {
}
.width(min: 60, ideal: gameWidth)
+ TableColumn("Tool") { prefix in
+ if let tool = model.lastTool(prefix) {
+ Text(tool).foregroundStyle(.secondary).help(tool)
+ } else {
+ Text("None")
+ .foregroundStyle(contrast == .increased ? .secondary : .tertiary)
+ }
+ }
+ .width(min: 60, ideal: toolWidth)
+
TableColumn("App ID") { prefix in
Text(prefix.appID).monospacedDigit().foregroundStyle(.secondary)
}
@@ -285,8 +302,10 @@ struct PrefixesView: View {
Button(PrefixPrompt.backUpButton(targets)) {
model.pendingConfirmation = .backUp(targets)
}
- Button(PrefixPrompt.rebuildButton(targets)) {
- model.pendingConfirmation = .rebuild(targets)
+ if model.tools.count > 1 {
+ Menu(PrefixPrompt.rebuildButton(targets)) { rebuildChoices(targets) }
+ } else {
+ rebuildChoices(targets, label: PrefixPrompt.rebuildButton(targets))
}
Button(PrefixPrompt.deleteButton(targets), role: .destructive) {
model.pendingConfirmation = .delete(targets)
@@ -296,6 +315,15 @@ struct PrefixesView: View {
.disabled(model.isBusy)
}
+ @ViewBuilder
+ private func rebuildChoices(_ targets: [WinePrefix], label: String? = nil) -> some View {
+ ForEach(model.tools) { tool in
+ Button(label ?? tool.display) {
+ model.pendingConfirmation = .rebuild(targets, tool)
+ }
+ }
+ }
+
@ViewBuilder
private func toolButtons(for prefix: WinePrefix?) -> some View {
Button("Run Program…") {
diff --git a/app/Sources/NotProtonApp/Views/StatusView.swift b/app/Sources/NotProtonApp/Views/StatusView.swift
index e752e22..70887b3 100644
--- a/app/Sources/NotProtonApp/Views/StatusView.swift
+++ b/app/Sources/NotProtonApp/Views/StatusView.swift
@@ -32,6 +32,7 @@ struct StatusAction {
var role: ButtonRole?
var help: String?
var isEnabled = true
+ var startsGroup = false
let perform: () -> Void
}
@@ -43,15 +44,16 @@ enum StatusMetrics {
struct StatusRow: View {
- @Environment(\.colorSchemeContrast) private var contrast
-
let title: String
var value: String?
var tone: StatusTone?
var detail: String?
+ var trailing: String?
var secondaryAction: StatusAction?
var action: StatusAction?
+ var menu: [StatusAction] = []
+ var toggle: Binding<Bool>?
var body: some View {
HStack(alignment: .center, spacing: 0) {
@@ -76,15 +78,26 @@ struct StatusRow: View {
if let detail {
Text(detail)
.font(.callout)
- .foregroundStyle(contrast == .increased ? .secondary : .tertiary)
+ .foregroundStyle(.secondary)
.textSelection(.enabled)
}
}
}
- if secondaryAction != nil || action != nil {
+ if secondaryAction != nil || action != nil || !menu.isEmpty || toggle != nil || trailing != nil {
Spacer(minLength: 12)
}
+ if let trailing {
+ Text(trailing)
+ .monospacedDigit()
+ .foregroundStyle(.secondary)
+ .padding(.trailing, action == nil && menu.isEmpty ? 0 : 8)
+ }
+ if let toggle {
+ Toggle(title, isOn: toggle)
+ .toggleStyle(.switch)
+ .labelsHidden()
+ }
if let secondaryAction {
button(secondaryAction)
.disabled(!secondaryAction.isEnabled)
@@ -98,9 +111,38 @@ struct StatusRow: View {
.help(action.help ?? "")
.accessibilityLabel("\(action.label), \(title)")
}
+ if !menu.isEmpty {
+ Menu {
+ menuItems(menu, hidingUnavailable: false)
+ } label: {
+ Label("More", systemImage: "ellipsis")
+ .labelStyle(.iconOnly)
+ }
+ .menuStyle(.button)
+ .buttonStyle(.bordered)
+ .menuIndicator(.hidden)
+ .fixedSize()
+ .help("More actions")
+ .accessibilityLabel("More actions, \(title)")
+ .padding(.leading, action == nil ? 0 : 8)
+ }
}
.accessibilityElement(children: .combine)
.padding(.vertical, 2)
+ .contentShape(Rectangle())
+ .contextMenu {
+ menuItems([action, secondaryAction].compactMap { $0 } + menu, hidingUnavailable: true)
+ }
+ }
+
+ @ViewBuilder
+ private func menuItems(_ items: [StatusAction], hidingUnavailable: Bool) -> some View {
+ let shown = hidingUnavailable ? items.filter(\.isEnabled) : items
+ ForEach(Array(shown.enumerated()), id: \.offset) { index, item in
+ if item.startsGroup && index > 0 { Divider() }
+ Button(item.label, role: item.role, action: item.perform)
+ .disabled(!item.isEnabled)
+ }
}
@ViewBuilder
@@ -170,21 +212,18 @@ struct StatusView: View {
)
}
.confirmationDialog(
- "Are you sure?",
+ status.pendingRemoval.map {
+ "Remove the \(SupportedRunners.displayVersion(forID: $0)) copy?"
+ } ?? "",
isPresented: asking(.removeBuild),
titleVisibility: .visible
) {
- Button("Remove", role: .destructive) {
+ Button("Remove Copy", role: .destructive) {
Task { await status.removePendingBuild() }
}
Button("Cancel", role: .cancel) { status.cancelBuildRemoval() }
} message: {
- if let build = status.pendingRemoval {
- Text(
- "Are you sure you want to remove "
- + "\(SupportedRunners.displayVersion(forID: build))?"
- )
- }
+ Text("CrossOver itself is not removed.")
}
.confirmationDialog(
"Remove everything NotProton has created?",
@@ -280,20 +319,15 @@ struct StatusView: View {
}
Section {
- crossOverRows(snapshot)
- runnerRow(snapshot.runner, payload: snapshot.payload)
- if snapshot.installedRunners.count > 1 || !snapshot.orphanedRunners.isEmpty
- || !snapshot.damagedRunners.isEmpty || !status.availableBuilds.isEmpty {
- buildRows(snapshot)
- }
+ crossOverSection(snapshot)
} header: {
- Text("Compatibility Tool")
+ Text("CrossOver")
} footer: {
- if status.usableCrossOvers.count > 1 {
- HStack {
- Spacer()
- crossOverLink
- }
+ HStack {
+ Spacer()
+ Button("Add CrossOver\u{2026}") { Task { await status.addCrossOver() } }
+ .disabled(!status.isIdle)
+ .help("Add a copy of CrossOver from another folder.")
}
}
@@ -393,19 +427,13 @@ struct StatusView: View {
}
private func updateBlockRow(_ blocked: Bool) -> some View {
- Toggle(isOn: blockUpdates) {
- VStack(alignment: .leading, spacing: 2) {
- Text("Block Steam client updates")
- .font(.headline)
- Text(
- blocked
- ? "The Steam client will not update itself."
- : "A Steam client update may break NotProton."
- )
- .foregroundStyle(.secondary)
- }
- .padding(.leading, StatusMetrics.textInset)
- }
+ StatusRow(
+ title: "Block Steam client updates",
+ value: blocked
+ ? "The Steam client will not update itself."
+ : "A Steam client update may break NotProton.",
+ toggle: blockUpdates
+ )
.disabled(!status.isIdle)
.help("Steam client updates may break NotProton.")
}
@@ -424,212 +452,155 @@ struct StatusView: View {
}
@ViewBuilder
- private func crossOverRows(_ snapshot: StatusSnapshot) -> some View {
- let installs = snapshot.crossOver.filter(\.isUsable)
- if !installs.isEmpty {
- ForEach(installs) { install in
- if case .supported(let build) = install.support {
- StatusRow(
- title: install.name,
- value: "Build \(build.displayVersion)",
- tone: snapshot.crossOverLicense[install.id]?.licensed == true ? .ok : .warning,
- detail: install.bundle.path(percentEncoded: false),
- action: installs.count > 1
- ? setUpAction(for: install, build: build, snapshot: snapshot)
- : crossOverAction()
- )
- }
- }
- } else {
+ private func crossOverSection(_ snapshot: StatusSnapshot) -> some View {
+ let rows = status.crossOverRows
+ if rows.isEmpty {
StatusRow(
title: "CrossOver",
value: "Not found. Supported: \(SupportedRunners.versionList).",
- tone: .bad,
- action: crossOverAction()
+ tone: .bad
)
}
- }
-
- private func crossOverAction(chooseLabel: String = "Choose\u{2026}") -> StatusAction {
- if status.chosenCrossOver != nil {
- return StatusAction(
- label: "Use Search",
- help: "Use the default CrossOver.",
- isEnabled: status.isIdle
- ) { Task { await status.clearCrossOverChoice() } }
+ let tools = SupportedRunners.tools(for: snapshot.installedRunners)
+ ForEach(rows) { row in
+ StatusRow(
+ title: row.title,
+ value: crossOverValue(row),
+ tone: crossOverTone(row),
+ detail: crossOverDetail(row, tools: tools),
+ trailing: row.copy == .ready ? buildSize(row.buildID) : nil,
+ action: crossOverAction(row, prominent: snapshot.runner == .none),
+ menu: crossOverMenu(row)
+ )
+ }
+ if case .ready = snapshot.runner, !snapshot.payload.missing(origin: .patched).isEmpty {
+ StatusRow(
+ title: "Compatibility Tool",
+ value: "Patched components are missing.",
+ tone: .warning,
+ action: StatusAction(
+ label: "Repair",
+ isProminent: true,
+ help: "Set up the compatibility tool again.",
+ isEnabled: status.isIdle && status.setupSource != nil
+ ) { Task { await status.requestCompatibilityTool() } }
+ )
}
- return StatusAction(
- label: chooseLabel,
- help: "Pick a CrossOver install.",
- isEnabled: status.isIdle
- ) { Task { await status.chooseCrossOver() } }
}
- @ViewBuilder
- private var crossOverLink: some View {
- let action = crossOverAction(chooseLabel: "Choose Another Copy\u{2026}")
- Button(action.label, action: action.perform)
- .buttonStyle(.link)
- .disabled(!action.isEnabled)
- .help(action.help ?? "")
+ private func crossOverValue(_ row: CrossOverRow) -> String {
+ if let version = row.unsupportedVersion {
+ return "Version \(version) not supported (supported: \(SupportedRunners.versionList))"
+ }
+ let build = "Build \(SupportedRunners.displayVersion(forID: row.buildID))"
+ switch row.copy {
+ case .ready: return build
+ case .none: return build + (row.licensed == false ? ", not set up or activated" : ", not set up")
+ case .unpatched: return build + ", not patched"
+ case .damaged: return build + ", copy damaged"
+ case .unsupported: return build + ", no longer supported"
+ }
}
- private func setUpAction(
- for install: CrossOverInstall, build: RunnerBuild, snapshot: StatusSnapshot
- ) -> StatusAction? {
- guard !snapshot.installedRunners.contains(build) else { return nil }
- return StatusAction(
- label: "Set Up",
- isProminent: snapshot.runner == .none,
- help: "Set up the compatibility tool from \(install.name).",
- isEnabled: status.isIdle
- ) {
- Task { await status.requestCompatibilityTool(from: install) }
+ private func crossOverTone(_ row: CrossOverRow) -> StatusTone {
+ if row.unsupportedVersion != nil { return .neutral }
+ switch row.copy {
+ case .none: return row.licensed == false ? .warning : .neutral
+ case .ready: return .ok
+ case .unpatched, .damaged, .unsupported: return .warning
}
}
- @ViewBuilder
- private func buildRows(_ snapshot: StatusSnapshot) -> some View {
- let active = snapshot.runner.buildIdentifier
- ForEach(SupportedRunners.all) { build in
- if snapshot.installedRunners.contains(build) {
- let isActive = build.id == active
- StatusRow(
- title: build.displayVersion,
- value: isActive ? "Active build." : buildSize(build.id),
- tone: isActive ? .ok : .neutral,
- secondaryAction: isActive ? nil : removeAction(build.id),
- action: isActive ? nil : useAction(build)
- )
- } else if snapshot.damagedRunners.contains(build.id) {
- StatusRow(
- title: build.displayVersion,
- value: "Damaged Copy",
- tone: .warning,
- detail: buildSize(build.id),
- secondaryAction: removeAction(build.id),
- action: status.availableBuilds.first(where: { $0.id == build.id })
- .map(copyAction)
- )
- } else if let available = status.availableBuilds.first(where: { $0.id == build.id }) {
- StatusRow(
- title: build.displayVersion,
- tone: .neutral,
- action: copyAction(available)
- )
- }
+ private func crossOverDetail(_ row: CrossOverRow, tools: [InstalledTool]) -> String? {
+ var lines: [String] = []
+ if row.copy == .ready || row.copy == .unpatched {
+ let names = tools.filter { $0.build == row.buildID }.map(\.display)
+ if !names.isEmpty { lines.append(names.joined(separator: ", ")) }
}
- ForEach(snapshot.orphanedRunners, id: \.self) { build in
- StatusRow(
- title: SupportedRunners.displayVersion(forID: build),
- value: "No longer supported.",
- tone: .warning,
- detail: buildSize(build),
- secondaryAction: removeAction(build)
- )
+ if row.copy == .none, row.licensed == false { lines.append("Open CrossOver to activate it.") }
+ if let install = row.install {
+ var path = install.bundle.path(percentEncoded: false)
+ if path.count > 1, path.hasSuffix("/") { path.removeLast() }
+ lines.append(path)
+ } else if row.copy != .unsupported {
+ lines.append("CrossOver app not found.")
}
+ return lines.isEmpty ? nil : lines.joined(separator: "\n")
}
- private func buildSize(_ build: String) -> String? {
- status.runnerSizes[build].map {
- ByteCountFormatter.string(fromByteCount: $0, countStyle: .file)
+ private func crossOverAction(_ row: CrossOverRow, prominent: Bool) -> StatusAction? {
+ let install = row.install
+ switch row.copy {
+ case .none where row.canSetUp:
+ return StatusAction(
+ label: "Set Up",
+ isProminent: prominent,
+ help: "Copy \(row.title) and set up its compatibility tool.",
+ isEnabled: status.isIdle
+ ) { Task { await status.requestCompatibilityTool(from: install) } }
+ case .unpatched where row.canSetUp, .damaged where row.canSetUp:
+ return StatusAction(
+ label: "Repair",
+ isProminent: true,
+ help: "Copy \(row.title) again.",
+ isEnabled: status.isIdle
+ ) { Task { await status.requestCompatibilityTool(from: install) } }
+ case .unsupported:
+ return removeCopyAction(row.buildID, label: "Remove\u{2026}")
+ default:
+ return nil
}
}
- private func copyAction(_ available: SystemStatus.AvailableBuild) -> StatusAction {
- StatusAction(
- label: "Copy",
- isProminent: true,
- help: "Copy this CrossOver build and use it.",
- isEnabled: status.isIdle
- ) {
- Task { await status.requestCompatibilityTool(from: available.install) }
+ private func crossOverMenu(_ row: CrossOverRow) -> [StatusAction] {
+ var items: [StatusAction] = []
+ let install = row.install
+ if row.copy == .ready {
+ items.append(StatusAction(
+ label: "Reinstall",
+ help: "Copy \(row.title) again.",
+ isEnabled: status.isIdle && row.canSetUp
+ ) { Task { await status.requestCompatibilityTool(from: install, replacingExisting: true) } })
+ }
+ let shown = install?.bundle
+ ?? (row.copy == .none ? nil : SupportPaths.runnerRoot(forBuild: row.buildID))
+ if let shown {
+ items.append(StatusAction(label: "Show in Finder") {
+ NSWorkspace.shared.activateFileViewerSelecting([shown])
+ })
}
+ if [.ready, .unpatched, .damaged].contains(row.copy) {
+ var remove = removeCopyAction(row.buildID, label: "Remove Copy\u{2026}")
+ remove.startsGroup = true
+ items.append(remove)
+ }
+ if let install, row.isManual {
+ items.append(StatusAction(
+ label: "Remove from List",
+ isEnabled: status.isIdle,
+ startsGroup: !items.contains(where: \.startsGroup)
+ ) { Task { await status.removeFromList(install) } })
+ }
+ return items
}
- private func useAction(_ build: RunnerBuild) -> StatusAction {
- StatusAction(
- label: "Use",
- help: "Launch games with this CrossOver build.",
- isEnabled: status.isIdle
- ) {
- Task { await status.switchRunner(to: build) }
+ private func buildSize(_ build: String) -> String? {
+ status.runnerSizes[build].map {
+ ByteCountFormatter.string(fromByteCount: $0, countStyle: .file)
}
}
- private func removeAction(_ build: String) -> StatusAction {
+ private func removeCopyAction(_ build: String, label: String) -> StatusAction {
StatusAction(
- label: "Remove",
+ label: label,
role: .destructive,
- help: "Delete this build from disk.",
+ help: "Delete NotProton's copy of this build.",
isEnabled: status.isIdle
) {
status.requestBuildRemoval(build)
}
}
- private func runnerAction(
- label: String = "Set Up", replacingExisting: Bool = false
- ) -> StatusAction {
- StatusAction(
- label: label,
- isProminent: true,
- help: "Set up the compatibility tool from CrossOver.",
- isEnabled: status.isIdle && status.setupSource != nil
- ) {
- Task { await status.requestCompatibilityTool(replacingExisting: replacingExisting) }
- }
- }
-
- private func runnerRow(_ state: RunnerState, payload: PayloadState) -> some View {
- let patchedMissing = !payload.missing(origin: .patched).isEmpty
-
- switch state {
- case .none:
- return StatusRow(
- title: "Compatibility Tool",
- value: "Not set up.",
- tone: .neutral,
- action: status.crossOverRowsOfferSetUp ? nil : runnerAction()
- )
- case .cloned(let build, let supported):
- let satisfied = supported && !patchedMissing
- let deployed = status.setupSourceIsDeployed
- return StatusRow(
- title: "Compatibility Tool",
- value: "Build \(SupportedRunners.displayVersion(forID: build))"
- + (supported ? "" : " (unsupported)"),
- tone: satisfied ? .ok : .warning,
- action: satisfied
- ? runnerAction(
- label: deployed ? "Copy Again" : "Copy", replacingExisting: true
- )
- : runnerAction()
- )
- case .unpatched(let build, _):
- return StatusRow(
- title: "Compatibility Tool",
- value: "Build \(SupportedRunners.displayVersion(forID: build)), not patched.",
- tone: .warning,
- action: runnerAction()
- )
- case .bundleShaped(let build):
- return StatusRow(
- title: "Compatibility Tool",
- value: "Build \(SupportedRunners.displayVersion(forID: build)), needs re-setup.",
- tone: .warning,
- action: runnerAction()
- )
- case .broken:
- return StatusRow(
- title: "Compatibility Tool",
- value: "Unusable.",
- tone: .bad,
- action: runnerAction()
- )
- }
- }
-
private func fetchAction() -> StatusAction {
StatusAction(
label: "Fetch Valve Binaries",
@@ -660,7 +631,7 @@ struct StatusView: View {
URL(filePath: $0.path).lastPathComponent
}.joined(separator: ", ")
StatusRow(
- title: "Missing",
+ title: "Missing.",
value: names,
tone: .bad,
action: payload.missing.contains(where: { $0.origin.isFetchable })
diff --git a/app/Tests/NotProtonAppTests/CrossOverRowTests.swift b/app/Tests/NotProtonAppTests/CrossOverRowTests.swift
new file mode 100644
index 0000000..8c1f4a4
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/CrossOverRowTests.swift
@@ -0,0 +1,157 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("CrossOver rows on the Status pane")
+struct CrossOverRowTests {
+
+ private static let preview = SupportedRunners.all.first { $0.flavor == "fex" }!
+ private static let release = SupportedRunners.all.first { $0.id == "26.3.0.39832" }!
+
+ private func install(_ name: String, _ build: RunnerBuild, root: String = "/Applications") -> CrossOverInstall {
+ CrossOverInstall(bundle: URL(filePath: "\(root)/\(name).app"), releaseVersion: "x", support: .supported(build))
+ }
+
+ private func rows(
+ _ installs: [CrossOverInstall],
+ installed: [RunnerBuild] = [],
+ damaged: [String] = [],
+ orphaned: [String] = [],
+ unpatched: String? = nil,
+ unlicensed: Set<String> = []
+ ) -> [CrossOverRow] {
+ var licenses: [String: CrossOverLicense.Status] = [:]
+ for install in installs {
+ licenses[install.id] = CrossOverLicense.Status(
+ licensed: !unlicensed.contains(install.id), detail: "", diagnostic: "test"
+ )
+ }
+ return CrossOverRow.rows(
+ installs: installs, licenses: licenses, installed: installed,
+ damaged: damaged, orphaned: orphaned, unpatched: unpatched
+ )
+ }
+
+ @Test("Each app gets its own row, tied to its own build")
+ func oneRowPerApp() {
+ let preview = install("CrossOver Preview", Self.preview)
+ let release = install("CrossOver", Self.release)
+
+ let made = rows([preview, release], installed: [Self.preview, Self.release])
+
+ #expect(made.map(\.install?.id) == [preview.id, release.id])
+ #expect(made.map(\.buildID) == [Self.preview.id, Self.release.id])
+ #expect(made.allSatisfy { $0.copy == .ready && $0.canSetUp })
+ }
+
+ @Test("An app with no copy yet can be set up, and its license shows on the row")
+ func appWithoutCopy() {
+ let release = install("CrossOver", Self.release)
+
+ let made = rows([release], unlicensed: [release.id])
+
+ #expect(made.count == 1)
+ #expect(made[0].copy == .none)
+ #expect(made[0].licensed == false)
+ #expect(made[0].canSetUp)
+ }
+
+ @Test("A copy whose app is gone keeps a row that cannot be recopied")
+ func copyWithoutApp() {
+ let made = rows([], installed: [Self.release])
+
+ #expect(made.count == 1)
+ #expect(made[0].install == nil)
+ #expect(made[0].copy == .ready)
+ #expect(!made[0].canSetUp)
+ #expect(made[0].title == "CrossOver \(Self.release.displayVersion)")
+ }
+
+ @Test("Damaged, unpatched and unsupported copies are marked on their own rows")
+ func problemCopies() {
+ let preview = install("CrossOver Preview", Self.preview)
+ let release = install("CrossOver", Self.release)
+
+ let made = rows(
+ [preview, release], installed: [Self.preview], damaged: [Self.release.id],
+ orphaned: ["25.0.0.1"], unpatched: Self.preview.id
+ )
+
+ #expect(made.map(\.copy) == [.unpatched, .damaged, .unsupported])
+ #expect(made[2].buildID == "25.0.0.1")
+ #expect(made[2].install == nil)
+ }
+
+ @Test("Two apps of the same build share one row, the preferred one")
+ func sameBuildTwice() {
+ let first = install("CrossOver", Self.release)
+ let second = install("CrossOver", Self.release, root: "/Volumes/Spare")
+
+ let made = rows([first, second], installed: [Self.release])
+
+ #expect(made.map(\.install?.id) == [first.id])
+ }
+
+ @Test("An app NotProton doesn't support is listed with its version and nothing to set up")
+ func unsupportedApp() {
+ let old = CrossOverInstall(
+ bundle: URL(filePath: "/Applications/CrossOver 24.app"), releaseVersion: "24.0.5",
+ support: .unsupportedBuild("24.0.5")
+ )
+
+ let made = rows([old])
+
+ #expect(made.count == 1)
+ #expect(made[0].unsupportedVersion == "24.0.5")
+ #expect(!made[0].canSetUp)
+ }
+}
+
+@Suite("Manually added CrossOver copies")
+struct ManualCrossOverTests {
+
+ private func defaults() -> UserDefaults {
+ let name = "np-manual-\(UUID().uuidString)"
+ let defaults = UserDefaults(suiteName: name)!
+ defaults.removePersistentDomain(forName: name)
+ return defaults
+ }
+
+ @Test("The single copy 1.0 remembered carries over as the first entry")
+ func legacyChoiceCarriesOver() {
+ let defaults = defaults()
+ defaults.set("/Volumes/Spare/CrossOver.app", forKey: "manualCrossOverPath")
+
+ #expect(CrossOverSource.manualBundles(defaults).map { $0.path(percentEncoded: false) }
+ == ["/Volumes/Spare/CrossOver.app/"])
+
+ CrossOverSource.addManualBundle(URL(filePath: "/Volumes/Other/CrossOver.app"), defaults)
+
+ #expect(CrossOverSource.manualBundles(defaults).count == 2)
+ #expect(defaults.string(forKey: "manualCrossOverPath") == nil)
+ }
+
+ @Test("Adding keeps earlier copies, skips repeats, and removing drops only the one named")
+ func addAndRemove() {
+ let defaults = defaults()
+ let spare = URL(filePath: "/Volumes/Spare/CrossOver.app", directoryHint: .isDirectory)
+ let other = URL(filePath: "/Volumes/Other/CrossOver Preview.app", directoryHint: .isDirectory)
+
+ CrossOverSource.addManualBundle(spare, defaults)
+ CrossOverSource.addManualBundle(other, defaults)
+ CrossOverSource.addManualBundle(spare, defaults)
+ #expect(CrossOverSource.manualBundles(defaults) == [spare, other])
+
+ CrossOverSource.removeManualBundle(spare, defaults)
+ #expect(CrossOverSource.manualBundles(defaults) == [other])
+ }
+
+ @Test("A remembered copy in a folder the search covers is not treated as added by hand")
+ func searchedFolderIsNotManual() {
+ #expect(CrossOverSource.isSearched(URL(filePath: "/Applications/CrossOver.app/")))
+ #expect(CrossOverSource.isSearched(URL(filePath: "/Applications/CrossOver.app")))
+ #expect(!CrossOverSource.isSearched(URL(filePath: "/Volumes/Spare/CrossOver.app")))
+ #expect(!CrossOverSource.isSearched(URL(filePath: "/Applications/Games/CrossOver.app")))
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/DetectionTests.swift b/app/Tests/NotProtonAppTests/DetectionTests.swift
index 3ba8517..93351c1 100644
--- a/app/Tests/NotProtonAppTests/DetectionTests.swift
+++ b/app/Tests/NotProtonAppTests/DetectionTests.swift
@@ -92,21 +92,64 @@ struct SupportedRunnerTests {
}
}
-@Suite("Runner store")
-struct RunnerStoreTests {
+@Suite("Steam tools")
+struct CompatToolOrderTests {
- @Test("The build comes out of the crossover- path component")
- func buildIdentifierParsing() {
- #expect(RunnerStore.buildIdentifier(
- inPath: "crossover-27.0.0.40921/CrossOver Preview.app/Contents/SharedSupport/CrossOver"
- ) == "27.0.0.40921")
+ private func build(_ id: String) throws -> RunnerBuild {
+ try #require(SupportedRunners.build(id: id))
+ }
+
+ @Test("Tools come out in preference order whatever order the builds are in")
+ func order() throws {
+ let tools = SupportedRunners.tools(for: [
+ try build("26.3.0.39832"), try build("27.0.0.40921-fex"),
+ ])
+ #expect(tools.map(\.name) == ["notproton", "notproton-fex-rosetta", "notproton-26.3"])
+ #expect(tools.map(\.build) == ["27.0.0.40921-fex", "27.0.0.40921-fex", "26.3.0.39832"])
+ }
- #expect(RunnerStore.buildIdentifier(
- inPath: "../runners/crossover-1.2.3/CrossOver Preview.app/Contents/SharedSupport/CrossOver"
- ) == "1.2.3")
+ @Test("Each Preview keeps its own tools when both are set up")
+ func bothPreviews() throws {
+ let tools = SupportedRunners.tools(for: [
+ try build("27.0.0.40921-fex"), try build("27.0.0.40921"),
+ ])
+ #expect(tools.map(\.name) == ["notproton", "notproton-fex-rosetta", "notproton-preview"])
+ #expect(tools.map(\.build) == ["27.0.0.40921-fex", "27.0.0.40921-fex", "27.0.0.40921"])
+ #expect(Set(tools.map(\.display)).count == tools.count)
+ }
+
+ @Test("The Rosetta-only Preview serves the legacy name when it is the only Preview")
+ func rosettaPreviewAlone() throws {
+ let tools = SupportedRunners.tools(for: [try build("27.0.0.40921")])
+ #expect(tools.map(\.name) == ["notproton"])
+ #expect(tools.first?.tool.flavor == .rosetta)
+ }
+
+ @Test("A named holder keeps the legacy name, and nobody leaves every Preview on its own name")
+ func explicitHolder() throws {
+ let builds = [try build("27.0.0.40921-fex"), try build("27.0.0.40921")]
+ let held = SupportedRunners.tools(for: builds, legacy: .build("27.0.0.40921"))
+ #expect(held.map(\.name) == ["notproton", "notproton-fex", "notproton-fex-rosetta"])
+ #expect(held.first?.build == "27.0.0.40921")
+ let none = SupportedRunners.tools(for: builds, legacy: .nobody)
+ #expect(none.map(\.name) == ["notproton-fex", "notproton-fex-rosetta", "notproton-preview"])
+ }
+
+ @Test("Every tool name is one the dylib accepts")
+ func namesParse() {
+ for tool in SupportedRunners.all.flatMap(\.tools) {
+ #expect(tool.name.hasPrefix("notproton"))
+ #expect(tool.name.contains("proton"))
+ #expect(tool.name.allSatisfy { $0.isLetter || $0.isNumber || "._-".contains($0) })
+ #expect(!tool.display.contains { "\"\\".contains($0) || $0.isNewline })
+ }
+ }
- #expect(RunnerStore.buildIdentifier(inPath: "CrossOver Preview.app/Contents") == nil)
- #expect(RunnerStore.buildIdentifier(inPath: "") == nil)
+ @Test("The list file has one tab-separated line per tool")
+ func contents() throws {
+ let tools = SupportedRunners.tools(for: [try build("26.3.0.39832")])
+ #expect(CompatToolList.contents(tools)
+ == "notproton-26.3\t26.3.0.39832\trosetta\tCrossOver 26.3\n")
}
}
@@ -153,8 +196,8 @@ struct SupportPathTests {
.hasSuffix("/notproton/signatures/macos.arm64"))
#expect(SupportPaths.overlayShim.path(percentEncoded: false)
.hasSuffix("/notproton/overlay-shim.dylib"))
- #expect(SupportPaths.currentRunner.path(percentEncoded: false)
- .hasSuffix("/notproton/runners/current"))
+ #expect(SupportPaths.toolList.path(percentEncoded: false)
+ .hasSuffix("/notproton/tools"))
#expect(SupportPaths.Steam.deployedDylib.path(percentEncoded: false)
== "/Applications/Steam.app/Contents/MacOS/notproton.dylib")
#expect(SupportPaths.Steam.infoPlist.path(percentEncoded: false)
diff --git a/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift b/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift
index f15da80..2d826c2 100644
--- a/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift
+++ b/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift
@@ -16,6 +16,9 @@ private struct StubPE {
static let bssVirtualAddress = 0x200
static let bssSize = 0x200
+ static let imageSize = sectionVirtualAddress + sectionSize
+ static let tableEnd = peOffset + 24 + 0xf0 + 2 * 40
+
static func rva(forOffset offset: Int) -> Int {
sectionVirtualAddress + (offset - sectionRawOffset)
}
@@ -32,6 +35,10 @@ private struct StubPE {
write(&bytes, peOffset + 20, optionalSize)
write(&bytes, peOffset + 24, magic)
+ write(&bytes, peOffset + 24 + 36, UInt32(0x200))
+ write(&bytes, peOffset + 24 + 56, UInt32(imageSize))
+ write(&bytes, peOffset + 24 + 60, UInt32(sectionRawOffset))
+
if magic == 0x20b {
write(&bytes, peOffset + 24 + 24, imageBase)
} else {
@@ -113,7 +120,7 @@ struct NtdllPatcherTests {
#expect(Array(result[(hookOffset + 5) ..< (hookOffset + stolen.count)]) == [0xcc, 0xcc, 0xcc, 0xcc])
}
- @Test("The file keeps its length, because a PE cannot absorb inserted bytes")
+ @Test("A padding cave keeps the file length, because a PE cannot absorb inserted bytes")
func patchDoesNotResize() throws {
let patch = stubPatch()
let image = stubImage()
@@ -121,6 +128,69 @@ struct NtdllPatcherTests {
#expect(result.count == image.count)
}
+ private func sectionPatch() -> NtdllPatch {
+ let base = stubPatch()
+ return NtdllPatch(
+ arch: base.arch, payloadResource: base.payloadResource, payloadSHA256: base.payloadSHA256,
+ caveRVA: StubPE.imageSize, payloadRVA: StubPE.imageSize, hooks: base.hooks,
+ caveSize: 0x1000, cavePad: 0, machine: base.machine, magic: base.magic,
+ imageBase: base.imageBase, placement: .section
+ )
+ }
+
+ private func u32(_ bytes: [UInt8], _ offset: Int) -> Int {
+ bytes[offset ..< offset + 4].reversed().reduce(0) { $0 << 8 | Int($1) }
+ }
+
+ @Test("A section cave appends one executable page and jumps into it")
+ func sectionPlacementAppendsPage() throws {
+ let patch = sectionPatch()
+ let image = stubImage()
+ let payload = Data([0x90, 0x91, 0x92, 0x93])
+ let result = [UInt8](try NtdllPatcher.apply(patch, to: image, payload: payload))
+
+ #expect(result.count == image.count + 0x1000)
+ #expect(result[StubPE.peOffset + 6] == 3)
+ #expect(u32(result, StubPE.peOffset + 24 + 56) == StubPE.imageSize + 0x1000)
+
+ let header = StubPE.tableEnd
+ #expect(Array(result[header ..< header + 8]) == Array(".npdet".utf8) + [0, 0])
+ #expect(u32(result, header + 8) == 0x1000)
+ #expect(u32(result, header + 12) == StubPE.imageSize)
+ #expect(u32(result, header + 16) == 0x1000)
+ #expect(u32(result, header + 20) == image.count)
+ #expect(u32(result, header + 36) == 0x6000_0020)
+ #expect(Array(result[image.count ..< image.count + 4]) == [0x90, 0x91, 0x92, 0x93])
+
+ let hookOffset = StubPE.sectionRawOffset + 0x100
+ #expect(result[hookOffset] == 0xe9)
+ #expect(Int(Int32(truncatingIfNeeded: u32(result, hookOffset + 1)))
+ == patch.payloadRVA - (patch.hooks[0].rva + 5))
+ }
+
+ @Test("A section cave pinned somewhere other than the image end is refused")
+ func sectionPlacementNeedsImageEnd() throws {
+ let base = sectionPatch()
+ let moved = NtdllPatch(
+ arch: base.arch, payloadResource: base.payloadResource, payloadSHA256: base.payloadSHA256,
+ caveRVA: base.caveRVA + 0x1000, payloadRVA: base.caveRVA + 0x1000, hooks: base.hooks,
+ caveSize: base.caveSize, cavePad: 0, machine: base.machine, magic: base.magic,
+ imageBase: base.imageBase, placement: .section
+ )
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(moved, to: stubImage(), payload: Data([0x90]))
+ }
+ }
+
+ @Test("A section cave with no free header slot is refused, so a second patch cannot stack")
+ func sectionPlacementNeedsFreeHeader() throws {
+ var bytes = [UInt8](stubImage())
+ bytes[StubPE.tableEnd] = 0x2e
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(sectionPatch(), to: Data(bytes), payload: Data([0x90]))
+ }
+ }
+
// MARK: - Refusals
@Test("A hook site holding something else is refused")
@@ -254,9 +324,10 @@ struct NtdllPatcherTests {
// The point of the port: the same input has to come out as the bytes apply.py and
// apply32.py produced, which SupportedRunners records. Needs an unpatched CrossOver.
- @Test("Patching the unpatched ntdll reproduces the recorded hashes")
- func realNtdllReproducesRecordedHashes() throws {
- let root = URL(filePath: "/Applications/CrossOver Preview.app/Contents/SharedSupport/CrossOver")
+ @Test("Patching the unpatched ntdll reproduces the recorded hashes",
+ arguments: ["CrossOver Preview", "CrossOver"])
+ func realNtdllReproducesRecordedHashes(app: String) throws {
+ let root = URL(filePath: "/Applications/\(app).app/Contents/SharedSupport/CrossOver")
guard FileManager.default.fileExists(atPath: root.path(percentEncoded: false)),
let installed = Digest.sha256IfPresent(CrossOverSource.unixLoader(inRoot: root)),
let build = SupportedRunners.build(loaderSHA256: installed)
@@ -325,7 +396,7 @@ struct NtdllPatcherTests {
// The bridge here came out of apply.py and apply32.py, so staging from the same clone has
// to be byte identical. A clean ntdll cannot be a fixture, so no runner means skip.
private static func cleanRunnerRoot(for build: RunnerBuild) -> URL? {
- let root = SupportPaths.currentRunner
+ let root = SupportPaths.clonedRoot(forBuild: build.id)
guard FileManager.default.fileExists(
atPath: root.appending(path: "lib/wine").path(percentEncoded: false)
) else { return nil }
@@ -357,9 +428,8 @@ struct NtdllPatcherTests {
var compared: [WineArch] = []
for patch in NtdllPatcher.patches(for: build) {
- let relative = "wine/\(patch.arch.rawValue)/ntdll.dll"
- let staged = scratch.appending(path: relative)
- let existing = SupportPaths.bridge.appending(path: relative)
+ let staged = NtdllPatcher.stagedCopy(of: patch.arch, build: build.id, in: scratch)
+ let existing = NtdllPatcher.stagedCopy(of: patch.arch, build: build.id)
#expect(Digest.sha256IfPresent(staged) == build.patchedNtdll[patch.arch])
guard let live = Digest.sha256IfPresent(existing) else { continue }
@@ -370,7 +440,7 @@ struct NtdllPatcherTests {
// A staged bridge that matched nothing is a test that skipped. Asked per build rather
// than against a fixed arch, so a bridge of another flavor does not stand this down.
let bridgeHoldsThisBuild = build.patchedNtdll.keys.contains { arch in
- Digest.sha256IfPresent(SupportPaths.bridge.appending(path: "wine/\(arch.rawValue)/ntdll.dll")) != nil
+ Digest.sha256IfPresent(NtdllPatcher.stagedCopy(of: arch, build: build.id)) != nil
}
if bridgeHoldsThisBuild {
#expect(compared.count == build.patchedNtdll.count)
@@ -424,7 +494,7 @@ struct NtdllStagingTests {
var hashes: [WineArch: String] = [:]
for arch in WineArch.allCases {
- let directory = bridge.appending(path: "wine/\(arch.rawValue)")
+ let directory = bridge.appending(path: "wine/27.0.0.40921/\(arch.rawValue)")
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let file = directory.appending(path: "ntdll.dll")
try Data("staged \(arch.rawValue)".utf8).write(to: file)
@@ -457,13 +527,47 @@ struct NtdllStagingTests {
let fm = FileManager.default
for arch in [WineArch.x86_64Windows, .i386Windows] {
- let kept = bridge.appending(path: "wine/\(arch.rawValue)/ntdll.dll")
+ let kept = NtdllPatcher.stagedCopy(of: arch, build: build.id, in: bridge)
#expect(fm.fileExists(atPath: kept.path(percentEncoded: false)))
}
- let foreign = bridge.appending(path: "wine/aarch64-windows/ntdll.dll")
+ let foreign = NtdllPatcher.stagedCopy(of: .aarch64Windows, build: build.id, in: bridge)
#expect(!fm.fileExists(atPath: foreign.path(percentEncoded: false)))
}
+
+ @Test("Restaging installed builds reports a build it cannot stage and carries on")
+ func stageInstalledCollectsFailures() throws {
+ let (bridge, build) = try stagedBridge()
+ defer { try? FileManager.default.removeItem(at: bridge) }
+ let broken = SupportedRunners.all[0]
+
+ let failures = NtdllPatcher.stageInstalled(
+ builds: [broken, build], runners: bridge.appending(path: "runners"), bridge: bridge
+ )
+
+ #expect(failures.map(\.build) == [broken.id])
+ #expect(FileManager.default.fileExists(atPath: NtdllPatcher.stagedCopy(
+ of: .x86_64Windows, build: build.id, in: bridge).path(percentEncoded: false)))
+ }
+
+ @Test("Pruning keeps the listed builds and drops every other entry under wine")
+ func pruneKeepsListedBuilds() throws {
+ let (bridge, build) = try stagedBridge()
+ defer { try? FileManager.default.removeItem(at: bridge) }
+ let fm = FileManager.default
+ let other = bridge.appending(path: "wine/26.3.0.39832")
+ let legacy = bridge.appending(path: "wine/x86_64-windows")
+ for directory in [other, legacy] {
+ try fm.createDirectory(at: directory, withIntermediateDirectories: true)
+ }
+
+ NtdllPatcher.pruneBuilds(keeping: [build.id], in: bridge)
+
+ #expect(fm.fileExists(atPath: NtdllPatcher.stagedCopy(
+ of: .x86_64Windows, build: build.id, in: bridge).path(percentEncoded: false)))
+ #expect(!fm.fileExists(atPath: other.path(percentEncoded: false)))
+ #expect(!fm.fileExists(atPath: legacy.path(percentEncoded: false)))
+ }
}
@Suite("Pinned patch payloads")
diff --git a/app/Tests/NotProtonAppTests/PayloadManifestTests.swift b/app/Tests/NotProtonAppTests/PayloadManifestTests.swift
index 8cb195e..5289383 100644
--- a/app/Tests/NotProtonAppTests/PayloadManifestTests.swift
+++ b/app/Tests/NotProtonAppTests/PayloadManifestTests.swift
@@ -88,7 +88,8 @@ struct PayloadInspectionTests {
try Data().write(to: file)
}
- let state = PayloadInspector.inspect(bridge: bridge)
+ let fex = try #require(SupportedRunners.all.first { $0.flavor == "fex" })
+ let state = PayloadInspector.inspect(bridge: bridge, builds: [fex])
#expect(state.manifestProblem == nil)
#expect(state.expected == 20)
#expect(state.present == 10)
diff --git a/app/Tests/NotProtonAppTests/PrefixToolsTests.swift b/app/Tests/NotProtonAppTests/PrefixToolsTests.swift
index 66a65b1..b33bb9c 100644
--- a/app/Tests/NotProtonAppTests/PrefixToolsTests.swift
+++ b/app/Tests/NotProtonAppTests/PrefixToolsTests.swift
@@ -94,14 +94,15 @@ struct PrefixToolsTests {
@Test("The prefix and the sync backend are set, and the game only variables are not")
func setsPrefixAndBackend() {
let prefix = samplePrefix()
- let environment = PrefixTools.environment(prefix: prefix)
+ let runner = SupportPaths.clonedRoot(forBuild: "27.0.0.40921-fex")
+ let environment = PrefixTools.environment(prefix: prefix, runner: runner)
#expect(environment["WINEPREFIX"] == prefix.pfx.path(percentEncoded: false))
#expect(environment["WINEPREFIX"]?.hasSuffix("/compatdata/1574480/pfx") == true)
#expect(environment["WINEMSYNC"] == PrefixTools.syncBackend(prefix: prefix))
// Derived rather than spelled out, because the support directory hangs off the
// running account's home and a literal here would only ever pass on one machine.
- let runnerBin = SupportPaths.currentRunner.appending(path: "bin")
+ let runnerBin = runner.appending(path: "bin")
.path(percentEncoded: false)
#expect(environment["PATH"]?.hasPrefix(runnerBin + ":") == true)
@@ -127,7 +128,7 @@ struct PrefixToolsTests {
#expect(
PrefixTools.syncBackend(prefix: prefix) == expected,
"recorded \(recorded.debugDescription)")
- #expect(PrefixTools.environment(prefix: prefix)["WINEMSYNC"] == expected)
+ #expect(PrefixTools.environment(prefix: prefix, runner: root)["WINEMSYNC"] == expected)
}
}
@@ -282,27 +283,24 @@ struct PrefixToolsTests {
#expect(closing.upperBound <= refusal.lowerBound)
}
- // Whichever unix tree the runner has decides the loader, and so decides the arch of
- // every windows file wineboot then installs. The two have to be read by one rule.
- @Test("The arch a runner builds prefixes for follows the loader it resolves")
- func prefixArchFollowsTheLoader() throws {
+ @Test("The Rosetta flavor takes the x86_64 tree on a runner that has both")
+ func rosettaFlavorTakesX86() throws {
let fm = FileManager.default
- for (arch, loaderTail, serverName, expected) in [
- ("aarch64-unix", "wine.app/Contents/MacOS/wine", "wineserver-arm64", PrefixArch.arm64),
- ("x86_64-unix", "wine", "wineserver-x86", PrefixArch.x86_64),
+ let runner = fm.temporaryDirectory.appending(path: "np-arch-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: runner) }
+ for path in [
+ "lib/wine/aarch64-unix/wine.app/Contents/MacOS/wine", "lib/wine/x86_64-unix/wine",
+ "CrossOver-Hosted Application/wineserver-arm64", "CrossOver-Hosted Application/wineserver",
] {
- let runner = FileManager.default.temporaryDirectory
- .appending(path: "np-arch-\(UUID().uuidString)")
- defer { try? fm.removeItem(at: runner) }
- for path in ["lib/wine/\(arch)/\(loaderTail)", "CrossOver-Hosted Application/\(serverName)"] {
- let file = runner.appending(path: path)
- try fm.createDirectory(
- at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
- try Data().write(to: file)
- try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path(percentEncoded: false))
- }
- #expect(PrefixTools.prefixArch(runner: runner) == expected)
+ let file = runner.appending(path: path)
+ try fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: file)
+ try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path(percentEncoded: false))
}
+
+ #expect(PrefixTools.layout(runner: runner, flavor: .fex).unixDir.lastPathComponent == "aarch64-unix")
+ #expect(PrefixTools.layout(runner: runner, flavor: .rosetta).unixDir.lastPathComponent == "x86_64-unix")
+ #expect(PrefixTools.layout(runner: runner, flavor: .rosetta).server.lastPathComponent == "wineserver")
}
// Stands in for wineboot --init, the one part of a rebuild a test cannot run: the windows
@@ -1351,3 +1349,106 @@ struct PrefixToolsTests {
#expect(try String(contentsOf: parked, encoding: .utf8) == "progress")
}
}
+
+@Suite("Which build last ran a prefix")
+struct PrefixLastBuildTests {
+
+ private static let release = "26.3.0.39832"
+ private static let preview = "27.0.0.40921-fex"
+
+ private func makeWorld() throws -> (dir: URL, runners: URL, prefix: WinePrefix) {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-lastbuild-\(UUID().uuidString)")
+ let runners = dir.appending(path: "runners")
+ for (build, time) in [(Self.release, 1_784_112_240), (Self.preview, 1_787_334_674)] {
+ let inf = SupportPaths.clonedRoot(forBuild: build, runners: runners)
+ .appending(path: "share/wine/wine.inf")
+ try fm.createDirectory(at: inf.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: inf)
+ try fm.setAttributes(
+ [.modificationDate: Date(timeIntervalSince1970: TimeInterval(time))],
+ ofItemAtPath: inf.path(percentEncoded: false))
+ }
+ let prefix = WinePrefix(
+ appID: "480", name: nil, library: SteamLibrary(root: dir.appending(path: "Steam")), lastUsed: nil)
+ try fm.createDirectory(at: prefix.pfx, withIntermediateDirectories: true)
+ return (dir, runners, prefix)
+ }
+
+ private func updated(_ prefix: WinePrefix, _ text: String) throws {
+ try text.write(to: prefix.pfx.appending(path: ".update-timestamp"), atomically: true, encoding: .utf8)
+ }
+
+ @Test("A prefix with nothing to read from belongs to no build yet")
+ func freshPrefix() throws {
+ let (dir, runners, prefix) = try makeWorld()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ #expect(PrefixTools.lastBuild(of: prefix, runners: runners) == nil)
+
+ try updated(prefix, "disable\n")
+ #expect(PrefixTools.lastBuild(of: prefix, runners: runners) == nil)
+ }
+
+ @Test("Without a record, the clone whose wine.inf matches is the build")
+ func readsTheWineThatUpdatedIt() throws {
+ let (dir, runners, prefix) = try makeWorld()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ try updated(prefix, "1787334674\n")
+ #expect(PrefixTools.lastBuild(of: prefix, runners: runners)
+ == PrefixBuildRecord(build: Self.preview, display: nil))
+
+ try updated(prefix, "12345\n")
+ let unknown = try #require(PrefixTools.lastBuild(of: prefix, runners: runners))
+ #expect(unknown.build.isEmpty)
+ }
+
+ @Test("A record outranks the Wine that last updated the prefix")
+ func recordWins() throws {
+ let (dir, runners, prefix) = try makeWorld()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ try updated(prefix, "1787334674\n")
+ try "\(Self.release)\nCrossOver 26.3\n".write(
+ to: prefix.root.appending(path: PrefixTools.buildRecordName), atomically: true, encoding: .utf8)
+ #expect(PrefixTools.lastBuild(of: prefix, runners: runners)
+ == PrefixBuildRecord(build: Self.release, display: "CrossOver 26.3"))
+ }
+
+ @Test("A tool of the other arch is never picked for a prefix")
+ func noToolOfTheOtherArch() throws {
+ let (dir, runners, prefix) = try makeWorld()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let system32 = prefix.pfx.appending(path: "drive_c/windows/system32")
+ try FileManager.default.createDirectory(at: system32, withIntermediateDirectories: true)
+ var header = [UInt8](repeating: 0, count: 0x40)
+ header[0x3c] = 0x40
+ try Data(header + [0x50, 0x45, 0, 0, 0x64, 0x86])
+ .write(to: system32.appending(path: "ntdll.dll"))
+ try "\(Self.preview)\nCrossOver Preview (Rosetta)\n".write(
+ to: prefix.root.appending(path: PrefixTools.buildRecordName), atomically: true, encoding: .utf8)
+
+ let fexOnly = [InstalledTool(
+ tool: CompatTool(name: "notproton", flavor: .fex, display: "CrossOver Preview (FEX)"),
+ build: Self.preview)]
+ #expect(PrefixTools.tool(for: prefix, among: fexOnly, runners: runners) == nil)
+
+ let fex = try #require(SupportedRunners.all.first { $0.id == Self.preview })
+ let both = SupportedRunners.tools(for: [fex])
+ #expect(PrefixTools.tool(for: prefix, among: both, runners: runners)?.name == "notproton-fex-rosetta")
+ }
+
+ @Test("A prefix another CrossOver updated gets no tool, so nothing runs over it")
+ func noToolForAnotherWine() throws {
+ let (dir, runners, prefix) = try makeWorld()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let release = try #require(SupportedRunners.all.first { $0.id == Self.release })
+ let tools = SupportedRunners.tools(for: [release])
+
+ try updated(prefix, "1787334674\n")
+ #expect(PrefixTools.tool(for: prefix, among: tools, runners: runners) == nil)
+
+ try updated(prefix, "1784112240\n")
+ #expect(PrefixTools.tool(for: prefix, among: tools, runners: runners)?.build == Self.release)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/PrefixesModelTests.swift b/app/Tests/NotProtonAppTests/PrefixesModelTests.swift
index 13c6ee6..e0403ad 100644
--- a/app/Tests/NotProtonAppTests/PrefixesModelTests.swift
+++ b/app/Tests/NotProtonAppTests/PrefixesModelTests.swift
@@ -66,10 +66,25 @@ private final class Recorder: @unchecked Sendable {
}
}
+private final class Asked: @unchecked Sendable {
+ private let lock = NSLock()
+ private var made: [String] = []
+
+ var calls: [String] { lock.withLock { made } }
+
+ func add(_ appID: String, _ build: String, _ keep: Bool) {
+ lock.withLock { made.append("\(appID) \(build) \(keep)") }
+ }
+}
+
@MainActor
@Suite("Loading prefixes")
struct PrefixesModelTests {
+ nonisolated private static let tool = InstalledTool(
+ tool: SupportedRunners.all[0].tools[0], build: SupportedRunners.all[0].id
+ )
+
private func makeLibrary(appIDs: [String]) throws -> (URL, SteamLibrary) {
let dir = FileManager.default.temporaryDirectory.appending(path: "np-model-\(UUID().uuidString)")
let library = SteamLibrary(root: dir)
@@ -87,40 +102,30 @@ struct PrefixesModelTests {
try Data(text.utf8).write(to: url)
}
- // Enough of an ntdll for the arch to be read out of it: e_lfanew at 0x3c pointing at a
- // PE signature and the machine word behind it.
- private func writeNtdll(machine: UInt16, in pfx: URL) throws {
- var bytes = [UInt8](repeating: 0, count: 0x40)
- withUnsafeBytes(of: UInt32(0x40).littleEndian) { bytes.replaceSubrange(0x3c..<0x40, with: $0) }
- bytes += [0x50, 0x45, 0x00, 0x00]
- bytes += withUnsafeBytes(of: machine.littleEndian) { Array($0) }
- let dll = pfx.appending(path: "drive_c/windows/system32/ntdll.dll")
- try FileManager.default.createDirectory(
- at: dll.deletingLastPathComponent(), withIntermediateDirectories: true)
- try Data(bytes).write(to: dll)
- }
-
- // The launcher refuses a prefix from the other compatibility tool, so the pane has to mark
- // those rows or the refusal is the first anyone hears. Never booted means no arch yet.
- @Test("A prefix built by the other compatibility tool is the only one flagged")
- func flagsForeignPrefixes() async throws {
+ @Test("Only a prefix recorded for a build that is no longer set up is stale")
+ func flagsStalePrefixes() async throws {
let (dir, library) = try makeLibrary(appIDs: ["1574480", "253750", "447700"])
defer { try? FileManager.default.removeItem(at: dir) }
let compatdata = library.compatdata
- try writeNtdll(machine: 0xaa64, in: compatdata.appending(path: "1574480/pfx"))
- try writeNtdll(machine: 0x8664, in: compatdata.appending(path: "253750/pfx"))
-
- let model = PrefixesModel(libraries: { [library] }, runnerArch: { .arm64 })
+ try "\(Self.tool.build)\n\(Self.tool.display)\n".write(
+ to: compatdata.appending(path: "1574480/\(PrefixTools.buildRecordName)"),
+ atomically: true, encoding: .utf8)
+ try "1.0.0.1\n".write(
+ to: compatdata.appending(path: "253750/\(PrefixTools.buildRecordName)"),
+ atomically: true, encoding: .utf8)
+
+ let model = PrefixesModel(libraries: { [library] }, installedTools: { [Self.tool] })
await model.load()
func prefix(_ appID: String) throws -> WinePrefix {
try #require(model.prefixes.first { $0.appID == appID })
}
- #expect(model.expectedArch == .arm64)
- #expect(model.isForeign(try prefix("1574480")) == false)
- #expect(model.isForeign(try prefix("253750")) == true)
- #expect(model.isForeign(try prefix("447700")) == false)
+ #expect(model.isStale(try prefix("1574480")) == false)
+ #expect(model.lastTool(try prefix("1574480")) == Self.tool.display)
+ #expect(model.isStale(try prefix("253750")) == true)
+ #expect(model.isStale(try prefix("447700")) == false)
+ #expect(model.lastTool(try prefix("447700")) == nil)
}
@Test("A load lists the prefixes and measures each one")
@@ -234,7 +239,33 @@ struct PrefixesModelTests {
#expect(model.selectedPrefix == nil)
}
- // Selecting every prefix that needs rebuilding used to offer nothing, so they had to be
+ @Test("Confirming the rebuild dialog runs it with the tool and backup choice it asked about")
+ func confirmingRunsTheRebuild() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let asked = Asked()
+ let model = PrefixesModel(
+ libraries: { [library] },
+ rebuild: { prefix, tool, keep in
+ asked.add(prefix.appID, tool.build, keep)
+ return nil
+ })
+ await model.load()
+
+ #expect(model.confirmRebuild() == nil)
+
+ model.pendingConfirmation = .rebuild(model.prefixes, Self.tool)
+ await model.confirmRebuild(keepBackup: false)?.value
+ #expect(model.pendingConfirmation == nil)
+
+ model.pendingConfirmation = .rebuild(model.prefixes, Self.tool)
+ await model.confirmRebuild()?.value
+
+ let build = Self.tool.build
+ #expect(asked.calls == ["1574480 \(build) false", "1574480 \(build) true"])
+ }
+
@Test("Declining the backup tells the rebuild not to keep one")
func rebuildForwardsTheBackupChoice() async throws {
let (dir, library) = try makeLibrary(appIDs: ["1574480"])
@@ -242,15 +273,15 @@ struct PrefixesModelTests {
let model = PrefixesModel(
libraries: { [library] },
- rebuild: { prefix, keep in keep ? Recorder.backup(of: prefix) : nil })
+ rebuild: { prefix, _, keep in keep ? Recorder.backup(of: prefix) : nil })
await model.load()
let targets = model.prefixes
let title = try #require(targets.first).title
- await model.recreate(targets, keepBackup: false)
+ await model.recreate(targets, as: Self.tool, keepBackup: false)
#expect(model.outcome == "Rebuilt the prefix for \(title).")
- await model.recreate(targets)
+ await model.recreate(targets, as: Self.tool)
#expect(model.outcome?.contains("The original is at") == true)
}
@@ -273,6 +304,7 @@ struct PrefixesModelTests {
#expect(model.outcome == "Backed up 2 prefixes.")
}
+ // Selecting every prefix that needs rebuilding used to offer nothing, so they had to be
// picked and confirmed one at a time.
@Test("Rebuilding takes every selected prefix, one after another")
func rebuildTakesTheWholeSelection() async throws {
@@ -283,13 +315,13 @@ struct PrefixesModelTests {
// runner while the first is still going is the failure this queue exists to avoid.
let log = Recorder()
let model = PrefixesModel(
- libraries: { [library] }, rebuild: { prefix, _ in try log.enter(prefix) })
+ libraries: { [library] }, rebuild: { prefix, _, _ in try log.enter(prefix) })
await model.load()
model.selection = Set(model.prefixes.map(\.id))
let targets = model.selectedPrefixes
#expect(targets.count == 3)
- await model.recreate(targets)
+ await model.recreate(targets, as: Self.tool)
#expect(log.visited == targets.map(\.title))
#expect(!log.overlapped)
@@ -310,11 +342,11 @@ struct PrefixesModelTests {
let log = Recorder()
let model = PrefixesModel(
libraries: { [library] },
- rebuild: { prefix, _ in try log.enter(prefix, failing: prefix.appID == "1649240") }
+ rebuild: { prefix, _, _ in try log.enter(prefix, failing: prefix.appID == "1649240") }
)
await model.load()
let targets = model.prefixes
- await model.recreate(targets)
+ await model.recreate(targets, as: Self.tool)
#expect(log.visited.count == 3)
#expect(model.outcome == "Rebuilt 2 prefixes. Each original is kept beside the game's "
@@ -333,12 +365,12 @@ struct PrefixesModelTests {
let model = PrefixesModel(
libraries: { [library] },
- rebuild: { prefix, _ in
+ rebuild: { prefix, _, _ in
throw WriteRefused(path: prefix.root.path(percentEncoded: false))
}
)
await model.load()
- await model.recreate(model.prefixes)
+ await model.recreate(model.prefixes, as: Self.tool)
let report = try #require(model.report)
#expect(report.remedy == .ownership, "a prefix the user owns was blamed on a permission")
@@ -356,11 +388,11 @@ struct PrefixesModelTests {
let log = Recorder()
let model = PrefixesModel(
- libraries: { [library] }, rebuild: { prefix, _ in try log.enter(prefix) })
+ libraries: { [library] }, rebuild: { prefix, _, _ in try log.enter(prefix) })
await model.load()
let target = try #require(model.prefixes.first)
- await model.recreate([target])
+ await model.recreate([target], as: Self.tool)
let backup = Recorder.backup(of: target).path(percentEncoded: false)
#expect(model.outcome == "Rebuilt the prefix for \(target.title). The original is at "
@@ -374,11 +406,11 @@ struct PrefixesModelTests {
let (dir, library) = try makeLibrary(appIDs: ["1574480"])
defer { try? FileManager.default.removeItem(at: dir) }
- let model = PrefixesModel(libraries: { [library] }, rebuild: { _, _ in nil })
+ let model = PrefixesModel(libraries: { [library] }, rebuild: { _, _, _ in nil })
await model.load()
let target = try #require(model.prefixes.first)
- await model.recreate([target])
+ await model.recreate([target], as: Self.tool)
#expect(model.outcome == "Rebuilt the prefix for \(target.title).")
}
@@ -485,9 +517,9 @@ struct PrefixesModelTests {
func rebuildOfAnEmptySelectionDoesNothing() async throws {
let log = Recorder()
let model = PrefixesModel(
- libraries: { [] }, rebuild: { prefix, _ in try log.enter(prefix) })
+ libraries: { [] }, rebuild: { prefix, _, _ in try log.enter(prefix) })
model.outcome = "untouched"
- await model.recreate([])
+ await model.recreate([], as: Self.tool)
#expect(log.visited.isEmpty)
#expect(model.outcome == "untouched")
@@ -502,11 +534,11 @@ struct PrefixesModelTests {
let log = Recorder(holdingEachTurn: true)
let model = PrefixesModel(
- libraries: { [library] }, rebuild: { prefix, _ in try log.enter(prefix) })
+ libraries: { [library] }, rebuild: { prefix, _, _ in try log.enter(prefix) })
await model.load()
let targets = model.prefixes
- let running = Task { await model.recreate(targets) }
+ let running = Task { await model.recreate(targets, as: Self.tool) }
// A prefix having started means the one before it is done and out of the set. The turn is
// held inside the rebuild, so the set cannot move between the wait and the read.
@@ -530,7 +562,7 @@ struct PrefixesModelTests {
let box = Libraries([library])
let log = Recorder()
let model = PrefixesModel(
- libraries: { box.current }, rebuild: { prefix, _ in try log.enter(prefix) })
+ libraries: { box.current }, rebuild: { prefix, _, _ in try log.enter(prefix) })
await model.load()
let targets = model.prefixes
#expect(targets.count == 2)
@@ -538,7 +570,7 @@ struct PrefixesModelTests {
// Taken away before the run finishes, so an empty list afterwards can only mean the
// run went back to the libraries for it.
box.current = []
- await model.recreate(targets)
+ await model.recreate(targets, as: Self.tool)
#expect(model.prefixes.isEmpty)
}
diff --git a/app/Tests/NotProtonAppTests/RealRebuildTests.swift b/app/Tests/NotProtonAppTests/RealRebuildTests.swift
index 9fdb90a..b0f0ea0 100644
--- a/app/Tests/NotProtonAppTests/RealRebuildTests.swift
+++ b/app/Tests/NotProtonAppTests/RealRebuildTests.swift
@@ -13,10 +13,10 @@ enum RealPrefixes {
// One prefix per profile shape: steamuser real, steamuser linked, and both real, which is
// the shape a save was lost from. All three have to come out on the steamuser layout.
+ static var tool: InstalledTool? { CompatToolList.installed().first }
+
static var candidates: [WinePrefix] {
- let loader = PrefixTools.layout(runner: SupportPaths.currentRunner).unixDir
- guard FileManager.default.fileExists(
- atPath: loader.path(percentEncoded: false)) else { return [] }
+ guard tool != nil else { return [] }
func realDirectory(_ url: URL) -> Bool {
let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey])
return values?.isSymbolicLink != true && values?.isDirectory == true
@@ -97,7 +97,8 @@ struct RealRebuildTests {
at: stray.deletingLastPathComponent(), withIntermediateDirectories: true)
try Data("exe".utf8).write(to: stray)
- try PrefixTools.recreate(prefix)
+ let tool = try #require(RealPrefixes.tool)
+ try PrefixTools.recreate(prefix, as: tool)
let after = inventory(prefix.pfx)
// Both profile names fold to one directory after a rebuild, as do the documents names
@@ -149,9 +150,9 @@ struct RealRebuildTests {
"\(prefix.appID) resolves \(folder) to \(resolved)")
}
- // The windows tree is the fresh one, for the arch the installed runner builds.
let ntdll = prefix.pfx.appending(path: "drive_c/windows/system32/ntdll.dll")
- #expect(PrefixStore.arch(of: prefix) == PrefixTools.prefixArch())
+ #expect(PrefixStore.arch(of: prefix) == tool.tool.prefixArch)
+ #expect(PrefixTools.buildRecord(of: prefix)?.build == tool.build)
#expect(FileManager.default.fileExists(atPath: ntdll.path(percentEncoded: false)))
}
}
diff --git a/app/Tests/NotProtonAppTests/RunnerInstallerTests.swift b/app/Tests/NotProtonAppTests/RunnerInstallerTests.swift
index e8d2ae3..ec219dc 100644
--- a/app/Tests/NotProtonAppTests/RunnerInstallerTests.swift
+++ b/app/Tests/NotProtonAppTests/RunnerInstallerTests.swift
@@ -3,7 +3,7 @@ import Testing
@testable import NotProtonApp
-@Suite("Pointing the current runner")
+@Suite("Cloning a runner")
struct RunnerInstallerTests {
private func makeRunners() throws -> URL {
@@ -13,57 +13,6 @@ struct RunnerInstallerTests {
return runners
}
- @Test("The link is relative and in the form the run script expects")
- func writesRelativeTarget() throws {
- let runners = try makeRunners()
- defer { try? FileManager.default.removeItem(at: runners) }
-
- try RunnerInstaller.pointCurrent(atBuild: "27.0.0.40921", runners: runners)
-
- let target = try FileManager.default.destinationOfSymbolicLink(
- atPath: runners.appending(path: "current").path(percentEncoded: false)
- )
- #expect(target == "crossover-27.0.0.40921/CrossOver")
- }
-
- // Switching builds happens over a link that already exists, and rename is what
- // makes that a single step rather than an unlink the launch path could land in.
- @Test("An existing link is replaced")
- func replacesExistingLink() throws {
- let runners = try makeRunners()
- defer { try? FileManager.default.removeItem(at: runners) }
-
- try RunnerInstaller.pointCurrent(atBuild: "1.0.0.1", runners: runners)
- try RunnerInstaller.pointCurrent(atBuild: "2.0.0.2", runners: runners)
-
- let target = try FileManager.default.destinationOfSymbolicLink(
- atPath: runners.appending(path: "current").path(percentEncoded: false)
- )
- #expect(target.hasPrefix("crossover-2.0.0.2/"))
-
- // No staging file left behind, or the next attempt starts from a dirty state.
- #expect(!FileManager.default.fileExists(
- atPath: runners.appending(path: ".current.new").path(percentEncoded: false)
- ))
- }
-
- @Test("A directory in the way is reported instead of being worked around")
- func refusesDirectoryInTheWay() throws {
- let runners = try makeRunners()
- defer { try? FileManager.default.removeItem(at: runners) }
-
- try FileManager.default.createDirectory(
- at: runners.appending(path: "current"), withIntermediateDirectories: true
- )
-
- #expect(throws: StepFailure.self) {
- try RunnerInstaller.pointCurrent(atBuild: "1.0.0.1", runners: runners)
- }
- #expect(!FileManager.default.fileExists(
- atPath: runners.appending(path: ".current.new").path(percentEncoded: false)
- ))
- }
-
// The clone is found afterwards at a fixed name inside the build directory, so the copy has
// to land as a child. cp keys that off the destination existing, and first time it does not.
@Test("The copy lands as a payload directory inside the build directory")
@@ -152,8 +101,8 @@ struct RunnerInstallerTests {
))
}
- @Test("Cloning another build leaves the active link alone until setup finishes")
- func cloneDoesNotActivate() throws {
+ @Test("Cloning another build leaves the first clone in place")
+ func cloneKeepsOtherBuilds() throws {
let runners = try makeRunners()
defer { try? FileManager.default.removeItem(at: runners) }
@@ -165,11 +114,9 @@ struct RunnerInstallerTests {
)
_ = try RunnerInstaller.clone(from: first, runners: runners)
- #expect(RunnerStore.currentBuild(runners: runners) == nil)
-
- try RunnerInstaller.pointCurrent(atBuild: firstBuild.id, runners: runners)
_ = try RunnerInstaller.clone(from: second, runners: runners)
- #expect(RunnerStore.currentBuild(runners: runners) == firstBuild.id)
+ #expect(RunnerInstaller.hasClone(forBuild: firstBuild.bundleVersion, runners: runners))
+ #expect(RunnerInstaller.hasClone(forBuild: "2.0.0.2", runners: runners))
}
// The first attempt left the build directory holding the payload's contents, not the payload.
@@ -223,26 +170,23 @@ struct RunnerInstallerTests {
}
// Replacing an intact clone used to remove it before the copy, so a failed copy took a
- // working 1.2G tree with it and left runners/current dangling, with nothing in the UI.
- @Test("A failed recopy leaves the working clone and the current link intact")
+ // working 1.2G tree with it, with nothing in the UI.
+ @Test("A failed recopy leaves the working clone intact")
func keepsWorkingCloneWhenRecopyFails() throws {
let runners = try makeRunners()
defer { try? FileManager.default.removeItem(at: runners) }
let (install, build) = try makeSupportedInstall(in: runners)
_ = try RunnerInstaller.clone(from: install, runners: runners)
- try RunnerInstaller.pointCurrent(atBuild: build.id, runners: runners)
let payload = SupportPaths
.clonedRoot(forBuild: build.bundleVersion, runners: runners)
.appending(path: "lib/wine")
- let current = runners.appending(path: "current")
let files = FileManager.default
// Asserted before the failure, or the checks afterwards pass on a clone that was
// never there to begin with.
#expect(files.fileExists(atPath: payload.path(percentEncoded: false)))
- #expect(files.fileExists(atPath: current.path(percentEncoded: false)))
// Removing the source fails the copy the same way running out of room part way
// through does, which is the case that costs the user a working runner.
@@ -256,11 +200,6 @@ struct RunnerInstallerTests {
files.fileExists(atPath: payload.path(percentEncoded: false)),
"a recopy that failed destroyed the working clone"
)
- // fileExists resolves the link, so a dangling current reads as absent here.
- #expect(
- files.fileExists(atPath: current.path(percentEncoded: false)),
- "runners/current is dangling, so a launch resolves it to nothing"
- )
}
@Test("The state reader agrees with what was just written")
@@ -273,9 +212,8 @@ struct RunnerInstallerTests {
at: runners.appending(path: "crossover-\(version)/CrossOver/lib/wine"),
withIntermediateDirectories: true
)
- try RunnerInstaller.pointCurrent(atBuild: version, runners: runners)
#expect(RunnerStore.state(runners: runners, verify: { _, _ in [] })
- == .cloned(build: version, supported: true))
+ == .ready(builds: [version]))
}
}
diff --git a/app/Tests/NotProtonAppTests/RunnerPatcherTests.swift b/app/Tests/NotProtonAppTests/RunnerPatcherTests.swift
index b9e1724..55036b8 100644
--- a/app/Tests/NotProtonAppTests/RunnerPatcherTests.swift
+++ b/app/Tests/NotProtonAppTests/RunnerPatcherTests.swift
@@ -9,16 +9,10 @@ struct RunnerPatcherTests {
// Only real CrossOver bytes can answer whether a repair works, since no tree a test builds
// meets the pinned hashes. An APFS clone costs a second and leaves the real one alone.
private static func healthyClone() throws -> (root: URL, build: RunnerBuild)? {
- // Resolved first, or cp copies runners/current itself and its relative target
- // lands as a dangling link in the scratch directory.
- let live = SupportPaths.currentRunner.resolvingSymlinksInPath()
-
- // Which build is installed decides the hashes the tree is held to. Taking the first in
- // the allow list calls a healthy tree of the other flavor broken, skipping the rest.
- guard let id = RunnerStore.buildIdentifier(inPath: live.path(percentEncoded: false)),
- let build = SupportedRunners.build(id: id),
- RunnerPatcher.verify(build: build, root: live).isEmpty
- else { return nil }
+ guard let build = RunnerStore.installedBuilds().first(where: {
+ RunnerPatcher.verify(build: $0, root: SupportPaths.clonedRoot(forBuild: $0.id)).isEmpty
+ }) else { return nil }
+ let live = SupportPaths.clonedRoot(forBuild: build.id)
let scratch = URL(filePath: NSTemporaryDirectory())
.appending(path: "notproton-runner-\(UUID().uuidString)")
diff --git a/app/Tests/NotProtonAppTests/RunnerStateTests.swift b/app/Tests/NotProtonAppTests/RunnerStateTests.swift
index 0660d50..71f2ab6 100644
--- a/app/Tests/NotProtonAppTests/RunnerStateTests.swift
+++ b/app/Tests/NotProtonAppTests/RunnerStateTests.swift
@@ -6,8 +6,6 @@ import Testing
@Suite("Runner state detection")
struct RunnerStateTests {
- // A stand in for the runners directory, built the same way the installer builds
- // the real one: a versioned directory plus a current symlink pointing into it.
struct Fixture: ~Copyable {
let runners: URL
@@ -17,39 +15,29 @@ struct RunnerStateTests {
try FileManager.default.createDirectory(at: runners, withIntermediateDirectories: true)
}
- func makeClone(build: String, withWine: Bool = true, inBundle: Bool = false) throws -> String {
- let payload = inBundle ? "CrossOver Preview.app/Contents/SharedSupport/CrossOver" : "CrossOver"
- let relative = "crossover-\(build)/\(payload)"
- let root = runners.appending(path: relative)
+ func makeClone(build: String, withWine: Bool = true) throws {
+ let root = runners.appending(path: "crossover-\(build)/CrossOver")
let leaf = withWine ? root.appending(path: "lib/wine") : root
try FileManager.default.createDirectory(at: leaf, withIntermediateDirectories: true)
- return relative
- }
-
- func linkCurrent(to relative: String) throws {
- try FileManager.default.createSymbolicLink(
- atPath: runners.appending(path: "current").path(percentEncoded: false),
- withDestinationPath: relative
- )
}
deinit { try? FileManager.default.removeItem(at: runners) }
}
- @Test("No current link means nothing is set up")
+ @Test("No clone means nothing is set up")
func reportsNone() throws {
let fixture = try Fixture()
#expect(RunnerStore.state(runners: fixture.runners) == .none)
}
- @Test("A supported clone is reported with its build")
- func reportsSupportedClone() throws {
+ @Test("Every patched clone is reported ready")
+ func reportsReadyClones() throws {
let fixture = try Fixture()
- let version = SupportedRunners.all[0].bundleVersion
- try fixture.linkCurrent(to: fixture.makeClone(build: version))
+ let ids = SupportedRunners.all.prefix(2).map(\.id)
+ for id in ids { try fixture.makeClone(build: id) }
#expect(RunnerStore.state(runners: fixture.runners, verify: { _, _ in [] })
- == .cloned(build: version, supported: true))
+ == .ready(builds: ids.sorted()))
}
// The launch path only reads the runner, so a clone the app never finished patching
@@ -57,77 +45,37 @@ struct RunnerStateTests {
@Test("A clone missing a file the app installs is reported as unpatched")
func reportsUnpatchedClone() throws {
let fixture = try Fixture()
- let version = SupportedRunners.all[0].bundleVersion
- try fixture.linkCurrent(to: fixture.makeClone(build: version))
+ let version = SupportedRunners.all[0].id
+ try fixture.makeClone(build: version)
#expect(RunnerStore.state(runners: fixture.runners, verify: { _, _ in ["ntdll is stock"] })
== .unpatched(build: version, problems: ["ntdll is stock"]))
}
- // A clone made by an older release of the app stays on disk and keeps working,
- // so it is reported rather than treated as broken.
- @Test("A clone outside the allow list is reported as unsupported")
+ @Test("A clone outside the allow list is orphaned, not ready")
func reportsUnsupportedClone() throws {
let fixture = try Fixture()
- try fixture.linkCurrent(to: fixture.makeClone(build: "1.0.0.1"))
-
- #expect(RunnerStore.state(runners: fixture.runners) == .cloned(build: "1.0.0.1", supported: false))
- }
-
- // Nothing about this clone is visibly wrong, and it runs, so only the shape says
- // the launch path has no way to install the ntdll patch into it.
- @Test("A clone still inside an .app is reported as the older layout")
- func reportsBundleShapedClone() throws {
- let fixture = try Fixture()
- let version = SupportedRunners.all[0].bundleVersion
- try fixture.linkCurrent(to: fixture.makeClone(build: version, inBundle: true))
+ try fixture.makeClone(build: "1.0.0.1")
- #expect(RunnerStore.state(runners: fixture.runners) == .bundleShaped(build: version))
+ #expect(RunnerStore.state(runners: fixture.runners) == .none)
+ #expect(RunnerStore.orphanedClones(in: fixture.runners) == ["1.0.0.1"])
}
- @Test("A link to a tree with no lib/wine is broken")
+ @Test("A supported clone with no lib/wine is damaged, not ready")
func detectsIncompleteTree() throws {
let fixture = try Fixture()
- try fixture.linkCurrent(to: fixture.makeClone(build: "27.0.0.40921", withWine: false))
-
- guard case .broken = RunnerStore.state(runners: fixture.runners) else {
- Issue.record("expected broken, got \(RunnerStore.state(runners: fixture.runners))")
- return
- }
- }
+ let version = SupportedRunners.all[0].id
+ try fixture.makeClone(build: version, withWine: false)
- @Test("A dangling link is broken")
- func detectsDanglingLink() throws {
- let fixture = try Fixture()
- try fixture.linkCurrent(to: "crossover-27.0.0.40921/nothing/here")
-
- guard case .broken = RunnerStore.state(runners: fixture.runners) else {
- Issue.record("expected broken for a dangling link")
- return
- }
- }
-
- // This is the case the trailing slash bug hid: with a directory URL, lstat
- // resolves through the link and a real clone looks like a plain directory.
- @Test("A directory in place of the link is broken, not mistaken for a clone")
- func detectsDirectoryInsteadOfLink() throws {
- let fixture = try Fixture()
- try FileManager.default.createDirectory(
- at: fixture.runners.appending(path: "current/lib/wine"), withIntermediateDirectories: true
- )
-
- guard case .broken(let detail) = RunnerStore.state(runners: fixture.runners) else {
- Issue.record("expected broken for a directory in place of the link")
- return
- }
- #expect(detail.contains("symlink"))
+ #expect(RunnerStore.state(runners: fixture.runners) == .none)
+ #expect(RunnerStore.damagedClones(in: fixture.runners) == [version])
}
@Test("Clones are listed by version")
func listsClones() throws {
let fixture = try Fixture()
- _ = try fixture.makeClone(build: "27.0.0.40921")
- _ = try fixture.makeClone(build: "26.0.0.1")
+ try fixture.makeClone(build: "27.0.0.40921")
+ try fixture.makeClone(build: "26.0.0.1")
#expect(RunnerStore.clonedBuilds(in: fixture.runners) == ["26.0.0.1", "27.0.0.40921"])
}
diff --git a/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift b/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift
index 5322f5e..bb5e310 100644
--- a/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift
+++ b/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift
@@ -3,11 +3,12 @@ import Testing
@testable import NotProtonApp
-@Suite("Switching between installed builds")
-struct RunnerSwitchTests {
+@Suite("Preparing an installed build")
+struct RunnerPrepareTests {
- private static let rosetta = SupportedRunners.all.first { $0.flavor == nil }!
+ private static let rosetta = SupportedRunners.all.first { $0.id == "27.0.0.40921" }!
private static let fex = SupportedRunners.all.first { $0.flavor == "fex" }!
+ private static let release = SupportedRunners.all.first { $0.id == "26.3.0.39832" }!
private static let licensed = CrossOverLicense.Status(
licensed: true, detail: "CrossOver is activated.", diagnostic: "test"
@@ -19,12 +20,11 @@ struct RunnerSwitchTests {
private final class Calls: @unchecked Sendable {
var staged: [String] = []
var patched: [String] = []
- var currentWhilePatching: String?
}
private func makeRunners(cloning builds: [RunnerBuild]) throws -> URL {
let runners = FileManager.default.temporaryDirectory
- .appending(path: "np-switch-\(UUID().uuidString)")
+ .appending(path: "np-prepare-\(UUID().uuidString)")
for build in builds {
try FileManager.default.createDirectory(
at: SupportPaths.clonedRoot(forBuild: build.id, runners: runners)
@@ -35,44 +35,37 @@ struct RunnerSwitchTests {
return runners
}
- private static func stagedCopy(_ arch: WineArch, in bridge: URL) -> URL {
- bridge.appending(path: "wine/\(arch.rawValue)/ntdll.dll")
- }
-
private static func writeStaged(for build: RunnerBuild, into bridge: URL) throws {
for arch in build.patchedNtdll.keys {
- try atomicReplace(stagedCopy(arch, in: bridge), with: Data("\(build.id) \(arch.rawValue)".utf8), step: "test")
- }
- }
-
- private static func seedBridge(_ bridge: URL, with copies: [WineArch: String]) throws -> [WineArch: Data] {
- var seeded: [WineArch: Data] = [:]
- for (arch, text) in copies {
- seeded[arch] = Data(text.utf8)
- try atomicReplace(stagedCopy(arch, in: bridge), with: seeded[arch]!, step: "test")
+ try atomicReplace(
+ NtdllPatcher.stagedCopy(of: arch, build: build.id, in: bridge),
+ with: Data("\(build.id) \(arch.rawValue)".utf8), step: "test"
+ )
}
- return seeded
}
- private static func bridgeContents(_ bridge: URL) -> [WineArch: Data] {
+ private static func staged(_ build: RunnerBuild, in bridge: URL) -> [WineArch: Data] {
var found: [WineArch: Data] = [:]
for arch in WineArch.allCases {
- if let data = try? Data(contentsOf: stagedCopy(arch, in: bridge)) { found[arch] = data }
+ let copy = NtdllPatcher.stagedCopy(of: arch, build: build.id, in: bridge)
+ if let data = try? Data(contentsOf: copy) { found[arch] = data }
}
return found
}
- private func activate(
+ private func prepare(
_ build: RunnerBuild,
runners: URL,
calls: Calls,
license: CrossOverLicense.Status = licensed,
failPatch: Bool = false
) throws -> RunnerSetup.Outcome {
- try RunnerSetup.activate(
+ try RunnerSetup.prepare(
build,
runners: runners,
bridge: runners.appending(path: "bridge"),
+ toolList: runners.appending(path: "tools"),
+ compatTools: runners.appending(path: "compatibilitytools.d"),
license: { _ in license },
verify: { _, _ in },
stage: { build, _, bridge in
@@ -82,169 +75,216 @@ struct RunnerSwitchTests {
},
patch: { build, _, _ in
calls.patched.append(build.id)
- calls.currentWhilePatching = RunnerStore.currentBuild(runners: runners)
if failPatch { throw StepFailure(step: "test", detail: "patch failed") }
return RunnerPatcher.Outcome()
}
)
}
- @Test("Switching moves the link to the other build")
- func switchesBuild() throws {
- let runners = try makeRunners(cloning: [Self.rosetta, Self.fex])
+ private func toolList(_ runners: URL) -> String? {
+ try? String(contentsOf: runners.appending(path: "tools"), encoding: .utf8)
+ }
+
+ @Test("Every set-up build is listed as its own tools")
+ func listsEveryBuild() throws {
+ let runners = try makeRunners(cloning: [Self.release, Self.fex])
defer { try? FileManager.default.removeItem(at: runners) }
- try RunnerInstaller.pointCurrent(atBuild: Self.rosetta.id, runners: runners)
let calls = Calls()
- let outcome = try activate(Self.fex, runners: runners, calls: calls)
+ let outcome = try prepare(Self.release, runners: runners, calls: calls)
- #expect(outcome.build == Self.fex)
- #expect(RunnerStore.currentBuild(runners: runners) == Self.fex.id)
- #expect(calls.staged == [Self.fex.id])
- #expect(calls.patched == [Self.fex.id])
+ #expect(outcome.toolsChanged)
+ #expect(calls.staged == [Self.release.id])
+ #expect(calls.patched == [Self.release.id])
+ #expect(toolList(runners) == CompatToolList.contents(
+ SupportedRunners.tools(for: [Self.release, Self.fex])
+ ))
+ #expect(toolList(runners)?.hasPrefix("notproton\t27.0.0.40921-fex\tfex\t") == true)
- _ = try activate(Self.rosetta, runners: runners, calls: calls)
- #expect(RunnerStore.currentBuild(runners: runners) == Self.rosetta.id)
+ let again = try prepare(Self.release, runners: runners, calls: calls)
+ #expect(!again.toolsChanged)
}
- @Test("The link only moves once the target is patched")
- func linkMovesLast() throws {
+ @Test("Preparing one build leaves another build's staged copies alone")
+ func keepsOtherBuildsStaged() throws {
let runners = try makeRunners(cloning: [Self.rosetta, Self.fex])
defer { try? FileManager.default.removeItem(at: runners) }
- try RunnerInstaller.pointCurrent(atBuild: Self.rosetta.id, runners: runners)
+ let bridge = runners.appending(path: "bridge")
+ try Self.writeStaged(for: Self.rosetta, into: bridge)
+ let before = Self.staged(Self.rosetta, in: bridge)
- let calls = Calls()
- _ = try activate(Self.fex, runners: runners, calls: calls)
+ _ = try prepare(Self.fex, runners: runners, calls: Calls())
- #expect(calls.currentWhilePatching == Self.rosetta.id)
+ #expect(Self.staged(Self.rosetta, in: bridge) == before)
+ #expect(Self.staged(Self.fex, in: bridge).count == Self.fex.patchedNtdll.count)
}
- @Test("A failed switch keeps the old build and puts its bridge copies back")
- func failedSwitchRestoresPrevious() throws {
- let runners = try makeRunners(cloning: [Self.rosetta, Self.fex])
+ @Test("A failed patch leaves the tool list as it was")
+ func failedPatchKeepsList() throws {
+ let runners = try makeRunners(cloning: [Self.fex])
defer { try? FileManager.default.removeItem(at: runners) }
- try RunnerInstaller.pointCurrent(atBuild: Self.rosetta.id, runners: runners)
- let bridge = runners.appending(path: "bridge")
- let seeded = try Self.seedBridge(bridge, with: [.x86_64Windows: "old x86_64", .i386Windows: "old i386"])
- let calls = Calls()
#expect(throws: StepFailure.self) {
- try activate(Self.fex, runners: runners, calls: calls, failPatch: true)
+ try prepare(Self.fex, runners: runners, calls: Calls(), failPatch: true)
+ }
+ #expect(toolList(runners) == nil)
+ }
+
+ @Test("Copies and links left by the single-build layout are cleared")
+ func clearsLegacyLayout() throws {
+ let runners = try makeRunners(cloning: [Self.fex])
+ defer { try? FileManager.default.removeItem(at: runners) }
+ let bridge = runners.appending(path: "bridge")
+ let legacy = bridge.appending(path: "wine/x86_64-windows/ntdll.dll")
+ let gone = NtdllPatcher.stagedCopy(of: .x86_64Windows, build: Self.rosetta.id, in: bridge)
+ for file in [legacy, gone] {
+ try atomicReplace(file, with: Data("old".utf8), step: "test")
}
+ try FileManager.default.createSymbolicLink(
+ atPath: runners.appending(path: "current").path(percentEncoded: false),
+ withDestinationPath: "crossover-\(Self.fex.id)/CrossOver"
+ )
+
+ _ = try prepare(Self.fex, runners: runners, calls: Calls())
- #expect(RunnerStore.currentBuild(runners: runners) == Self.rosetta.id)
- #expect(calls.staged == [Self.fex.id])
- #expect(Self.bridgeContents(bridge) == seeded)
+ let fm = FileManager.default
+ #expect(!fm.fileExists(atPath: legacy.deletingLastPathComponent().path(percentEncoded: false)))
+ #expect(!fm.fileExists(atPath: gone.path(percentEncoded: false)))
+ #expect((try? fm.destinationOfSymbolicLink(
+ atPath: runners.appending(path: "current").path(percentEncoded: false))) == nil)
+ #expect(Self.staged(Self.fex, in: bridge).count == Self.fex.patchedNtdll.count)
+ }
+
+ @Test("With nothing set up and no list yet, no list is written")
+ func writesNoEmptyList() throws {
+ let runners = try makeRunners(cloning: [])
+ defer { try? FileManager.default.removeItem(at: runners) }
+ let file = runners.appending(path: "support/tools")
+
+ let changed = try CompatToolList.sync(
+ runners: runners, bridge: runners.appending(path: "bridge"), file: file,
+ compatTools: runners.appending(path: "compatibilitytools.d")
+ )
+
+ #expect(!changed)
#expect(!FileManager.default.fileExists(
- atPath: bridge.appending(path: "wine/aarch64-windows").path(percentEncoded: false)))
+ atPath: file.deletingLastPathComponent().path(percentEncoded: false)))
}
- @Test("A failed switch away from a build the app no longer lists puts its bridge copies back")
- func failedSwitchFromUnlistedBuild() throws {
- let unlisted = "26.0.0.1"
- #expect(SupportedRunners.build(id: unlisted) == nil)
+ private func sync(_ runners: URL) throws {
+ try CompatToolList.sync(
+ runners: runners, bridge: runners.appending(path: "bridge"), file: runners.appending(path: "tools"),
+ compatTools: runners.appending(path: "compatibilitytools.d")
+ )
+ }
- let runners = try makeRunners(cloning: [Self.fex])
+ private func holder(_ runners: URL) -> String? {
+ toolList(runners)?.split(separator: "\n").map { $0.split(separator: "\t") }
+ .first { $0.first == "notproton" }.map { String($0[1]) }
+ }
+
+ @Test("A 1.0 install keeps the legacy name on the build runners/current pointed at")
+ func legacyNameFollowsCurrent() throws {
+ let runners = try makeRunners(cloning: [Self.rosetta, Self.fex])
defer { try? FileManager.default.removeItem(at: runners) }
- try FileManager.default.createDirectory(
- at: SupportPaths.clonedRoot(forBuild: unlisted, runners: runners).appending(path: "lib/wine"),
- withIntermediateDirectories: true
+ let current = runners.appending(path: "current").path(percentEncoded: false)
+ try FileManager.default.createSymbolicLink(
+ atPath: current, withDestinationPath: "crossover-\(Self.rosetta.id)/CrossOver"
)
- try RunnerInstaller.pointCurrent(atBuild: unlisted, runners: runners)
- let bridge = runners.appending(path: "bridge")
- let seeded = try Self.seedBridge(bridge, with: [.x86_64Windows: "old x86_64", .i386Windows: "old i386"])
- let calls = Calls()
- #expect(throws: StepFailure.self) {
- try activate(Self.fex, runners: runners, calls: calls, failPatch: true)
- }
+ try sync(runners)
+ #expect(holder(runners) == Self.rosetta.id)
+ #expect((try? FileManager.default.destinationOfSymbolicLink(atPath: current)) == nil)
- #expect(RunnerStore.currentBuild(runners: runners) == unlisted)
- #expect(Self.bridgeContents(bridge) == seeded)
+ try sync(runners)
+ #expect(holder(runners) == Self.rosetta.id)
+ #expect(toolList(runners)?.contains("notproton-fex\t\(Self.fex.id)\tfex\t") == true)
}
- @Test("A failed first setup leaves no staged copies behind")
- func failedFirstSetupLeavesBridgeEmpty() throws {
+ @Test("Setting up a second Preview leaves the legacy name where it is")
+ func secondPreviewRenamesNothing() throws {
let runners = try makeRunners(cloning: [Self.fex])
defer { try? FileManager.default.removeItem(at: runners) }
- let bridge = runners.appending(path: "bridge")
+ try sync(runners)
+ #expect(holder(runners) == Self.fex.id)
- let calls = Calls()
- #expect(throws: StepFailure.self) {
- try activate(Self.fex, runners: runners, calls: calls, failPatch: true)
- }
-
- #expect(RunnerStore.currentBuild(runners: runners) == nil)
- #expect(calls.staged == [Self.fex.id])
- #expect(Self.bridgeContents(bridge).isEmpty)
+ try FileManager.default.createDirectory(
+ at: SupportPaths.clonedRoot(forBuild: Self.rosetta.id, runners: runners).appending(path: "lib/wine"),
+ withIntermediateDirectories: true
+ )
+ try sync(runners)
+ #expect(holder(runners) == Self.fex.id)
+ #expect(toolList(runners)?.contains("notproton-preview\t\(Self.rosetta.id)\t") == true)
+ #expect(toolList(runners)?.contains("notproton-fex-rosetta\t\(Self.fex.id)\t") == true)
}
- @Test("A failed bridge restore reports both failures")
- func failedRestoreIsReported() throws {
+ @Test("A Preview listed under its own name does not take the legacy name later")
+ func ownNameSticks() throws {
let runners = try makeRunners(cloning: [Self.rosetta, Self.fex])
+ defer { try? FileManager.default.removeItem(at: runners) }
+ try CompatToolList.contents(SupportedRunners.tools(for: [Self.rosetta, Self.fex], legacy: .nobody))
+ .write(to: runners.appending(path: "tools"), atomically: true, encoding: .utf8)
+
+ try sync(runners)
+ #expect(holder(runners) == nil)
+ }
+
+ @Test("The single-build layout stays while Steam still runs a tool that reads it")
+ func keepsLegacyLayoutForOldRunScript() throws {
+ let runners = try makeRunners(cloning: [Self.fex])
+ defer { try? FileManager.default.removeItem(at: runners) }
let bridge = runners.appending(path: "bridge")
- let locked = bridge.appending(path: "wine/x86_64-windows")
- defer {
- try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path(percentEncoded: false))
- try? FileManager.default.removeItem(at: runners)
- }
- try RunnerInstaller.pointCurrent(atBuild: Self.rosetta.id, runners: runners)
- _ = try Self.seedBridge(bridge, with: [.x86_64Windows: "old x86_64"])
+ let legacy = bridge.appending(path: "wine/x86_64-windows/ntdll.dll")
+ try atomicReplace(legacy, with: Data("old".utf8), step: "test")
+ let current = runners.appending(path: "current").path(percentEncoded: false)
+ try FileManager.default.createSymbolicLink(
+ atPath: current, withDestinationPath: "crossover-\(Self.fex.id)/CrossOver"
+ )
+ let run = runners.appending(path: "compatibilitytools.d/notproton/run")
+ try atomicReplace(
+ run, with: Data("CX_ROOT=\"$HOME/Library/Application Support/notproton/runners/current\"\n".utf8),
+ step: "test"
+ )
- let failure = try #require(throws: StepFailure.self) {
- try RunnerSetup.activate(
- Self.fex,
- runners: runners,
- bridge: bridge,
- license: { _ in Self.licensed },
- verify: { _, _ in },
- stage: { build, _, bridge in
- try Self.writeStaged(for: build, into: bridge)
- try FileManager.default.setAttributes(
- [.posixPermissions: 0o555], ofItemAtPath: locked.path(percentEncoded: false))
- return []
- },
- patch: { _, _, _ in
- throw StepFailure(step: "patch", detail: "patch failed")
- }
- )
- }
+ _ = try prepare(Self.fex, runners: runners, calls: Calls())
- #expect(RunnerStore.currentBuild(runners: runners) == Self.rosetta.id)
- #expect(failure.detail.contains("patch failed"))
- #expect(failure.detail.contains("Restoring the previous build also failed"))
- #expect(failure.detail.contains("x86_64-windows"))
+ let fm = FileManager.default
+ #expect(fm.fileExists(atPath: legacy.path(percentEncoded: false)))
+ #expect((try? fm.destinationOfSymbolicLink(atPath: current)) != nil)
+
+ try atomicReplace(run, with: Data("CX_ROOT=\"$np_support/runners/crossover-$np_build\"\n".utf8), step: "test")
+ _ = try prepare(Self.fex, runners: runners, calls: Calls())
+ #expect(!fm.fileExists(atPath: legacy.path(percentEncoded: false)))
+ #expect((try? fm.destinationOfSymbolicLink(atPath: current)) == nil)
}
@Test("A build with no clone is refused without touching anything")
func refusesMissingClone() throws {
let runners = try makeRunners(cloning: [Self.rosetta])
defer { try? FileManager.default.removeItem(at: runners) }
- try RunnerInstaller.pointCurrent(atBuild: Self.rosetta.id, runners: runners)
let calls = Calls()
let failure = try #require(throws: StepFailure.self) {
- try activate(Self.fex, runners: runners, calls: calls)
+ try prepare(Self.fex, runners: runners, calls: calls)
}
#expect(failure.detail.contains("has not been set up"))
#expect(calls.staged.isEmpty)
- #expect(RunnerStore.currentBuild(runners: runners) == Self.rosetta.id)
+ #expect(toolList(runners) == nil)
}
- @Test("Switching is refused when CrossOver is not activated")
+ @Test("Preparing is refused when CrossOver is not activated")
func refusesUnlicensed() throws {
let runners = try makeRunners(cloning: [Self.rosetta, Self.fex])
defer { try? FileManager.default.removeItem(at: runners) }
- try RunnerInstaller.pointCurrent(atBuild: Self.rosetta.id, runners: runners)
let calls = Calls()
#expect(throws: StepFailure.self) {
- try activate(Self.fex, runners: runners, calls: calls, license: Self.unlicensed)
+ try prepare(Self.fex, runners: runners, calls: calls, license: Self.unlicensed)
}
#expect(calls.staged.isEmpty)
- #expect(RunnerStore.currentBuild(runners: runners) == Self.rosetta.id)
+ #expect(toolList(runners) == nil)
}
@Test("Installed builds are supported clones that still have their payload")
@@ -286,18 +326,18 @@ struct SetupSourceTests {
crossOver: installs,
crossOverLicense: [:],
runner: runner,
- payload: PayloadInspector.inspect(bridge: FileManager.default.temporaryDirectory)
+ payload: PayloadInspector.inspect(bridge: FileManager.default.temporaryDirectory, builds: [])
)
return status
}
- @Test("A recopy comes from the install the current build was cloned from")
- func prefersCurrentBuild() {
+ @Test("A recopy comes from the install a set-up build was cloned from")
+ func prefersInstalledBuild() {
let rosetta = install("CrossOver", SupportedRunners.all[0])
let fex = install("CrossOver FEX", SupportedRunners.all[1])
let status = status(
- runner: .cloned(build: SupportedRunners.all[1].id, supported: true),
+ runner: .ready(builds: [SupportedRunners.all[1].id]),
installs: [rosetta, fex]
)
@@ -315,55 +355,51 @@ struct SetupSourceTests {
#expect(status.usableCrossOvers.map(\.id) == [rosetta.id, fex.id])
}
- @Test("An install matching the current build can repair it")
- func repairSourceMatchesCurrentBuild() {
+ @Test("An install matching a set-up build can repair it")
+ func repairSourceMatchesInstalledBuild() {
let rosetta = install("CrossOver", SupportedRunners.all[0])
let status = status(
- runner: .cloned(build: SupportedRunners.all[0].id, supported: true),
+ runner: .ready(builds: [SupportedRunners.all[0].id]),
installs: [rosetta]
)
status.snapshot?.installedRunners = [SupportedRunners.all[0]]
#expect(status.repairSource?.id == rosetta.id)
- #expect(status.availableBuilds.isEmpty)
}
- @Test("An install offering another build cannot repair the current one")
+ @Test("An install offering another build cannot repair a set-up one")
func repairSourceIsNilWhenBuildDiffers() {
let rosetta = install("CrossOver", SupportedRunners.all[0])
let status = status(
- runner: .cloned(build: SupportedRunners.all[1].id, supported: true),
+ runner: .ready(builds: [SupportedRunners.all[1].id]),
installs: [rosetta]
)
status.snapshot?.installedRunners = [SupportedRunners.all[1]]
#expect(status.repairSource == nil)
#expect(status.setupSource?.id == rosetta.id)
- #expect(status.availableBuilds.map(\.id) == [SupportedRunners.all[0].id])
}
- @Test("A build already on disk is not offered as available")
- func deployedBuildIsNotOffered() {
+ @Test("With every build on disk, a repair comes from the set-up build's install")
+ func repairSourceWithEveryBuildCopied() {
let rosetta = install("CrossOver", SupportedRunners.all[0])
let fex = install("CrossOver FEX", SupportedRunners.all[1])
let status = status(
- runner: .cloned(build: SupportedRunners.all[1].id, supported: true),
+ runner: .ready(builds: [SupportedRunners.all[1].id]),
installs: [rosetta, fex]
)
status.snapshot?.installedRunners = SupportedRunners.all
#expect(status.repairSource?.id == fex.id)
- #expect(status.availableBuilds.isEmpty)
}
- @Test("With nothing set up the runner row keeps the offer to itself")
- func nothingOfferedBeforeFirstSetUp() {
+ @Test("With nothing set up there is no repair source")
+ func noRepairSourceBeforeFirstSetUp() {
let rosetta = install("CrossOver", SupportedRunners.all[0])
let status = status(runner: .none, installs: [rosetta])
#expect(status.repairSource == nil)
#expect(status.setupSource?.id == rosetta.id)
- #expect(status.availableBuilds.isEmpty)
}
}
@@ -386,29 +422,62 @@ struct RunnerRemovalTests {
return runners
}
- @Test("A build that is not active is deleted from disk")
- func removesInactiveBuild() throws {
- let runners = try makeRunners(cloning: [Self.rosetta.id, Self.fex.id])
- defer { try? FileManager.default.removeItem(at: runners) }
- try RunnerInstaller.pointCurrent(atBuild: Self.rosetta.id, runners: runners)
+ private func remove(_ build: String, runners: URL, running: Bool = false) throws -> Bool {
+ try RunnerInstaller.removeClone(
+ forBuild: build, runners: runners,
+ bridge: runners.appending(path: "bridge"), toolList: runners.appending(path: "tools"),
+ compatTools: runners.appending(path: "compatibilitytools.d"),
+ running: { _ in running }
+ )
+ }
- try RunnerInstaller.removeClone(forBuild: Self.fex.id, runners: runners)
+ @Test("A build with a game still running on it is not removed")
+ func keepsRunningBuild() throws {
+ let runners = try makeRunners(cloning: [Self.rosetta.id])
+ defer { try? FileManager.default.removeItem(at: runners) }
- #expect(!RunnerInstaller.hasClone(forBuild: Self.fex.id, runners: runners))
+ #expect(throws: StepFailure.self) { try remove(Self.rosetta.id, runners: runners, running: true) }
#expect(RunnerInstaller.hasClone(forBuild: Self.rosetta.id, runners: runners))
- #expect(RunnerStore.currentBuild(runners: runners) == Self.rosetta.id)
}
- @Test("The active build is refused so the tool keeps working")
- func refusesActiveBuild() throws {
+ @Test("A process runs from a clone only when its executable sits inside it")
+ func readsRunningExecutables() throws {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-ps-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let ps = dir.appending(path: "ps")
+ try """
+ #!/bin/sh
+ echo "/launchd"
+ echo "/R/crossover-26.3.0.39832/CrossOver/CrossOver-Hosted Application/wineserver"
+ """.write(to: ps, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: ps.path(percentEncoded: false))
+ let path = ps.path(percentEncoded: false)
+
+ #expect(RunnerInstaller.isRunning(from: URL(filePath: "/R/crossover-26.3.0.39832"), ps: path))
+ #expect(!RunnerInstaller.isRunning(from: URL(filePath: "/R/crossover-26.3.0"), ps: path))
+ #expect(!RunnerInstaller.isRunning(from: URL(filePath: "/R/crossover-27.0.0.40921"), ps: path))
+ #expect(RunnerInstaller.isRunning(from: URL(filePath: "/R/x"), ps: "/nonexistent/ps"))
+ }
+
+ @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])
defer { try? FileManager.default.removeItem(at: runners) }
- try RunnerInstaller.pointCurrent(atBuild: Self.rosetta.id, runners: runners)
+ let bridge = runners.appending(path: "bridge")
+ let staged = NtdllPatcher.stagedCopy(of: .x86_64Windows, build: Self.fex.id, in: bridge)
+ try atomicReplace(staged, with: Data("fex".utf8), step: "test")
- #expect(throws: StepFailure.self) {
- try RunnerInstaller.removeClone(forBuild: Self.rosetta.id, runners: runners)
- }
+ #expect(try remove(Self.fex.id, runners: runners))
+
+ #expect(!RunnerInstaller.hasClone(forBuild: Self.fex.id, runners: runners))
#expect(RunnerInstaller.hasClone(forBuild: Self.rosetta.id, runners: runners))
+ #expect(!FileManager.default.fileExists(atPath: staged.path(percentEncoded: false)))
+ let list = try String(contentsOf: runners.appending(path: "tools"), encoding: .utf8)
+ #expect(list == CompatToolList.contents(SupportedRunners.tools(for: [Self.rosetta])))
+
+ #expect(try remove(Self.rosetta.id, runners: runners))
+ #expect(try String(contentsOf: runners.appending(path: "tools"), encoding: .utf8).isEmpty)
}
@Test("A build with no clone reports rather than succeeding quietly")
@@ -417,7 +486,7 @@ struct RunnerRemovalTests {
defer { try? FileManager.default.removeItem(at: runners) }
#expect(throws: StepFailure.self) {
- try RunnerInstaller.removeClone(forBuild: Self.fex.id, runners: runners)
+ try remove(Self.fex.id, runners: runners)
}
}
@@ -468,9 +537,8 @@ struct RunnerRemovalTests {
func removesOrphanedClone() throws {
let runners = try makeRunners(cloning: [Self.rosetta.id, "1.2.3.4567"])
defer { try? FileManager.default.removeItem(at: runners) }
- try RunnerInstaller.pointCurrent(atBuild: Self.rosetta.id, runners: runners)
- try RunnerInstaller.removeClone(forBuild: "1.2.3.4567", runners: runners)
+ _ = try remove("1.2.3.4567", runners: runners)
#expect(RunnerStore.orphanedClones(in: runners).isEmpty)
#expect(RunnerInstaller.hasClone(forBuild: Self.rosetta.id, runners: runners))
diff --git a/app/Tests/NotProtonAppTests/SystemStatusTests.swift b/app/Tests/NotProtonAppTests/SystemStatusTests.swift
index 1757fae..e2e92fb 100644
--- a/app/Tests/NotProtonAppTests/SystemStatusTests.swift
+++ b/app/Tests/NotProtonAppTests/SystemStatusTests.swift
@@ -421,7 +421,7 @@ struct ActivationQuestionTests {
func installWithToolAsksNothing() {
#expect(
SystemStatus.activationQuestion(
- .install, licensed: false, runner: .cloned(build: "27.0.0.40921", supported: true)
+ .install, licensed: false, runner: .ready(builds: ["27.0.0.40921"])
) == nil
)
}
@@ -435,7 +435,7 @@ struct ActivationQuestionTests {
// whatever is already set up.
@Test("Setting up the tool asks whenever CrossOver is unactivated")
func unactivatedToolAsks() {
- for runner in [RunnerState.none, .cloned(build: "27.0.0.40921", supported: true)] {
+ for runner in [RunnerState.none, .ready(builds: ["27.0.0.40921"])] {
#expect(
SystemStatus.activationQuestion(.compatibilityTool, licensed: false, runner: runner)
== .toolUnlicensed
diff --git a/app/Tests/NotProtonAppTests/UninstallTests.swift b/app/Tests/NotProtonAppTests/UninstallTests.swift
index dad906b..5c13941 100644
--- a/app/Tests/NotProtonAppTests/UninstallTests.swift
+++ b/app/Tests/NotProtonAppTests/UninstallTests.swift
@@ -26,6 +26,12 @@ struct UninstallTests {
let support: URL
let caches: URL
+ var compatTools: [URL] {
+ SupportPaths.Steam.notprotonTools(in: compatTool.deletingLastPathComponent())
+ }
+ var secondTool: URL { compatTool.deletingLastPathComponent().appending(path: "notproton-26.3") }
+ var foreignTool: URL { compatTool.deletingLastPathComponent().appending(path: "GE-Proton9-1") }
+
var outerPlist: URL { app.appending(path: "Contents/Info.plist") }
var dylib: URL { app.appending(path: "Contents/MacOS/\(SupportPaths.dylibName)") }
}
@@ -41,7 +47,9 @@ struct UninstallTests {
let support = root.appending(path: "notproton")
let caches = root.appending(path: "valve-packages")
- for dir in [macOS, inner, legacyCompat, compatTool, support, caches] {
+ let tools = compatTool.deletingLastPathComponent()
+ for dir in [macOS, inner, legacyCompat, compatTool, support, caches,
+ tools.appending(path: "notproton-26.3"), tools.appending(path: "GE-Proton9-1")] {
try files.createDirectory(at: dir, withIntermediateDirectories: true)
}
@@ -198,7 +206,7 @@ struct UninstallTests {
innerPlist: layout.innerPlist,
updateBlocks: [layout.updateBlock],
legacyCompat: layout.legacyCompat,
- compatTool: layout.compatTool,
+ compatTools: layout.compatTools,
directories: [layout.support, layout.caches],
repair: { _ in throw Offline() },
stop: { _ in false }
@@ -214,6 +222,8 @@ struct UninstallTests {
!files.fileExists(atPath: layout.compatTool.path(percentEncoded: false)),
"Steam would still list the tool in its dropdown after a removal"
)
+ #expect(!files.fileExists(atPath: layout.secondTool.path(percentEncoded: false)))
+ #expect(files.fileExists(atPath: layout.foreignTool.path(percentEncoded: false)))
#expect(unpinnedWithoutLosingTheRest(layout.updateBlock))
}
@@ -229,7 +239,7 @@ struct UninstallTests {
innerPlist: layout.innerPlist,
updateBlocks: [layout.updateBlock],
legacyCompat: layout.legacyCompat,
- compatTool: layout.compatTool,
+ compatTools: layout.compatTools,
directories: [layout.support, caches],
repair: { _ in
let staged = caches.appending(path: "bundle")
@@ -256,7 +266,7 @@ struct UninstallTests {
innerPlist: layout.innerPlist,
updateBlocks: [layout.updateBlock],
legacyCompat: layout.legacyCompat,
- compatTool: layout.compatTool,
+ compatTools: layout.compatTools,
directories: [layout.support, layout.caches],
report: { log.add($0) },
repair: { report in
diff --git a/lsteamclient/build.sh b/lsteamclient/build.sh
index d47ac42..6df1768 100755
--- a/lsteamclient/build.sh
+++ b/lsteamclient/build.sh
@@ -64,7 +64,17 @@ TREE=${TREE:-$repo/build/lsteamclient}
# The cloned runner, not the user's installed CrossOver. --install writes into this
# tree, and the installed app has to stay stock: it is the only clean copy on the
# machine and it is what the clone and the ntdll patcher are both taken from.
-CX_ROOT=${CX_ROOT:-$HOME/Library/Application Support/notproton/runners/current}
+if [ -z "${CX_ROOT:-}" ]; then
+ for clone in "$HOME/Library/Application Support/notproton/runners"/crossover-*/CrossOver; do
+ [ -d "$clone" ] || continue
+ if [ -n "${CX_ROOT:-}" ]; then
+ echo "==> more than one runner clone is set up, set CX_ROOT to one of them" >&2
+ exit 1
+ fi
+ CX_ROOT=$clone
+ done
+fi
+CX_ROOT=${CX_ROOT:-$HOME/Library/Application Support/notproton/runners/(none set up)}
BRIDGE_DIR=${BRIDGE_DIR:-$HOME/Library/Application Support/notproton/bridge}
install=0
diff --git a/ntdll-patch/apply.py b/ntdll-patch/apply.py
index 2e1b679..770037c 100644
--- a/ntdll-patch/apply.py
+++ b/ntdll-patch/apply.py
@@ -7,7 +7,7 @@ import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from resolve import PE, resolve, shell_vars # noqa: E402
+from resolve import PE, SECTION_FLAGS, SECTION_NAME, SECTION_SIZE, resolve, shell_vars # noqa: E402
# A new build needs its ntdll hash added here and in build-ntdll.sh.
PAYLOAD_BY_CLEAN_SHA = {
@@ -16,6 +16,8 @@ PAYLOAD_BY_CLEAN_SHA = {
"f4fa556a3dc20f6e966a803f5de554359227a61a24cd5b5a2ad88a427ceeec58": "detour2-fex.bin",
"09474795d6f306163cebab6429819999fcff50e07dbc4b067a90ec4f74a3a7d7": "detour32-fex.bin",
"7823d71fbce6c9947163bf8b96beb299eabb02878245bcaf6759f2a22e81f071": "detour64-fex.bin",
+ "6dff64c00793ce92124f1316985c63783f539f26b392975c70f57637458d2387": "detour2-cx26.bin",
+ "2c60ee6b00dd13b7f6cb11017778a041ba6a321eaea194f1fa0dca7eab8403e2": "detour32-cx26.bin",
}
UNAMBIGUOUS_PAYLOAD = {0xaa64: "detour64-fex.bin"}
@@ -34,6 +36,20 @@ def default_payload(src, machine):
f"third argument")
+def append_section(pe, d, r):
+ """Grows the image by one executable section and returns its file offset."""
+ import struct
+ raw = r['rawOffset']
+ e = struct.unpack_from('<I', d, 0x3c)[0]
+ d[pe.table_end:pe.table_end + 40] = struct.pack(
+ '<8sIIIIIIHHI', SECTION_NAME, SECTION_SIZE, r['caveRVA'], SECTION_SIZE, raw,
+ 0, 0, 0, 0, SECTION_FLAGS)
+ struct.pack_into('<H', d, e + 6, struct.unpack_from('<H', d, e + 6)[0] + 1)
+ struct.pack_into('<I', d, pe.opt + 56, r['caveRVA'] + SECTION_SIZE)
+ d.extend(b"\0" * (raw + SECTION_SIZE - len(d)))
+ return raw
+
+
def main():
if len(sys.argv) < 2:
raise SystemExit(f"usage: {sys.argv[0]} <src ntdll.dll> [dst] [payload.bin]")
@@ -54,7 +70,10 @@ def main():
pe = PE(src)
d = bytearray(pe.d)
- cave_off = pe.off(payload_rva)
+ if r['placement'] == 'section':
+ cave_off = append_section(pe, d, r)
+ else:
+ cave_off = pe.off(payload_rva)
if any(b != fill for b in d[cave_off:cave_off + len(detour)]):
raise SystemExit(f"cave at {cave_off:#x} is not {fill:#02x} pad for {len(detour)} bytes")
diff --git a/ntdll-patch/build-ntdll.sh b/ntdll-patch/build-ntdll.sh
index 747aea4..db022b5 100755
--- a/ntdll-patch/build-ntdll.sh
+++ b/ntdll-patch/build-ntdll.sh
@@ -18,6 +18,11 @@ ROSETTA_CLEAN_I386=94cc7c14c1e9dcf58ef501015c115f8405c73b2a65cefe31faa5d9e47f36e
ROSETTA_PATCHED_X86_64=b6a98622fb8f7e6a998bc038f442b17d257da3df5e9e135f0c35f7bbc46ea5d6
ROSETTA_PATCHED_I386=25bfde1f50ee96485763968ef10b9d9ad35e38214232f17ebdc009b098af44a0
+CX26_CLEAN_X86_64=6dff64c00793ce92124f1316985c63783f539f26b392975c70f57637458d2387
+CX26_CLEAN_I386=2c60ee6b00dd13b7f6cb11017778a041ba6a321eaea194f1fa0dca7eab8403e2
+CX26_PATCHED_X86_64=c0e21a9a5250f0a97c08d3c3e1798566255387213e2553b1e555264fb9ded97e
+CX26_PATCHED_I386=e641d7b2e81ee13877823494679ba2d87e0d61b8a87e8a1ce92b4fe73631ae74
+
FEX_CLEAN_X86_64=f4fa556a3dc20f6e966a803f5de554359227a61a24cd5b5a2ad88a427ceeec58
FEX_CLEAN_I386=09474795d6f306163cebab6429819999fcff50e07dbc4b067a90ec4f74a3a7d7
FEX_CLEAN_AARCH64=7823d71fbce6c9947163bf8b96beb299eabb02878245bcaf6759f2a22e81f071
@@ -44,10 +49,13 @@ flavor_of() {
for cand in "$CX_ROOT/lib/wine/x86_64-windows/ntdll.dll.notproton-orig" \
"$CX_ROOT/lib/wine/x86_64-windows/ntdll.dll"; do
[ -f "$cand" ] || continue
- if [ "$(sha "$cand")" = "$ROSETTA_CLEAN_X86_64" ]; then echo rosetta; return 0; fi
+ case "$(sha "$cand")" in
+ "$ROSETTA_CLEAN_X86_64") echo rosetta; return 0 ;;
+ "$CX26_CLEAN_X86_64") echo cx26; return 0 ;;
+ esac
done
die "no ntdll under $CX_ROOT/lib/wine matches a pinned build
- pass FLAVOR=rosetta or FLAVOR=fex to choose the pins anyway"
+ pass FLAVOR=rosetta, FLAVOR=cx26 or FLAVOR=fex to choose the pins anyway"
}
if [ -z "${FLAVOR:-}" ]; then
@@ -55,9 +63,11 @@ if [ -z "${FLAVOR:-}" ]; then
fi
case "$FLAVOR" in
- rosetta) tools="x86_64-w64-mingw32-gcc i686-w64-mingw32-gcc" ;;
- fex) tools="x86_64-w64-mingw32-gcc i686-w64-mingw32-gcc clang ld.lld" ;;
- *) die "unknown flavor $FLAVOR, expected rosetta or fex" ;;
+ rosetta) tools="x86_64-w64-mingw32-gcc i686-w64-mingw32-gcc"; BUILD=27.0.0.40921 ;;
+ cx26) tools="x86_64-w64-mingw32-gcc i686-w64-mingw32-gcc"; BUILD=26.3.0.39832 ;;
+ fex) tools="x86_64-w64-mingw32-gcc i686-w64-mingw32-gcc clang ld.lld"
+ BUILD=27.0.0.40921-fex ;;
+ *) die "unknown flavor $FLAVOR, expected rosetta, cx26 or fex" ;;
esac
for t in $tools; do
@@ -109,6 +119,13 @@ case "$FLAVOR" in
patch_one i386-windows build32.sh rosetta detour32.bin \
"$ROSETTA_CLEAN_I386" "$ROSETTA_PATCHED_I386"
;;
+ cx26)
+ ARCHES="x86_64-windows i386-windows"
+ patch_one x86_64-windows build.sh cx26 detour2-cx26.bin \
+ "$CX26_CLEAN_X86_64" "$CX26_PATCHED_X86_64"
+ patch_one i386-windows build32.sh cx26 detour32-cx26.bin \
+ "$CX26_CLEAN_I386" "$CX26_PATCHED_I386"
+ ;;
fex)
# The FEX build ships a version of Wine that runs through Rosetta as well as
# the FEX/ARM version, so all three ntdlls need patching.
@@ -128,9 +145,9 @@ if [ "$install" -eq 0 ]; then
fi
for arch in $ARCHES; do
- d="$BRIDGE_DIR/wine/$arch"
+ d="$BRIDGE_DIR/wine/$BUILD/$arch"
mkdir -p "$d"
cp "$OUT/$arch/ntdll.dll" "$d/ntdll.dll"
echo "==> installed $arch $(sha "$d/ntdll.dll" | cut -c1-16) $d/ntdll.dll"
done
-echo "==> RUN_SCRIPT copies these into the CrossOver tree on the next Steam launch"
+echo "==> setting build $BUILD up in NotProton copies these into its runner clone"
diff --git a/ntdll-patch/build32.sh b/ntdll-patch/build32.sh
index dde8717..8bb0320 100755
--- a/ntdll-patch/build32.sh
+++ b/ntdll-patch/build32.sh
@@ -21,7 +21,7 @@ CFLAGS="-Os -fno-asynchronous-unwind-tables -ffreestanding -fno-stack-protector
# shellcheck disable=SC2086 # CFLAGS carries several flags and has to split
"$CC" -c $CFLAGS detour32.c -o detour32_c.o \
- "-DFLAGS_SLOT=$NP_FLAGS_SLOT" "-DLOAD_PATH_SLOT=$NP_LOAD_PATH"
+ "-DFLAGS_SLOT=$NP_FLAGS_SLOT" "-DFLAGS_BIT=$NP_FLAGS_BIT" "-DLOAD_PATH_SLOT=$NP_LOAD_PATH"
"$CC" -c -x assembler-with-cpp shim32.S -o shim32.o \
"-DWM_REG=$NP_WM" "-DSTOLEN_HEAD_BYTES=$NP_STOLEN_HEAD_BYTES" \
"-DSTOLE_BRANCH=${NP_STOLE_BRANCH:-0}"
diff --git a/ntdll-patch/detour32.c b/ntdll-patch/detour32.c
index 24f66b8..7013390 100644
--- a/ntdll-patch/detour32.c
+++ b/ntdll-patch/detour32.c
@@ -253,7 +253,7 @@ void detour_build_module32(struct ctx *c, void *wm, void *fp)
if (is_steamclient32)
{
*WM_FLAGS(wm) |= LDR_DONT_RESOLVE_REFS;
- *ARG_FLAGS(fp) |= LDR_DONT_RESOLVE_REFS;
+ *ARG_FLAGS(fp) |= FLAGS_BIT;
restore_image_base(c, wm, sc);
}
else
diff --git a/ntdll-patch/resolve.py b/ntdll-patch/resolve.py
index a9ab712..9928f6a 100755
--- a/ntdll-patch/resolve.py
+++ b/ntdll-patch/resolve.py
@@ -37,6 +37,19 @@ PINNED = {
'exports': {'LdrGetDllHandle': 0x7bc2a6b0, 'LdrLoadDll': 0x7bc286d0,
'NtProtectVirtualMemory': 0x7bc4d020, 'NtOpenFile': 0x7bc4ce50,
'NtReadFile': 0x7bc4cb80, 'NtClose': 0x7bc4cc10}},
+ '6dff64c00793ce92124f1316985c63783f539f26b392975c70f57637458d2387':
+ {'hookRVA': 0x44972, 'stolen': '4883bc24f000000000', 'caveRVA': 0xae000, 'caveSize': 4096,
+ 'wm': 'r14', 'resume': 0x4497b, 'load_path': 0xd0,
+ 'payload': 'e35b834408599c45f30b23a6d2bf38acfa5c3df4d15206617c471e23a4a01bfb',
+ 'exports': {'LdrGetDllHandle': 0x170014bc0, 'LdrLoadDll': 0x170015680,
+ 'NtProtectVirtualMemory': 0x17000f380}},
+ '2c60ee6b00dd13b7f6cb11017778a041ba6a321eaea194f1fa0dca7eab8403e2':
+ {'hookRVA': 0x43b40, 'stolen': 'f645c0017526', 'caveRVA': 0xaa000, 'caveSize': 4096,
+ 'resume': 0x43b46, 'wm': 'esi', 'load_path': -0x54,
+ 'payload': 'be465bc936cafafae4aa1b4c41f668e08848492d9858c2cf2ad483a9f1ab25e5',
+ 'exports': {'LdrGetDllHandle': 0x7bc12c60, 'LdrLoadDll': 0x7bc13750,
+ 'NtProtectVirtualMemory': 0x7bc0d584, 'NtOpenFile': 0x7bc0d3b4,
+ 'NtReadFile': 0x7bc0d0e4, 'NtClose': 0x7bc0d174}},
'7823d71fbce6c9947163bf8b96beb299eabb02878245bcaf6759f2a22e81f071':
{'caveRVA': 0xf1185, 'caveSize': 61051,
# This image carries the loader twice, once for the native side and once for the
@@ -56,6 +69,7 @@ PINNED = {
}
EXPORTS = ['LdrGetDllHandle', 'LdrLoadDll', 'NtProtectVirtualMemory',
'NtOpenFile', 'NtReadFile', 'NtClose']
+SECTION_NAME, SECTION_SIZE, SECTION_FLAGS = b'.npdet', 0x1000, 0x60000020
PROLOGUES = [rb'\x55\x89\xe5', rb'\x55\x8b\xec']
NOP64 = bytes.fromhex('1f2003d5')
@@ -87,6 +101,9 @@ class PE:
if roff:
self.secs.append((name, vrva, vsize, roff, rsize))
self.dirs = self.opt + (112 if wide else 96)
+ self.table_end = e + 24 + optsz + nsec * 40
+ self.sect_align, self.file_align = struct.unpack_from('<II', self.d, self.opt + 32)
+ self.size_of_image, self.size_of_headers = struct.unpack_from('<II', self.d, self.opt + 56)
def sec(self, prefix):
for s in self.secs:
@@ -142,7 +159,17 @@ class PE:
# at the end that the loader maps but nothing touches. Detour goes there.
_, vrva, vsize, roff, rsize = self.sec('.text')
end = vrva + vsize
- return {'caveRVA': end, 'caveSize': (vrva + rsize) - end, 'fill': self.d[roff + vsize]}
+ return {'caveRVA': end, 'caveSize': (vrva + rsize) - end, 'fill': self.d[roff + vsize],
+ 'placement': 'padding'}
+
+ def appended(self):
+ # The section is mapped at SizeOfImage, and its raw data goes after everything else in
+ # the file, the certificate included.
+ if self.table_end + 40 > self.size_of_headers or any(self.d[self.table_end:self.table_end + 40]):
+ raise SystemExit(f"{self.path}: no free section header slot after the table")
+ raw = (len(self.d) + self.file_align - 1) & ~(self.file_align - 1)
+ return {'caveRVA': self.size_of_image, 'caveSize': SECTION_SIZE, 'fill': 0,
+ 'placement': 'section', 'rawOffset': raw}
def string_refs(self, name):
"""RVAs of instructions referencing a .rdata C string, however the arch addresses it."""
@@ -285,13 +312,14 @@ def resolve_i386(pe):
raise SystemExit(f"{pe.path}: no MODREF flag test in build_module")
wm = re.search(r'\[(e\w\w) \+ 0x37\]', body[anchor].op_str).group(1)
- # The module flags are tested for bit 2 just above. Either the value is still in memory
- # or the compiler loaded it first, in which case that load starts the hook.
+ # The module flags are tested just above, with bit 2 in Wine 11.15 and bit 1 in 11.0.
+ # Either the value is still in memory or the compiler loaded it first, in which case that
+ # load starts the hook.
gate = None
for k in range(anchor - 1, max(anchor - 24, 0), -1):
i = body[k]
if i.mnemonic == 'test' and i.operands and i.operands[-1].type == X86.X86_OP_IMM \
- and i.operands[-1].imm == 2:
+ and i.operands[-1].imm in (1, 2):
gate = k
break
if gate is None:
@@ -347,7 +375,7 @@ def resolve_i386(pe):
'insn': ' ; '.join(f"{i.mnemonic} {i.op_str}" for i in taken),
'load_path': load_path, 'skip': skip, 'stole_branch': stole_branch,
'stolen_head': b''.join(i.bytes for i in (taken[:-1] if stole_branch else taken)).hex(),
- 'flags_slot': flags_slot}
+ 'flags_slot': flags_slot, 'flags_bit': body[gate].operands[-1].imm}
def aarch64_walk(md, text, tv):
@@ -549,6 +577,8 @@ def resolve(path):
r = (resolve_aarch64(pe) if pe.machine == 0xaa64 else
resolve_amd64(pe) if pe.machine == 0x8664 else resolve_i386(pe))
r.update(pe.cave())
+ if r['caveSize'] < PAYLOAD[pe.machine]:
+ r.update(pe.appended())
r['machine'], r['magic'], r['imageBase'] = pe.machine, pe.magic, pe.imagebase
ex = pe.exports()
r['exports'] = {n: pe.imagebase + ex[n] for n in EXPORTS if n in ex}
@@ -599,6 +629,7 @@ def report(path):
line('caveRVA', r['caveRVA'], 'caveRVA')
line('caveSize', r['caveSize'], 'caveSize', fmt=str)
need = PAYLOAD[r['machine']]
+ print(f" {'placement':13} {r['placement']}")
print(f" {'cave fill':13} {r['fill']:#02x} room {r['caveSize']} bytes, payload {need}"
f" -> {'fits' if r['caveSize'] >= need else 'TOO SMALL'}")
def table(items, want):
@@ -664,6 +695,7 @@ def shell_vars(path):
'NP_CAVE_RVA': f"{r['caveRVA']:#x}", 'NP_CAVE_SIZE': str(r['caveSize']),
'NP_PAYLOAD_RVA': f"{payload:#x}", 'NP_PAYLOAD_VA': f"{r['imageBase'] + payload:#x}",
'NP_CAVE_ROOM': str(room), 'NP_FILL': f"{r['fill']:#04x}",
+ 'NP_PLACEMENT': r['placement'],
}
if PINNED.get(r['sha256'], {}).get('payload'):
out['NP_PAYLOAD_SHA256'] = PINNED[r['sha256']]['payload']
@@ -673,6 +705,7 @@ def shell_vars(path):
out['NP_STOLEN_HEAD_BYTES'] = ','.join(
f"0x{b:02x}" for b in bytes.fromhex(r['stolen_head']))
out['NP_FLAGS_SLOT'] = ('%#x' if r['flags_slot'] >= 0 else '-%#x') % abs(r['flags_slot'])
+ out['NP_FLAGS_BIT'] = f"{r['flags_bit']:#x}"
for n, s in enumerate(r.get('sites') or [], 1):
out[f'NP_HOOK_RVA_{n}'] = f"{s['hookRVA']:#x}"