Run a virtual iPhone on an Apple Silicon Mac.
Swift
Show IPSW download progress on Launchpad's firmware step
Jacky49e1538692c8
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swiftindex ac647d11..77002289 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift@@ -66,13 +66,9 @@ enum VPhoneFirmwarePreparer {// inside the machine downloaded both again for each new one (#513).// Local IPSWs are read in place and are never copied into the cache.print("[*] Resolving iPhone IPSW...")- let phone = try vphoneRunBlocking {- try await VPhoneIPSWCache.resolve(iPhoneSource, in: ipswCacheDirectory)- }+ let phone = try resolve(iPhoneSource, in: ipswCacheDirectory, label: "downloading iPhone IPSW")print("[*] Resolving cloudOS IPSW...")- let cloud = try vphoneRunBlocking {- try await VPhoneIPSWCache.resolve(cloudOSSource, in: ipswCacheDirectory)- }+ let cloud = try resolve(cloudOSSource, in: ipswCacheDirectory, label: "downloading cloudOS IPSW")try VPhoneIPSWCache.checkPair(iPhone: phone, cloudOS: cloud)let device = VPhoneIPSWCache.guestDevice(for: phone, preferring: productType) ?? .defaultif let productType, VPhoneGuestDevice.named(productType) != device {@@ -156,6 +152,20 @@ enum VPhoneFirmwarePreparer {try recordGuestDevice(device, in: bundle)}+ /// Resolves one source, with a progress bar while it downloads. Launchpad+ /// reads the bar as `progress` lines and shows the percentage on its+ /// firmware step (#590).+ private static func resolve(_ source: String, in cacheDirectory: URL, label: String) throws -> VPhoneIPSWCache.Archive {+ let bar = VPhoneProgressBar(label: label)+ let archive = try vphoneRunBlocking {+ try await VPhoneIPSWCache.resolve(source, in: cacheDirectory) { done, total in+ bar.update(done: done, total: total)+ }+ }+ bar.finish()+ return archive+ }+/// Records which device's OS the VM runs, and gives it that device's/// display. `fw patch` reads the device back from the restore tree; the/// manifest is what the VM window and the guest's screen size follow.diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Support/VPhoneProgressBar.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Support/VPhoneProgressBar.swiftindex ab0e897d..e89c74f6 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Support/VPhoneProgressBar.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Support/VPhoneProgressBar.swift@@ -9,7 +9,12 @@ import Foundation/// A caller that reads the output through a pipe, such as vphone-launchpad,/// sets `VPHONE_PROGRESS=lines` to get `progress <done> <total>` lines on/// stderr instead, at most a few per second.-final class VPhoneProgressBar {+///+/// Unchecked Sendable so a transfer's callback can drive it from another+/// thread: every caller reports serially (URLSession calls one task's+/// delegate one at a time) and calls `finish()` only after the transfer has+/// returned.+final class VPhoneProgressBar: @unchecked Sendable {private enum Mode {case off, bar, lines}@@ -20,6 +25,7 @@ final class VPhoneProgressBar {private let width = 28private var lastRender = Date.distantPastprivate var total: Int64 = 0+ private var updated = falseinit(label: String) {self.label = label@@ -35,6 +41,7 @@ final class VPhoneProgressBar {func update(done: Int64, total: Int64) {guard mode != .off else { return }self.total = total+ updated = truelet now = Date()let interval = mode == .bar ? 0.066 : 0.25 // ~15 fps, or 4 lines a secondif done < total, now.timeIntervalSince(lastRender) < interval {@@ -44,7 +51,10 @@ final class VPhoneProgressBar {render(done: done, now: now)}+ /// Draws the final state. Draws nothing when no update came, such as for+ /// a download the cache already held.func finish() {+ guard updated else { return }switch mode {case .off:returndiff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swiftindex fd245b69..0ab1465d 100644--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift@@ -47,10 +47,14 @@ public enum VPhoneIPSWCache {}}+ /// `progress` is called with `(bytesDone, totalBytes)` while a remote+ /// IPSW downloads, only when the server states the size. A local source+ /// or a cache hit never calls it.public static func resolve(_ source: String,in cacheDirectory: URL,session: URLSession = URLSession(configuration: .ephemeral),+ progress: (@Sendable (Int64, Int64) -> Void)? = nil,) async throws -> Archive {guard let url = URL(string: source), let scheme = url.scheme?.lowercased() else {return try inspect(URL(fileURLWithPath: source))@@ -82,7 +86,7 @@ public enum VPhoneIPSWCache {}let output = try FileHandle(forWritingTo: pending)defer { try? output.close() }- let (response, size) = try await download(request, into: output, session: session)+ let (response, size) = try await download(request, into: output, session: session, progress: progress)try output.close()guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {throw Error.unexpectedHTTP(url, (response as? HTTPURLResponse)?.statusCode ?? 0)@@ -187,9 +191,10 @@ public enum VPhoneIPSWCache {_ request: URLRequest,into output: FileHandle,session: URLSession,+ progress: (@Sendable (Int64, Int64) -> Void)?,) async throws -> (URLResponse, Int64) {let task = session.dataTask(with: request)- let writer = DownloadWriter(output: output)+ let writer = DownloadWriter(output: output, progress: progress)task.delegate = writerreturn try await withTaskCancellationHandler {try await withCheckedThrowingContinuation { continuation in@@ -205,13 +210,15 @@ public enum VPhoneIPSWCache {/// before the task resumes, so the mutable state is never shared.private final class DownloadWriter: NSObject, URLSessionDataDelegate, @unchecked Sendable {let output: FileHandle+ let progress: (@Sendable (Int64, Int64) -> Void)?var continuation: CheckedContinuation<(URLResponse, Int64), Swift.Error>?private var response: URLResponse?private var written: Int64 = 0private var writeError: Swift.Error?- init(output: FileHandle) {+ init(output: FileHandle, progress: (@Sendable (Int64, Int64) -> Void)?) {self.output = output+ self.progress = progress}func urlSession(@@ -230,6 +237,9 @@ public enum VPhoneIPSWCache {do {try output.write(contentsOf: data)written += Int64(data.count)+ if let progress, let total = response?.expectedContentLength, total > 0 {+ progress(written, total)+ }} catch {writeError = errordataTask.cancel()diff --git a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swiftindex ec4c83ff..9f1d19da 100644--- a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift+++ b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift@@ -29,6 +29,19 @@ private final class IPSWStubProtocol: URLProtocol {override func stopLoading() {}}+private final class ProgressReports: @unchecked Sendable {+ private let lock = NSLock()+ private var storage: [(done: Int64, total: Int64)] = []++ func append(_ done: Int64, _ total: Int64) {+ lock.withLock { storage.append((done, total)) }+ }++ var values: [(done: Int64, total: Int64)] {+ lock.withLock { storage }+ }+}+@Suite("IPSW cache", .serialized)struct IPSWCacheTests {private func fixture(in root: URL) throws -> URL {@@ -120,6 +133,44 @@ struct IPSWCacheTests {))}+ /// Launchpad shows this on its firmware step (#590). A cache hit downloads+ /// nothing and reports nothing.+ @Test func `download reports progress against the stated size`() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let source = try fixture(in: root)+ IPSWStubProtocol.payload = try Data(contentsOf: source)+ IPSWStubProtocol.status = 200+ let configuration = URLSessionConfiguration.ephemeral+ configuration.protocolClasses = [IPSWStubProtocol.self]+ let session = URLSession(configuration: configuration)+ defer { session.invalidateAndCancel() }++ let size = Int64(IPSWStubProtocol.payload.count)+ let reports = ProgressReports()+ let cacheDir = root.appendingPathComponent("cache")+ _ = try await VPhoneIPSWCache.resolve(+ "https://example.invalid/input.ipsw",+ in: cacheDir,+ session: session,+ progress: { done, total in reports.append(done, total) },+ )+ let downloaded = reports.values+ #expect(!downloaded.isEmpty)+ #expect(downloaded.allSatisfy { $0.total == size })+ #expect(downloaded.last?.done == size)++ let cached = ProgressReports()+ _ = try await VPhoneIPSWCache.resolve(+ "https://example.invalid/input.ipsw",+ in: cacheDir,+ session: session,+ progress: { done, total in cached.append(done, total) },+ )+ #expect(cached.values.isEmpty)+ }+/// The cache is shared by every machine, so a download killed midway would/// otherwise leave its partial file there for good.@Test func `abandoned partial downloads are removed and live ones kept`() async throws {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swiftindex 53660f92..0e5ed181 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift@@ -102,6 +102,8 @@await sheet(.newMachine, "07-new-machine-advanced", suffix)newMachinePage = .generalawait sheet(.creation(path("ios27-rc")), "08-creation-progress", suffix)+ creation.applyPreview(downloading: 0.42)+ await sheet(.creation(path("ios27-rc")), "08a-creation-downloading", suffix)creation.applyPreview(failed: true)await sheet(.creation(path("ios27-rc")), "08b-creation-failed", suffix)creation.applyPreview()diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swiftindex b020846d..deb7bac5 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift@@ -81,6 +81,10 @@ final class VPhoneLaunchpadCreationPipeline {private(set) var statuses: [Step: VPhoneLaunchpadStatus] = [:]private(set) var durations: [Step: TimeInterval] = [:]private(set) var current: Step?+ /// How far the IPSW `fw prepare` is downloading has come, while one is+ /// downloading. Each of the two IPSWs counts from zero; a cached one and+ /// a Core Bundle that reports no progress leave it nil.+ private(set) var downloadFraction: Double?/// The creation log. The sheet shows it in a terminal; the model keeps/// only the last few lines, for error details.private let log: VPhoneLaunchpadLogWriter@@ -178,6 +182,7 @@ final class VPhoneLaunchpadCreationPipeline {defer {isRunning = falsecurrent = nil+ downloadFraction = nildfu?.terminate()dfu = nil}@@ -271,9 +276,13 @@ final class VPhoneLaunchpadCreationPipeline {let log = loglet output: @Sendable (String) -> Void = { line in log.write(line) }- func run(_ arguments: [String], onLine: @escaping @Sendable (String) -> Void = output) async throws {+ func run(+ _ arguments: [String],+ onLine: @escaping @Sendable (String) -> Void = output,+ onProgress: (@Sendable (Double) -> Void)? = nil,+ ) async throws {onLine("$ \(VPhoneLaunchpadCommandLine.display(arguments))")- try await commandLine.runChecked(arguments, onLine: onLine)+ try await commandLine.runChecked(arguments, onLine: onLine, onProgress: onProgress)}switch step {@@ -296,8 +305,18 @@ final class VPhoneLaunchpadCreationPipeline {await self.library?.refresh()case .prepare:+ // Progress arrives on the reader thread and may land after the+ // step has moved on, so only the firmware step takes it. A finished+ // download clears it: extraction follows with no progress of its own.+ defer { downloadFraction = nil }try await run(["fw", "prepare", name, "--iphone-source", options.iphoneSource,- "--cloudos-source", options.cloudOSSource] + deviceArguments + library)+ "--cloudos-source", options.cloudOSSource] + deviceArguments + library,+ onProgress: { [weak self] fraction in+ Task { @MainActor in+ guard let self, self.current == .prepare else { return }+ self.downloadFraction = fraction < 1 ? fraction : nil+ }+ })case .patch:// The preset rides on `fw patch` itself; per-patch overrides are@@ -527,10 +546,21 @@ final class VPhoneLaunchpadCreationPipeline {#if DEBUGextension VPhoneLaunchpadCreationPipeline {- /// Running the restore, or failed while preparing firmware.- func applyPreview(failed: Bool = false) {+ /// Running the restore, failed while preparing firmware, or partway+ /// through downloading an IPSW.+ func applyPreview(failed: Bool = false, downloading: Double? = nil) {statuses = [:]durations = [:]+ downloadFraction = nil+ if let downloading {+ statuses[.create] = .passed+ durations[.create] = 1+ statuses[.prepare] = .running+ downloadFraction = downloading+ current = .prepare+ isRunning = true+ return+ }if failed {statuses[.create] = .passeddurations[.create] = 0diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swiftindex 58325ee3..cb3ad711 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift@@ -535,6 +535,14 @@ struct VPhoneLaunchpadCreationView: View {private func stepRow(_ step: VPhoneLaunchpadCreationPipeline.Step) -> some View {LabeledContent {HStack(spacing: 8) {+ if step == .prepare, let fraction = creation.downloadFraction {+ ProgressView(value: fraction)+ .controlSize(.small)+ .frame(width: 120)+ Text(fraction, format: .percent.precision(.fractionLength(0)))+ .monospacedDigit()+ .foregroundStyle(.secondary)+ }if let duration = creation.durations[step] {Text(Self.duration(duration)).monospacedDigit()