Run a virtual iPhone on an Apple Silicon Mac.
Swift
Measure exclusive disk use by physical extents, not APFS private size
Jacky9e063a7daf8d
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.mdindex 385f2006..69c484e8 100644--- a/Documents/Guides/create-and-run.md+++ b/Documents/Guides/create-and-run.md@@ -132,7 +132,7 @@ Launchpad 2.9 creates machines from templates by default. New Machine has a SlimThe creation runs `vm template find` first. When a current template matches, it clones the machine (`vm create --template <id> --skip-first-boot`) and boots it. When none does, it builds the template in a temporary machine of the same library, named `template-` and eight hex digits, with its usual steps (restore, then `cfw install` through the helper), then `vm template trim`, the headless `vm template setup` and `vm template adopt --iphone-source … --cloudos-source …`, and clones the machine from the result. Each is a step of its own with its duration, and a failed one shows the reason `vphone-cli` gave. Once it has built a template, the creation offers to delete the two IPSWs it came from; nothing is deleted without confirming.-File > Templates… lists every library's templates with their machines, slimming, size and state, and deletes them. Guest System… (in a machine's Actions menu and inspector) switches a running machine's service profile and restores system apps the template removed. The inspector and the machine list show each machine's exclusive disk use, the blocks only it holds, beside what its files allocate.+File > Templates… lists every library's templates with their machines, slimming, size and state, and deletes them. Guest System… (in a machine's Actions menu and inspector) switches a running machine's service profile and restores system apps the template removed. The inspector and the machine list show each machine's exclusive disk use beside what its files allocate: the blocks no other machine or template holds, which deleting it frees (a local Time Machine snapshot taken before keeps them until it expires).### Shared secretsdiff --git a/Research/Host/machine_templates.md b/Research/Host/machine_templates.mdindex 392a0f06..b2223795 100644--- a/Research/Host/machine_templates.md+++ b/Research/Host/machine_templates.md@@ -119,6 +119,50 @@ re-resolves with the template's own `PatchSelection.plist`.`--no-template`; `adopt` says it removed it.- A clone drops `Template.plist`, `Snapshots/` and `vphone.sock`.+## Disk use++Launchpad shows each machine's and template's **Exclusive** size beside what+its files allocate (`st_blocks`): the blocks no other machine or template in+its libraries holds, what deleting it frees. `VPhoneLaunchpadDiskMeter`+measures every machine and template folder of every library in one pass+(templates are found as `.templates/<12 hex>`, builds left out): each file's+data ranges come from `SEEK_DATA`/`SEEK_HOLE` and `fcntl(F_LOG2PHYS_EXT)`+(`VPhoneLaunchpadDiskExtents`), and a sweep over the range ends of all+folders, per device, credits a stretch covered by exactly one folder to it.+Blocks a folder's own files share (its `Snapshots/`) count once, as its own; a+file the volume does not map (a compressed one) counts its allocated size.++It does not use APFS's private size (`ATTR_CMNEXT_PRIVATESIZE`), which+Launchpad used at first: a Time Machine local snapshot shares every block+that existed when it was taken, so after each hourly snapshot every machine's+and template's private size read 0 until it wrote again (Launchpad 2.9+end-to-end test, B7), and users read that as "deleting it frees nothing".+Those blocks are freed once the snapshot expires (Time Machine keeps hourly+local snapshots for 24 hours), so the extent comparison counts them as the+folder's own, and the help text says a local snapshot can keep them until+then. macOS has no public per-file "held by a snapshot" figure to show the+difference: `tmutil` and the volume's purgeable size are per volume.++Cost, measured 2026-10-09 on clones of a booted 64 GB sparse machine image+(21.6 GB allocated, 123,030 physical ranges): 0.08–0.11 s to map one image,+3 ms for the sweep over three of them, 0.27 s for a first pass over three+folders, 4 ms for a pass that maps nothing. A file is mapped again only when+its size, mtime or ctime changes; the pass runs off the main actor at most+every 30 s, with a 15 s mapping budget after which the rest is mapped on a+later pass (those folders show no exclusive size meanwhile).++Mapping opens the file (`O_EVTONLY`), and while it is open `lsof` lists+Launchpad for the image. `vm stop` signals whoever holds a disk, and `cfw+install` refuses a disk someone holds, so Launchpad never opens a folder it is+working on (a creation, a template build, an export, an install), keeps a+stopped machine's last ranges until its files change, and leaves its own+process out when it asks `lsof` which machines run. A `vphone-cli` run outside+Launchpad in the ~0.1 s a changed image is being mapped can still see it held.++Blocks shared with a file outside the libraries (a `cp -c` copy elsewhere)+count as the folder's own; the CLI's `vm template list/show` print only the+allocated size.+## Never booting once frozenThe P0 measurement: booting a template after clones exist raised one clone'sdiff --git a/VPhoneLaunchpad/Tests/TemplatesTests.sh b/VPhoneLaunchpad/Tests/TemplatesTests.shindex b0b99488..87e299c3 100755--- a/VPhoneLaunchpad/Tests/TemplatesTests.sh+++ b/VPhoneLaunchpad/Tests/TemplatesTests.sh@@ -11,6 +11,7 @@ trap '/bin/rm -rf "$temporary"' EXIT"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift" \"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPlan.swift" \"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskUsage.swift" \+ "$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskExtents.swift" \"$launchpad/Tests/TemplatesTests.swift" \-o "$temporary/templates-tests""$temporary/templates-tests" "$@"diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.swift b/VPhoneLaunchpad/Tests/TemplatesTests.swiftindex 4159fc3b..fcf528fe 100644--- a/VPhoneLaunchpad/Tests/TemplatesTests.swift+++ b/VPhoneLaunchpad/Tests/TemplatesTests.swift@@ -3,14 +3,14 @@ import Foundation@mainstruct TemplatesTests {- static func main() throws {+ static func main() async throws {slimmingArguments()commandArguments()creationPlan()try templateList()try templateFind()notices()- try diskUsage()+ try await diskUsage()}// MARK: - Switches@@ -336,7 +336,7 @@ struct TemplatesTests {// MARK: - Disk use- static func diskUsage() throws {+ static func diskUsage() async throws {let english = Locale(identifier: "en_US")precondition(VPhoneLaunchpadDiskUsage.format(17_580_000_000, locale: english) == "17.58 GB",VPhoneLaunchpadDiskUsage.format(17_580_000_000, locale: english))@@ -345,42 +345,138 @@ struct TemplatesTests {let partial = VPhoneLaunchpadDiskUsage(allocated: 17_580_000_000, exclusive: 610_000_000)precondition(partial.summary(locale: english).contains("610 MB") && partial.summary(locale: english).contains("17.58 GB"),partial.summary(locale: english))- precondition(VPhoneLaunchpadDiskUsage(allocated: 1_000_000_000, exclusive: nil).summary(locale: english) == "1 GB", "Without a private size")+ precondition(VPhoneLaunchpadDiskUsage(allocated: 1_000_000_000, exclusive: nil).summary(locale: english) == "1 GB", "Without an exclusive size")+ extentArithmetic()+ try await sharedExtents()+ print("Disk use tests passed")+ }++ /// The sweep on made-up extents.+ static func extentArithmetic() {+ typealias Extents = VPhoneLaunchpadDiskExtents+ func extents(_ ranges: [(Int64, Int64)], device: Int64 = 1) -> Extents {+ Extents(device: device, ranges: ranges.map { Extents.Range(start: $0.0, end: $0.1) })+ }+ let merged = extents([(30, 40), (0, 10), (10, 20), (35, 50), (60, 60)])+ precondition(merged.ranges == [Extents.Range(start: 0, end: 20), Extents.Range(start: 30, end: 50)], "Normalized: \(merged.ranges)")+ precondition(merged.bytes == 40, "Bytes \(merged.bytes)")++ // A template and two clones: each clone rewrote a part, one of them+ // also wrote where the template has a hole.+ let template = extents([(0, 1000)])+ let first = extents([(0, 100), (2000, 2100), (200, 1000)])+ let second = extents([(0, 500), (3000, 3050), (600, 1000)])+ precondition(Extents.exclusiveBytes(of: [[template], [first], [second]]) == [0, 100, 50],+ "Clones: \(Extents.exclusiveBytes(of: [[template], [first], [second]]))")+ // Once the clones are gone, all of it is the template's own.+ precondition(Extents.exclusiveBytes(of: [[template]]) == [1000], "Alone")+ // What only the template and one clone share is neither's own.+ precondition(Extents.exclusiveBytes(of: [[extents([(0, 100)])], [extents([(50, 150)])]]) == [50, 50], "Overlap")+ // Two files of one folder sharing blocks count them once, as its own.+ precondition(Extents.exclusiveBytes(of: [[extents([(0, 100)]), extents([(0, 100)])], [extents([(500, 600)])]]) == [100, 100],+ "Own clones")+ // The same offsets on another device are other blocks.+ precondition(Extents.exclusiveBytes(of: [[extents([(0, 100)], device: 1)], [extents([(0, 100)], device: 2)]]) == [100, 100],+ "Devices")+ precondition(Extents.exclusiveBytes(of: [[], [extents([(0, 10)])]]) == [0, 10], "An empty folder")+ }- // A clone shares its blocks until it writes: on APFS (the temporary- // directory is on the boot volume) the original keeps its blocks to- // itself only once the clone has rewritten them.+ /// Real clones on APFS (the temporary directory is on the boot volume).+ /// The images are 256 MiB and sparse, as a disk image is: APFS fills a+ /// small file's holes with zeros when it writes into one, which would+ /// count as written.+ static func sharedExtents() async throws {let fm = FileManager.defaultlet folder = fm.temporaryDirectory.appendingPathComponent("disk-usage-\(UUID().uuidString)", isDirectory: true)defer { try? fm.removeItem(at: folder) }- let machine = folder.appendingPathComponent("machine", isDirectory: true)- try fm.createDirectory(at: machine, withIntermediateDirectories: true)- let disk = machine.appendingPathComponent("Disk.img")- let block = Data((0 ..< (8 << 20)).map { UInt8(truncatingIfNeeded: $0 &* 31) })- try block.write(to: disk)- let alone = try require(VPhoneLaunchpadDiskUsage.privateSize(of: disk.path), "A private size on APFS")- precondition(alone >= 8 << 20, "A file shares nothing yet: \(alone)")-- let clone = folder.appendingPathComponent("clone.img")- precondition(clonefile(disk.path, clone.path, 0) == 0, "clonefile")- let shared = try require(VPhoneLaunchpadDiskUsage.privateSize(of: disk.path), "Private size after a clone")- precondition(shared < 1 << 20, "A cloned file shares its blocks: \(shared)")-- let handle = try FileHandle(forWritingTo: clone)- try handle.write(contentsOf: Data(repeating: 0x5A, count: 2 << 20))+ let library = folder.appendingPathComponent("library", isDirectory: true)+ let template = library.appendingPathComponent(".templates/0123456789ab", isDirectory: true)+ let first = library.appendingPathComponent("first", isDirectory: true)+ let second = library.appendingPathComponent("second", isDirectory: true)+ for directory in [template, first, second] {+ try fm.createDirectory(at: directory, withIntermediateDirectories: true)+ }+ try fm.createDirectory(at: library.appendingPathComponent(".templates/.building-0123456789ab-1"), withIntermediateDirectories: true)+ precondition(VPhoneLaunchpadDiskMeter.templateFolders(in: library.path) == [template.path],+ "Template folders: \(VPhoneLaunchpadDiskMeter.templateFolders(in: library.path))")++ let disk = template.appendingPathComponent("Disk.img")+ precondition(fm.createFile(atPath: disk.path, contents: nil), "Disk.img")+ try write(disk, at: 0, count: 8 << 20, byte: 0x11)+ try write(disk, at: 32 << 20, count: 8 << 20, byte: 0x22)+ try truncate(disk, to: 256 << 20)++ let mapped = try VPhoneLaunchpadDiskExtents.map(disk.path).get()+ let allocated = try allocatedBytes(disk)+ precondition(mapped.bytes == allocated && allocated >= 16 << 20 && allocated < 24 << 20,+ "Holes are not mapped: \(mapped.bytes) of \(allocated)")+ precondition(VPhoneLaunchpadDiskExtents.map(folder.path) == .failure(.unsupported), "A directory is not mapped")++ let meter = VPhoneLaunchpadDiskMeter()+ let alone = await meter.measure([.init(path: template.path)])+ precondition(alone[template.path] == VPhoneLaunchpadDiskUsage(allocated: allocated, exclusive: allocated),+ "A template alone: \(String(describing: alone[template.path]))")++ for machine in [first, second] {+ precondition(clonefile(disk.path, machine.appendingPathComponent("Disk.img").path, 0) == 0, "clonefile")+ }+ // The first clone rewrites 2 MiB of the template's data and writes+ // 4 MiB into a hole; the second rewrites the same 2 MiB.+ try write(first.appendingPathComponent("Disk.img"), at: 1 << 20, count: 2 << 20, byte: 0x33)+ try write(first.appendingPathComponent("Disk.img"), at: 128 << 20, count: 4 << 20, byte: 0x44)+ try write(second.appendingPathComponent("Disk.img"), at: 1 << 20, count: 2 << 20, byte: 0x55)+ let folders: [VPhoneLaunchpadDiskMeter.Folder] = [.init(path: template.path), .init(path: first.path), .init(path: second.path)]+ let usage = await meter.measure(folders)+ let templateUsage = try require(usage[template.path]?.exclusive, "Template measured")+ let firstUsage = try require(usage[first.path]?.exclusive, "First measured")+ let secondUsage = try require(usage[second.path]?.exclusive, "Second measured")+ // The template keeps the 2 MiB both clones rewrote to itself.+ precondition(templateUsage == 2 << 20, "Template: \(templateUsage)")+ precondition(firstUsage == 6 << 20, "First: \(firstUsage)")+ precondition(secondUsage == 2 << 20, "Second: \(secondUsage)")+ let firstAllocated = try allocatedBytes(first.appendingPathComponent("Disk.img"))+ precondition(usage[first.path]?.allocated == firstAllocated, "Allocated")++ // A folder that may not be opened keeps the extents last mapped; one+ // never mapped is unknown, and does not open its files.+ let third = library.appendingPathComponent("third", isDirectory: true)+ try fm.createDirectory(at: third, withIntermediateDirectories: true)+ precondition(clonefile(disk.path, third.appendingPathComponent("Disk.img").path, 0) == 0, "clonefile")+ try write(first.appendingPathComponent("Disk.img"), at: 192 << 20, count: 1 << 20, byte: 0x66)+ let busy = await meter.measure([.init(path: template.path), .init(path: first.path, mayOpen: false), .init(path: second.path), .init(path: third.path, mayOpen: false)])+ precondition(busy[first.path]?.exclusive == 6 << 20, "Last mapped: \(String(describing: busy[first.path]))")+ precondition(busy[third.path]?.exclusive == nil && (busy[third.path]?.allocated ?? 0) >= 16 << 20,+ "Never mapped: \(String(describing: busy[third.path]))")+ let open = await meter.measure([.init(path: template.path), .init(path: first.path), .init(path: second.path), .init(path: third.path)])+ precondition(open[first.path]?.exclusive == 7 << 20, "Mapped again once changed: \(String(describing: open[first.path]))")+ // The third clone shares everything it holds.+ precondition(open[third.path]?.exclusive == 0, "Third: \(String(describing: open[third.path]))")+ precondition(open[template.path]?.exclusive == 0, "Template with a clone that wrote nothing: \(String(describing: open[template.path]))")++ // Links are not followed.+ try fm.createSymbolicLink(at: second.appendingPathComponent("link.img"), withDestinationURL: disk)+ let linked = await meter.measure([.init(path: second.path)])+ precondition(linked[second.path]?.allocated == usage[second.path]?.allocated, "A link is not followed")+ }++ static func write(_ file: URL, at offset: UInt64, count: Int, byte: UInt8) throws {+ let handle = try FileHandle(forWritingTo: file)+ try handle.seek(toOffset: offset)+ try handle.write(contentsOf: Data(repeating: byte, count: count))try handle.synchronize()try handle.close()- let written = try require(VPhoneLaunchpadDiskUsage.privateSize(of: clone.path), "Private size of the written clone")- precondition(written >= 2 << 20 && written < 4 << 20, "Only rewritten blocks are its own: \(written)")-- // The folder's own walk: everything allocated, little of it exclusive.- let usage = VPhoneLaunchpadDiskUsage.measure(machine)- precondition(usage.allocated >= 8 << 20, "Allocated \(usage.allocated)")- precondition((usage.exclusive ?? .max) <= 3 << 20, "Exclusive \(String(describing: usage.exclusive))")- let link = machine.appendingPathComponent("link.img")- try fm.createSymbolicLink(at: link, withDestinationURL: clone)- precondition(VPhoneLaunchpadDiskUsage.measure(machine).allocated == usage.allocated, "A link is not followed")- print("Disk use tests passed")+ }++ static func truncate(_ file: URL, to size: UInt64) throws {+ let handle = try FileHandle(forWritingTo: file)+ try handle.truncate(atOffset: size)+ try handle.close()+ }++ static func allocatedBytes(_ file: URL) throws -> Int64 {+ var status = stat()+ precondition(lstat(file.path, &status) == 0, "lstat \(file.path)")+ return Int64(status.st_blocks) * 512}static func require<T>(_ value: T?, _ message: String) throws -> T {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstringsindex ffcf873d..09d2d17a 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings@@ -443,36 +443,36 @@}}},- "Allocated on disk; deleting it frees %@ now, the blocks no machine shares." : {+ "Allocated on disk; deleting it frees about %@, the blocks no machine shares, once no local Time Machine snapshot keeps them." : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Allocated on disk; deleting it frees %@ now, the blocks no machine shares."+ "value" : "Allocated on disk; deleting it frees about %@, the blocks no machine shares, once no local Time Machine snapshot keeps them."}},"ja" : {"stringUnit" : {"state" : "translated",- "value" : "ディスク上の割り当て量です。今削除すると、どのマシンとも共有していない %@ が解放されます。"+ "value" : "ディスク上の割り当て量です。削除すると、どのマシンとも共有していない約 %@ が解放されます。Time Machine のローカルスナップショットが保持している場合は、その期限が切れたときに解放されます。"}},"ko" : {"stringUnit" : {"state" : "translated",- "value" : "디스크에 할당된 크기입니다. 지금 삭제하면 어떤 머신과도 공유하지 않는 %@이(가) 확보됩니다."+ "value" : "디스크에 할당된 크기입니다. 삭제하면 어떤 머신과도 공유하지 않는 약 %@이(가) 확보됩니다. Time Machine 로컬 스냅샷이 보관 중이면 스냅샷이 만료될 때 확보됩니다."}},"vi" : {"stringUnit" : {"state" : "translated",- "value" : "Dung lượng đã cấp phát trên ổ đĩa; xóa ngay sẽ giải phóng %@, phần không máy ảo nào dùng chung."+ "value" : "Dung lượng đã cấp phát trên ổ đĩa; xóa sẽ giải phóng khoảng %@, phần không máy ảo nào dùng chung, sau khi không còn bản chụp nhanh cục bộ Time Machine nào giữ chúng."}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "磁盘上已分配的空间;现在删除可释放 %@,即没有虚拟机共享的数据块。"+ "value" : "磁盘上已分配的空间;删除约可释放 %@,即没有虚拟机共享的数据块;若 Time Machine 本地快照仍保留这些块,要等快照过期后才释放。"}}}@@ -1191,36 +1191,36 @@}}},- "Deleting it frees about %@ now; the blocks its machines share are freed once they change or are deleted." : {+ "Deleting it frees about %@, once no local Time Machine snapshot keeps those blocks; the blocks its machines share are freed once they change or are deleted." : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Deleting it frees about %@ now; the blocks its machines share are freed once they change or are deleted."+ "value" : "Deleting it frees about %@, once no local Time Machine snapshot keeps those blocks; the blocks its machines share are freed once they change or are deleted."}},"ja" : {"stringUnit" : {"state" : "translated",- "value" : "今削除すると約 %@ が解放されます。マシンと共有しているブロックは、それらが変更または削除されたときに解放されます。"+ "value" : "削除すると約 %@ が解放されます。Time Machine のローカルスナップショットが保持している場合は、その期限が切れたときに解放されます。マシンと共有しているブロックは、それらが変更または削除されたときに解放されます。"}},"ko" : {"stringUnit" : {"state" : "translated",- "value" : "지금 삭제하면 약 %@이(가) 확보됩니다. 머신과 공유하는 블록은 해당 머신이 변경되거나 삭제될 때 확보됩니다."+ "value" : "삭제하면 약 %@이(가) 확보됩니다. Time Machine 로컬 스냅샷이 보관 중이면 스냅샷이 만료될 때 확보됩니다. 머신과 공유하는 블록은 해당 머신이 변경되거나 삭제될 때 확보됩니다."}},"vi" : {"stringUnit" : {"state" : "translated",- "value" : "Xóa ngay sẽ giải phóng khoảng %@; các khối dùng chung với máy ảo được giải phóng khi chúng thay đổi hoặc bị xóa."+ "value" : "Xóa sẽ giải phóng khoảng %@, sau khi không còn bản chụp nhanh cục bộ Time Machine nào giữ các khối đó; các khối dùng chung với máy ảo được giải phóng khi chúng thay đổi hoặc bị xóa."}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "现在删除约可释放 %@;与虚拟机共享的数据块会在这些虚拟机改写或被删除后释放。"+ "value" : "删除约可释放 %@,若 Time Machine 本地快照仍保留这些块,要等快照过期后才释放;与虚拟机共享的数据块会在这些虚拟机改写或被删除后释放。"}}}@@ -3197,36 +3197,36 @@}}},- "The blocks only this machine holds: what deleting it frees. The rest is shared with its template or clones." : {+ "The blocks no other machine or template holds: what deleting it frees, once no local Time Machine snapshot keeps them. The rest is shared with its template or clones." : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "The blocks only this machine holds: what deleting it frees. The rest is shared with its template or clones."+ "value" : "The blocks no other machine or template holds: what deleting it frees, once no local Time Machine snapshot keeps them. The rest is shared with its template or clones."}},"ja" : {"stringUnit" : {"state" : "translated",- "value" : "このマシンだけが保持しているブロックで、削除すると解放される量です。残りはテンプレートまたは複製と共有しています。"+ "value" : "他のマシンやテンプレートが保持していないブロックで、削除すると解放される量です。Time Machine のローカルスナップショットが保持している場合は、その期限が切れたときに解放されます。残りはテンプレートまたは複製と共有しています。"}},"ko" : {"stringUnit" : {"state" : "translated",- "value" : "이 머신만 차지하는 블록으로, 삭제하면 확보되는 크기입니다. 나머지는 템플릿 또는 복제본과 공유합니다."+ "value" : "다른 머신이나 템플릿이 차지하지 않는 블록으로, 삭제하면 확보되는 크기입니다. Time Machine 로컬 스냅샷이 보관 중이면 스냅샷이 만료될 때 확보됩니다. 나머지는 템플릿 또는 복제본과 공유합니다."}},"vi" : {"stringUnit" : {"state" : "translated",- "value" : "Các khối chỉ riêng máy ảo này giữ: phần được giải phóng khi xóa. Phần còn lại dùng chung với mẫu hoặc các bản nhân bản."+ "value" : "Các khối không máy ảo hay mẫu nào khác giữ: phần được giải phóng khi xóa, sau khi không còn bản chụp nhanh cục bộ Time Machine nào giữ chúng. Phần còn lại dùng chung với mẫu hoặc các bản nhân bản."}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "仅此虚拟机占用的数据块,即删除后可释放的空间。其余部分与模板或克隆共享。"+ "value" : "没有其他虚拟机或模板占用的数据块,即删除后可释放的空间;若 Time Machine 本地快照仍保留这些块,要等快照过期后才释放。其余部分与模板或克隆共享。"}}}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskExtents.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskExtents.swiftnew file mode 100644index 00000000..0875edbb--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskExtents.swift@@ -0,0 +1,173 @@+import Darwin+import Foundation++// MARK: - Physical extents++/// Where a file's data lies on its device, as `fcntl(F_LOG2PHYS_EXT)`+/// reports it: sorted, disjoint, half-open byte ranges of device offsets.+///+/// Two files share a block exactly when their ranges overlap, which is how+/// APFS clones (a machine and its template, two clones of one template)+/// are told apart from blocks a file holds alone. Unlike APFS's private size+/// (`ATTR_CMNEXT_PRIVATESIZE`), a Time Machine local snapshot does not make+/// a file's blocks look shared: only the files compared count.+nonisolated struct VPhoneLaunchpadDiskExtents: Hashable, Sendable {+ struct Range: Hashable, Sendable {+ var start: Int64+ var end: Int64++ var length: Int64 {+ end - start+ }+ }++ /// The device the offsets are on. Ranges on different devices never+ /// overlap, whatever their numbers.+ var device: Int64+ private(set) var ranges: [Range]++ init(device: Int64, ranges: [Range]) {+ self.device = device+ self.ranges = Self.normalized(ranges)+ }++ var bytes: Int64 {+ ranges.reduce(0) { $0 + $1.length }+ }++ /// Sorted, with overlapping and touching ranges merged and empty ones+ /// dropped.+ static func normalized(_ ranges: [Range]) -> [Range] {+ var merged: [Range] = []+ merged.reserveCapacity(ranges.count)+ for range in ranges.sorted(by: { $0.start < $1.start }) where range.end > range.start {+ if let last = merged.last, range.start <= last.end {+ merged[merged.count - 1].end = max(last.end, range.end)+ } else {+ merged.append(range)+ }+ }+ return merged+ }++ /// For each owner, the bytes no other owner covers. An owner is a set of+ /// files (a machine folder): blocks shared among its own files count+ /// once and are still its own.+ static func exclusiveBytes(of owners: [[Self]]) -> [Int64] {+ var exclusive = [Int64](repeating: 0, count: owners.count)+ var byDevice: [Int64: [(owner: Int, ranges: [Range])]] = [:]+ for (owner, files) in owners.enumerated() {+ var perDevice: [Int64: [Range]] = [:]+ for file in files {+ perDevice[file.device, default: []] += file.ranges+ }+ for (device, ranges) in perDevice {+ byDevice[device, default: []].append((owner, normalized(ranges)))+ }+ }+ for owners in byDevice.values {+ // A sweep over every range's ends: a stretch covered by exactly+ // one owner is that owner's. Each owner's ranges are disjoint,+ // so it is counted at most once at any offset, and the sum of+ // the covering owners names the owner when only one covers it.+ var events: [(offset: Int64, owner: Int, delta: Int)] = []+ events.reserveCapacity(owners.reduce(0) { $0 + $1.ranges.count } * 2)+ for (owner, ranges) in owners {+ for range in ranges {+ events.append((range.start, owner, 1))+ events.append((range.end, owner, -1))+ }+ }+ events.sort { $0.offset < $1.offset }+ var covering = 0+ var ownerSum = 0+ var previous: Int64 = 0+ for event in events {+ if covering == 1 {+ exclusive[ownerSum] += event.offset - previous+ }+ covering += event.delta+ ownerSum += event.delta * event.owner+ previous = event.offset+ }+ }+ return exclusive+ }++ // MARK: Reading++ enum MapError: Error, Equatable {+ /// The file system does not map this file (not a regular file, a+ /// compressed file, a volume without block maps).+ case unsupported+ /// More ranges than `rangeLimit`, or past the deadline.+ case tooLarge+ }++ /// The file's data ranges. Holes are skipped with `SEEK_DATA`, so a+ /// sparse disk image costs its written extents, not its size.+ ///+ /// The descriptor is `O_EVTONLY` and held only while mapping, but it is+ /// an open descriptor: `lsof` lists this process for the file meanwhile.+ static func map(_ path: String, rangeLimit: Int = 4_000_000, deadline: ContinuousClock.Instant? = nil) -> Result<Self, MapError> {+ let descriptor = open(path, O_EVTONLY | O_NOFOLLOW | O_CLOEXEC)+ guard descriptor >= 0 else {+ return .failure(.unsupported)+ }+ defer { close(descriptor) }+ var status = stat()+ var volume = statfs()+ guard fstat(descriptor, &status) == 0, status.st_mode & S_IFMT == S_IFREG,+ fstatfs(descriptor, &volume) == 0+ else {+ return .failure(.unsupported)+ }+ // Whole file system blocks: the last one is allocated in full even+ // when the file ends inside it.+ let block = Int64(max(volume.f_bsize, 512))+ var ranges: [Range] = []+ var offset: off_t = 0+ while offset < status.st_size {+ let data = lseek(descriptor, offset, SEEK_DATA)+ if data < 0 {+ // ENXIO: no data past `offset`.+ if errno == ENXIO {+ break+ }+ return .failure(.unsupported)+ }+ var hole = lseek(descriptor, data, SEEK_HOLE)+ if hole < 0 {+ hole = status.st_size+ }+ var position = data+ while position < hole {+ var request = log2phys()+ request.l2p_devoffset = position+ request.l2p_contigbytes = hole - position+ guard fcntl(descriptor, F_LOG2PHYS_EXT, &request) == 0, request.l2p_contigbytes > 0 else {+ return .failure(.unsupported)+ }+ let run = min(request.l2p_contigbytes, hole - position)+ if request.l2p_devoffset >= 0 {+ let start = request.l2p_devoffset / block * block+ let end = (request.l2p_devoffset + run + block - 1) / block * block+ if let last = ranges.last, last.end == start {+ ranges[ranges.count - 1].end = end+ } else {+ ranges.append(Range(start: start, end: end))+ if ranges.count > rangeLimit {+ return .failure(.tooLarge)+ }+ }+ }+ position += run+ }+ if let deadline, ContinuousClock.now > deadline {+ return .failure(.tooLarge)+ }+ offset = hole+ }+ return .success(Self(device: Int64(status.st_dev), ranges: ranges))+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskUsage.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskUsage.swiftindex cb182d62..c683cdfd 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskUsage.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskUsage.swift@@ -1,75 +1,34 @@import Darwinimport Foundation-/// What a machine folder takes on disk.+/// What a machine or template folder takes on disk.////// `allocated` counts every block its files hold (`st_blocks`), shared or-/// not. `exclusive` counts the blocks no other file shares: APFS's private-/// size (`ATTR_CMNEXT_PRIVATESIZE`), what deleting the folder would free. A-/// machine cloned from a template shares every block it has not written with-/// the template and its other clones, so its exclusive size is a fraction of-/// what is allocated. A Time Machine local snapshot also counts as sharing.+/// not. `exclusive` counts the blocks no other measured folder holds: what+/// deleting the folder frees once nothing else keeps them. A machine cloned+/// from a template shares every block it has not written with the template+/// and its other clones, so its exclusive size is a fraction of what is+/// allocated.+///+/// It is measured by comparing physical extents (`VPhoneLaunchpadDiskExtents`),+/// not with APFS's private size (`ATTR_CMNEXT_PRIVATESIZE`): a Time Machine+/// local snapshot shares every block that existed when it was taken, so+/// after each hourly snapshot the private size of every machine is 0 until+/// it writes again. The blocks a snapshot holds are still freed when it+/// expires, and the comparison counts them as the folder's own.nonisolated struct VPhoneLaunchpadDiskUsage: Hashable, Sendable {var allocated: Int64- /// Nil when the volume does not report private sizes (not APFS).+ /// Nil when it could not be measured (the volume maps no extents, or the+ /// measurement ran out of time).var exclusive: Int64?- /// Walks `folder` without following links. Slow for a big folder of many- /// files; call it off the main actor.- static func measure(_ folder: URL) -> Self {- let keys: [URLResourceKey] = [.isRegularFileKey, .isSymbolicLinkKey, .totalFileAllocatedSizeKey]- var usage = Self(allocated: 0, exclusive: 0)- guard let walker = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: keys, options: []) else {- return Self(allocated: 0, exclusive: nil)- }- for case let file as URL in walker {- guard let values = try? file.resourceValues(forKeys: Set(keys)),- values.isSymbolicLink != true, values.isRegularFile == true- else {- continue- }- usage.allocated += Int64(values.totalFileAllocatedSize ?? 0)- if let exclusive = usage.exclusive {- usage.exclusive = privateSize(of: file.path).map { exclusive + $0 }- }- }- return usage- }-- /// The bytes of `path` no other file shares, or nil when the file system- /// does not say. A link is not followed.- static func privateSize(of path: String) -> Int64? {- var request = attrlist()- request.bitmapcount = u_short(ATTR_BIT_MAP_COUNT)- request.commonattr = attrgroup_t(ATTR_CMN_RETURNED_ATTRS)- // Extended common attributes are asked for in the fork field.- request.forkattr = attrgroup_t(ATTR_CMNEXT_PRIVATESIZE)- // u_int32_t length, attribute_set_t returned, off_t private size.- var buffer = [UInt8](repeating: 0, count: 64)- let options = UInt32(FSOPT_ATTR_CMN_EXTENDED) | UInt32(FSOPT_NOFOLLOW)- let status = buffer.withUnsafeMutableBytes { bytes in- getattrlist(path, &request, bytes.baseAddress, bytes.count, options)- }- guard status == 0 else {- return nil- }- return buffer.withUnsafeBytes { bytes -> Int64? in- let returned = bytes.loadUnaligned(fromByteOffset: 4, as: attribute_set_t.self)- guard returned.forkattr & attrgroup_t(ATTR_CMNEXT_PRIVATESIZE) != 0 else {- return nil- }- let offset = 4 + MemoryLayout<attribute_set_t>.size- return Int64(bytes.loadUnaligned(fromByteOffset: offset, as: off_t.self))- }- }-/// `17.58 GB`, decimal as the Finder counts.static func format(_ bytes: Int64, locale: Locale = .current) -> String {bytes.formatted(.byteCount(style: .file).locale(locale))}/// The inspector's value: `0.61 GB of 17.58 GB`, or the allocated size- /// alone when the volume gives no private size.+ /// alone when the exclusive size is unknown.func summary(locale: Locale = .current) -> String {guard let exclusive else {return Self.format(allocated, locale: locale)@@ -77,3 +36,154 @@ nonisolated struct VPhoneLaunchpadDiskUsage: Hashable, Sendable {return String(localized: "\(Self.format(exclusive, locale: locale)) of \(Self.format(allocated, locale: locale))")}}++// MARK: - Measuring++/// Measures machine and template folders against each other, keeping each+/// file's extents between passes.+///+/// A file is mapped again only when its size, modification or change time+/// is different, so a stopped machine's 20 GB image is opened once after it+/// changes, not on every pass. Mapping opens the file: `lsof` then lists+/// Launchpad for it, which `vm stop` and `cfw install` read as the machine+/// running. Folders Launchpad is working on are therefore never opened+/// (`Folder.mayOpen`), and Launchpad leaves its own process out when it asks+/// `lsof` which machines run.+actor VPhoneLaunchpadDiskMeter {+ nonisolated struct Folder: Hashable, Sendable {+ var path: String+ /// False while something works on the folder: its files' last+ /// extents are used, and a file never mapped leaves it unknown.+ var mayOpen = true+ }++ private nonisolated struct FileKey: Hashable {+ var device: Int64+ var inode: UInt64+ var size: Int64+ var modified: Int+ var modifiedNanoseconds: Int+ var changed: Int+ var changedNanoseconds: Int+ }++ private nonisolated struct Mapped {+ var key: FileKey+ /// Nil for a file the volume does not map (a compressed file): its+ /// allocated size counts as its folder's own.+ var extents: VPhoneLaunchpadDiskExtents?+ }++ private var cache: [String: Mapped] = [:]+ private let budget: Duration++ /// `budget` bounds the mapping of one pass. Files left over are mapped+ /// on a later pass, and their folders are unknown meanwhile.+ init(budget: Duration = .seconds(15)) {+ self.budget = budget+ }++ /// Each folder's usage, by `Folder.path`. Files are not followed through+ /// links.+ func measure(_ folders: [Folder]) -> [String: VPhoneLaunchpadDiskUsage] {+ let deadline = ContinuousClock.now + budget+ var seen: Set<String> = []+ var owners: [[VPhoneLaunchpadDiskExtents]] = []+ var usages: [VPhoneLaunchpadDiskUsage] = []+ var unmappedBytes: [Int64] = []+ for folder in folders {+ var usage = VPhoneLaunchpadDiskUsage(allocated: 0, exclusive: 0)+ var extents: [VPhoneLaunchpadDiskExtents] = []+ var unmapped: Int64 = 0+ for file in Self.files(in: folder.path) {+ var status = stat()+ guard lstat(file, &status) == 0, status.st_mode & S_IFMT == S_IFREG else {+ continue+ }+ seen.insert(file)+ let allocated = Int64(status.st_blocks) * 512+ usage.allocated += allocated+ guard allocated > 0 else {+ continue+ }+ let key = FileKey(+ device: Int64(status.st_dev), inode: status.st_ino, size: status.st_size,+ modified: status.st_mtimespec.tv_sec, modifiedNanoseconds: status.st_mtimespec.tv_nsec,+ changed: status.st_ctimespec.tv_sec, changedNanoseconds: status.st_ctimespec.tv_nsec,+ )+ var mapped = cache[file].flatMap { $0.key == key ? $0 : nil }+ if mapped == nil, folder.mayOpen, ContinuousClock.now < deadline {+ switch VPhoneLaunchpadDiskExtents.map(file, deadline: deadline) {+ case let .success(result):+ mapped = Mapped(key: key, extents: result)+ case .failure(.unsupported):+ mapped = Mapped(key: key, extents: nil)+ case .failure(.tooLarge):+ break+ }+ if let mapped {+ cache[file] = mapped+ }+ }+ // A folder that may not be opened keeps what was last+ // mapped, which is close: its blocks rarely move.+ guard let found = mapped ?? (folder.mayOpen ? nil : cache[file]) else {+ usage.exclusive = nil+ continue+ }+ if let result = found.extents {+ extents.append(result)+ } else {+ unmapped += allocated+ }+ }+ owners.append(extents)+ usages.append(usage)+ unmappedBytes.append(unmapped)+ }+ cache = cache.filter { seen.contains($0.key) }+ let exclusive = VPhoneLaunchpadDiskExtents.exclusiveBytes(of: owners)+ var result: [String: VPhoneLaunchpadDiskUsage] = [:]+ for (index, folder) in folders.enumerated() {+ var usage = usages[index]+ // Rounding to whole blocks can only add to what st_blocks says.+ usage.exclusive = usage.exclusive.map { _ in min(usage.allocated, exclusive[index] + unmappedBytes[index]) }+ result[folder.path] = usage+ }+ return result+ }++ /// Every entry under `path`, not through links. The walk does not+ /// descend into a linked directory, and `lstat` rejects a linked file.+ private nonisolated static func files(in path: String) -> [String] {+ let root = URL(fileURLWithPath: path, isDirectory: true)+ guard let walker = FileManager.default.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey], options: []) else {+ return []+ }+ var files: [String] = []+ for case let file as URL in walker {+ if (try? file.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true {+ files.append(file.path)+ }+ }+ return files+ }++ /// The template folders of a library: `.templates/<12 hex>`. Builds+ /// (`.building-…`) are left out; they are written while they exist.+ nonisolated static func templateFolders(in libraryRoot: String) -> [String] {+ let templates = URL(fileURLWithPath: libraryRoot, isDirectory: true).appendingPathComponent(".templates", isDirectory: true)+ let names = (try? FileManager.default.contentsOfDirectory(atPath: templates.path)) ?? []+ return names.sorted().compactMap { name in+ guard name.wholeMatch(of: /[0-9a-f]{12}/) != nil else {+ return nil+ }+ let folder = templates.appendingPathComponent(name, isDirectory: true)+ var status = stat()+ guard lstat(folder.path, &status) == 0, status.st_mode & S_IFMT == S_IFDIR else {+ return nil+ }+ return folder.path+ }+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swiftindex 083ca3ee..95aed9dd 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift@@ -138,7 +138,7 @@ struct VPhoneLaunchpadMachineInspector: View {if let exclusive = usage.exclusive {LabeledContent("Exclusive") {Text(VPhoneLaunchpadDiskUsage.format(exclusive))- .help(String(localized: "The blocks only this machine holds: what deleting it frees. The rest is shared with its template or clones."))+ .help(String(localized: "The blocks no other machine or template holds: what deleting it frees, once no local Time Machine snapshot keeps them. The rest is shared with its template or clones."))}}LabeledContent("Allocated") {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swiftindex 951017fe..6304698e 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift@@ -243,7 +243,7 @@ final class VPhoneLaunchpadMachineLibrary {}let process = Process()process.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")- process.arguments = ["-F", "n", "--"] + diskOwners.keys.sorted()+ process.arguments = ["-F", "pn", "--"] + diskOwners.keys.sorted()let pipe = Pipe()process.standardOutput = pipeprocess.standardError = FileHandle.nullDevice@@ -252,9 +252,19 @@ final class VPhoneLaunchpadMachineLibrary {}let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)process.waitUntilExit()+ return runningMachines(lsofOutput: output, diskOwners: diskOwners, excluding: getpid())+ }++ /// The machines whose disks `lsof -F pn` lists a process for. Launchpad+ /// itself (`excluding`) holds a disk only while measuring its extents,+ /// which does not make the machine run.+ nonisolated static func runningMachines(lsofOutput output: String, diskOwners: [String: Path], excluding ownProcess: pid_t) -> Set<Path> {var running: Set<Path> = []- for line in output.split(separator: "\n") where line.hasPrefix("n") {- if let machine = diskOwners[String(line.dropFirst())] {+ var process: pid_t?+ for line in output.split(separator: "\n") {+ if line.hasPrefix("p") {+ process = pid_t(line.dropFirst())+ } else if line.hasPrefix("n"), process != ownProcess, let machine = diskOwners[String(line.dropFirst())] {running.insert(machine)}}@@ -735,37 +745,77 @@ final class VPhoneLaunchpadMachineLibrary {private(set) var templateSources: [Path: String] = [:]private var diskUsageMeasured: Date?private var isMeasuringDiskUsage = false+ /// A forced measurement asked for while one ran.+ private var isDiskUsageRequested = false+ private let diskMeter = VPhoneLaunchpadDiskMeter()private static let diskUsageInterval: TimeInterval = 30/// Measures again when the last measurement is old, or a machine was- /// added. Private sizes take APFS a walk of each file's extents, so this- /// never runs on every five-second refresh.+ /// added. Every machine and template of every library is measured in one+ /// pass, because a folder's exclusive size depends on all the others.+ /// Only files that changed are mapped again, and never on every+ /// five-second refresh.private func refreshDiskUsage(force: Bool = false) {let paths = machines.map(\.path)let isNew = paths.contains { diskUsage[$0] == nil }let isOld = diskUsageMeasured.map { Date().timeIntervalSince($0) > Self.diskUsageInterval } ?? true- guard !isMeasuringDiskUsage, force || isNew || isOld else {+ guard !isMeasuringDiskUsage else {+ isDiskUsageRequested = isDiskUsageRequested || force+ return+ }+ guard force || isNew || isOld else {return}isMeasuringDiskUsage = true+ // A machine being created, exported or installed into is not opened:+ // `lsof` would show Launchpad holding its disk to `cfw install`.+ let machineFolders = machines.map { machine in+ let isBusy = if case .busy = state(of: machine.path) { true } else { false }+ return VPhoneLaunchpadDiskMeter.Folder(path: machine.path.url.path, mayOpen: !isBusy)+ }+ let libraryRoots = roots.filter { $0 == libraryRoot || VPhoneLaunchpadMachineLocations.isAvailable($0) }+ let meter = diskMeterTask {- let measured = await Self.measure(paths)+ let measured = await Self.measure(machineFolders, paths: paths, libraryRoots: libraryRoots, meter: meter)diskUsage = measured.usagetemplateSources = measured.sources+ templateUsage = measured.templatesdiskUsageMeasured = Date()isMeasuringDiskUsage = false+ if isDiskUsageRequested {+ isDiskUsageRequested = false+ refreshDiskUsage(force: true)+ }}}@concurrent- private nonisolated static func measure(_ paths: [Path]) async -> (usage: [Path: VPhoneLaunchpadDiskUsage], sources: [Path: String]) {+ private nonisolated static func measure(+ _ machineFolders: [VPhoneLaunchpadDiskMeter.Folder],+ paths: [Path],+ libraryRoots: [String],+ meter: VPhoneLaunchpadDiskMeter,+ ) async -> (usage: [Path: VPhoneLaunchpadDiskUsage], sources: [Path: String], templates: [String: VPhoneLaunchpadDiskUsage]) {+ // Templates are keyed as `usage(of:)` looks them up.+ var templateKeys: [String: String] = [:]+ for root in libraryRoots {+ for folder in VPhoneLaunchpadDiskMeter.templateFolders(in: root) {+ templateKeys[folder] = URL(fileURLWithPath: folder).lastPathComponent + "@" + root+ }+ }+ let folders = machineFolders + templateKeys.keys.sorted().map { VPhoneLaunchpadDiskMeter.Folder(path: $0) }+ let measured = await meter.measure(folders)var usage: [Path: VPhoneLaunchpadDiskUsage] = [:]var sources: [Path: String] = [:]for path in paths {- usage[path] = VPhoneLaunchpadDiskUsage.measure(path.url)+ usage[path] = measured[path.url.path]sources[path] = templateSource(in: path.url)}- return (usage, sources)+ var templates: [String: VPhoneLaunchpadDiskUsage] = [:]+ for (folder, key) in templateKeys {+ templates[key] = measured[folder]+ }+ return (usage, sources, templates)}/// The `Identifier` of `TemplateSource.plist`, when it names a template.@@ -790,7 +840,8 @@ final class VPhoneLaunchpadMachineLibrary {/// Template builds a create left behind (or is running), by library.private(set) var templateBuilds: [(libraryRoot: String, build: VPhoneLaunchpadTemplateList.Building)] = []private(set) var templatesError: String?- /// Each template's private size, read off the main actor.+ /// Each template's disk use, by `<identifier>@<library root>`, measured+ /// with the machines.private(set) var templateUsage: [String: VPhoneLaunchpadDiskUsage] = [:]func refreshTemplates() async {@@ -818,10 +869,7 @@ final class VPhoneLaunchpadMachineLibrary {templates = found.sorted { $0.created > $1.created }templateBuilds = buildstemplatesError = errors.first- let urls = found.map { ($0.id + "@" + $0.libraryRoot, $0.url) }- templateUsage = await Task.detached {- Dictionary(uniqueKeysWithValues: urls.map { ($0.0, VPhoneLaunchpadDiskUsage.measure($0.1)) })- }.value+ refreshDiskUsage(force: true)}func usage(of template: VPhoneLaunchpadTemplate) -> VPhoneLaunchpadDiskUsage? {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplatesView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplatesView.swiftindex 889aae0f..0a2d130d 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplatesView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplatesView.swift@@ -230,7 +230,7 @@ struct VPhoneLaunchpadTemplatesView: View {guard let exclusive = library.usage(of: template)?.exclusive else {return String(localized: "Allocated on disk.")}- return String(localized: "Allocated on disk; deleting it frees \(VPhoneLaunchpadDiskUsage.format(exclusive)) now, the blocks no machine shares.")+ return String(localized: "Allocated on disk; deleting it frees about \(VPhoneLaunchpadDiskUsage.format(exclusive)), the blocks no machine shares, once no local Time Machine snapshot keeps them.")}private func deletionMessage(_ template: VPhoneLaunchpadTemplate) -> String {@@ -241,7 +241,7 @@ struct VPhoneLaunchpadTemplatesView: View {parts.append(String(localized: "\(template.machines.joined(separator: ", ")) keep working: they share its blocks but do not need it."))}if let exclusive = library.usage(of: template)?.exclusive {- parts.append(String(localized: "Deleting it frees about \(VPhoneLaunchpadDiskUsage.format(exclusive)) now; the blocks its machines share are freed once they change or are deleted."))+ parts.append(String(localized: "Deleting it frees about \(VPhoneLaunchpadDiskUsage.format(exclusive)), once no local Time Machine snapshot keeps those blocks; the blocks its machines share are freed once they change or are deleted."))}parts.append(String(localized: "The next machine with its options builds a new template, which takes a restore."))return parts.joined(separator: " ")