Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 42 additions & 16 deletions palium/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,15 @@ struct ContentView: View {
Text("Update Available")
.font(.headline)

Text("v\(appState.localGameVersion) → v\(appState.gameVersion)")
.font(.subheadline)
.foregroundStyle(.secondary)
Group {
if appState.localGameVersion == appState.gameVersion {
Text("New content available for v\(appState.gameVersion)")
} else {
Text("v\(appState.localGameVersion) → v\(appState.gameVersion)")
}
}
.font(.subheadline)
.foregroundStyle(.secondary)

if let manifest = appState.manifest {
Text("\(manifest.files.count) files — only changed files will be downloaded")
Expand Down Expand Up @@ -415,9 +421,14 @@ struct ContentView: View {
// Install VC++ runtime if not already present in prefix
if !WineManager.isVCRuntimeInstalled(info: info) {
appState.statusMessage = "Installing VC++ runtime..."
appState.showDebugLog = true
appState.log("VC++ runtime not found in prefix, installing...")
do {
try await WineManager.installVCRuntime(info: info)
try await WineManager.installVCRuntime(info: info) { [appState] message, level in
Task { @MainActor in
appState.log(message, level: level)
}
}
appState.log("VC++ runtime installed", level: .success)
} catch {
appState.log("VC++ runtime install failed: \(error.localizedDescription) — game may still work", level: .warning)
Expand Down Expand Up @@ -473,19 +484,34 @@ struct ContentView: View {
appState.log("Game found at \(info.gameInstallPath.path)", level: .success)

let localVersion = LaunchSettings.shared.installedVersion
let localHash = LaunchSettings.shared.installedManifestHash
let cdnHash = appState.manifest?.contentsHash

if let localVersion {
appState.localGameVersion = localVersion
appState.log("Installed version: \(localVersion)", level: .info)

if localVersion != appState.gameVersion {
appState.log("Update available: \(localVersion) → \(appState.gameVersion)", level: .warning)
let versionChanged = localVersion != appState.gameVersion
// A stale hash always signals a real content change; a missing hash just
// means this build predates hash tracking — backfill it, don't force an update.
let contentChanged = localHash != nil && localHash != cdnHash

if versionChanged || contentChanged {
let reason = versionChanged
? "\(localVersion) → \(appState.gameVersion)"
: "content update for v\(appState.gameVersion)"
appState.log("Update available: \(reason)", level: .warning)
appState.phase = .needsUpdate
} else {
if localHash == nil {
LaunchSettings.shared.installedManifestHash = cdnHash
}
appState.phase = .ready
}
} else {
appState.log("No stored version found — assuming up to date", level: .warning)
LaunchSettings.shared.installedVersion = appState.gameVersion
LaunchSettings.shared.installedManifestHash = cdnHash
appState.phase = .ready
}
} else {
Expand Down Expand Up @@ -519,6 +545,7 @@ struct ContentView: View {
installDirectory: info.gameInstallPath
)
LaunchSettings.shared.installedVersion = appState.gameVersion
LaunchSettings.shared.installedManifestHash = manifest.contentsHash
appState.phase = .ready
} catch is CancellationError {
appState.log("Download cancelled", level: .warning)
Expand Down Expand Up @@ -550,21 +577,16 @@ struct ContentView: View {
)
appState.log("Launching game (DX11, Metal HUD: \(options.metalHUD ? "ON" : "OFF"))...")
do {
let process = try GameLauncher.launch(info: info, options: options)
appState.gameProcess = process
appState.phase = .launching
appState.log("Game process started (PID: \(process.processIdentifier))", level: .success)

// Monitor process in background
Task.detached {
process.waitUntilExit()
let status = process.terminationStatus
await MainActor.run {
let process = try GameLauncher.launch(info: info, options: options) { [appState] status in
Task { @MainActor in
appState.log("Game exited with status \(status)", level: status == 0 ? .info : .warning)
appState.gameProcess = nil
appState.phase = .ready
}
}
appState.gameProcess = process
appState.phase = .launching
appState.log("Game process started (PID: \(process.processIdentifier))", level: .success)
} catch let error as PaliumError {
appState.log("Launch failed: \(error.localizedDescription)", level: .error)
appState.phase = .error(error)
Expand Down Expand Up @@ -596,6 +618,8 @@ struct ContentView: View {

if corruptFiles.isEmpty {
appState.statusMessage = "All files verified successfully"
LaunchSettings.shared.installedVersion = appState.gameVersion
LaunchSettings.shared.installedManifestHash = manifest.contentsHash
appState.phase = .ready
return
}
Expand All @@ -613,6 +637,8 @@ struct ContentView: View {
version: appState.gameVersion,
installDirectory: info.gameInstallPath
)
LaunchSettings.shared.installedVersion = appState.gameVersion
LaunchSettings.shared.installedManifestHash = manifest.contentsHash
appState.phase = .ready
} catch let error as PaliumError {
appState.log("Repair failed: \(error.localizedDescription)", level: .error)
Expand Down
4 changes: 3 additions & 1 deletion palium/Models/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,12 @@ class AppState {
}

private static let maxLogEntries = 1000
// Trim in batches so the O(n) removeFirst runs once per batch, not per append.
private static let logTrimBatch = 100

func log(_ message: String, level: LogEntry.Level = .info) {
logEntries.append(LogEntry(level: level, message: message))
if logEntries.count > Self.maxLogEntries {
if logEntries.count >= Self.maxLogEntries + Self.logTrimBatch {
logEntries.removeFirst(logEntries.count - Self.maxLogEntries)
}
}
Expand Down
34 changes: 21 additions & 13 deletions palium/Models/LaunchSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,36 +24,44 @@ class LaunchSettings {
// Installed game version (persisted to detect updates)
var installedVersion: String? { didSet { save() } }

// SHA-256 of the manifest's "contents" node at install time — catches
// content updates the CDN ships without bumping the channel version.
var installedManifestHash: Data? { didSet { save() } }

private static let storageKey = "launchSettings_v2"

/// Suppresses the didSet-triggered save() while restoring persisted values —
/// property observers fire for assignments made during load.
@ObservationIgnored private var isLoaded = false

private init() {
load()
if let data = UserDefaults.standard.data(forKey: Self.storageKey),
let stored = try? JSONDecoder().decode(StoredSettings.self, from: data) {
wineSource = stored.wineSource
metalHUD = stored.metalHUD
useAllCores = stored.useAllCores
installedVersion = stored.installedVersion
installedManifestHash = stored.installedManifestHash
}
isLoaded = true
}

private struct StoredSettings: Codable {
var wineSource: WineSource = .auto
var metalHUD: Bool = false
var useAllCores: Bool = true
var installedVersion: String?
}

private func load() {
guard let data = UserDefaults.standard.data(forKey: Self.storageKey),
let stored = try? JSONDecoder().decode(StoredSettings.self, from: data) else {
return
}
wineSource = stored.wineSource
metalHUD = stored.metalHUD
useAllCores = stored.useAllCores
installedVersion = stored.installedVersion
var installedManifestHash: Data?
}

private func save() {
guard isLoaded else { return }
let stored = StoredSettings(
wineSource: wineSource,
metalHUD: metalHUD,
useAllCores: useAllCores,
installedVersion: installedVersion
installedVersion: installedVersion,
installedManifestHash: installedManifestHash
)
if let data = try? JSONEncoder().encode(stored) {
UserDefaults.standard.set(data, forKey: Self.storageKey)
Expand Down
11 changes: 4 additions & 7 deletions palium/Models/ManifestModels.swift
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import Foundation

struct ManifestChunk: Sendable {
let offset: UInt64
let size: UInt64
let hash: Data
}

struct ManifestFile: Sendable, Identifiable {
var id: String { path }
let path: String
let size: UInt64
let hash: Data
let chunks: [ManifestChunk]
}

struct UpdateManifest: Sendable {
Expand All @@ -20,4 +13,8 @@ struct UpdateManifest: Sendable {
let platform: String
let files: [ManifestFile]
let totalSize: UInt64
/// SHA-256 digest over every file's (path, size, hash), computed locally from `files`
/// rather than trusted from the manifest's own "contents.hash" field. Lets us detect
/// content changes the CDN ships without bumping the channel version.
let contentsHash: Data
}
74 changes: 42 additions & 32 deletions palium/Services/CDNClient.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import CryptoKit

nonisolated enum CDNClient {

Expand Down Expand Up @@ -62,17 +63,19 @@ nonisolated enum CDNClient {
// MARK: - Manifest Parsing

static func parseManifest(_ data: Data) throws -> UpdateManifest {
let root = try FlexBuffersParser.decode(data)
// Walk the manifest lazily: only the fields we keep are ever decoded,
// which avoids materializing the (large) per-chunk metadata.
let root = try FlexBuffersParser.root(data)

guard let rootMap = root.mapValue else {
guard root.isMap else {
throw PaliumError.manifestParseFailed("Root is not a map")
}

let bundleName = rootMap["bundle"]?.stringValue ?? ""
let version = rootMap["version"]?.stringValue ?? ""
let platformName = rootMap["platform"]?.stringValue ?? ""
let bundleName = root["bundle"]?.stringValue ?? ""
let version = root["version"]?.stringValue ?? ""
let platformName = root["platform"]?.stringValue ?? ""

guard let contents = rootMap["contents"]?.mapValue else {
guard let contents = root["contents"], contents.isMap else {
throw PaliumError.manifestParseFailed("No 'contents' in manifest")
}

Expand All @@ -85,37 +88,44 @@ nonisolated enum CDNClient {
version: version,
platform: platformName,
files: files,
totalSize: totalSize
totalSize: totalSize,
contentsHash: filesDigest(files)
)
}

private static func collectFiles(from node: [String: FlexValue], into files: inout [ManifestFile]) {
guard let children = node["files"]?.vectorValue else { return }

for child in children {
guard let childMap = child.mapValue else { continue }
let path = childMap["path"]?.stringValue ?? ""
let size = childMap["size"]?.uintValue ?? 0
let hash = childMap["hash"]?.blobValue ?? Data()

if let chunksVec = childMap["chunks"]?.vectorValue, !chunksVec.isEmpty {
// Leaf file with chunks
let chunks = chunksVec.compactMap { chunkVal -> ManifestChunk? in
guard let arr = chunkVal.vectorValue, arr.count >= 3 else { return nil }
return ManifestChunk(
offset: arr[0].uintValue ?? 0,
size: arr[1].uintValue ?? 0,
hash: arr[2].blobValue ?? Data()
)
}
files.append(ManifestFile(path: path, size: size, hash: hash, chunks: chunks))
} else if childMap["files"] != nil {
/// Digest over (path, size, hash) of every file, computed locally rather than trusting
/// the CDN's own "contents.hash" field, which can be absent/empty on a malformed manifest.
/// Sorted by path first since manifest tree-walk order isn't a guaranteed stable key.
private static func filesDigest(_ files: [ManifestFile]) -> Data {
var hasher = SHA256()
for file in files.sorted(by: { $0.path < $1.path }) {
hasher.update(data: Data(file.path.utf8))
var size = file.size
withUnsafeBytes(of: &size) { hasher.update(bufferPointer: $0) }
hasher.update(data: file.hash)
}
return Data(hasher.finalize())
}

private static func collectFiles(from node: FlexRef, into files: inout [ManifestFile]) {
guard let children = node["files"], children.isVector else { return }

for i in 0..<children.count {
guard let child = children[i], child.isMap else { continue }

if child["files"] != nil {
// Directory — recurse
collectFiles(from: childMap, into: &files)
} else {
// File with no chunks (possibly empty)
files.append(ManifestFile(path: path, size: size, hash: hash, chunks: []))
collectFiles(from: child, into: &files)
continue
}

// Leaf file. Per-chunk metadata is deliberately skipped: downloads
// and verification operate on whole files.
files.append(ManifestFile(
path: child["path"]?.stringValue ?? "",
size: child["size"]?.uintValue ?? 0,
hash: child["hash"]?.blobValue ?? Data()
))
}
}
}
Loading
Loading