Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

List and delete downloaded IPSWs in Launchpad

Jacky1c2c23e14cfa
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.md
index 6a6ab42a..2f5b80a0 100644
--- a/Documents/Guides/create-and-run.md
+++ b/Documents/Guides/create-and-run.md
@@ -65,7 +65,7 @@ The online restore obtains its ticket in process. For an offline restore, see `v
| `~/.vphone/ipsws/` | Remote source IPSWs, shared by every VM; local IPSWs are read in place |
| `~/.vphone/gpu-drivers/<version>_<build>/` | GPU driver bundles extracted from cloudOS, shared by every VM |
-`VPHONE_ROOT` relocates the VM library and both caches. `VPHONE_LIBRARY_ROOT` takes precedence for the library alone, and `--ipsw-cache <dir>` on `vm create` and `fw prepare` for the IPSW cache alone. Downloaded IPSWs stay cached until you delete them, so a second VM from the same URL downloads nothing; the prepared restore tree is removed after a successful `vm create` unless `--keep-artifacts` is set. VMs prepared by an earlier build may still hold a `.ipsw-cache/` directory; it is safe to delete, and `vm export` leaves it out.
+`VPHONE_ROOT` relocates the VM library and both caches. `VPHONE_LIBRARY_ROOT` takes precedence for the library alone, and `--ipsw-cache <dir>` on `vm create` and `fw prepare` for the IPSW cache alone. Downloaded IPSWs stay cached until you delete them (in Launchpad, with File > Downloaded IPSWs…), so a second VM from the same URL downloads nothing; the prepared restore tree is removed after a successful `vm create` unless `--keep-artifacts` is set. VMs prepared by an earlier build may still hold a `.ipsw-cache/` directory; it is safe to delete, and `vm export` leaves it out.
```sh
vphone-cli vm list
diff --git a/VPhoneLaunchpad/Tests/IPSWCacheTests.sh b/VPhoneLaunchpad/Tests/IPSWCacheTests.sh
new file mode 100755
index 00000000..4e713264
--- /dev/null
+++ b/VPhoneLaunchpad/Tests/IPSWCacheTests.sh
@@ -0,0 +1,16 @@
+#!/bin/zsh
+set -euo pipefail
+
+launchpad="${0:a:h:h}"
+cache="$launchpad/VPhoneLaunchpad/IPSWCache"
+temporary="$(/usr/bin/mktemp -d)"
+trap '/bin/rm -rf "$temporary"' EXIT
+
+/usr/bin/xcrun swiftc -swift-version 6 -strict-concurrency=complete \
+ -parse-as-library \
+ "$cache/VPhoneLaunchpadIPSW.swift" \
+ "$cache/VPhoneLaunchpadIPSWCache.swift" \
+ "$cache/VPhoneLaunchpadIPSWRows.swift" \
+ "$launchpad/Tests/IPSWCacheTests.swift" \
+ -o "$temporary/ipsw-cache-tests"
+"$temporary/ipsw-cache-tests" "$@"
diff --git a/VPhoneLaunchpad/Tests/IPSWCacheTests.swift b/VPhoneLaunchpad/Tests/IPSWCacheTests.swift
new file mode 100644
index 00000000..9bd452d5
--- /dev/null
+++ b/VPhoneLaunchpad/Tests/IPSWCacheTests.swift
@@ -0,0 +1,359 @@
+import Foundation
+
+/// The Downloaded IPSWs sheet's IPSW reading, cache listing, deletion rules
+/// and safe removal, against fixtures made in a temporary folder.
+@main
+struct IPSWCacheTests {
+ static func expect(_ condition: Bool, _ message: @autoclosure () -> String, line: Int = #line) {
+ precondition(condition, "line \(line): \(message())")
+ }
+
+ static func main() async throws {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("ipsw-cache-tests-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ // The shared IPSW cache is looked up under VPHONE_ROOT; keep it in the fixture.
+ setenv("VPHONE_ROOT", root.appendingPathComponent("data").path, 1)
+
+ fileNames()
+ try zips(in: root)
+ try await listing(in: root)
+ try await removal(in: root)
+ uses()
+ deletion()
+ rows()
+ print("IPSWCacheTests passed")
+ }
+
+ // MARK: - IPSW names
+
+ static func fileNames() {
+ let cached = VPhoneLaunchpadIPSW(fileName: "iPhone17_3_27.0_24A435_Restore-3c6d6dc0803d.ipsw")
+ expect(cached?.productTypes == ["iPhone17,3"], "\(String(describing: cached?.productTypes))")
+ expect(cached?.version == "27.0" && cached?.build == "24A435", "cached version and build")
+ expect(cached?.kind == .iPhone && cached?.title == "iOS 27.0 (24A435)", "cached kind and title")
+ expect(cached?.fromManifest == false, "name facts are guesses")
+
+ let pad = VPhoneLaunchpadIPSW(fileName: "iPad16,1,iPad16,2_26.6.2_23G90_Restore.ipsw")
+ expect(pad?.productTypes == ["iPad16,1", "iPad16,2"], "\(String(describing: pad?.productTypes))")
+ expect(pad?.kind == .iPad && pad?.title == "iPadOS 26.6.2 (23G90)", "iPad title")
+
+ let cachedPad = VPhoneLaunchpadIPSW(fileName: "iPad16_1_iPad16_2_26.6.2_23G90_Restore-0123456789ab.ipsw")
+ expect(cachedPad?.productTypes == ["iPad16,1", "iPad16,2"], "\(String(describing: cachedPad?.productTypes))")
+
+ expect(VPhoneLaunchpadIPSW(fileName: "c0ecdb4b310cf5239ab2b248dd3098eec297dc5aa3bbe6ad-b80d96a0b616.ipsw") == nil, "hash name")
+ expect(VPhoneLaunchpadIPSW(fileName: "notes.txt") == nil, "not an IPSW")
+ expect(VPhoneLaunchpadIPSW.productTypes(in: "iPhoneOS_iPad16,1") == ["iPad16,1"], "tree name products")
+
+ let beta = VPhoneLaunchpadIPSW(version: "26.4", build: "23E5207q", productTypes: [], deviceClasses: ["vresearch101ap"], fromManifest: true)
+ expect(beta.isBeta && beta.kind == .cloudOS, "cloudOS beta")
+
+ // The names `fw prepare` gave two real downloads (`VPhoneIPSWCache.cacheName`).
+ let rc = URL(string: "https://updates.cdn-apple.com/2026FallFCS/2d0cd01d-b4f9-4a20-a1e8-f3be54570da7/iPhone17,3_27.0_24A435_Restore.ipsw")!
+ expect(VPhoneLaunchpadIPSW.cacheName(for: rc) == "iPhone17_3_27.0_24A435_Restore-3c6d6dc0803d.ipsw", VPhoneLaunchpadIPSW.cacheName(for: rc))
+ let point = URL(string: "https://updates.cdn-apple.com/2026FallFCS/38dca0ee-bb5d-4132-ad13-62d57bcd6d32/iPhone17,3_27.0.1_24A446_Restore.ipsw")!
+ expect(VPhoneLaunchpadIPSW.cacheName(for: point) == "iPhone17_3_27.0.1_24A446_Restore-1c2c1e8da8de.ipsw", VPhoneLaunchpadIPSW.cacheName(for: point))
+
+ let uuid = UUID().uuidString
+ expect(VPhoneLaunchpadIPSW.finalName(ofPartial: ".a-0123456789ab.ipsw.\(uuid).partial") == "a-0123456789ab.ipsw", "partial name")
+ expect(VPhoneLaunchpadIPSW.finalName(ofPartial: ".a.ipsw.partial") == nil, "partial without UUID")
+ expect(VPhoneLaunchpadIPSW.finalName(ofPartial: "a.ipsw") == nil, "not partial")
+ expect(VPhoneLaunchpadIPSW.finalName(ofPartial: "..\(uuid).partial") == nil, "partial without a final name")
+ }
+
+ // MARK: - Zip
+
+ static var cloudManifest: [String: Any] { [
+ "ProductVersion": "26.4",
+ "ProductBuildVersion": "23E5207q",
+ "SupportedProductTypes": ["ComputeModule14,1"],
+ "BuildIdentities": [
+ ["Info": ["DeviceClass": "VRESEARCH101AP"]],
+ ["Info": ["DeviceClass": "vphone600ap"]],
+ ],
+ ] }
+
+ static func manifestData(_ plist: [String: Any]) throws -> Data {
+ // Padding that deflates well, so the member is really compressed.
+ var plist = plist
+ plist["Padding"] = String(repeating: "BuildIdentity ", count: 4000)
+ return try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
+ }
+
+ static func zip(_ arguments: [String], in directory: URL) throws {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/zip")
+ process.arguments = arguments
+ process.currentDirectoryURL = directory
+ process.standardOutput = FileHandle.nullDevice
+ try process.run()
+ process.waitUntilExit()
+ expect(process.terminationStatus == 0, "zip \(arguments)")
+ }
+
+ static func zips(in root: URL) throws {
+ let source = root.appendingPathComponent("source", isDirectory: true)
+ try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true)
+ try manifestData(cloudManifest).write(to: source.appendingPathComponent("BuildManifest.plist"))
+ try Data(repeating: 7, count: 100_000).write(to: source.appendingPathComponent("Firmware.bin"))
+
+ for (name, level) in [("deflated.ipsw", "-6"), ("stored.ipsw", "-0")] {
+ try zip(["-q", level, "../\(name)", "Firmware.bin", "BuildManifest.plist"], in: source)
+ let facts = try VPhoneLaunchpadIPSW.read(root.appendingPathComponent(name))
+ expect(facts.version == "26.4" && facts.build == "23E5207q", "\(name) version")
+ expect(facts.kind == .cloudOS && facts.fromManifest, "\(name) is a cloudOS")
+ expect(facts.title == "cloudOS 26.4 (23E5207q)", "\(name) title")
+ }
+
+ let zip64 = root.appendingPathComponent("zip64.ipsw")
+ let iPhone: [String: Any] = [
+ "ProductVersion": "26.6.2", "ProductBuildVersion": "23G90",
+ "SupportedProductTypes": ["iPhone17,3"],
+ "BuildIdentities": [["Info": ["DeviceClass": "d47ap"]]],
+ ]
+ try zip64Archive(member: "BuildManifest.plist", contents: manifestData(iPhone)).write(to: zip64)
+ let facts = try VPhoneLaunchpadIPSW.read(zip64)
+ expect(facts.kind == .iPhone && facts.productTypes == ["iPhone17,3"] && facts.build == "23G90", "ZIP64 manifest")
+
+ let notZip = root.appendingPathComponent("broken.ipsw")
+ try Data(repeating: 0, count: 4096).write(to: notZip)
+ expect((try? VPhoneLaunchpadIPSW.read(notZip)) == nil, "not a zip")
+ }
+
+ /// A one-member stored archive whose entry and end record go through
+ /// ZIP64, as an IPSW over 4 GB has them.
+ static func zip64Archive(member: String, contents: Data) -> Data {
+ var data = Data()
+ func le16(_ value: Int) { withUnsafeBytes(of: UInt16(value).littleEndian) { data.append(contentsOf: $0) } }
+ func le32(_ value: UInt32) { withUnsafeBytes(of: value.littleEndian) { data.append(contentsOf: $0) } }
+ func le64(_ value: Int) { withUnsafeBytes(of: UInt64(value).littleEndian) { data.append(contentsOf: $0) } }
+ let name = Data(member.utf8)
+
+ le32(0x0403_4B50); le16(45); le16(0); le16(0); le16(0); le16(0); le32(0)
+ le32(UInt32(contents.count)); le32(UInt32(contents.count)); le16(name.count); le16(0)
+ data.append(name)
+ data.append(contents)
+
+ let directory = data.count
+ le32(0x0201_4B50); le16(45); le16(45); le16(0); le16(0); le16(0); le16(0); le32(0)
+ le32(.max); le32(.max); le16(name.count); le16(4 + 24); le16(0); le16(0); le16(0); le32(0); le32(.max)
+ data.append(name)
+ le16(1); le16(24); le64(contents.count); le64(contents.count); le64(0)
+ let directorySize = data.count - directory
+
+ let record = data.count
+ le32(0x0606_4B50); le64(44); le16(45); le16(45); le32(0); le32(0)
+ le64(1); le64(1); le64(directorySize); le64(directory)
+ le32(0x0706_4B50); le32(0); le64(record); le32(1)
+ le32(0x0605_4B50); le16(0); le16(0); le16(0xFFFF); le16(0xFFFF); le32(.max); le32(.max); le16(0)
+ return data
+ }
+
+ // MARK: - Listing
+
+ static func listing(in root: URL) async throws {
+ let manager = FileManager.default
+ let shared = VPhoneLaunchpadIPSWCache.sharedDirectory
+ expect(shared.path == root.appendingPathComponent("data/ipsws").path, shared.path)
+ try manager.createDirectory(at: shared, withIntermediateDirectories: true)
+
+ let cache = root.appendingPathComponent("ipsws", isDirectory: true)
+ try manager.createDirectory(at: cache, withIntermediateDirectories: true)
+ try manager.copyItem(at: root.appendingPathComponent("deflated.ipsw"), to: cache.appendingPathComponent("c0ecdb4b310cf5239ab2b248dd3098eec297dc5aa3bbe6ad-b80d96a0b616.ipsw"))
+ try Data(repeating: 5, count: 1000).write(to: cache.appendingPathComponent(".iPhone17_3_27.0_24A435_Restore-3c6d6dc0803d.ipsw.\(UUID().uuidString).partial"))
+ try Data(repeating: 6, count: 10).write(to: cache.appendingPathComponent("readme.txt"))
+ try Data(repeating: 6, count: 10).write(to: cache.appendingPathComponent(".hidden.ipsw"))
+ // A link with an IPSW's name is not listed, and its target is not read.
+ try manager.createSymbolicLink(at: cache.appendingPathComponent("link.ipsw"), withDestinationURL: root.appendingPathComponent("stored.ipsw"))
+
+ let files = try VPhoneLaunchpadIPSWCache.ipsws(in: cache)
+ expect(files.count == 2, "\(files.map(\.name))")
+ let cloud = files.first { !$0.isDownloading }
+ expect(cloud?.facts?.kind == .cloudOS && cloud?.facts?.fromManifest == true, "cached cloudOS read from its manifest")
+ let partial = files.first(where: \.isDownloading)
+ expect(partial?.name == "iPhone17_3_27.0_24A435_Restore-3c6d6dc0803d.ipsw" && partial?.facts?.kind == .iPhone, "download in progress")
+ expect(partial?.size == 1000, "partial size")
+
+ // The `ipsws` folder beside a library is a cache too, once and only
+ // when it exists; the shared cache comes first.
+ let library = root.appendingPathComponent("machines", isDirectory: true).path
+ let missing = root.appendingPathComponent("elsewhere/machines", isDirectory: true).path
+ let sharedLibrary = root.appendingPathComponent("data/machines", isDirectory: true).path
+ let directories = VPhoneLaunchpadIPSWCache.cacheDirectories(libraryRoots: [sharedLibrary, library, library, missing])
+ expect(directories.map(\.standardizedFileURL.path) == [shared.path, cache.path], "\(directories.map(\.path))")
+
+ // A machine's product type: config.plist first, the restore tree kept
+ // in FirmwareOriginals otherwise.
+ let pad = root.appendingPathComponent("machines/ipad-lab", isDirectory: true)
+ try manager.createDirectory(at: pad, withIntermediateDirectories: true)
+ expect((["guestProductType": "iPad16,1"] as NSDictionary).write(to: pad.appendingPathComponent("config.plist"), atomically: true), "config.plist")
+ let phone = root.appendingPathComponent("machines/phone", isDirectory: true)
+ try manager.createDirectory(at: phone.appendingPathComponent("FirmwareOriginals/iPhone17,3_26.6.2_23G90_Restore", isDirectory: true), withIntermediateDirectories: true)
+ expect((["diskImage": "Disk.img"] as NSDictionary).write(to: phone.appendingPathComponent("config.plist"), atomically: true), "config.plist")
+ expect(VPhoneLaunchpadIPSWCache.guestProductType(in: pad) == "iPad16,1", "config product type")
+ expect(VPhoneLaunchpadIPSWCache.guestProductType(in: phone) == "iPhone17,3", "FirmwareOriginals product type")
+
+ let scan = try await VPhoneLaunchpadIPSWCache.scan(libraryRoots: [library], machineFolders: [pad, phone])
+ expect(scan.ipsws.count == 2 && scan.cacheDirectories.count == 2, "\(scan.ipsws.map(\.name))")
+ expect(scan.productTypes[pad.path] == "iPad16,1" && scan.productTypes[phone.path] == "iPhone17,3", "\(scan.productTypes)")
+ }
+
+ // MARK: - Removal
+
+ /// Only a regular file directly in a cache folder, named as an IPSW or a
+ /// partial download, is deleted.
+ static func removal(in root: URL) async throws {
+ let manager = FileManager.default
+ let cache = root.appendingPathComponent("ipsw-delete", isDirectory: true)
+ let other = root.appendingPathComponent("ipsw-delete-other", isDirectory: true)
+ let nested = cache.appendingPathComponent("nested", isDirectory: true)
+ try manager.createDirectory(at: nested, withIntermediateDirectories: true)
+ try manager.createDirectory(at: other, withIntermediateDirectories: true)
+ let ipsw = cache.appendingPathComponent("iPhone17,3_27.0_24A435_Restore.ipsw")
+ let partial = cache.appendingPathComponent(".iPad16,1_27.0.1_24A446_Restore.ipsw.\(UUID().uuidString).partial")
+ let notes = cache.appendingPathComponent("notes.txt")
+ let hidden = cache.appendingPathComponent(".hidden.ipsw")
+ let deeper = nested.appendingPathComponent("deeper.ipsw")
+ let outside = other.appendingPathComponent("kept.ipsw")
+ let target = other.appendingPathComponent("target.ipsw")
+ let link = cache.appendingPathComponent("link.ipsw")
+ let folder = cache.appendingPathComponent("folder.ipsw", isDirectory: true)
+ for file in [ipsw, partial, notes, hidden, deeper, outside, target] {
+ try Data("x".utf8).write(to: file)
+ }
+ try manager.createSymbolicLink(at: link, withDestinationURL: target)
+ try manager.createDirectory(at: folder, withIntermediateDirectories: true)
+ func refused(_ url: URL, _ message: String) async {
+ do {
+ try await VPhoneLaunchpadIPSWCache.removeIPSW(url, cacheDirectories: [cache])
+ expect(false, message)
+ } catch is VPhoneLaunchpadIPSWCache.RemovalError {} catch {
+ expect(false, "\(message): \(error)")
+ }
+ }
+ await refused(notes, "not an IPSW")
+ await refused(hidden, "a hidden file that is not a partial download")
+ await refused(deeper, "not directly in the cache")
+ await refused(outside, "outside the cache")
+ await refused(link, "a symbolic link")
+ await refused(folder, "a folder")
+ await refused(cache.appendingPathComponent("gone.ipsw"), "missing file")
+ await refused(cache.appendingPathComponent("nested/../../ipsw-delete-other/kept.ipsw"), "a path out of the cache")
+ // Listed as a regular file, then replaced by a link before the delete.
+ let swapped = cache.appendingPathComponent("swapped.ipsw")
+ try Data("x".utf8).write(to: swapped)
+ let listed = try VPhoneLaunchpadIPSWCache.ipsws(in: cache).first { $0.name == "swapped.ipsw" }
+ expect(listed != nil, "swapped listed")
+ try manager.removeItem(at: swapped)
+ try manager.createSymbolicLink(at: swapped, withDestinationURL: target)
+ await refused(listed!.url, "a file replaced by a link since it was listed")
+
+ try await VPhoneLaunchpadIPSWCache.removeIPSW(ipsw, cacheDirectories: [cache])
+ try await VPhoneLaunchpadIPSWCache.removeIPSW(partial, cacheDirectories: [cache])
+ expect(!manager.fileExists(atPath: ipsw.path) && !manager.fileExists(atPath: partial.path), "IPSW and partial deleted")
+ for kept in [notes, hidden, deeper, outside, target, folder] {
+ expect(manager.fileExists(atPath: kept.path), "\(kept.lastPathComponent) kept")
+ }
+ expect((try? manager.destinationOfSymbolicLink(atPath: link.path)) != nil, "link kept")
+ }
+
+ // MARK: - Uses
+
+ static func file(_ name: String, _ facts: VPhoneLaunchpadIPSW?, downloading: Bool = false) -> VPhoneLaunchpadIPSWFile {
+ VPhoneLaunchpadIPSWFile(
+ url: URL(fileURLWithPath: "/cache/\(name)"),
+ name: name,
+ size: 10_000_000_000,
+ facts: facts,
+ isDownloading: downloading,
+ )
+ }
+
+ static let padFile = file("iPad16,1,iPad16,2_26.6.2_23G90_Restore.ipsw", VPhoneLaunchpadIPSW(version: "26.6.2", build: "23G90", productTypes: ["iPad16,1", "iPad16,2"], deviceClasses: ["j717ap"], fromManifest: true))
+ static let phoneFile = file("iPhone17_3_27.0_24A435_Restore-3c6d6dc0803d.ipsw", VPhoneLaunchpadIPSW(fileName: "iPhone17_3_27.0_24A435_Restore-3c6d6dc0803d.ipsw"))
+ static let cloudFile = file("c0ecdb4b-b80d96a0b616.ipsw", VPhoneLaunchpadIPSW(version: "26.4", build: "23E5207q", productTypes: [], deviceClasses: ["vresearch101ap", "vphone600ap"], fromManifest: true))
+ static let unknownFile = file("mystery.ipsw", nil)
+ static let rcSource = "https://updates.cdn-apple.com/2026FallFCS/2d0cd01d-b4f9-4a20-a1e8-f3be54570da7/iPhone17,3_27.0_24A435_Restore.ipsw"
+
+ static func uses() {
+ let release = VPhoneLaunchpadIPSWUse.Release(version: "26.6.2", build: "23G90")
+ let cloud = VPhoneLaunchpadIPSWUse.Release(version: "26.4", build: "23E5207q")
+ let pad = VPhoneLaunchpadIPSWUse(machine: "ipad-mini-01", productType: "iPad16,1", ios: release, cloudOS: cloud)
+ let otherPad = VPhoneLaunchpadIPSWUse(machine: "ipad-pro-13", productType: "iPad17,3", ios: release, cloudOS: cloud)
+ let creating = VPhoneLaunchpadIPSWUse(machine: "phone", sources: [rcSource], isCreating: true)
+ expect(pad.uses(padFile) && !otherPad.uses(padFile), "iPad match by product type")
+ expect(pad.uses(cloudFile) && otherPad.uses(cloudFile), "cloudOS match by build")
+ expect(creating.uses(phoneFile) && !creating.uses(padFile), "creation source match")
+ expect(!pad.uses(unknownFile), "unknown file")
+ expect(VPhoneLaunchpadIPSWUse.source("/cache/mystery.ipsw", is: unknownFile), "local source match")
+ expect(VPhoneLaunchpadIPSWUse.source("file:///cache/mystery.ipsw", is: unknownFile), "file URL source match")
+ expect(!VPhoneLaunchpadIPSWUse.source("/elsewhere/mystery.ipsw", is: unknownFile), "another local file")
+ }
+
+ // MARK: - Deletion rules
+
+ /// A restored machine does not hold its IPSW; a creation that has not
+ /// finished does, and a partial file waits while any creation runs.
+ static func deletion() {
+ let url = "https://updates.cdn-apple.com/x/iPhone17,3_27.0_24A435_Restore.ipsw"
+ let cached = VPhoneLaunchpadIPSW.cacheName(for: URL(string: url)!)
+ let phone = file(cached, VPhoneLaunchpadIPSW(fileName: cached))
+ let partial = file(cached, nil, downloading: true)
+ let restored = VPhoneLaunchpadIPSWUse(machine: "done", productType: "iPhone17,3", ios: .init(version: "27.0", build: "24A435"))
+ let running = VPhoneLaunchpadIPSWUse(machine: "new", sources: [url], isCreating: true, needsSources: true)
+ let failed = VPhoneLaunchpadIPSWUse(machine: "retry", sources: [url], needsSources: true)
+ let finished = VPhoneLaunchpadIPSWUse(machine: "made", sources: [url])
+ let otherSource = VPhoneLaunchpadIPSWUse(machine: "other", sources: [rcSource], isCreating: true, needsSources: true)
+ typealias Rows = VPhoneLaunchpadIPSWRows
+ expect(restored.uses(phone) && Rows.deletionBlock(phone, uses: [restored, finished], isCreating: false) == nil, "restored and finished do not hold it")
+ expect(Rows.deletionBlock(phone, uses: [otherSource], isCreating: true) == nil, "a creation from another IPSW does not hold it")
+ let held = Rows.deletionBlock(phone, uses: [running], isCreating: true)
+ expect(held == "Creating new reads this IPSW until the creation finishes.", String(describing: held))
+ expect(Rows.deletionBlock(phone, uses: [failed], isCreating: false)?.contains("retry") == true, "an unfinished creation holds it")
+ expect(Rows.deletionBlock(phone, uses: [running, failed], isCreating: true)?.contains("new, retry") == true, "both creations named")
+ expect(Rows.deletionBlock(partial, uses: [], isCreating: true) == "This IPSW is still downloading.", "a partial file waits while a creation runs")
+ expect(Rows.deletionBlock(partial, uses: [], isCreating: false) == nil, "a stale partial file can go")
+ let rows = Rows.rows([phone], catalog: nil, uses: [restored, failed])
+ expect(rows[0].blockedReason != nil && rows[0].usedBy == ["done", "retry"], "\(rows[0])")
+
+ // The confirmation names the file, the machines that keep working and
+ // what brings it back.
+ var row = Rows.rows([phone], catalog: nil, uses: [restored])[0]
+ expect(Rows.deletionMessage(row) == "\(cached) is deleted from the IPSW cache. done keep working without it. Creating a machine from this release downloads it again.", Rows.deletionMessage(row))
+ row.usedBy = []
+ expect(Rows.deletionMessage(row) == "\(cached) is deleted from the IPSW cache. Creating a machine from this release downloads it again.", Rows.deletionMessage(row))
+ let partialRow = Rows.rows([partial], catalog: nil, uses: [])[0]
+ expect(Rows.deletionMessage(partialRow) == "The partial download of \(cached) is deleted.", Rows.deletionMessage(partialRow))
+ }
+
+ // MARK: - Rows
+
+ static func rows() {
+ let release = VPhoneLaunchpadIPSWUse.Release(version: "26.6.2", build: "23G90")
+ let cloud = VPhoneLaunchpadIPSWUse.Release(version: "26.4", build: "23E5207q")
+ let pad = VPhoneLaunchpadIPSWUse(machine: "ipad-mini-01", productType: "iPad16,1", ios: release, cloudOS: cloud)
+ let otherPad = VPhoneLaunchpadIPSWUse(machine: "ipad-pro-13", productType: "iPad17,3", ios: release, cloudOS: cloud)
+ let creating = VPhoneLaunchpadIPSWUse(machine: "phone", sources: [rcSource], isCreating: true, needsSources: true)
+ let catalog = VPhoneLaunchpadIPSWCatalogNames(images: [
+ (name: "iOS 27.0 RC", url: rcSource),
+ (name: "cloudOS 26.4", url: "https://updates.cdn-apple.com/x/c0ecdb4b"),
+ ])
+ expect(catalog.name(forFile: "iPhone17,3_27.0_24A435_Restore.ipsw") == "iOS 27.0 RC", "a copy kept under the URL's own name")
+
+ let rows = VPhoneLaunchpadIPSWRows.rows([unknownFile, cloudFile, padFile, phoneFile], catalog: catalog, uses: [pad, otherPad, creating])
+ expect(rows.map(\.kind) == [.iPhone, .iPad, .cloudOS, .unknown], "\(rows.map(\.kind))")
+ expect(rows[0].title == "iOS 27.0 RC (24A435)" && rows[0].usedBy == ["phone (creating)"], "\(rows[0])")
+ expect(rows[0].kindLabel == "iPhone" && rows[0].blockedReason != nil, "\(rows[0])")
+ expect(rows[1].title == "iPadOS 26.6.2 (23G90)" && rows[1].usedBy == ["ipad-mini-01"] && rows[1].blockedReason == nil, "\(rows[1])")
+ expect(rows[2].kindLabel == "cloudOS · beta" && rows[2].title == "cloudOS 26.4 (23E5207q)", "\(rows[2])")
+ expect(rows[2].usedBy == ["ipad-mini-01", "ipad-pro-13"], "\(rows[2].usedBy)")
+ expect(rows[3].title == "mystery.ipsw" && rows[3].kindLabel == "Unknown", "\(rows[3])")
+
+ // Newest first within a kind.
+ let older = file("iPhone17,3_26.6.2_23G90_Restore.ipsw", VPhoneLaunchpadIPSW(fileName: "iPhone17,3_26.6.2_23G90_Restore.ipsw"))
+ let newer = file("iPhone17,3_27.0.1_24A446_Restore.ipsw", VPhoneLaunchpadIPSW(fileName: "iPhone17,3_27.0.1_24A446_Restore.ipsw"))
+ let sorted = VPhoneLaunchpadIPSWRows.rows([older, newer], catalog: nil, uses: [])
+ expect(sorted.map(\.title) == ["iOS 27.0.1 (24A446)", "iOS 26.6.2 (23G90)"], "\(sorted.map(\.title))")
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift
index 1442c07b..d5fd8404 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift
@@ -26,7 +26,9 @@ struct VPhoneLaunchpadApp: App {
// Nor is any saved: the window's frame is kept under its own name.
.restorationBehavior(.disabled)
.commands {
- CommandGroup(replacing: .newItem) {}
+ CommandGroup(replacing: .newItem) {
+ Button("Downloaded IPSWs…") { model.present(.ipswCache) }
+ }
CommandGroup(after: .appSettings) {
Button("Host Setup…") { model.present(.hostSetup) }
Button("Core Bundle…") { model.present(.coreBundle) }
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
index a8b6505d..9d11a9a1 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
@@ -12,6 +12,7 @@ final class VPhoneLaunchpadModel {
case hostSetup
case coreBundle
case bundleInstall
+ case ipswCache
var id: Self {
self
@@ -22,6 +23,7 @@ final class VPhoneLaunchpadModel {
case .hostSetup: String(localized: "Host Setup")
case .coreBundle: String(localized: "Core Bundle")
case .bundleInstall: String(localized: "Core Bundle Install")
+ case .ipswCache: String(localized: "Downloaded IPSWs")
}
}
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
index 883a57b5..92617260 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
@@ -141,6 +141,10 @@
}
await sheet(.export([labMachine]), "11-export", suffix)
await sheet(.console(path("research-01")), "12-console", suffix)
+ ipswSelection = ipswScan.ipsws[1].id
+ await panel(model, .ipswCache, "13-downloaded-ipsws", suffix)
+ ipswSelection = ipswScan.ipsws[0].id
+ await panel(model, .ipswCache, "13a-downloaded-ipsws-in-use", suffix)
}
NSApp.terminate(nil)
}
@@ -325,6 +329,42 @@
return try? JSONDecoder().decode(VPhoneLaunchpadFirmwareCatalog.self, from: Data(json.utf8))
}()
+ /// Stands in for the IPSW cache: the creation's source, IPSWs the
+ /// restored machines were made from, and one nothing uses.
+ static let ipswScan: VPhoneLaunchpadIPSWCache.Scan = {
+ let base = "https://updates.cdn-apple.com/example"
+ let cache = VPhoneLaunchpadIPSWCache.sharedDirectory
+ func file(_ source: String, _ size: Int64, facts: VPhoneLaunchpadIPSW? = nil) -> VPhoneLaunchpadIPSWFile {
+ let name = VPhoneLaunchpadIPSW.cacheName(for: URL(string: source)!)
+ return VPhoneLaunchpadIPSWFile(
+ url: cache.appendingPathComponent(name),
+ name: name,
+ size: size,
+ facts: facts ?? VPhoneLaunchpadIPSW(fileName: name),
+ isDownloading: false,
+ )
+ }
+ let cloudOS = VPhoneLaunchpadIPSW(
+ version: "26.4", build: "23E224", productTypes: [],
+ deviceClasses: ["vresearch101ap", "vphone600ap"], fromManifest: true,
+ )
+ var scan = VPhoneLaunchpadIPSWCache.Scan(cacheDirectories: [cache])
+ scan.ipsws = [
+ file(creationOptions.iphoneSource, 9_835_120_455),
+ file("\(base)/iPhone17,3_26.6.2_23G90_Restore.ipsw", 9_612_301_228),
+ file("\(base)/iPhone17,3_26.4.2_23E261_Restore.ipsw", 9_401_877_310),
+ file("\(base)/iPad16,1,iPad16,2_26.6.2_23G90_Restore.ipsw", 8_903_455_119),
+ file(creationOptions.cloudOSSource, 14_220_648_901, facts: cloudOS),
+ ]
+ for machine in machines {
+ scan.productTypes[machine.path.url.path] = "iPhone17,3"
+ }
+ return scan
+ }()
+
+ /// The row the Downloaded IPSWs sheet opens with selected.
+ static var ipswSelection: String?
+
static let creationOptions = VPhoneLaunchpadCreationPipeline.Options(
name: "ios27-rc",
libraryRoot: VPhoneLaunchpadMachineLocations.defaultRoot,
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift
index 1c09bed3..9b3d17ce 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift
@@ -39,6 +39,8 @@ struct VPhoneLaunchpadRootView: View {
VPhoneLaunchpadCoreBundleView()
case .bundleInstall:
VPhoneLaunchpadInstallView()
+ case .ipswCache:
+ VPhoneLaunchpadIPSWCacheView()
}
}
.environment(model)
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift
new file mode 100644
index 00000000..43c497d6
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift
@@ -0,0 +1,396 @@
+import Compression
+import CryptoKit
+import Foundation
+
+// MARK: - IPSW facts
+
+/// What an IPSW is for, read from its BuildManifest (the same fields
+/// `VPhoneIPSWCache.inspect` reads), or guessed from its file name when the
+/// manifest cannot be read.
+nonisolated struct VPhoneLaunchpadIPSW: Hashable, Sendable {
+ enum Kind: Hashable, Sendable {
+ case iPhone, iPad, cloudOS, unknown
+
+ /// The system the IPSW installs: the first word of its title.
+ var systemName: String? {
+ switch self {
+ case .iPhone: "iOS"
+ case .iPad: "iPadOS"
+ case .cloudOS: "cloudOS"
+ case .unknown: nil
+ }
+ }
+ }
+
+ /// The cloudOS build identity vphone boots the guest's hardware from
+ /// (`VPhoneIPSWCache.cloudOSDeviceClass`).
+ static let cloudOSDeviceClass = "vresearch101ap"
+
+ var version: String
+ var build: String
+ /// `SupportedProductTypes`, such as `iPhone17,3`.
+ var productTypes: [String]
+ /// Every build identity's `Info.DeviceClass`, lowercased. Empty when the
+ /// facts come from the file name.
+ var deviceClasses: Set<String>
+ /// False when the facts were guessed from the file name.
+ var fromManifest: Bool
+
+ var kind: Kind {
+ if deviceClasses.contains(Self.cloudOSDeviceClass) {
+ return .cloudOS
+ }
+ if productTypes.contains(where: { $0.hasPrefix("iPad") }) {
+ return .iPad
+ }
+ if productTypes.contains(where: { $0.hasPrefix("iPhone") }) {
+ return .iPhone
+ }
+ return .unknown
+ }
+
+ /// Apple's beta and seed builds end in a lowercase letter (`23E5207q`).
+ var isBeta: Bool {
+ build.last.map(\.isLowercase) ?? false
+ }
+
+ /// `iOS 26.6.2 (23G90)`; nil for a kind it cannot name.
+ var title: String? {
+ kind.systemName.map { "\($0) \(version) (\(build))" }
+ }
+
+ // MARK: Manifest
+
+ init(version: String, build: String, productTypes: [String], deviceClasses: Set<String>, fromManifest: Bool) {
+ self.version = version
+ self.build = build
+ self.productTypes = productTypes
+ self.deviceClasses = deviceClasses
+ self.fromManifest = fromManifest
+ }
+
+ /// The facts in a parsed BuildManifest; nil without a version and build.
+ init?(manifest plist: [String: Any]) {
+ guard let version = plist["ProductVersion"] as? String, !version.isEmpty,
+ let build = plist["ProductBuildVersion"] as? String, !build.isEmpty
+ else {
+ return nil
+ }
+ let identities = plist["BuildIdentities"] as? [[String: Any]] ?? []
+ let classes = identities.compactMap { identity in
+ ((identity["Info"] as? [String: Any])?["DeviceClass"] as? String)?.lowercased()
+ }
+ self.init(
+ version: version,
+ build: build,
+ productTypes: plist["SupportedProductTypes"] as? [String] ?? [],
+ deviceClasses: Set(classes),
+ fromManifest: true,
+ )
+ }
+
+ /// Reads `BuildManifest.plist` out of the archive without unpacking
+ /// anything else: the central directory at the end of the file, then the
+ /// one member.
+ static func read(_ file: URL) throws -> VPhoneLaunchpadIPSW {
+ let data = try VPhoneLaunchpadZipReader.readMember("BuildManifest.plist", from: file)
+ guard let plist = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
+ let facts = VPhoneLaunchpadIPSW(manifest: plist)
+ else {
+ throw VPhoneLaunchpadZipReader.Failure.malformed
+ }
+ return facts
+ }
+
+ // MARK: File name
+
+ /// The facts an IPSW's name carries: `iPhone17,3_27.0_24A435_Restore.ipsw`,
+ /// `iPad16,1,iPad16,2_26.6.2_23G90_Restore.ipsw`, and the cache's spelling
+ /// of either, `iPhone17_3_27.0_24A435_Restore-3c6d6dc0803d.ipsw`.
+ init?(fileName: String) {
+ var stem = fileName
+ if stem.lowercased().hasSuffix(".ipsw") {
+ stem = String(stem.dropLast(5))
+ }
+ // The cache appends a dash and twelve hex digits of the URL's digest.
+ if let dash = stem.lastIndex(of: "-") {
+ let digest = stem[stem.index(after: dash)...]
+ if digest.count == 12, digest.allSatisfy(\.isHexDigit) {
+ stem = String(stem[..<dash])
+ }
+ }
+ let fields = stem.split(separator: "_", omittingEmptySubsequences: false).map(String.init)
+ guard let restore = fields.lastIndex(where: { $0.caseInsensitiveCompare("Restore") == .orderedSame }),
+ restore >= 3
+ else {
+ return nil
+ }
+ let build = fields[restore - 1]
+ let version = fields[restore - 2]
+ guard !build.isEmpty, version.first?.isNumber == true, version.allSatisfy({ $0.isNumber || $0 == "." }) else {
+ return nil
+ }
+ let products = Self.productTypes(in: fields[..<(restore - 2)].joined(separator: "_"))
+ let isCloud = stem.localizedCaseInsensitiveContains("cloudOS")
+ self.init(
+ version: version,
+ build: build,
+ productTypes: products,
+ deviceClasses: isCloud ? [Self.cloudOSDeviceClass] : [],
+ fromManifest: false,
+ )
+ }
+
+ /// `iPad16,1,iPad16,2` or the cache's `iPad16_1_iPad16_2` as product types.
+ static func productTypes(in text: String) -> [String] {
+ var types: [String] = []
+ var remaining = Substring(text)
+ while let start = remaining.firstIndex(where: \.isLetter) {
+ remaining = remaining[start...]
+ let letters = remaining.prefix(while: \.isLetter)
+ let afterLetters = remaining[letters.endIndex...]
+ let major = afterLetters.prefix(while: \.isNumber)
+ guard !major.isEmpty else {
+ remaining = afterLetters
+ continue
+ }
+ var rest = afterLetters[major.endIndex...]
+ var type = "\(letters)\(major)"
+ if let separator = rest.first, separator == "," || separator == "_" {
+ let minor = rest.dropFirst().prefix(while: \.isNumber)
+ if !minor.isEmpty {
+ type += ",\(minor)"
+ rest = rest.dropFirst().dropFirst(minor.count)
+ }
+ }
+ types.append(type)
+ remaining = rest
+ }
+ return types
+ }
+
+ // MARK: Cache names
+
+ /// The name `fw prepare` gives the file it downloads from `url`
+ /// (`VPhoneIPSWCache.cacheName`): the URL's last component made safe, a
+ /// dash and twelve hex digits of the URL's SHA-256.
+ static func cacheName(for url: URL) -> String {
+ let base = url.lastPathComponent
+ let stem = base.lowercased().hasSuffix(".ipsw") ? String(base.dropLast(5)) : base
+ let safe = String(stem.prefix(48).unicodeScalars.map { scalar in
+ let value = scalar.value
+ return (value >= 48 && value <= 57) || (value >= 65 && value <= 90)
+ || (value >= 97 && value <= 122) || value == 45 || value == 46 || value == 95
+ ? Character(scalar) : "_"
+ })
+ let digest = SHA256.hash(data: Data(url.absoluteString.utf8))
+ let suffix = digest.prefix(6).map { String(format: "%02x", $0) }.joined()
+ return "\(safe.isEmpty ? "firmware" : safe)-\(suffix).ipsw"
+ }
+
+ /// The cache file a download in progress becomes:
+ /// `.<cache name>.<UUID>.partial` is `<cache name>`.
+ static func finalName(ofPartial name: String) -> String? {
+ guard name.hasPrefix("."), name.hasSuffix(".partial") else {
+ return nil
+ }
+ let inner = name.dropFirst().dropLast(".partial".count)
+ guard let dot = inner.lastIndex(of: "."), UUID(uuidString: String(inner[inner.index(after: dot)...])) != nil else {
+ return nil
+ }
+ let final = String(inner[..<dot])
+ return final.isEmpty ? nil : final
+ }
+}
+
+// MARK: - Zip
+
+/// Reads one member of a zip archive, ZIP64 included, the way an IPSW is laid
+/// out: stored or deflated members, a central directory at the end.
+nonisolated enum VPhoneLaunchpadZipReader {
+ enum Failure: Error {
+ case notZip
+ case missing(String)
+ case unsupported(UInt16)
+ case malformed
+ case tooLarge
+ }
+
+ /// A manifest is a few megabytes; refuse anything absurd rather than
+ /// allocate it.
+ static let memberLimit: UInt64 = 64 << 20
+ static let directoryLimit: UInt64 = 64 << 20
+
+ static func readMember(_ name: String, from file: URL) throws -> Data {
+ let handle = try FileHandle(forReadingFrom: file)
+ defer { try? handle.close() }
+ let size = try handle.seekToEnd()
+ let directory = try centralDirectory(handle, size: size)
+ guard let entry = try find(name, in: directory) else {
+ throw Failure.missing(name)
+ }
+ guard entry.compressedSize <= memberLimit, entry.uncompressedSize <= memberLimit else {
+ throw Failure.tooLarge
+ }
+ let local = try read(handle, at: entry.localHeaderOffset, count: 30)
+ guard local.u32(0) == 0x0403_4B50 else {
+ throw Failure.malformed
+ }
+ let start = entry.localHeaderOffset + 30 + UInt64(local.u16(26)) + UInt64(local.u16(28))
+ let stored = try read(handle, at: start, count: Int(entry.compressedSize))
+ switch entry.method {
+ case 0:
+ return stored
+ case 8:
+ return try inflate(stored, expected: Int(entry.uncompressedSize))
+ default:
+ throw Failure.unsupported(entry.method)
+ }
+ }
+
+ struct Entry {
+ var method: UInt16
+ var compressedSize: UInt64
+ var uncompressedSize: UInt64
+ var localHeaderOffset: UInt64
+ }
+
+ /// The central directory's bytes, found through the end record and, for
+ /// archives over 4 GB, its ZIP64 counterpart.
+ static func centralDirectory(_ handle: FileHandle, size: UInt64) throws -> Data {
+ let tailLength = min(size, 65_535 + 22 + 20)
+ let tail = try read(handle, at: size - tailLength, count: Int(tailLength))
+ guard tail.count >= 22 else {
+ throw Failure.notZip
+ }
+ var end: Int?
+ var index = tail.count - 22
+ while index >= 0 {
+ if tail.u32(index) == 0x0605_4B50 {
+ end = index
+ break
+ }
+ index -= 1
+ }
+ guard let end else {
+ throw Failure.notZip
+ }
+ var directorySize = UInt64(tail.u32(end + 12))
+ var directoryOffset = UInt64(tail.u32(end + 16))
+ let locator = end - 20
+ if locator >= 0, tail.u32(locator) == 0x0706_4B50 {
+ let recordOffset = tail.u64(locator + 8)
+ let record = try read(handle, at: recordOffset, count: 56)
+ guard record.u32(0) == 0x0606_4B50 else {
+ throw Failure.malformed
+ }
+ directorySize = record.u64(40)
+ directoryOffset = record.u64(48)
+ }
+ guard directorySize <= directoryLimit, directoryOffset + directorySize <= size else {
+ throw Failure.malformed
+ }
+ return try read(handle, at: directoryOffset, count: Int(directorySize))
+ }
+
+ static func find(_ name: String, in directory: Data) throws -> Entry? {
+ let wanted = Data(name.utf8)
+ var offset = 0
+ while offset + 46 <= directory.count, directory.u32(offset) == 0x0201_4B50 {
+ let nameLength = Int(directory.u16(offset + 28))
+ let extraLength = Int(directory.u16(offset + 30))
+ let commentLength = Int(directory.u16(offset + 32))
+ let next = offset + 46 + nameLength + extraLength + commentLength
+ guard next <= directory.count else {
+ throw Failure.malformed
+ }
+ let nameRange = (offset + 46) ..< (offset + 46 + nameLength)
+ if directory[directory.startIndex + nameRange.lowerBound ..< directory.startIndex + nameRange.upperBound] == wanted {
+ var entry = Entry(
+ method: directory.u16(offset + 10),
+ compressedSize: UInt64(directory.u32(offset + 20)),
+ uncompressedSize: UInt64(directory.u32(offset + 24)),
+ localHeaderOffset: UInt64(directory.u32(offset + 42)),
+ )
+ applyZIP64(&entry, extra: directory, from: nameRange.upperBound, length: extraLength)
+ return entry
+ }
+ offset = next
+ }
+ return nil
+ }
+
+ /// Sizes and the offset that do not fit 32 bits are 0xFFFFFFFF in the
+ /// entry and follow, in that order, in the ZIP64 extra field (id 1).
+ static func applyZIP64(_ entry: inout Entry, extra data: Data, from start: Int, length: Int) {
+ let marker = UInt64(UInt32.max)
+ var offset = start
+ let end = start + length
+ while offset + 4 <= end {
+ let id = data.u16(offset)
+ let size = Int(data.u16(offset + 2))
+ if id == 1 {
+ var field = offset + 4
+ let fieldEnd = min(field + size, end)
+ if entry.uncompressedSize == marker, field + 8 <= fieldEnd {
+ entry.uncompressedSize = data.u64(field)
+ field += 8
+ }
+ if entry.compressedSize == marker, field + 8 <= fieldEnd {
+ entry.compressedSize = data.u64(field)
+ field += 8
+ }
+ if entry.localHeaderOffset == marker, field + 8 <= fieldEnd {
+ entry.localHeaderOffset = data.u64(field)
+ }
+ return
+ }
+ offset += 4 + size
+ }
+ }
+
+ static func inflate(_ data: Data, expected: Int) throws -> Data {
+ guard expected > 0 else {
+ return Data()
+ }
+ var output = Data(count: expected)
+ let written = output.withUnsafeMutableBytes { destination in
+ data.withUnsafeBytes { source in
+ // COMPRESSION_ZLIB is raw deflate, as zip stores it.
+ compression_decode_buffer(
+ destination.bindMemory(to: UInt8.self).baseAddress!, expected,
+ source.bindMemory(to: UInt8.self).baseAddress!, data.count,
+ nil, COMPRESSION_ZLIB,
+ )
+ }
+ }
+ guard written == expected else {
+ throw Failure.malformed
+ }
+ return output
+ }
+
+ static func read(_ handle: FileHandle, at offset: UInt64, count: Int) throws -> Data {
+ try handle.seek(toOffset: offset)
+ let data = try handle.read(upToCount: count) ?? Data()
+ guard data.count == count else {
+ throw Failure.malformed
+ }
+ return data
+ }
+}
+
+private extension Data {
+ nonisolated func u16(_ offset: Int) -> UInt16 {
+ let base = startIndex + offset
+ return UInt16(self[base]) | UInt16(self[base + 1]) << 8
+ }
+
+ nonisolated func u32(_ offset: Int) -> UInt32 {
+ UInt32(u16(offset)) | UInt32(u16(offset + 2)) << 16
+ }
+
+ nonisolated func u64(_ offset: Int) -> UInt64 {
+ UInt64(u32(offset)) | UInt64(u32(offset + 4)) << 32
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCache.swift b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCache.swift
new file mode 100644
index 00000000..ef49b03f
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCache.swift
@@ -0,0 +1,202 @@
+import Foundation
+import Synchronization
+
+// MARK: - Files
+
+/// One file in an IPSW cache: a downloaded IPSW, or the partial file of a
+/// download in progress.
+nonisolated struct VPhoneLaunchpadIPSWFile: Identifiable, Hashable, Sendable {
+ var url: URL
+ /// The name the file will have; for a download in progress, the name it
+ /// gets once it finishes.
+ var name: String
+ var size: Int64
+ /// Read from the manifest, else guessed from the name; nil when neither works.
+ var facts: VPhoneLaunchpadIPSW?
+ var isDownloading: Bool
+
+ var id: String {
+ url.path
+ }
+}
+
+// MARK: - Cache
+
+/// The IPSW caches `fw prepare` downloads into, read and pruned off the main
+/// actor. Reading follows no symbolic link, and deleting takes only a
+/// regular file with an IPSW's or a partial download's name.
+nonisolated enum VPhoneLaunchpadIPSWCache {
+ struct Scan: Sendable {
+ var cacheDirectories: [URL] = []
+ var ipsws: [VPhoneLaunchpadIPSWFile] = []
+ /// Each machine folder's guest product type, by folder path.
+ var productTypes: [String: String] = [:]
+ }
+
+ /// `$VPHONE_ROOT/ipsws`, else `~/.vphone/ipsws`: where `fw prepare`
+ /// downloads (`VPhoneResources.ipswCacheDirectory()`).
+ static var sharedDirectory: URL {
+ let environment = ProcessInfo.processInfo.environment["VPHONE_ROOT"].flatMap { $0.isEmpty ? nil : $0 }
+ let root = environment.map { URL(fileURLWithPath: $0, isDirectory: true) }
+ ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".vphone", isDirectory: true)
+ return root.appendingPathComponent("ipsws", isDirectory: true)
+ }
+
+ /// The shared cache, then the `ipsws` folder beside each library that has
+ /// one, as `VPhoneBoardDeviceTree.searchDirectories` looks.
+ static func cacheDirectories(libraryRoots: [String]) -> [URL] {
+ var directories = [sharedDirectory]
+ for root in libraryRoots {
+ let beside = URL(fileURLWithPath: root, isDirectory: true)
+ .deletingLastPathComponent()
+ .appendingPathComponent("ipsws", isDirectory: true)
+ let path = beside.standardizedFileURL.path
+ guard !directories.contains(where: { $0.standardizedFileURL.path == path }),
+ isDirectory(beside)
+ else {
+ continue
+ }
+ directories.append(beside)
+ }
+ return directories
+ }
+
+ /// Every cache's IPSWs, and the product type of each machine in
+ /// `machineFolders`, for matching an IPSW to the machines restored from it.
+ @concurrent
+ static func scan(libraryRoots: [String], machineFolders: [URL]) async throws -> Scan {
+ var scan = Scan()
+ scan.cacheDirectories = cacheDirectories(libraryRoots: libraryRoots)
+ for directory in scan.cacheDirectories {
+ scan.ipsws += try ipsws(in: directory)
+ }
+ for folder in machineFolders {
+ try Task.checkCancellation()
+ scan.productTypes[folder.path] = guestProductType(in: folder)
+ }
+ return scan
+ }
+
+ // MARK: IPSWs
+
+ private struct ManifestKey: Hashable {
+ var path: String
+ var size: Int64
+ var modified: Date?
+ }
+
+ /// Manifests already read, by path, size and modification date, so
+ /// opening the list again reads only the directory.
+ private static let manifests = Mutex<[ManifestKey: VPhoneLaunchpadIPSW?]>([:])
+
+ static func ipsws(in directory: URL) throws -> [VPhoneLaunchpadIPSWFile] {
+ let keys: Set<URLResourceKey> = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey]
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
+ var files: [VPhoneLaunchpadIPSWFile] = []
+ for name in names.sorted() {
+ try Task.checkCancellation()
+ let partial = VPhoneLaunchpadIPSW.finalName(ofPartial: name)
+ guard partial != nil || isIPSWName(name) else {
+ continue
+ }
+ let url = directory.appendingPathComponent(name, isDirectory: false)
+ // A symbolic link reports isRegularFile false: it is not followed.
+ guard let values = try? url.resourceValues(forKeys: keys), values.isRegularFile == true else {
+ continue
+ }
+ let size = Int64(values.fileSize ?? 0)
+ let facts: VPhoneLaunchpadIPSW?
+ if let partial {
+ facts = VPhoneLaunchpadIPSW(fileName: partial)
+ } else {
+ facts = manifestFacts(url, size: size, modified: values.contentModificationDate)
+ ?? VPhoneLaunchpadIPSW(fileName: name)
+ }
+ files.append(VPhoneLaunchpadIPSWFile(
+ url: url,
+ name: partial ?? name,
+ size: size,
+ facts: facts,
+ isDownloading: partial != nil,
+ ))
+ }
+ return files
+ }
+
+ /// `*.ipsw`, not hidden. A partial download is hidden.
+ static func isIPSWName(_ name: String) -> Bool {
+ !name.hasPrefix(".") && name.lowercased().hasSuffix(".ipsw")
+ }
+
+ private static func manifestFacts(_ url: URL, size: Int64, modified: Date?) -> VPhoneLaunchpadIPSW? {
+ let key = ManifestKey(path: url.path, size: size, modified: modified)
+ if let known = manifests.withLock({ $0[key] }) {
+ return known
+ }
+ let facts = try? VPhoneLaunchpadIPSW.read(url)
+ manifests.withLock { $0[key] = .some(facts) }
+ return facts
+ }
+
+ // MARK: Machines
+
+ /// config.plist's `guestProductType`, else the product type in the name
+ /// of the restore tree kept in `FirmwareOriginals`. An iPhone machine of
+ /// the default model records none in config.plist.
+ static func guestProductType(in folder: URL) -> String? {
+ let config = NSDictionary(contentsOf: folder.appendingPathComponent("config.plist"))
+ if let type = config?["guestProductType"] as? String, !type.isEmpty {
+ return type
+ }
+ let originals = folder.appendingPathComponent("FirmwareOriginals", isDirectory: true)
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: originals.path)) ?? []
+ // `fw prepare`'s restore tree: `iPhone17,3_…_Restore`, or for an iPad
+ // `iPhoneOS_iPad16,1_…_Restore`.
+ for name in names.sorted() where name.hasPrefix("iPhone") && name.hasSuffix("_Restore") {
+ if let type = VPhoneLaunchpadIPSW(fileName: name)?.productTypes.first {
+ return type
+ }
+ }
+ return nil
+ }
+
+ static func isDirectory(_ url: URL) -> Bool {
+ var isDirectory: ObjCBool = false
+ return FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) && isDirectory.boolValue
+ }
+
+ // MARK: Removal
+
+ enum RemovalError: LocalizedError {
+ case notIPSW(String)
+
+ var errorDescription: String? {
+ switch self {
+ case let .notIPSW(name): String(localized: "\(name) is not an IPSW in the IPSW cache.")
+ }
+ }
+ }
+
+ /// Deletes one IPSW, or the partial file of a download, only while it is
+ /// still a regular file directly inside one of `cacheDirectories` with an
+ /// IPSW's or a partial download's name. A symbolic link is refused, not
+ /// followed.
+ @concurrent
+ static func removeIPSW(_ url: URL, cacheDirectories: [URL]) async throws {
+ let name = url.lastPathComponent
+ let folder = url.deletingLastPathComponent().standardizedFileURL.path
+ guard isIPSWName(name) || VPhoneLaunchpadIPSW.finalName(ofPartial: name) != nil,
+ cacheDirectories.contains(where: { $0.standardizedFileURL.path == folder })
+ else {
+ throw RemovalError.notIPSW(name)
+ }
+ // Read now, not from the URL's cached resource values: the file may
+ // have changed since the list was read. The attributes are lstat's,
+ // so a symbolic link reports itself instead of its target.
+ let type = (try? FileManager.default.attributesOfItem(atPath: url.path))?[.type] as? FileAttributeType
+ guard type == .typeRegular else {
+ throw RemovalError.notIPSW(name)
+ }
+ try FileManager.default.removeItem(at: url)
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCacheView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCacheView.swift
new file mode 100644
index 00000000..2d68043a
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCacheView.swift
@@ -0,0 +1,289 @@
+import SwiftUI
+
+// MARK: - Downloaded IPSWs
+
+/// The IPSWs `fw prepare` has downloaded, with Delete. The files are those in
+/// the shared IPSW cache and in the `ipsws` folder beside each library,
+/// named by their BuildManifest and, when the default Core Bundle's `fw
+/// catalog` lists them, by the catalog. A machine uses an IPSW when its
+/// restore-info.json names that release (and its product type is among the
+/// IPSW's), or when its creation was given the IPSW as a source.
+struct VPhoneLaunchpadIPSWCacheView: View {
+ @Environment(VPhoneLaunchpadModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ /// Nil until the first scan answers.
+ @State private var scan: VPhoneLaunchpadIPSWCache.Scan?
+ @State private var catalog: VPhoneLaunchpadIPSWCatalogNames?
+ @State private var selection: VPhoneLaunchpadIPSWRow.ID?
+ @State private var deletion: VPhoneLaunchpadIPSWRow?
+ @State private var isDeleting = false
+ @State private var actionError: VPhoneLaunchpadError?
+
+ private var library: VPhoneLaunchpadMachineLibrary {
+ model.machines
+ }
+
+ private var rows: [VPhoneLaunchpadIPSWRow] {
+ guard let scan else {
+ return []
+ }
+ return VPhoneLaunchpadIPSWRows.rows(scan.ipsws, catalog: catalog, uses: uses(scan), isCreating: library.hasActiveCreation)
+ }
+
+ private var selected: VPhoneLaunchpadIPSWRow? {
+ rows.first { $0.id == selection }
+ }
+
+ var body: some View {
+ VPhoneLaunchpadSheet(Text("Downloaded IPSWs")) {
+ VStack(spacing: 0) {
+ list
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ if let reason = selected?.blockedReason {
+ Divider()
+ Label(reason, systemImage: "info.circle")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 16)
+ .padding(.vertical, 8)
+ }
+ }
+ } accessory: {
+ Button("Delete…") { confirmDeletion() }
+ .disabled(selected == nil || selected?.blockedReason != nil || isDeleting)
+ .help(selected?.blockedReason ?? String(localized: "Delete the selected IPSW from the IPSW cache."))
+ } actions: {
+ Button("Done") { dismiss() }
+ .keyboardShortcut(.defaultAction)
+ }
+ .frame(width: 760, height: 440)
+ // Again whenever the machines or creations change, and every few
+ // seconds while a creation runs, since its download grows.
+ .task(id: scanKey) {
+ await rescan()
+ while library.hasActiveCreation, !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(5))
+ await rescan()
+ }
+ }
+ .task(id: model.bundles.defaultVersion) { await loadCatalog() }
+ .confirmationDialog(
+ deletion.map { String(localized: "Delete \($0.title)?") } ?? "",
+ isPresented: Binding(get: { deletion != nil }, set: {
+ if !$0 {
+ deletion = nil
+ }
+ }),
+ presenting: deletion,
+ ) { row in
+ Button(String(localized: "Delete \(Self.size(row.size))"), role: .destructive) {
+ Task { await delete(row) }
+ }
+ } message: { row in
+ Text(VPhoneLaunchpadIPSWRows.deletionMessage(row))
+ }
+ .errorAlert($actionError)
+ }
+
+ // MARK: - List
+
+ @ViewBuilder
+ private var list: some View {
+ if scan == nil {
+ ProgressView()
+ .controlSize(.small)
+ } else if rows.isEmpty {
+ ContentUnavailableView {
+ Label("No Downloaded IPSWs", systemImage: "externaldrive")
+ } description: {
+ Text("The IPSWs a machine is created from are downloaded into the IPSW cache and listed here.")
+ }
+ } else {
+ table
+ }
+ }
+
+ private var table: some View {
+ Table(rows, selection: $selection) {
+ TableColumn("Image") { row in
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: row.title)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Text(row.isDownloading ? String(localized: "\(row.fileName) (partial download)") : row.fileName)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ .help(row.fileName)
+ }
+ .width(min: 200, ideal: 320)
+ TableColumn("Kind") { row in
+ Text(verbatim: row.kindLabel)
+ }
+ .width(min: 60, ideal: 80, max: 120)
+ TableColumn("Size") { row in
+ Text(verbatim: Self.size(row.size))
+ .monospacedDigit()
+ }
+ .width(min: 60, ideal: 80, max: 100)
+ .alignment(.numeric)
+ TableColumn("Used By") { row in
+ let names = row.usedBy.joined(separator: ", ")
+ Text(verbatim: names.isEmpty ? "—" : names)
+ .foregroundStyle(names.isEmpty ? .secondary : .primary)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ .help(names)
+ }
+ }
+ .onDeleteCommand { confirmDeletion() }
+ }
+
+ static func size(_ bytes: Int64) -> String {
+ ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
+ }
+
+ // MARK: - Data
+
+ /// Changes when a scan, or the uses read from the library, would change.
+ private var scanKey: [String] {
+ let machines = library.machines.map { machine in
+ "\(machine.libraryRoot)/\(machine.name):\(machine.restoreInfo.map { "\($0.ios.build)+\($0.cloudOS.build)" } ?? "")"
+ }
+ let creations = library.creations.map { path, creation in
+ "\(path.libraryRoot)/\(path.name):\(creation.isRunning):\(creation.isFinished)"
+ }
+ return [library.hasListed ? "listed" : "unlisted"] + library.roots + machines + creations.sorted()
+ }
+
+ private func rescan() async {
+ #if DEBUG
+ if VPhoneLaunchpadPreview.isActive {
+ scan = VPhoneLaunchpadPreview.ipswScan
+ selection = selection ?? VPhoneLaunchpadPreview.ipswSelection
+ return
+ }
+ #endif
+ do {
+ let scan = try await VPhoneLaunchpadIPSWCache.scan(
+ libraryRoots: library.roots,
+ machineFolders: library.machines.map(\.path.url),
+ )
+ self.scan = scan
+ if let selection, !scan.ipsws.contains(where: { $0.id == selection }) {
+ self.selection = nil
+ }
+ } catch {
+ // Cancelled: the sheet closed or the machines changed again.
+ }
+ }
+
+ /// Each listed machine, with the sources of its creation if it has one,
+ /// then each creation whose machine is not listed yet.
+ private func uses(_ scan: VPhoneLaunchpadIPSWCache.Scan) -> [VPhoneLaunchpadIPSWUse] {
+ var uses: [VPhoneLaunchpadIPSWUse] = []
+ for machine in library.machines {
+ let creation = library.creations[machine.path]
+ uses.append(VPhoneLaunchpadIPSWUse(
+ machine: machine.name,
+ productType: scan.productTypes[machine.path.url.path],
+ ios: machine.restoreInfo.map { .init(version: $0.ios.version, build: $0.ios.build) },
+ cloudOS: machine.restoreInfo.map { .init(version: $0.cloudOS.version, build: $0.cloudOS.build) },
+ sources: creation.map { [$0.options.iphoneSource, $0.options.cloudOSSource] } ?? [],
+ isCreating: creation?.isRunning == true,
+ needsSources: creation.map { !$0.isFinished } ?? false,
+ ))
+ }
+ for (path, creation) in library.creations where !library.machines.contains(where: { $0.path == path }) {
+ uses.append(VPhoneLaunchpadIPSWUse(
+ machine: path.name,
+ sources: [creation.options.iphoneSource, creation.options.cloudOSSource],
+ isCreating: creation.isRunning,
+ needsSources: !creation.isFinished,
+ ))
+ }
+ return uses
+ }
+
+ // MARK: - Catalog
+
+ /// The catalog names of each Core Bundle version, read once per session.
+ private static var catalogs: [String: VPhoneLaunchpadIPSWCatalogNames] = [:]
+
+ private func loadCatalog() async {
+ #if DEBUG
+ if VPhoneLaunchpadPreview.isActive {
+ catalog = VPhoneLaunchpadPreview.catalog.map(VPhoneLaunchpadIPSWCatalogNames.init)
+ return
+ }
+ #endif
+ guard let version = model.bundles.defaultVersion,
+ let commandLine = model.bundles.commandLine(version: version)
+ else {
+ return
+ }
+ if let known = Self.catalogs[version] {
+ catalog = known
+ return
+ }
+ // Without a catalog the rows are named from their manifests.
+ guard let result = try? await commandLine.run(["fw", "catalog", "--json"], recordInHistory: false),
+ result.succeeded, let data = result.jsonData,
+ let report = try? JSONDecoder().decode(VPhoneLaunchpadFirmwareCatalog.self, from: data)
+ else {
+ return
+ }
+ let names = VPhoneLaunchpadIPSWCatalogNames(report)
+ Self.catalogs[version] = names
+ catalog = names
+ }
+
+ // MARK: - Deleting
+
+ /// A row that cannot go says why at once; any other asks first.
+ private func confirmDeletion() {
+ guard let row = selected, !isDeleting else {
+ return
+ }
+ if let reason = row.blockedReason {
+ actionError = VPhoneLaunchpadError(String(localized: "Unable to Delete \(row.title)"), detail: reason)
+ } else {
+ deletion = row
+ }
+ }
+
+ /// Checks the IPSW again at the moment of deletion: a creation may have
+ /// started since the list was read.
+ private func delete(_ row: VPhoneLaunchpadIPSWRow) async {
+ guard !isDeleting, let scan, let file = scan.ipsws.first(where: { $0.id == row.id }) else {
+ return
+ }
+ let failure = String(localized: "Unable to Delete \(row.title)")
+ if let reason = VPhoneLaunchpadIPSWRows.deletionBlock(file, uses: uses(scan), isCreating: library.hasActiveCreation) {
+ actionError = VPhoneLaunchpadError(failure, detail: reason)
+ return
+ }
+ isDeleting = true
+ defer { isDeleting = false }
+ do {
+ try await VPhoneLaunchpadIPSWCache.removeIPSW(file.url, cacheDirectories: scan.cacheDirectories)
+ } catch {
+ actionError = VPhoneLaunchpadError(failure, detail: error.localizedDescription)
+ }
+ await rescan()
+ }
+}
+
+extension VPhoneLaunchpadIPSWCatalogNames {
+ /// Every iOS, iPadOS and cloudOS image the catalog names.
+ init(_ catalog: VPhoneLaunchpadFirmwareCatalog) {
+ self.init(images: catalog.guests.flatMap { device in
+ device.pairings.flatMap { pairing in
+ [(pairing.ios.name, pairing.ios.url), (pairing.recommendedCloudOS.name, pairing.recommendedCloudOS.url)]
+ }
+ })
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWRows.swift b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWRows.swift
new file mode 100644
index 00000000..a9d1d185
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWRows.swift
@@ -0,0 +1,199 @@
+import Foundation
+
+// MARK: - Rows
+
+/// One IPSW in the Downloaded IPSWs table.
+nonisolated struct VPhoneLaunchpadIPSWRow: Identifiable, Hashable, Sendable {
+ var id: String
+ var title: String
+ var fileName: String
+ var kind: VPhoneLaunchpadIPSW.Kind
+ var kindLabel: String
+ var size: Int64
+ var usedBy: [String]
+ var isDownloading: Bool
+ /// Why the IPSW cannot be deleted now; nil when it can.
+ var blockedReason: String?
+}
+
+// MARK: - Catalog names
+
+/// Names from `fw catalog --json`, found by the file a catalog URL becomes
+/// in the cache, or by the URL's own file name for a copy kept elsewhere.
+nonisolated struct VPhoneLaunchpadIPSWCatalogNames: Sendable {
+ private var names: [String: String] = [:]
+
+ /// Each image's name and URL.
+ init(images: [(name: String, url: String)]) {
+ for image in images {
+ guard let url = URL(string: image.url) else {
+ continue
+ }
+ names[VPhoneLaunchpadIPSW.cacheName(for: url)] = image.name
+ names[url.lastPathComponent] = image.name
+ }
+ }
+
+ func name(forFile fileName: String) -> String? {
+ names[fileName]
+ }
+}
+
+// MARK: - Machines
+
+/// What a machine was restored from, or is being created from, for the Used
+/// By column and the deletion rules.
+nonisolated struct VPhoneLaunchpadIPSWUse: Hashable, Sendable {
+ struct Release: Hashable, Sendable {
+ var version: String
+ var build: String
+ }
+
+ var machine: String
+ /// `guestProductType` from the machine's config.plist.
+ var productType: String?
+ var ios: Release?
+ var cloudOS: Release?
+ /// The `--iphone-source` and `--cloudos-source` of a creation: URLs, or
+ /// paths of local files.
+ var sources: [String] = []
+ var isCreating = false
+ /// A creation that has not finished: under way, or stopped short and
+ /// waiting for a retry, which reads its sources again.
+ var needsSources = false
+
+ func uses(_ file: VPhoneLaunchpadIPSWFile) -> Bool {
+ if sources.contains(where: { Self.source($0, is: file) }) {
+ return true
+ }
+ guard let facts = file.facts else {
+ return false
+ }
+ if facts.kind == .cloudOS {
+ return cloudOS == Release(version: facts.version, build: facts.build)
+ }
+ guard ios == Release(version: facts.version, build: facts.build) else {
+ return false
+ }
+ guard let productType, !facts.productTypes.isEmpty else {
+ return true
+ }
+ return facts.productTypes.contains(productType)
+ }
+
+ /// Whether a creation's source is this file: a URL by the name `fw
+ /// prepare` gives its download, a local file by its path.
+ static func source(_ source: String, is file: VPhoneLaunchpadIPSWFile) -> Bool {
+ if let url = URL(string: source), let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" {
+ return VPhoneLaunchpadIPSW.cacheName(for: url) == file.name
+ }
+ let path = source.hasPrefix("file://") ? URL(string: source)?.path ?? source : source
+ return URL(fileURLWithPath: path).standardizedFileURL.path == file.url.standardizedFileURL.path
+ }
+}
+
+// MARK: - Building
+
+nonisolated enum VPhoneLaunchpadIPSWRows {
+ /// iPhone IPSWs first, then iPad, cloudOS and unknown, each newest first.
+ static func rows(
+ _ files: [VPhoneLaunchpadIPSWFile],
+ catalog: VPhoneLaunchpadIPSWCatalogNames?,
+ uses: [VPhoneLaunchpadIPSWUse],
+ isCreating: Bool = false,
+ ) -> [VPhoneLaunchpadIPSWRow] {
+ files.map { file in
+ let facts = file.facts
+ let kind = facts?.kind ?? .unknown
+ let catalogName = catalog?.name(forFile: file.name)
+ return VPhoneLaunchpadIPSWRow(
+ id: file.id,
+ title: title(file, catalogName: catalogName),
+ fileName: file.name,
+ kind: kind,
+ kindLabel: kindLabel(kind, beta: facts?.isBeta == true || catalogName?.localizedCaseInsensitiveContains("beta") == true),
+ size: file.size,
+ usedBy: uses.filter { $0.uses(file) }.map { use in
+ use.isCreating ? String(localized: "\(use.machine) (creating)") : use.machine
+ },
+ isDownloading: file.isDownloading,
+ blockedReason: deletionBlock(file, uses: uses, isCreating: isCreating),
+ )
+ }
+ .sorted { lhs, rhs in
+ lhs.kind == rhs.kind
+ ? lhs.title.localizedStandardCompare(rhs.title) == .orderedDescending
+ : order(lhs.kind) < order(rhs.kind)
+ }
+ }
+
+ private static func order(_ kind: VPhoneLaunchpadIPSW.Kind) -> Int {
+ switch kind {
+ case .iPhone: 0
+ case .iPad: 1
+ case .cloudOS: 2
+ case .unknown: 3
+ }
+ }
+
+ /// The catalog's name with the build, `iOS 27.0 RC (24A435)`, else the
+ /// manifest's `iOS 27.0 (24A435)`, else the file name.
+ static func title(_ file: VPhoneLaunchpadIPSWFile, catalogName: String?) -> String {
+ if let catalogName {
+ guard let build = file.facts?.build, !catalogName.contains(build) else {
+ return catalogName
+ }
+ return "\(catalogName) (\(build))"
+ }
+ return file.facts?.title ?? file.name
+ }
+
+ static func kindLabel(_ kind: VPhoneLaunchpadIPSW.Kind, beta: Bool) -> String {
+ let name = switch kind {
+ case .iPhone: String(localized: "iPhone")
+ case .iPad: String(localized: "iPad")
+ case .cloudOS: String(localized: "cloudOS")
+ case .unknown: String(localized: "Unknown")
+ }
+ return beta ? String(localized: "\(name) · beta") : name
+ }
+
+ // MARK: Deleting
+
+ /// Why `file` cannot be deleted now, or nil. A restored machine no longer
+ /// reads its IPSWs: Update Kernel and Update Guest Environment work from
+ /// the machine folder. So only a creation that has not finished holds
+ /// one, since a retry reads its sources again. A partial file is a
+ /// download, and only a creation under way downloads (`isCreating`).
+ static func deletionBlock(
+ _ file: VPhoneLaunchpadIPSWFile,
+ uses: [VPhoneLaunchpadIPSWUse],
+ isCreating: Bool,
+ ) -> String? {
+ let creations = uses
+ .filter { use in use.needsSources && use.sources.contains { VPhoneLaunchpadIPSWUse.source($0, is: file) } }
+ .map(\.machine)
+ if !creations.isEmpty {
+ return String(localized: "Creating \(creations.joined(separator: ", ")) reads this IPSW until the creation finishes.")
+ }
+ if file.isDownloading, isCreating {
+ return String(localized: "This IPSW is still downloading.")
+ }
+ return nil
+ }
+
+ /// The confirmation's text: what goes, which machines keep working, and
+ /// what brings it back.
+ static func deletionMessage(_ row: VPhoneLaunchpadIPSWRow) -> String {
+ if row.isDownloading {
+ return String(localized: "The partial download of \(row.fileName) is deleted.")
+ }
+ let deleted = String(localized: "\(row.fileName) is deleted from the IPSW cache.")
+ let again = String(localized: "Creating a machine from this release downloads it again.")
+ guard !row.usedBy.isEmpty else {
+ return "\(deleted) \(again)"
+ }
+ let keep = String(localized: "\(row.usedBy.joined(separator: ", ")) keep working without it.")
+ return "\(deleted) \(keep) \(again)"
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index f30fd79f..3566610b 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -13738,6 +13738,213 @@
"vi" : { "stringUnit" : { "state" : "translated", "value" : "Tạo ảnh chụp nhanh" } },
"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "拍摄快照" } }
}
+ },
+ "Downloaded IPSWs…" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Downloaded IPSWs…" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ダウンロード済みの IPSW…" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "다운로드한 IPSW…" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "IPSW đã tải xuống…" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "已下载的 IPSW…" } }
+ }
+ },
+ "Downloaded IPSWs" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Downloaded IPSWs" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ダウンロード済みの IPSW" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "다운로드한 IPSW" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "IPSW đã tải xuống" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "已下载的 IPSW" } }
+ }
+ },
+ "No Downloaded IPSWs" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "No Downloaded IPSWs" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ダウンロード済みの IPSW はありません" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "다운로드한 IPSW 없음" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chưa có IPSW nào được tải xuống" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "没有已下载的 IPSW" } }
+ }
+ },
+ "The IPSWs a machine is created from are downloaded into the IPSW cache and listed here." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "The IPSWs a machine is created from are downloaded into the IPSW cache and listed here." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "マシンの作成に使う IPSW は IPSW キャッシュにダウンロードされ、ここに表示されます。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "머신을 생성할 때 사용하는 IPSW는 IPSW 캐시에 다운로드되며 여기에 표시됩니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Các IPSW dùng để tạo máy ảo được tải vào bộ nhớ đệm IPSW và hiển thị tại đây." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "创建虚拟机所用的 IPSW 会下载到 IPSW 缓存,并显示在这里。" } }
+ }
+ },
+ "Image" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Image" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "イメージ" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이미지" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Bản firmware" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "映像" } }
+ }
+ },
+ "Kind" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Kind" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "種類" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "종류" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Loại" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "种类" } }
+ }
+ },
+ "Size" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Size" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "サイズ" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "크기" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Dung lượng" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "大小" } }
+ }
+ },
+ "Used By" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Used By" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "使用しているマシン" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "사용 중인 머신" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Máy ảo sử dụng" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "使用它的虚拟机" } }
+ }
+ },
+ "iPhone" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "iPhone" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "iPhone" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "iPhone" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "iPhone" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "iPhone" } }
+ }
+ },
+ "iPad" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "iPad" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "iPad" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "iPad" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "iPad" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "iPad" } }
+ }
+ },
+ "%@ · beta" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "%@ · beta" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ · ベータ" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@ · 베타" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%@ · beta" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%@ · 测试版" } }
+ }
+ },
+ "%@ (creating)" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "%@ (creating)" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@(作成中)" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@(생성 중)" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%@ (đang tạo)" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%@(创建中)" } }
+ }
+ },
+ "%@ (partial download)" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "%@ (partial download)" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@(未完了のダウンロード)" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@(완료되지 않은 다운로드)" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%@ (tải xuống dở dang)" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%@(未完成的下载)" } }
+ }
+ },
+ "Delete the selected IPSW from the IPSW cache." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Delete the selected IPSW from the IPSW cache." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "選択した IPSW を IPSW キャッシュから削除します。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "선택한 IPSW를 IPSW 캐시에서 삭제합니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Xóa IPSW đã chọn khỏi bộ nhớ đệm IPSW." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "从 IPSW 缓存中删除所选的 IPSW。" } }
+ }
+ },
+ "Delete %@" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Delete %@" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ を削除" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@ 삭제" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Xóa %@" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "删除 %@" } }
+ }
+ },
+ "Unable to Delete %@" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Unable to Delete %@" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ を削除できません" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@을(를) 삭제할 수 없음" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Không thể xóa %@" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "无法删除 %@" } }
+ }
+ },
+ "Creating %@ reads this IPSW until the creation finishes." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Creating %@ reads this IPSW until the creation finishes." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ の作成が完了するまで、この IPSW を読み込みます。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@ 생성이 끝날 때까지 이 IPSW를 읽습니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Quá trình tạo %@ đọc IPSW này cho đến khi hoàn tất." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "创建 %@ 完成之前需要读取这个 IPSW。" } }
+ }
+ },
+ "This IPSW is still downloading." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "This IPSW is still downloading." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "この IPSW はまだダウンロード中です。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이 IPSW는 아직 다운로드 중입니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "IPSW này vẫn đang được tải xuống." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "这个 IPSW 仍在下载中。" } }
+ }
+ },
+ "%@ is deleted from the IPSW cache." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "%@ is deleted from the IPSW cache." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ を IPSW キャッシュから削除します。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "IPSW 캐시에서 %@을(를) 삭제합니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%@ sẽ bị xóa khỏi bộ nhớ đệm IPSW." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "将从 IPSW 缓存中删除 %@。" } }
+ }
+ },
+ "%@ keep working without it." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "%@ keep working without it." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ はこのファイルがなくても引き続き使えます。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@은(는) 이 파일 없이도 계속 작동합니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%@ vẫn hoạt động bình thường khi không có tệp này." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%@ 不受影响,可以继续使用。" } }
+ }
+ },
+ "Creating a machine from this release downloads it again." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Creating a machine from this release downloads it again." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "このリリースからマシンを作成するときは、もう一度ダウンロードされます。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이 릴리스로 머신을 생성하면 다시 다운로드됩니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Khi tạo máy ảo từ bản phát hành này, tệp sẽ được tải lại." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "之后用这个版本新建虚拟机时会重新下载。" } }
+ }
+ },
+ "The partial download of %@ is deleted." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "The partial download of %@ is deleted." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ の未完了のダウンロードを削除します。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@의 완료되지 않은 다운로드를 삭제합니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Phần tải xuống dở dang của %@ sẽ bị xóa." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "将删除 %@ 未完成的下载。" } }
+ }
+ },
+ "%@ is not an IPSW in the IPSW cache." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "%@ is not an IPSW in the IPSW cache." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ は IPSW キャッシュ内の IPSW ではありません。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@은(는) IPSW 캐시에 있는 IPSW가 아닙니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%@ không phải là IPSW trong bộ nhớ đệm IPSW." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%@ 不是 IPSW 缓存中的 IPSW。" } }
+ }
}
},
"version" : "1.0"