Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
feat(setup): downloads show their size, progress and time left
raymondchinsd8f330f88b9f
diff --git a/app/Sources/BridgeplayApp/Support/PinnedDownload.swift b/app/Sources/BridgeplayApp/Support/PinnedDownload.swiftindex 37ae5ac..53d0324 100644--- a/app/Sources/BridgeplayApp/Support/PinnedDownload.swift+++ b/app/Sources/BridgeplayApp/Support/PinnedDownload.swift@@ -7,13 +7,31 @@ enum PinnedDownload {enum Progress: Sendable {case reusingcase fetching(host: String)+ case receiving(host: String, received: Int64, total: Int64, remaining: TimeInterval?)var label: String {switch self {case .reusing: String(localized: "Preparing")case .fetching(let host): String(localized: "Downloading from \(host)")+ case .receiving(let host, let received, let total, let remaining):+ Self.label(host: host, received: received, total: total, remaining: remaining)}}++ static func label(host: String, received: Int64, total: Int64, remaining: TimeInterval?) -> String {+ let amount = ByteCountFormatter.string(fromByteCount: received, countStyle: .file) + " / "+ + ByteCountFormatter.string(fromByteCount: total, countStyle: .file)+ let time = DateComponentsFormatter()+ time.unitsStyle = .full+ time.maximumUnitCount = 1+ time.allowedUnits = [.hour, .minute, .second]+ // Seconds only near the end, so the estimate doesn't tick every second.+ let rounded = remaining.map { $0 < 60 ? $0 : ($0 / 60).rounded(.up) * 60 }+ guard let rounded, let left = time.string(from: max(rounded, 1)) else {+ return String(localized: "Downloading from \(host): \(amount)")+ }+ return String(localized: "Downloading from \(host): \(amount), about \(left) left")+ }}static let session = session(deadline: 30 * 60)@@ -48,7 +66,11 @@ enum PinnedDownload {report(.fetching(host: host))let body: URL, response: URLResponsedo {- (body, response) = try await session.download(from: base.appending(path: file))+ (body, response) = try await withoutActuallyEscaping(report) { report in+ let relay = ProgressRelay(host: host, report: report)+ defer { relay.finish() }+ return try await session.download(from: base.appending(path: file), delegate: relay)+ }} catch {refusals.append("\(host): \(error.localizedDescription)")kinds.insert(.unreachable)@@ -105,3 +127,48 @@ enum PinnedDownload {return String(localized: "Bridgeplay could not download the files it needs from \(source). Please try again later.")}}++// Turns the task's byte count into .receiving reports, once per percent.+private final class ProgressRelay: NSObject, URLSessionTaskDelegate, @unchecked Sendable {+ private let host: String+ // Dropped by finish(): the caller's closure only lives as long as the download.+ private var report: (@Sendable (PinnedDownload.Progress) -> Void)?+ private let started = Date()+ private let lock = NSLock()+ private var observation: NSKeyValueObservation?+ private var shown = -1++ init(host: String, report: @escaping @Sendable (PinnedDownload.Progress) -> Void) {+ self.host = host+ self.report = report+ }++ func urlSession(_ session: URLSession, didCreateTask task: URLSessionTask) {+ let observation = task.progress.observe(\.completedUnitCount) { [weak self] progress, _ in+ self?.update(received: progress.completedUnitCount, total: progress.totalUnitCount)+ }+ lock.withLock { self.observation = observation }+ }++ func finish() {+ lock.withLock {+ observation?.invalidate()+ observation = nil+ report = nil+ }+ }++ private func update(received: Int64, total: Int64) {+ guard total > 0, received <= total else { return }+ let percent = Int(received * 100 / total)+ let elapsed = Date().timeIntervalSince(started)+ // A few seconds in, so the first estimate isn't wild.+ let remaining = received > 0 && elapsed > 3 ? elapsed * Double(total - received) / Double(received) : nil+ // Reported under the lock, so finish() can't drop the closure mid-call.+ lock.withLock {+ guard percent != shown, let report else { return }+ shown = percent+ report(.receiving(host: host, received: received, total: total, remaining: remaining))+ }+ }+}diff --git a/app/Tests/BridgeplayAppTests/DownloadProgressLabelTests.swift b/app/Tests/BridgeplayAppTests/DownloadProgressLabelTests.swiftnew file mode 100644index 0000000..1d0a47d--- /dev/null+++ b/app/Tests/BridgeplayAppTests/DownloadProgressLabelTests.swift@@ -0,0 +1,16 @@+import Testing+@testable import BridgeplayApp++@Suite("Download progress label")+struct DownloadProgressLabelTests {+ @Test func showsAmountAndRoundsTheEstimateUpToMinutes() {+ let label = PinnedDownload.Progress.label(host: "github.com", received: 100_000_000, total: 400_000_000, remaining: 61)+ #expect(label.hasPrefix("Downloading from github.com: 100 MB / 400 MB"))+ #expect(label.hasSuffix("about 2 minutes left"))+ }++ @Test func leavesTheEstimateOutUntilThereIsOne() {+ let label = PinnedDownload.Progress.label(host: "github.com", received: 0, total: 400_000_000, remaining: nil)+ #expect(label == "Downloading from github.com: Zero KB / 400 MB")+ }+}diff --git a/app/Tests/BridgeplayAppTests/PinnedDownloadTests.swift b/app/Tests/BridgeplayAppTests/PinnedDownloadTests.swiftindex 16c4f1d..6493d95 100644--- a/app/Tests/BridgeplayAppTests/PinnedDownloadTests.swift+++ b/app/Tests/BridgeplayAppTests/PinnedDownloadTests.swift@@ -109,7 +109,8 @@ struct PinnedDownloadTests {#expect(!failure.detail.contains("could not reach"))#expect(failure.detail.contains(downloads.path(percentEncoded: false)))- #expect(reported.all.count == 1)+ // One host tried; byte counts (" / ") follow it.+ #expect(reported.all.filter { !$0.contains(" / ") }.count == 1)}@Test("A download has an overall deadline, not only an idle one")@@ -202,7 +203,8 @@ struct PinnedDownloadTests {)let label = try #require(reported.all.first)- #expect(reported.all.count == 1)+ // One host tried; byte counts (" / ") follow it.+ #expect(reported.all.filter { !$0.contains(" / ") }.count == 1)#expect(label.hasPrefix("Downloading from "))#expect(label.contains(serving.lastPathComponent))}