Run a virtual iPhone on an Apple Silicon Mac.
Swift
Install a local VPhone.bundle build from Launchpad
Lakr233bb26d0250a5d
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swiftindex 06d2e594..642b0301 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift@@ -149,6 +149,12 @@ final class VPhoneLaunchpadModel {advance(selectNewest: false)}+ func installLocalBundle(_ source: URL) async {+ await bundles.installLocal(source)+ await machines.refresh()+ advance(selectNewest: false)+ }+func removeBundle(_ version: String) async {await bundles.remove(version)if let active = bundles.activeVersion, bundles.active?.preflight == .pending {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swiftindex c57f7824..b860cbfd 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift@@ -28,6 +28,7 @@ final class VPhoneLaunchpadCoreBundle {// MARK: - Install progressenum InstallStep: CaseIterable, Identifiable {+ case preparecase downloadcase verifycase install@@ -40,6 +41,7 @@ final class VPhoneLaunchpadCoreBundle {var title: String {switch self {+ case .prepare: String(localized: "Read local build")case .download: String(localized: "Download")case .verify: String(localized: "Verify SHA-256")case .install: String(localized: "Install as root")@@ -50,11 +52,29 @@ final class VPhoneLaunchpadCoreBundle {}struct InstallProgress {- let release: VPhoneLaunchpadRelease+ /// The store version, once known. A local build's comes from its+ /// Info.plist in the prepare step.+ var version: String?+ let source: String+ let size: Int64+ let plan: [InstallStep]var steps: [InstallStep: VPhoneLaunchpadStatus] = [:]var received: Int64 = 0var error: VPhoneLaunchpadError?+ init(release: VPhoneLaunchpadRelease) {+ version = release.version+ source = release.assetName+ size = release.size+ plan = [.download, .verify, .install, .policy, .preflight]+ }++ init(local: URL) {+ source = local.lastPathComponent+ size = 0+ plan = [.prepare, .install, .policy, .preflight]+ }+func status(_ step: InstallStep) -> VPhoneLaunchpadStatus {steps[step] ?? .pending}@@ -197,7 +217,7 @@ final class VPhoneLaunchpadCoreBundle {$0.preflightDetail = result.succeeded? String(localized: "Passed"): (failure.isEmpty ? String(localized: "Preflight failed") : failure)- .replacingOccurrences(of: "Error: ", with: "")+ .replacingOccurrences(of: "Error: ", with: "")}} catch {update(version) {@@ -242,33 +262,66 @@ final class VPhoneLaunchpadCoreBundle {}set(.verify, .passed)- set(.install, .running)- let handle = try FileHandle(forReadingFrom: file)- defer { try? handle.close() }- try await helper.installBundle(version: release.version, archive: handle, sha256: release.sha256)- set(.install, .passed)-- loadInstalled()- activeVersion = release.version- set(.policy, .running)- set(.preflight, .running)- await verify(release.version)- let installed = installed.first { $0.version == release.version }- set(.policy, installed?.policy ?? .failed)- set(.preflight, installed?.preflight ?? .failed)- if installed?.preflight != .passed {- throw VPhoneLaunchpadError(- String(localized: "Host preflight failed. Fix the issue below, then choose Run Preflight Again."),- detail: installed?.preflightDetail,- )- }+ try await installAndVerify(version: release.version, archive: file, sha256: release.sha256)} catch {- for step in InstallStep.allCases where progress?.status(step) == .running {- set(step, .failed)+ fail(error)+ }+ }++ /// Installs a VPhone.bundle folder or .zip built on this Mac as+ /// `<version>-local`.+ func installLocal(_ source: URL) async {+ progress = InstallProgress(local: source)+ var work: URL?+ defer {+ if let work {+ try? FileManager.default.removeItem(at: work)}- progress?.error = error as? VPhoneLaunchpadError- ?? VPhoneLaunchpadError(String(localized: "Unable to install the bundle. Try again."), detail: error.localizedDescription)}+ do {+ set(.prepare, .running)+ let local = try await VPhoneLaunchpadLocalBundle.prepare(source)+ work = local.workDirectory+ progress?.version = local.version+ set(.prepare, .passed)++ try await installAndVerify(version: local.version, archive: local.archive, sha256: local.sha256)+ } catch {+ fail(error)+ }+ }++ /// The steps a release and a local build share: the helper installs the+ /// archive as root, then the new version becomes active and is checked.+ private func installAndVerify(version: String, archive: URL, sha256: String) async throws {+ set(.install, .running)+ let handle = try FileHandle(forReadingFrom: archive)+ defer { try? handle.close() }+ try await helper.installBundle(version: version, archive: handle, sha256: sha256)+ set(.install, .passed)++ loadInstalled()+ activeVersion = version+ set(.policy, .running)+ set(.preflight, .running)+ await verify(version)+ let installed = installed.first { $0.version == version }+ set(.policy, installed?.policy ?? .failed)+ set(.preflight, installed?.preflight ?? .failed)+ if installed?.preflight != .passed {+ throw VPhoneLaunchpadError(+ String(localized: "Host preflight failed. Fix the issue below, then choose Run Preflight Again."),+ detail: installed?.preflightDetail,+ )+ }+ }++ private func fail(_ error: Error) {+ for step in InstallStep.allCases where progress?.status(step) == .running {+ set(step, .failed)+ }+ progress?.error = error as? VPhoneLaunchpadError+ ?? VPhoneLaunchpadError(String(localized: "Unable to install the bundle. Try again."), detail: error.localizedDescription)}func dismissProgress() {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundleView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundleView.swiftindex 38269ce4..0aae3942 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundleView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundleView.swift@@ -1,4 +1,5 @@import SwiftUI+import UniformTypeIdentifiersstruct VPhoneLaunchpadCoreBundleView: View {@Environment(VPhoneLaunchpadModel.self) private var model@@ -39,6 +40,17 @@ struct VPhoneLaunchpadCoreBundleView: View {}.formStyle(.grouped).toolbar {+ ToolbarItem(placement: .primaryAction) {+ Button {+ chooseLocalBuild()+ } label: {+ Label("Install Local Build…", systemImage: "shippingbox")+ }+ .help(model.canInstallBundles+ ? "Install a VPhone.bundle folder or .zip built on this Mac."+ : "Installing needs the privileged helper and Developer Tools access.")+ .disabled(!model.canInstallBundles)+ }ToolbarItem(placement: .primaryAction) {Button {Task { await bundles.refresh() }@@ -51,7 +63,11 @@ struct VPhoneLaunchpadCoreBundleView: View {}.confirmationDialog("Remove VPhone.bundle \(removal ?? "")?",- isPresented: Binding(get: { removal != nil }, set: { if !$0 { removal = nil } }),+ isPresented: Binding(get: { removal != nil }, set: {+ if !$0 {+ removal = nil+ }+ }),) {Button("Remove", role: .destructive) {if let version = removal {@@ -65,7 +81,6 @@ struct VPhoneLaunchpadCoreBundleView: View {// MARK: - Latest- @ViewBuilderprivate var latestSection: some View {Section("Latest Release") {if let latest = bundles.releases.first {@@ -87,13 +102,13 @@ struct VPhoneLaunchpadCoreBundleView: View {private func progressSection(_ progress: VPhoneLaunchpadCoreBundle.InstallProgress) -> some View {Section {if progress.status(.download) == .running {- ProgressView(value: Double(progress.received), total: Double(max(progress.release.size, 1))) {+ ProgressView(value: Double(progress.received), total: Double(max(progress.size, 1))) {Text("Downloading…")} currentValueLabel: {- Text("\(Self.size(progress.received)) of \(Self.size(progress.release.size))")+ Text("\(Self.size(progress.received)) of \(Self.size(progress.size))")}}- ForEach(VPhoneLaunchpadCoreBundle.InstallStep.allCases) { step in+ ForEach(progress.plan) { step inLabel {Text(step.title)} icon: {@@ -113,7 +128,7 @@ struct VPhoneLaunchpadCoreBundleView: View {}} header: {HStack {- Text("Installing \(progress.release.version)")+ Text("Installing \(progress.version ?? progress.source)")Spacer()if !bundles.isInstalling {Button("Dismiss") { bundles.dismissProgress() }@@ -142,9 +157,15 @@ struct VPhoneLaunchpadCoreBundleView: View {.foregroundStyle(isActive ? AnyShapeStyle(.green) : AnyShapeStyle(.primary)).accessibilityValue(isActive ? "In use" : "").help(isActive ? "In use" : "")- Text("Installed \(bundle.receipt.installedAt.formatted(date: .abbreviated, time: .omitted)) · SHA-256 \(Self.shortDigest(bundle.receipt.sha256))")- .font(.caption)- .foregroundStyle(.secondary)+ Group {+ if VPhoneLaunchpadLocalBundle.isLocal(version: bundle.version) {+ Text("Local build · Installed \(bundle.receipt.installedAt.formatted(date: .abbreviated, time: .shortened)) · SHA-256 \(Self.shortDigest(bundle.receipt.sha256))")+ } else {+ Text("Installed \(bundle.receipt.installedAt.formatted(date: .abbreviated, time: .omitted)) · SHA-256 \(Self.shortDigest(bundle.receipt.sha256))")+ }+ }+ .font(.caption)+ .foregroundStyle(.secondary)}Spacer()Label {@@ -217,6 +238,24 @@ struct VPhoneLaunchpadCoreBundleView: View {.help(model.canInstallBundles ? "" : "Installing needs the privileged helper and Developer Tools access.")}+ // MARK: - Local build++ private func chooseLocalBuild() {+ let panel = NSOpenPanel()+ panel.title = String(localized: "Install Local Build")+ panel.message = String(localized: "Choose a VPhone.bundle folder or a .zip that contains one.")+ panel.prompt = String(localized: "Install")+ panel.canChooseFiles = true+ panel.canChooseDirectories = true+ panel.treatsFilePackagesAsDirectories = false+ panel.allowsMultipleSelection = false+ panel.allowedContentTypes = [.zip, .bundle]+ guard panel.runModal() == .OK, let url = panel.url else {+ return+ }+ Task { await model.installLocalBundle(url) }+ }+// MARK: - Formattingstatic func size(_ bytes: Int64) -> String {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadLocalBundle.swift b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadLocalBundle.swiftnew file mode 100644index 00000000..94a949d9--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadLocalBundle.swift@@ -0,0 +1,174 @@+import CryptoKit+import Foundation++/// A VPhone.bundle built on this Mac, chosen either as the bundle folder or as+/// a .zip that holds `VPhone.bundle` at its top level, like a release asset.+///+/// It goes through the helper's normal install verb: the app hands over a zip+/// and its SHA-256, and the helper hashes the copy it takes and validates the+/// bundle's code signature before it moves it into the store. A local build+/// has no published digest, so the hash only proves that the helper installs+/// the bytes prepared here.+nonisolated struct VPhoneLaunchpadLocalBundle: Sendable {+ /// Local builds are stored as `<version>-local`. They never replace a+ /// release of the same version, and a newer local build of that version+ /// replaces the older one.+ static let versionSuffix = "-local"+ static let bundleIdentifier = "com.vphone.bundle"++ let version: String+ let archive: URL+ let sha256: String+ /// Removed once the install finishes. It holds the zip made from a+ /// folder; a chosen .zip is read where it is.+ let workDirectory: URL++ static func isLocal(version: String) -> Bool {+ version.hasSuffix(versionSuffix)+ }++ // MARK: - Prepare++ /// Reads the version from the bundle's Info.plist and produces the zip+ /// and digest the helper expects.+ @concurrent static func prepare(_ source: URL) async throws -> VPhoneLaunchpadLocalBundle {+ let values = try? source.resourceValues(forKeys: [.isDirectoryKey])+ let isDirectory = values?.isDirectory ?? false+ let fileManager = FileManager.default+ let work = fileManager.temporaryDirectory+ .appendingPathComponent("vphone-launchpad-\(UUID().uuidString)", isDirectory: true)+ try fileManager.createDirectory(at: work, withIntermediateDirectories: true)++ do {+ let infoPlist: Data+ let archive: URL+ if isDirectory {+ guard source.pathExtension == "bundle" else {+ throw unsupported()+ }+ guard let data = try? Data(contentsOf: source.appendingPathComponent("Contents/Info.plist")) else {+ throw notVPhoneBundle(source)+ }+ infoPlist = data+ // The helper expects VPhone.bundle at the top of the zip, so a+ // renamed build is copied under that name first.+ var bundle = source+ if source.lastPathComponent != "VPhone.bundle" {+ bundle = work.appendingPathComponent("VPhone.bundle", isDirectory: true)+ try run("/usr/bin/ditto", [source.path, bundle.path])+ }+ archive = work.appendingPathComponent("VPhone.zip")+ try run("/usr/bin/ditto", ["-c", "-k", "--keepParent", bundle.path, archive.path])+ } else {+ guard source.pathExtension.lowercased() == "zip" else {+ throw unsupported()+ }+ guard let data = try? run("/usr/bin/unzip", ["-p", source.path, "VPhone.bundle/Contents/Info.plist"]),+ !data.isEmpty+ else {+ throw VPhoneLaunchpadError(+ String(localized: "\(source.lastPathComponent) does not contain VPhone.bundle at its top level."),+ detail: String(localized: "Zip the bundle with `ditto -c -k --keepParent VPhone.bundle VPhone.zip`, or choose the VPhone.bundle folder."),+ )+ }+ infoPlist = data+ archive = source+ }++ let version = try version(from: infoPlist, source: source)+ return try VPhoneLaunchpadLocalBundle(+ version: version,+ archive: archive,+ sha256: sha256(of: archive),+ workDirectory: work,+ )+ } catch {+ try? fileManager.removeItem(at: work)+ throw error+ }+ }++ private static func version(from infoPlist: Data, source: URL) throws -> String {+ guard let plist = try? PropertyListSerialization.propertyList(from: infoPlist, format: nil) as? [String: Any],+ plist["CFBundleIdentifier"] as? String == bundleIdentifier,+ let shortVersion = plist["CFBundleShortVersionString"] as? String+ else {+ throw notVPhoneBundle(source)+ }+ let version = shortVersion + versionSuffix+ guard VPhoneLaunchpadNames.isValidVersion(version) else {+ throw VPhoneLaunchpadError(String(localized: "VPhone.bundle has an unsupported version \"\(shortVersion)\"."))+ }+ return version+ }++ // MARK: - Helpers++ private static func sha256(of file: URL) throws -> String {+ let handle = try FileHandle(forReadingFrom: file)+ defer { try? handle.close() }+ var hasher = SHA256()+ while let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty {+ hasher.update(data: chunk)+ }+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()+ }++ /// Runs a system tool and returns its standard output.+ @discardableResult+ private static func run(_ tool: String, _ arguments: [String]) throws -> Data {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: tool)+ process.arguments = arguments+ let output = Pipe()+ let error = Pipe()+ process.standardInput = FileHandle.nullDevice+ process.standardOutput = output+ process.standardError = error+ try process.run()+ // Drain stderr on its own thread so a chatty tool cannot block on a+ // full pipe while stdout is read here.+ let errorData = LockedData()+ let drained = DispatchSemaphore(value: 0)+ Thread.detachNewThread {+ errorData.set(error.fileHandleForReading.readDataToEndOfFile())+ drained.signal()+ }+ let data = output.fileHandleForReading.readDataToEndOfFile()+ drained.wait()+ process.waitUntilExit()+ guard process.terminationStatus == 0 else {+ let message = String(decoding: errorData.get(), as: UTF8.self)+ .trimmingCharacters(in: .whitespacesAndNewlines)+ throw VPhoneLaunchpadError(+ String(localized: "Unable to read the local build."),+ detail: message.isEmpty ? "\(tool) exited with status \(process.terminationStatus)." : message,+ )+ }+ return data+ }++ private final class LockedData: @unchecked Sendable {+ private let lock = NSLock()+ private var data = Data()++ func set(_ value: Data) {+ lock.withLock { data = value }+ }++ func get() -> Data {+ lock.withLock { data }+ }+ }++ private static func unsupported() -> VPhoneLaunchpadError {+ VPhoneLaunchpadError(String(localized: "Choose a VPhone.bundle folder or a .zip that contains one."))+ }++ private static func notVPhoneBundle(_ source: URL) -> VPhoneLaunchpadError {+ VPhoneLaunchpadError(+ String(localized: "\(source.lastPathComponent) is not a VPhone.bundle."),+ detail: String(localized: "Its Info.plist must have the bundle identifier \(bundleIdentifier) and a version."),+ )+ }+}