Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Let New Machine choose where a machine is stored

dazi20112b8ac4c67d32
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
index 3f49c025..7ad7a2a3 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
@@ -42,13 +42,10 @@ final class VPhoneLaunchpadModel {
private static let showAllSectionsKey = "VPhoneLaunchpadShowAllSections"
init() {
- let environment = ProcessInfo.processInfo.environment["VPHONE_LIBRARY_ROOT"]
- libraryRoot = environment.map { URL(fileURLWithPath: $0, isDirectory: true) }
- ?? FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent(".vphone/machines", isDirectory: true)
+ libraryRoot = URL(fileURLWithPath: VPhoneLaunchpadMachineLocations.defaultRoot, isDirectory: true)
host = VPhoneLaunchpadHostSetup(helper: helper, libraryRoot: libraryRoot)
bundles = VPhoneLaunchpadCoreBundle(helper: helper, history: history)
- machines = VPhoneLaunchpadMachineLibrary(libraryRoot: libraryRoot, bundles: bundles, helper: helper)
+ machines = VPhoneLaunchpadMachineLibrary(bundles: bundles, helper: helper)
}
// MARK: - Sections
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
index 365b1629..ac820b89 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
@@ -26,7 +26,6 @@
let creation = VPhoneLaunchpadCreationPipeline(
options: creationOptions,
- libraryRoot: model.libraryRoot,
bundles: model.bundles,
helper: model.helper,
library: model.machines,
@@ -68,7 +67,7 @@
model.selection = .hostSetup
await shot("04-host-setup-passed", suffix)
- model.machines.selection = "research-01"
+ model.machines.selection = path("research-01")
model.selection = .machines
await shot("05-machines", suffix)
if let machine = model.machines.selected {
@@ -78,24 +77,24 @@
}
}
- model.machines.selection = "ios27-rc"
+ model.machines.selection = path("ios27-rc")
await shot("06-machines-creating", suffix)
await sheet(.newMachine, "07-new-machine", suffix)
- await sheet(.creation("ios27-rc"), "08-creation-progress", suffix)
+ await sheet(.creation(path("ios27-rc")), "08-creation-progress", suffix)
creation.applyPreview(failed: true)
- await sheet(.creation("ios27-rc"), "08b-creation-failed", suffix)
+ await sheet(.creation(path("ios27-rc")), "08b-creation-failed", suffix)
creation.applyPreview()
await standalone("08c-creation-log", suffix, size: NSSize(width: 960, height: 700)) {
VPhoneLaunchpadConsoleView(title: "ios27-rc Creation Log", url: creation.logFile)
}
- model.machines.selection = "frida-lab"
+ model.machines.selection = labMachine
if let machine = model.machines.selected {
await sheet(.settings(machine), "09-machine-settings", suffix)
}
- await sheet(.clone("frida-lab"), "10-clone", suffix)
- await sheet(.export("frida-lab"), "11-export", suffix)
- await sheet(.console("research-01"), "12-console", suffix)
+ await sheet(.clone(labMachine), "10-clone", suffix)
+ await sheet(.export(labMachine), "11-export", suffix)
+ await sheet(.console(path("research-01")), "12-console", suffix)
}
NSApp.terminate(nil)
}
@@ -191,9 +190,23 @@
"udid":"00008140-0011223344556677"}
]
"""
- return (try? JSONDecoder().decode([VPhoneLaunchpadMachine].self, from: Data(json.utf8))) ?? []
+ var machines = (try? JSONDecoder().decode([VPhoneLaunchpadMachine].self, from: Data(json.utf8))) ?? []
+ for index in machines.indices {
+ machines[index].libraryRoot = machines[index].name == labMachine.name
+ ? labMachine.libraryRoot
+ : VPhoneLaunchpadMachineLocations.defaultRoot
+ }
+ return machines
}()
+ /// A machine in the default library.
+ static func path(_ name: String) -> VPhoneLaunchpadMachinePath {
+ VPhoneLaunchpadMachinePath(libraryRoot: VPhoneLaunchpadMachineLocations.defaultRoot, name: name)
+ }
+
+ /// A machine in a second library, on an external volume.
+ static let labMachine = VPhoneLaunchpadMachinePath(libraryRoot: "/Volumes/Lab/machines", name: "frida-lab")
+
static let catalog: VPhoneLaunchpadFirmwareCatalog? = {
let base = "https://updates.cdn-apple.com/example"
let json = """
@@ -209,6 +222,7 @@
static let creationOptions = VPhoneLaunchpadCreationPipeline.Options(
name: "ios27-rc",
+ libraryRoot: VPhoneLaunchpadMachineLocations.defaultRoot,
iphoneSource: "https://updates.cdn-apple.com/example/iPhone17,3_27.0_24A435_Restore.ipsw",
cloudOSSource: "https://updates.cdn-apple.com/example/cloudos-26.4",
cpuCount: 8,
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index 5920d73b..e691f8a8 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -205,6 +205,108 @@
}
}
},
+ "%@ is a machine. Choose the folder that contains it." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ is a machine. Choose the folder that contains it."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ はマシンです。それを含むフォルダを選択してください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@은(는) 머신입니다. 이 머신이 들어 있는 폴더를 선택하십시오."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ là một máy ảo. Hãy chọn thư mục chứa nó."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 是一台虚拟机。请选择包含它的文件夹。"
+ }
+ }
+ }
+ },
+ "%@ is not on an APFS volume." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ is not on an APFS volume."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ は APFS ボリューム上にありません。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@은(는) APFS 볼륨에 있지 않습니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ không nằm trên ổ đĩa APFS."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 不在 APFS 宗卷上。"
+ }
+ }
+ }
+ },
+ "%@ is not owned by your user account." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ is not owned by your user account."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ の所有者があなたのユーザアカウントではありません。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@의 소유자가 사용자 계정이 아닙니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ không thuộc sở hữu của tài khoản người dùng của bạn."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 的所有者不是你的用户账户。"
+ }
+ }
+ }
+ },
"%@ is on %@" : {
"localizations" : {
"en" : {
@@ -239,6 +341,40 @@
}
}
},
+ "%@ is on a volume that ignores ownership. Select the volume in the Finder, choose File > Get Info, and turn off “Ignore ownership on this volume”." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ is on a volume that ignores ownership. Select the volume in the Finder, choose File > Get Info, and turn off “Ignore ownership on this volume”."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ は所有権を無視するボリューム上にあります。Finder でボリュームを選択し、「ファイル」>「情報を見る」を選択して、「このボリューム上の所有権を無視」をオフにしてください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@은(는) 소유권을 무시하는 볼륨에 있습니다. Finder에서 볼륨을 선택하고 파일 > 정보 가져오기를 선택한 다음 ‘이 볼륨의 소유권 무시’를 끄십시오."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ nằm trên ổ đĩa bỏ qua quyền sở hữu. Hãy chọn ổ đĩa trong Finder, chọn Tệp > Lấy thông tin, rồi tắt “Bỏ qua quyền sở hữu trên ổ đĩa này”."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 所在的宗卷忽略了所有权。请在访达中选中该宗卷,选取“文件”>“显示简介”,然后取消勾选“忽略此宗卷上的所有权”。"
+ }
+ }
+ }
+ },
"%@ is too old" : {
"localizations" : {
"en" : {
@@ -591,6 +727,40 @@
}
}
},
+ "A folder with this name already exists in this location." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "A folder with this name already exists in this location."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "この場所には同じ名前のフォルダが既に存在します。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "이 위치에 같은 이름의 폴더가 이미 있습니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Vị trí này đã có một thư mục trùng tên."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "此位置已存在同名文件夹。"
+ }
+ }
+ }
+ },
"A machine with this name already exists." : {
"localizations" : {
"en" : {
@@ -1373,6 +1543,40 @@
}
}
},
+ "Choose" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Choose"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "選択"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "선택"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Chọn"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "选取"
+ }
+ }
+ }
+ },
"Choose a .tzst or .txz archive made by Export." : {
"localizations" : {
"en" : {
@@ -1407,6 +1611,40 @@
}
}
},
+ "Choose a Location" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Choose a Location"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "場所を選択"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "위치 선택"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Chọn vị trí"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "选取位置"
+ }
+ }
+ }
+ },
"Choose Location…" : {
"localizations" : {
"en" : {
@@ -5839,6 +6077,40 @@
}
}
},
+ "Other…" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Other…"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "その他…"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "기타…"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Khác…"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "其他…"
+ }
+ }
+ }
+ },
"Owner" : {
"localizations" : {
"en" : {
@@ -8695,6 +8967,40 @@
}
}
},
+ "The machine is created in a folder with its name inside the folder you choose." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "The machine is created in a folder with its name inside the folder you choose."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "マシンは、選択したフォルダの中にマシン名のフォルダとして作成されます。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "머신은 선택한 폴더 안에 머신 이름으로 된 폴더로 생성됩니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Máy ảo được tạo trong một thư mục mang tên của nó, bên trong thư mục bạn chọn."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "虚拟机会创建在你所选文件夹中以其名称命名的子文件夹里。"
+ }
+ }
+ }
+ },
"The machine stopped before first boot finished." : {
"localizations" : {
"en" : {
@@ -8797,6 +9103,40 @@
}
}
},
+ "The path is too long. Use a shorter name, or a location with a shorter path." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "The path is too long. Use a shorter name, or a location with a shorter path."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "パスが長すぎます。短い名前にするか、パスの短い場所を選択してください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "경로가 너무 깁니다. 더 짧은 이름을 사용하거나 경로가 더 짧은 위치를 선택하십시오."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Đường dẫn quá dài. Hãy dùng tên ngắn hơn hoặc chọn vị trí có đường dẫn ngắn hơn."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "路径太长。请使用更短的名称,或选择路径更短的位置。"
+ }
+ }
+ }
+ },
"The VM exited before vphoned answered." : {
"localizations" : {
"en" : {
@@ -10089,6 +10429,40 @@
}
}
},
+ "You cannot write to %@." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "You cannot write to %@."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ に書き込めません。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@에 쓸 수 없습니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bạn không thể ghi vào %@."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你无法写入 %@。"
+ }
+ }
+ }
+ },
"Zero the dyld cache maxSlide" : {
"localizations" : {
"en" : {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
index 5263ec39..8de6853e 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
@@ -16,6 +16,8 @@ import Observation
final class VPhoneLaunchpadCreationPipeline {
struct Options: Sendable {
var name: String
+ /// The canonical library the machine is created in.
+ var libraryRoot: String
var iphoneSource: String
var cloudOSSource: String
var cpuCount: Int
@@ -25,6 +27,10 @@ final class VPhoneLaunchpadCreationPipeline {
var enableFrida: Bool
var forceDyldSharedCacheMaxSlide: Bool
var keepArtifacts: Bool
+
+ var machine: VPhoneLaunchpadMachinePath {
+ VPhoneLaunchpadMachinePath(libraryRoot: libraryRoot, name: name)
+ }
}
enum Step: Int, CaseIterable, Identifiable, Comparable {
@@ -75,7 +81,6 @@ final class VPhoneLaunchpadCreationPipeline {
private(set) var failure: VPhoneLaunchpadError?
private(set) var isRunning = false
- private let libraryRoot: URL
private let bundles: VPhoneLaunchpadCoreBundle
private let helper: VPhoneLaunchpadHelperClient
private weak var library: VPhoneLaunchpadMachineLibrary?
@@ -87,23 +92,25 @@ final class VPhoneLaunchpadCreationPipeline {
init(
options: Options,
- libraryRoot: URL,
bundles: VPhoneLaunchpadCoreBundle,
helper: VPhoneLaunchpadHelperClient,
library: VPhoneLaunchpadMachineLibrary,
) {
self.options = options
- self.libraryRoot = libraryRoot
self.bundles = bundles
self.helper = helper
self.library = library
- log = VPhoneLaunchpadLogWriter(url: VPhoneLaunchpadMachineLibrary.consoleLog(options.name, suffix: "-create"))
+ log = VPhoneLaunchpadLogWriter(url: VPhoneLaunchpadMachineLibrary.consoleLog(options.machine, suffix: "-create"))
}
var logFile: URL {
log.url
}
+ var machine: VPhoneLaunchpadMachinePath {
+ options.machine
+ }
+
var isFinished: Bool {
statuses[.firstBoot] == .passed
}
@@ -195,8 +202,8 @@ final class VPhoneLaunchpadCreationPipeline {
throw VPhoneLaunchpadError(String(localized: "No Core Bundle version is in use. Choose a version in Core Bundle."))
}
let name = options.name
- let library = ["--library-root", libraryRoot.path]
- let machine = libraryRoot.appendingPathComponent(name, isDirectory: true)
+ let library = machine.libraryArguments
+ let bundle = machine.url
let log = log
let output: @Sendable (String) -> Void = { line in log.write(line) }
@@ -227,14 +234,14 @@ final class VPhoneLaunchpadCreationPipeline {
dfuPanicked = false
dfu = try commandLine.start(
arguments,
- logFile: VPhoneLaunchpadMachineLibrary.consoleLog(name, suffix: "-dfu"),
+ logFile: VPhoneLaunchpadMachineLibrary.consoleLog(machine, suffix: "-dfu"),
) { [weak self] line in
log.write("dfu \(line)")
if Self.isPanic(line) {
Task { @MainActor in self?.dfuPanicked = true }
}
}
- let identity = machine.appendingPathComponent("udid-prediction.txt")
+ let identity = bundle.appendingPathComponent("udid-prediction.txt")
for _ in 0 ..< 30 {
if FileManager.default.fileExists(atPath: identity.path) {
return
@@ -245,7 +252,7 @@ final class VPhoneLaunchpadCreationPipeline {
throw VPhoneLaunchpadError(String(localized: "The machine did not enter DFU mode within 30 seconds."))
case .waitDFU:
- let ecid = try Self.ecid(in: machine)
+ let ecid = try Self.ecid(in: bundle)
append("$ vphone-cli recovery-probe --ecid \(ecid) --timeout 2 (up to 90 attempts)")
for attempt in 1 ... 90 {
try Task.checkCancellation()
@@ -287,7 +294,7 @@ final class VPhoneLaunchpadCreationPipeline {
let status = try await helper.installCustomFirmware(
bundleVersion: version,
machineName: name,
- libraryRoot: Self.canonicalPath(libraryRoot),
+ libraryRoot: Self.canonicalPath(URL(fileURLWithPath: options.libraryRoot, isDirectory: true)),
forceDyldSharedCacheMaxSlide: options.forceDyldSharedCacheMaxSlide,
keepArtifacts: options.keepArtifacts,
onLine: output,
@@ -297,26 +304,27 @@ final class VPhoneLaunchpadCreationPipeline {
}
case .firstBoot:
- try await firstBoot(name: name, machine: machine)
+ try await firstBoot()
}
}
/// Boots with a window, as `vm create` does, and waits for vphoned to
/// answer on the VM's automation socket. The machine keeps running.
- private func firstBoot(name: String, machine: URL) async throws {
+ private func firstBoot() async throws {
guard let library else {
return
}
+ let name = options.name
append("$ vphone-cli vm launch \(name)")
- library.start(name)
- guard let child = library.launchedProcess(name) else {
+ library.start(machine)
+ guard let child = library.launchedProcess(machine) else {
throw VPhoneLaunchpadError(String(localized: "\(name) could not be started."))
}
- let socket = machine.appendingPathComponent("vphone.sock").path
+ let socket = machine.url.appendingPathComponent("vphone.sock").path
append("waiting up to 300s for vphoned")
for _ in 0 ..< 300 {
try Task.checkCancellation()
- if library.panicked.contains(name) {
+ if library.panicked.contains(machine) {
throw VPhoneLaunchpadError(String(localized: "The machine had a kernel panic during first boot."), detail: String(localized: "See the machine's console."))
}
guard child.isRunning else {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
index c7bf47b0..a5c479c8 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
@@ -1,5 +1,23 @@
import Foundation
+// MARK: - Machine path
+
+/// A machine's library root and name. Machines in two libraries may share a
+/// name, so the pair, not the name, identifies a machine.
+nonisolated struct VPhoneLaunchpadMachinePath: Hashable, Sendable {
+ /// A canonical root, as `VPhoneLaunchpadMachineLocations.canonical` makes it.
+ let libraryRoot: String
+ let name: String
+
+ var url: URL {
+ URL(fileURLWithPath: libraryRoot, isDirectory: true).appendingPathComponent(name, isDirectory: true)
+ }
+
+ var libraryArguments: [String] {
+ ["--library-root", libraryRoot]
+ }
+}
+
// MARK: - vm list / vm info
/// Mirrors `VPhoneBundleReport`, the JSON `vphone-cli vm list --json` and
@@ -30,9 +48,19 @@ nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Se
let network: Network
let restoreInfo: RestoreInfo?
let udid: String?
+ /// The library `vm list` was run on. Not part of the JSON.
+ var libraryRoot = ""
+
+ private enum CodingKeys: String, CodingKey {
+ case name, cpuCount, memoryMB, diskSizeBytes, network, restoreInfo, udid
+ }
+
+ var path: VPhoneLaunchpadMachinePath {
+ VPhoneLaunchpadMachinePath(libraryRoot: libraryRoot, name: name)
+ }
- var id: String {
- name
+ var id: VPhoneLaunchpadMachinePath {
+ path
}
var networkDescription: String {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
index 9532a7cf..08fc3c3d 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
@@ -28,8 +28,8 @@ struct VPhoneLaunchpadMachineStateLabel: View {
/// middle.
struct VPhoneLaunchpadMachineInspector: View {
let machine: VPhoneLaunchpadMachine
- let onShowProgress: (String) -> Void
- let onOpenConsole: (String) -> Void
+ let onShowProgress: (VPhoneLaunchpadMachinePath) -> Void
+ let onOpenConsole: (VPhoneLaunchpadMachinePath) -> Void
@Environment(VPhoneLaunchpadModel.self) private var model
private var library: VPhoneLaunchpadMachineLibrary {
@@ -39,13 +39,13 @@ struct VPhoneLaunchpadMachineInspector: View {
var body: some View {
Form {
Section {
- if let creation = library.creations[machine.name] {
+ if let creation = library.creations[machine.path] {
creationSummary(creation)
}
LabeledContent("State") {
- VPhoneLaunchpadMachineStateLabel(state: library.state(of: machine.name))
+ VPhoneLaunchpadMachineStateLabel(state: library.state(of: machine.path))
}
- if let started = library.startedAt[machine.name] {
+ if let started = library.startedAt[machine.path] {
LabeledContent("Started", value: started.formatted(date: .omitted, time: .shortened))
}
if let variant = machine.restoreInfo?.variant {
@@ -78,13 +78,13 @@ struct VPhoneLaunchpadMachineInspector: View {
}
value(
"Location",
- VPhoneLaunchpadHostSetup.abbreviated(library.libraryRoot.appendingPathComponent(machine.name)),
+ VPhoneLaunchpadHostSetup.abbreviated(machine.path.url),
)
}
Section("Console") {
Button {
- onOpenConsole(machine.name)
+ onOpenConsole(machine.path)
} label: {
Label("Open Console", systemImage: "arrow.up.right")
}
@@ -109,7 +109,7 @@ struct VPhoneLaunchpadMachineInspector: View {
private func creationSummary(_ creation: VPhoneLaunchpadCreationPipeline) -> some View {
LabeledContent {
- Button("Show Progress") { onShowProgress(creation.options.name) }
+ Button("Show Progress") { onShowProgress(creation.machine) }
} label: {
if creation.isRunning {
Label { Text("Creating: \(creation.current?.title ?? "")") } icon: { VPhoneLaunchpadStatusIcon(status: .running) }
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index f62da19b..f7ea8ef8 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -2,6 +2,11 @@ import Foundation
import Observation
/// The third stage: the VM library, driven entirely through `vphone-cli vm`.
+///
+/// Machines can live in several libraries: the default one, and folders
+/// chosen in New Machine. Each library is listed with its own
+/// `--library-root`, and every action on a machine passes the root it was
+/// listed from.
@MainActor
@Observable
final class VPhoneLaunchpadMachineLibrary {
@@ -11,63 +16,125 @@ final class VPhoneLaunchpadMachineLibrary {
case busy(String)
}
+ typealias Path = VPhoneLaunchpadMachinePath
+
private(set) var machines: [VPhoneLaunchpadMachine] = []
private(set) var listError: String?
- private(set) var startedAt: [String: Date] = [:]
+ private(set) var startedAt: [Path: Date] = [:]
/// Machines whose console printed a panic since Launchpad last started
/// them. The console text itself stays in the log file.
- private(set) var panicked: Set<String> = []
- private(set) var creations: [String: VPhoneLaunchpadCreationPipeline] = [:]
+ private(set) var panicked: Set<Path> = []
+ private(set) var creations: [Path: VPhoneLaunchpadCreationPipeline] = [:]
private(set) var globalActivity: String?
- var selection: String?
+ /// Folders chosen in New Machine, in the order they were added. The
+ /// default library is not among them.
+ private(set) var addedRoots: [String]
+ var selection: Path?
var actionError: VPhoneLaunchpadError?
- let libraryRoot: URL
+ /// The default library, canonical. Import writes here.
+ let libraryRoot: String
private let bundles: VPhoneLaunchpadCoreBundle
private let helper: VPhoneLaunchpadHelperClient
- private var launched: [String: VPhoneLaunchpadChildProcess] = [:]
- private var externallyRunning: Set<String> = []
- private var activities: [String: String] = [:]
+ private var launched: [Path: VPhoneLaunchpadChildProcess] = [:]
+ private var externallyRunning: Set<Path> = []
+ private var activities: [Path: String] = [:]
private var isRefreshing = false
private var timer: Timer?
- init(libraryRoot: URL, bundles: VPhoneLaunchpadCoreBundle, helper: VPhoneLaunchpadHelperClient) {
- self.libraryRoot = libraryRoot
+ private static let addedRootsKey = "VPhoneLaunchpadLibraryRoots"
+ private static let lastRootKey = "VPhoneLaunchpadLastLibraryRoot"
+
+ init(bundles: VPhoneLaunchpadCoreBundle, helper: VPhoneLaunchpadHelperClient) {
+ libraryRoot = VPhoneLaunchpadMachineLocations.defaultRoot
self.bundles = bundles
self.helper = helper
+ var roots: [String] = []
+ for root in UserDefaults.standard.stringArray(forKey: Self.addedRootsKey) ?? []
+ where root.hasPrefix("/") && root != libraryRoot && !roots.contains(root)
+ {
+ roots.append(root)
+ }
+ addedRoots = roots
}
- var libraryArguments: [String] {
- ["--library-root", libraryRoot.path]
+ /// Every library, the default one first.
+ var roots: [String] {
+ [libraryRoot] + addedRoots
}
var selected: VPhoneLaunchpadMachine? {
- machines.first { $0.name == selection }
+ machines.first { $0.id == selection }
}
var runningCount: Int {
- machines.count(where: { state(of: $0.name) == .running })
+ machines.count(where: { state(of: $0.path) == .running })
}
var hasActiveCreation: Bool {
creations.values.contains(where: \.isRunning)
}
- func state(of name: String) -> RunState {
- if let creation = creations[name], creation.isRunning, let step = creation.current {
+ /// True while machines from more than one library are listed.
+ var spansLibraries: Bool {
+ Set(machines.map(\.libraryRoot)).count > 1
+ }
+
+ func state(of machine: Path) -> RunState {
+ if let creation = creations[machine], creation.isRunning, let step = creation.current {
return .busy(String(localized: "Creating: \(step.title)"))
}
- if let activity = activities[name] {
+ if let activity = activities[machine] {
return .busy(activity)
}
- if launched[name]?.isRunning == true || externallyRunning.contains(name) {
+ if launched[machine]?.isRunning == true || externallyRunning.contains(machine) {
return .running
}
return .stopped
}
- func launchedProcess(_ name: String) -> VPhoneLaunchpadChildProcess? {
- launched[name]
+ func launchedProcess(_ machine: Path) -> VPhoneLaunchpadChildProcess? {
+ launched[machine]
+ }
+
+ // MARK: - Locations
+
+ /// The library New Machine offers first: the one last created in, while
+ /// it is mounted and usable (even once it holds no machine), else the
+ /// default library.
+ var preferredRoot: String {
+ if let last = UserDefaults.standard.string(forKey: Self.lastRootKey), last.hasPrefix("/"),
+ VPhoneLaunchpadMachineLocations.isAvailable(last),
+ VPhoneLaunchpadMachineLocations.problem(with: last) == nil
+ {
+ return last
+ }
+ return libraryRoot
+ }
+
+ /// Remembers a folder so its machines are listed with the others.
+ func addLocation(_ root: String) {
+ guard root != libraryRoot, !addedRoots.contains(root) else {
+ return
+ }
+ addedRoots.append(root)
+ UserDefaults.standard.set(addedRoots, forKey: Self.addedRootsKey)
+ Task { await refresh() }
+ }
+
+ /// Forgets added folders that were listed and hold no machine. A folder
+ /// that is missing, or could not be listed, is kept: its volume may just
+ /// not be mounted.
+ private func forgetEmptyLocations(listed: Set<String>) {
+ let kept = addedRoots.filter { root in
+ !listed.contains(root)
+ || machines.contains { $0.libraryRoot == root }
+ || creations.keys.contains { $0.libraryRoot == root }
+ }
+ if kept != addedRoots {
+ addedRoots = kept
+ UserDefaults.standard.set(kept, forKey: Self.addedRootsKey)
+ }
}
// MARK: - Refresh
@@ -87,36 +154,54 @@ final class VPhoneLaunchpadMachineLibrary {
}
isRefreshing = true
defer { isRefreshing = false }
- do {
- let result = try await commandLine.run(["vm", "list", "--json"] + libraryArguments, recordInHistory: false)
- if result.succeeded, let data = result.jsonData {
- machines = try JSONDecoder().decode([VPhoneLaunchpadMachine].self, from: data)
- listError = nil
- } else {
- listError = result.tail
+ var found: [VPhoneLaunchpadMachine] = []
+ var listed: Set<String> = []
+ var errors: [String] = []
+ for root in roots {
+ // vm list reports an empty library for a missing default root;
+ // a missing added folder is skipped, and its machines go with it.
+ guard root == libraryRoot || VPhoneLaunchpadMachineLocations.isAvailable(root) else {
+ continue
}
- } catch {
- listError = error.localizedDescription
+ do {
+ let result = try await commandLine.run(["vm", "list", "--json", "--library-root", root], recordInHistory: false)
+ if result.succeeded, let data = result.jsonData {
+ var machines = try JSONDecoder().decode([VPhoneLaunchpadMachine].self, from: data)
+ for index in machines.indices {
+ machines[index].libraryRoot = root
+ }
+ found += machines
+ listed.insert(root)
+ continue
+ }
+ errors.append(result.tail)
+ } catch {
+ errors.append(error.localizedDescription)
+ }
+ // Keep what this library listed last time, as before.
+ found += machines.filter { $0.libraryRoot == root }
}
- if selection == nil || !machines.contains(where: { $0.name == selection }) {
- selection = machines.first?.name
+ machines = found
+ listError = errors.first
+ forgetEmptyLocations(listed: listed)
+ if selection == nil || !machines.contains(where: { $0.id == selection }) {
+ selection = machines.first?.id
}
- let root = libraryRoot
- let names = machines.map(\.name)
- externallyRunning = await Task.detached { Self.machinesHoldingDisks(root: root, names: names) }.value
+ let paths = machines.map(\.path)
+ externallyRunning = await Task.detached { Self.machinesHoldingDisks(paths) }.value
}
/// The same test `vm stop` uses: a machine runs while some process holds
/// its disk image open. This also finds guests started outside Launchpad.
- private nonisolated static func machinesHoldingDisks(root: URL, names: [String]) -> Set<String> {
- var diskOwners: [String: String] = [:]
- for name in names {
- let bundle = root.appendingPathComponent(name, isDirectory: true)
+ private nonisolated static func machinesHoldingDisks(_ machines: [Path]) -> Set<Path> {
+ var diskOwners: [String: Path] = [:]
+ for machine in machines {
+ let bundle = machine.url
let manifest = NSDictionary(contentsOf: bundle.appendingPathComponent("config.plist"))
// Only a plain file name inside the bundle: a crafted manifest must
// not point lsof, and then `vm stop`, at another path.
let disk = (manifest?["diskImage"] as? String).flatMap(Self.plainFileName) ?? "Disk.img"
- diskOwners[bundle.appendingPathComponent(disk).path] = name
+ diskOwners[bundle.appendingPathComponent(disk).path] = machine
}
guard !diskOwners.isEmpty else {
return []
@@ -132,10 +217,10 @@ final class VPhoneLaunchpadMachineLibrary {
}
let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
process.waitUntilExit()
- var running: Set<String> = []
+ var running: Set<Path> = []
for line in output.split(separator: "\n") where line.hasPrefix("n") {
- if let name = diskOwners[String(line.dropFirst())] {
- running.insert(name)
+ if let machine = diskOwners[String(line.dropFirst())] {
+ running.insert(machine)
}
}
return running
@@ -151,16 +236,22 @@ final class VPhoneLaunchpadMachineLibrary {
// MARK: - Console
- static func consoleLog(_ name: String, suffix: String = "") -> URL {
- FileManager.default.homeDirectoryForCurrentUser
+ /// Machines in the default library keep their log names. Elsewhere the
+ /// name gains a digest of the library, since two libraries may each hold
+ /// a machine with the same name.
+ static func consoleLog(_ machine: Path, suffix: String = "") -> URL {
+ let stem = machine.libraryRoot == VPhoneLaunchpadMachineLocations.defaultRoot
+ ? machine.name
+ : "\(machine.name)-\(VPhoneLaunchpadMachineLocations.digest(machine.libraryRoot))"
+ return FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Library/Logs/vphone-launchpad", isDirectory: true)
- .appendingPathComponent("\(name)\(suffix).log")
+ .appendingPathComponent("\(stem)\(suffix).log")
}
/// Adds a line of Launchpad's own to the console log, after the process
/// that wrote it has exited.
- private func appendConsoleLog(_ name: String, _ line: String) {
- guard let handle = try? FileHandle(forWritingTo: Self.consoleLog(name)) else {
+ private func appendConsoleLog(_ machine: Path, _ line: String) {
+ guard let handle = try? FileHandle(forWritingTo: Self.consoleLog(machine)) else {
return
}
defer { try? handle.close() }
@@ -170,46 +261,46 @@ final class VPhoneLaunchpadMachineLibrary {
// MARK: - Start and stop
- func start(_ name: String, headless: Bool = false) {
+ func start(_ machine: Path, headless: Bool = false) {
guard let commandLine = bundles.commandLine() else {
return
}
- var arguments = ["vm", "launch", name] + libraryArguments
+ var arguments = ["vm", "launch", machine.name] + machine.libraryArguments
if headless {
arguments.append("--headless")
}
- panicked.remove(name)
+ panicked.remove(machine)
do {
- let child = try commandLine.start(arguments, logFile: Self.consoleLog(name)) { [weak self] line in
+ let child = try commandLine.start(arguments, logFile: Self.consoleLog(machine)) { [weak self] line in
if VPhoneLaunchpadCreationPipeline.isPanic(line) {
- Task { @MainActor in self?.panicked.insert(name) }
+ Task { @MainActor in self?.panicked.insert(machine) }
}
}
- launched[name] = child
- startedAt[name] = Date()
+ launched[machine] = child
+ startedAt[machine] = Date()
Task {
let status = await child.wait()
- if launched[name] === child {
- launched[name] = nil
- startedAt[name] = nil
- appendConsoleLog(name, "vm launch exited with status \(status)")
+ if launched[machine] === child {
+ launched[machine] = nil
+ startedAt[machine] = nil
+ appendConsoleLog(machine, "vm launch exited with status \(status)")
}
await refresh()
}
} catch {
- actionError = VPhoneLaunchpadError(String(localized: "Unable to Start \(name)"), detail: error.localizedDescription)
+ actionError = VPhoneLaunchpadError(String(localized: "Unable to Start \(machine.name)"), detail: error.localizedDescription)
}
}
- func stop(_ name: String) async {
- await perform(String(localized: "Stopping…"), on: name, ["vm", "stop", name] + libraryArguments)
- launched[name]?.interrupt()
+ func stop(_ machine: Path) async {
+ await perform(String(localized: "Stopping…"), on: machine, ["vm", "stop", machine.name] + machine.libraryArguments)
+ launched[machine]?.interrupt()
}
// MARK: - Edits
- func configure(_ name: String, cpu: Int?, memoryMB: Int?, network: String?, bridgeInterface: String?) async {
- var arguments = ["vm", "config", name] + libraryArguments
+ func configure(_ machine: Path, cpu: Int?, memoryMB: Int?, network: String?, bridgeInterface: String?) async {
+ var arguments = ["vm", "config", machine.name] + machine.libraryArguments
if let cpu {
arguments += ["--cpu", String(cpu)]
}
@@ -222,53 +313,57 @@ final class VPhoneLaunchpadMachineLibrary {
if let bridgeInterface, !bridgeInterface.isEmpty {
arguments += ["--bridge-interface", bridgeInterface]
}
- await perform(String(localized: "Saving settings…"), on: name, arguments)
+ await perform(String(localized: "Saving settings…"), on: machine, arguments)
}
- func rename(_ name: String, to newName: String) async {
- if await perform(String(localized: "Renaming…"), on: name, ["vm", "rename", name, newName] + libraryArguments) {
- selection = newName
+ func rename(_ machine: Path, to newName: String) async {
+ if await perform(String(localized: "Renaming…"), on: machine, ["vm", "rename", machine.name, newName] + machine.libraryArguments) {
+ selection = Path(libraryRoot: machine.libraryRoot, name: newName)
}
}
- func clone(_ name: String, as newName: String) async {
- if await perform(String(localized: "Cloning…"), on: name, ["vm", "clone", name, newName] + libraryArguments) {
- selection = newName
+ func clone(_ machine: Path, as newName: String) async {
+ if await perform(String(localized: "Cloning…"), on: machine, ["vm", "clone", machine.name, newName] + machine.libraryArguments) {
+ selection = Path(libraryRoot: machine.libraryRoot, name: newName)
}
}
- func delete(_ name: String) async {
- await perform(String(localized: "Deleting…"), on: name, ["vm", "delete", name, "--force"] + libraryArguments)
+ func delete(_ machine: Path) async {
+ await perform(String(localized: "Deleting…"), on: machine, ["vm", "delete", machine.name, "--force"] + machine.libraryArguments)
}
- func export(_ name: String, to destination: URL, densest: Bool, includeIPSW: Bool) async {
- var arguments = ["vm", "export", name, "--out", destination.path] + libraryArguments
+ func export(_ machine: Path, to destination: URL, densest: Bool, includeIPSW: Bool) async {
+ var arguments = ["vm", "export", machine.name, "--out", destination.path] + machine.libraryArguments
if densest {
arguments.append("--max")
}
if includeIPSW {
arguments.append("--include-ipsw")
}
- await perform(String(localized: "Exporting…"), on: name, arguments)
+ await perform(String(localized: "Exporting…"), on: machine, arguments)
}
func importArchive(_ archive: URL) async {
- await perform(String(localized: "Importing \(archive.lastPathComponent)"), on: nil, ["vm", "import", archive.path] + libraryArguments)
+ await perform(
+ String(localized: "Importing \(archive.lastPathComponent)"),
+ on: nil,
+ ["vm", "import", archive.path, "--library-root", libraryRoot],
+ )
}
@discardableResult
- private func perform(_ activity: String, on name: String?, _ arguments: [String]) async -> Bool {
+ private func perform(_ activity: String, on machine: Path?, _ arguments: [String]) async -> Bool {
guard let commandLine = bundles.commandLine() else {
return false
}
- if let name {
- activities[name] = activity
+ if let machine {
+ activities[machine] = activity
} else {
globalActivity = activity
}
defer {
- if let name {
- activities[name] = nil
+ if let machine {
+ activities[machine] = nil
} else {
globalActivity = nil
}
@@ -290,19 +385,20 @@ final class VPhoneLaunchpadMachineLibrary {
func create(_ options: VPhoneLaunchpadCreationPipeline.Options) -> VPhoneLaunchpadCreationPipeline {
let pipeline = VPhoneLaunchpadCreationPipeline(
options: options,
- libraryRoot: libraryRoot,
bundles: bundles,
helper: helper,
library: self,
)
- creations[options.name] = pipeline
+ creations[pipeline.machine] = pipeline
+ UserDefaults.standard.set(options.libraryRoot, forKey: Self.lastRootKey)
+ addLocation(options.libraryRoot)
pipeline.start()
return pipeline
}
- func discardCreation(_ name: String) {
- if creations[name]?.isRunning == false {
- creations[name] = nil
+ func discardCreation(_ machine: Path) {
+ if creations[machine]?.isRunning == false {
+ creations[machine] = nil
}
}
}
@@ -311,10 +407,10 @@ final class VPhoneLaunchpadMachineLibrary {
extension VPhoneLaunchpadMachineLibrary {
func applyPreview(creation: VPhoneLaunchpadCreationPipeline) {
machines = VPhoneLaunchpadPreview.machines
- externallyRunning = ["research-01"]
- startedAt = ["research-01": Date().addingTimeInterval(-6130)]
- creations = ["ios27-rc": creation]
- selection = "research-01"
+ externallyRunning = [VPhoneLaunchpadPreview.path("research-01")]
+ startedAt = [VPhoneLaunchpadPreview.path("research-01"): Date().addingTimeInterval(-6130)]
+ creations = [creation.machine: creation]
+ selection = VPhoneLaunchpadPreview.path("research-01")
}
}
#endif
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLocations.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLocations.swift
new file mode 100644
index 00000000..68012b8e
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLocations.swift
@@ -0,0 +1,100 @@
+import CryptoKit
+import Darwin
+import Foundation
+
+/// The folders machines live in. The default library (`VPHONE_LIBRARY_ROOT`,
+/// else ~/.vphone/machines) is always one; New Machine can add others. Each
+/// is passed to vphone-cli as `--library-root`.
+///
+/// Roots are canonical: the helper refuses a library path with a symbolic
+/// link in it, and comparing canonical paths keeps one folder from being
+/// listed twice under two spellings.
+nonisolated enum VPhoneLaunchpadMachineLocations {
+ static let defaultRoot: String = {
+ let environment = ProcessInfo.processInfo.environment["VPHONE_LIBRARY_ROOT"].flatMap { $0.isEmpty ? nil : $0 }
+ return canonical(
+ environment.map { URL(fileURLWithPath: $0, isDirectory: true) }
+ ?? FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".vphone/machines", isDirectory: true),
+ )
+ }()
+
+ /// The resolved path of an existing folder, else the standardized path.
+ static func canonical(_ url: URL) -> String {
+ let path = url.standardizedFileURL.path
+ guard let resolved = realpath(path, nil) else {
+ return path
+ }
+ defer { free(resolved) }
+ return String(cString: resolved)
+ }
+
+ /// False while a chosen folder is missing, for example on a volume that
+ /// is not mounted.
+ static func isAvailable(_ root: String) -> Bool {
+ var isDirectory: ObjCBool = false
+ return FileManager.default.fileExists(atPath: root, isDirectory: &isDirectory) && isDirectory.boolValue
+ }
+
+ /// The name of the volume holding `root`, for a narrow column. The full
+ /// path goes in the column's help and the inspector.
+ static func volumeName(_ root: String) -> String {
+ let url = VPhoneLaunchpadHostSetup.existingAncestor(of: URL(fileURLWithPath: root, isDirectory: true))
+ return (try? url.resourceValues(forKeys: [.volumeLocalizedNameKey]))?.volumeLocalizedName
+ ?? VPhoneLaunchpadHostSetup.abbreviated(url)
+ }
+
+ /// Eight hex digits that tell libraries apart in log file names.
+ static func digest(_ root: String) -> String {
+ SHA256.hash(data: Data(root.utf8)).prefix(4).map { String(format: "%02x", $0) }.joined()
+ }
+
+ /// vphone-vm binds the machine's control socket at `<machine>/vphone.sock`
+ /// and skips it when the path does not fit `sun_path`; first boot then
+ /// waits for vphoned in vain.
+ static func socketPathFits(root: String, name: String) -> Bool {
+ let path = URL(fileURLWithPath: root, isDirectory: true)
+ .appendingPathComponent(name, isDirectory: true)
+ .appendingPathComponent("vphone.sock").path
+ return path.utf8CString.count <= MemoryLayout.size(ofValue: sockaddr_un().sun_path)
+ }
+
+ /// Why machines cannot be created in `root`, or nil. These are the
+ /// conditions the helper enforces before `cfw install` (a root owned by
+ /// the user), plus the APFS volume Host Setup requires of the default
+ /// library.
+ static func problem(with root: String) -> String? {
+ let url = URL(fileURLWithPath: root, isDirectory: true)
+ let shown = VPhoneLaunchpadHostSetup.abbreviated(url)
+ // A root that does not exist yet is created by `vm new`.
+ let existing = VPhoneLaunchpadHostSetup.existingAncestor(of: url)
+ var volume = statfs()
+ guard statfs(existing.path, &volume) == 0 else {
+ return String(localized: "Cannot read the volume of \(shown)")
+ }
+ let type = withUnsafeBytes(of: volume.f_fstypename) { String(decoding: $0.prefix { $0 != 0 }, as: UTF8.self) }
+ guard type == "apfs" else {
+ return String(localized: "\(shown) is not on an APFS volume.")
+ }
+ // Files there report an unknown owner to root, which the helper refuses.
+ guard volume.f_flags & UInt32(MNT_IGNORE_OWNERSHIP) == 0 else {
+ return String(localized: "\(shown) is on a volume that ignores ownership. Select the volume in the Finder, choose File > Get Info, and turn off “Ignore ownership on this volume”.")
+ }
+ if existing.path == url.path {
+ var status = stat()
+ guard stat(root, &status) == 0, (status.st_mode & S_IFMT) == S_IFDIR else {
+ return String(localized: "Cannot read the volume of \(shown)")
+ }
+ guard status.st_uid == getuid() else {
+ return String(localized: "\(shown) is not owned by your user account.")
+ }
+ if FileManager.default.fileExists(atPath: url.appendingPathComponent("config.plist").path) {
+ return String(localized: "\(shown) is a machine. Choose the folder that contains it.")
+ }
+ }
+ guard access(existing.path, W_OK) == 0 else {
+ return String(localized: "You cannot write to \(VPhoneLaunchpadHostSetup.abbreviated(existing)).")
+ }
+ return nil
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
index 96ace8c5..3eaddf56 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
@@ -59,7 +59,7 @@ struct VPhoneLaunchpadMachineSettingsView: View {
let bridgeChanged = bridgeInterface != (machine.network.bridgeInterface ?? "")
Task {
await model.machines.configure(
- machine.name,
+ machine.path,
cpu: cpu == machine.cpuCount ? nil : cpu,
memoryMB: memoryMB == machine.memoryMB ? nil : memoryMB,
network: network == currentNetwork && !bridgeChanged ? nil : network,
@@ -76,13 +76,18 @@ struct VPhoneLaunchpadNameSheet: View {
let title: LocalizedStringKey
let action: LocalizedStringKey
let initial: String
- let existingName: String
+ /// The machine renamed or cloned. The new name stays in its library.
+ let machine: VPhoneLaunchpadMachinePath
let onConfirm: (String) -> Void
@Environment(\.dismiss) private var dismiss
@State private var name = ""
+ private var fitsLocation: Bool {
+ VPhoneLaunchpadMachineLocations.socketPathFits(root: machine.libraryRoot, name: name)
+ }
+
private var isValid: Bool {
- VPhoneLaunchpadNames.isValidMachineName(name) && name != existingName
+ VPhoneLaunchpadNames.isValidMachineName(name) && name != machine.name && fitsLocation
}
var body: some View {
@@ -90,8 +95,13 @@ struct VPhoneLaunchpadNameSheet: View {
Section {
TextField("Name", text: $name)
} footer: {
- Text("Use letters, numbers, periods, hyphens, and underscores.")
- .foregroundStyle(.secondary)
+ if fitsLocation {
+ Text("Use letters, numbers, periods, hyphens, and underscores.")
+ .foregroundStyle(.secondary)
+ } else {
+ Text("The path is too long. Use a shorter name, or a location with a shorter path.")
+ .foregroundStyle(.red)
+ }
}
}
.formStyle(.grouped)
@@ -117,12 +127,16 @@ struct VPhoneLaunchpadNameSheet: View {
// MARK: - Export
struct VPhoneLaunchpadExportView: View {
- let name: String
+ let machine: VPhoneLaunchpadMachinePath
@Environment(VPhoneLaunchpadModel.self) private var model
@Environment(\.dismiss) private var dismiss
@State private var densest = false
@State private var includeIPSW = false
+ private var name: String {
+ machine.name
+ }
+
var body: some View {
Form {
Section {
@@ -158,7 +172,7 @@ struct VPhoneLaunchpadExportView: View {
}
let densest = densest
let includeIPSW = includeIPSW
- Task { await model.machines.export(name, to: url, densest: densest, includeIPSW: includeIPSW) }
+ Task { await model.machines.export(machine, to: url, densest: densest, includeIPSW: includeIPSW) }
dismiss()
}
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
index da5023e0..a97ee226 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
@@ -2,31 +2,33 @@ import AppKit
import SwiftUI
struct VPhoneLaunchpadMachinesView: View {
+ typealias MachinePath = VPhoneLaunchpadMachinePath
+
enum Sheet: Identifiable {
case newMachine
- case creation(String)
+ case creation(MachinePath)
case settings(VPhoneLaunchpadMachine)
- case rename(String)
- case clone(String)
- case export(String)
- case console(String)
+ case rename(MachinePath)
+ case clone(MachinePath)
+ case export(MachinePath)
+ case console(MachinePath)
var id: String {
switch self {
case .newMachine: "new"
- case let .creation(name): "creation-\(name)"
- case let .settings(machine): "settings-\(machine.name)"
- case let .rename(name): "rename-\(name)"
- case let .clone(name): "clone-\(name)"
- case let .export(name): "export-\(name)"
- case let .console(name): "console-\(name)"
+ case let .creation(machine): "creation-\(machine.url.path)"
+ case let .settings(machine): "settings-\(machine.path.url.path)"
+ case let .rename(machine): "rename-\(machine.url.path)"
+ case let .clone(machine): "clone-\(machine.url.path)"
+ case let .export(machine): "export-\(machine.url.path)"
+ case let .console(machine): "console-\(machine.url.path)"
}
}
}
@Environment(VPhoneLaunchpadModel.self) private var model
@State private var sheet: Sheet?
- @State private var deletion: String?
+ @State private var deletion: MachinePath?
@State private var showsInspector = true
private var library: VPhoneLaunchpadMachineLibrary {
@@ -47,8 +49,8 @@ struct VPhoneLaunchpadMachinesView: View {
if let machine = library.selected {
VPhoneLaunchpadMachineInspector(
machine: machine,
- onShowProgress: { name in sheet = .creation(name) },
- onOpenConsole: { name in sheet = .console(name) },
+ onShowProgress: { path in sheet = .creation(path) },
+ onOpenConsole: { path in sheet = .console(path) },
)
} else {
ContentUnavailableView("No Selection", systemImage: "iphone")
@@ -67,7 +69,7 @@ struct VPhoneLaunchpadMachinesView: View {
.environment(model)
}
.confirmationDialog(
- "Delete \(deletion ?? "")?",
+ "Delete \(deletion?.name ?? "")?",
isPresented: Binding(get: { deletion != nil }, set: {
if !$0 {
deletion = nil
@@ -75,8 +77,8 @@ struct VPhoneLaunchpadMachinesView: View {
}),
) {
Button("Delete", role: .destructive) {
- if let name = deletion {
- Task { await library.delete(name) }
+ if let machine = deletion {
+ Task { await library.delete(machine) }
}
}
} message: {
@@ -102,11 +104,11 @@ struct VPhoneLaunchpadMachinesView: View {
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
let selected = library.selected
- let state = selected.map { library.state(of: $0.name) }
+ let state = selected.map { library.state(of: $0.path) }
ToolbarItemGroup(placement: .primaryAction) {
if state == .running, let selected {
Button {
- Task { await library.stop(selected.name) }
+ Task { await library.stop(selected.path) }
} label: {
Label("Stop", systemImage: "stop.fill")
}
@@ -114,7 +116,7 @@ struct VPhoneLaunchpadMachinesView: View {
} else {
Button {
if let selected {
- library.start(selected.name)
+ library.start(selected.path)
}
} label: {
Label("Start", systemImage: "play.fill")
@@ -154,44 +156,53 @@ struct VPhoneLaunchpadMachinesView: View {
@ViewBuilder
private func machineActions(_ machine: VPhoneLaunchpadMachine?) -> some View {
if let machine {
- let isStopped = library.state(of: machine.name) == .stopped
- Button("Start Headless") { library.start(machine.name, headless: true) }
+ let isStopped = library.state(of: machine.path) == .stopped
+ Button("Start Headless") { library.start(machine.path, headless: true) }
.disabled(!isStopped)
Divider()
Button("Settings…") { sheet = .settings(machine) }
.disabled(!isStopped)
- Button("Rename…") { sheet = .rename(machine.name) }
+ Button("Rename…") { sheet = .rename(machine.path) }
.disabled(!isStopped)
- Button("Clone…") { sheet = .clone(machine.name) }
+ Button("Clone…") { sheet = .clone(machine.path) }
.disabled(!isStopped)
- Button("Export…") { sheet = .export(machine.name) }
+ Button("Export…") { sheet = .export(machine.path) }
.disabled(!isStopped)
Divider()
Button("Show in Finder") {
- NSWorkspace.shared.activateFileViewerSelecting([library.libraryRoot.appendingPathComponent(machine.name)])
+ NSWorkspace.shared.activateFileViewerSelecting([machine.path.url])
}
- Button("Open Console") { sheet = .console(machine.name) }
+ Button("Open Console") { sheet = .console(machine.path) }
Button("Show Console Log") {
- NSWorkspace.shared.open(VPhoneLaunchpadMachineLibrary.consoleLog(machine.name))
+ NSWorkspace.shared.open(VPhoneLaunchpadMachineLibrary.consoleLog(machine.path))
}
Divider()
- Button("Delete…", role: .destructive) { deletion = machine.name }
+ Button("Delete…", role: .destructive) { deletion = machine.path }
.disabled(!isStopped)
}
}
// MARK: - Table
- private func table(selection: Binding<String?>) -> some View {
+ private func table(selection: Binding<MachinePath?>) -> some View {
Table(library.machines, selection: selection) {
TableColumn("Name", value: \.name)
.width(min: 90, ideal: 110)
+ if library.spansLibraries {
+ TableColumn("Location") { machine in
+ Text(verbatim: VPhoneLaunchpadMachineLocations.volumeName(machine.libraryRoot))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .help(VPhoneLaunchpadHostSetup.abbreviated(URL(fileURLWithPath: machine.libraryRoot, isDirectory: true)))
+ }
+ .width(min: 80, ideal: 110)
+ }
TableColumn("iOS") { machine in
Text(verbatim: machine.restoreInfo.map { "\($0.ios.version) (\($0.ios.build))" } ?? "—")
}
.width(min: 110, ideal: 120)
TableColumn("State") { machine in
- VPhoneLaunchpadMachineStateLabel(state: library.state(of: machine.name))
+ VPhoneLaunchpadMachineStateLabel(state: library.state(of: machine.path))
}
.width(min: 150, ideal: 160)
TableColumn("CPU") { machine in
@@ -207,11 +218,11 @@ struct VPhoneLaunchpadMachinesView: View {
}
.width(64)
}
- .contextMenu(forSelectionType: String.self) { names in
- machineActions(library.machines.first { names.contains($0.name) })
- } primaryAction: { names in
- if let name = names.first, library.state(of: name) == .stopped {
- library.start(name)
+ .contextMenu(forSelectionType: MachinePath.self) { paths in
+ machineActions(library.machines.first { paths.contains($0.path) })
+ } primaryAction: { paths in
+ if let path = paths.first, library.state(of: path) == .stopped {
+ library.start(path)
}
}
}
@@ -220,7 +231,7 @@ struct VPhoneLaunchpadMachinesView: View {
ContentUnavailableView {
Label("No Machines", systemImage: "iphone")
} description: {
- Text(library.listError ?? String(localized: "Machines in \(VPhoneLaunchpadHostSetup.abbreviated(library.libraryRoot)) appear here."))
+ Text(library.listError ?? String(localized: "Machines in \(VPhoneLaunchpadHostSetup.abbreviated(URL(fileURLWithPath: library.libraryRoot, isDirectory: true))) appear here."))
} actions: {
Button("New Machine…") { sheet = .newMachine }
.buttonStyle(.borderedProminent)
@@ -234,32 +245,32 @@ struct VPhoneLaunchpadMachinesView: View {
private func sheetContent(_ sheet: Sheet) -> some View {
switch sheet {
case .newMachine:
- VPhoneLaunchpadNewMachineView { name in
- self.sheet = .creation(name)
+ VPhoneLaunchpadNewMachineView { path in
+ self.sheet = .creation(path)
}
- case let .creation(name):
- if let creation = library.creations[name] {
+ case let .creation(path):
+ if let creation = library.creations[path] {
VPhoneLaunchpadCreationView(creation: creation)
}
case let .settings(machine):
VPhoneLaunchpadMachineSettingsView(machine: machine)
- case let .rename(name):
- VPhoneLaunchpadNameSheet(title: "Rename \(name)", action: "Rename", initial: name, existingName: name) { newName in
- Task { await library.rename(name, to: newName) }
+ case let .rename(path):
+ VPhoneLaunchpadNameSheet(title: "Rename \(path.name)", action: "Rename", initial: path.name, machine: path) { newName in
+ Task { await library.rename(path, to: newName) }
}
- case let .clone(name):
+ case let .clone(path):
VPhoneLaunchpadNameSheet(
- title: "Clone \(name)",
+ title: "Clone \(path.name)",
action: "Clone",
- initial: "\(name)-clone",
- existingName: name,
+ initial: "\(path.name)-clone",
+ machine: path,
) { newName in
- Task { await library.clone(name, as: newName) }
+ Task { await library.clone(path, as: newName) }
}
- case let .export(name):
- VPhoneLaunchpadExportView(name: name)
- case let .console(name):
- VPhoneLaunchpadConsoleView(title: "\(name) Console", url: VPhoneLaunchpadMachineLibrary.consoleLog(name))
+ case let .export(path):
+ VPhoneLaunchpadExportView(machine: path)
+ case let .console(path):
+ VPhoneLaunchpadConsoleView(title: "\(path.name) Console", url: VPhoneLaunchpadMachineLibrary.consoleLog(path))
}
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
index 70f37164..d4ba9000 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
@@ -1,14 +1,18 @@
import AppKit
import SwiftUI
-/// Name, firmware pairing from `fw catalog`, hardware and options. Create
-/// hands off to the pipeline sheet.
+/// Name, location, firmware pairing from `fw catalog`, hardware and options.
+/// Create hands off to the pipeline sheet.
struct VPhoneLaunchpadNewMachineView: View {
- let onCreate: (String) -> Void
+ let onCreate: (VPhoneLaunchpadMachinePath) -> Void
@Environment(VPhoneLaunchpadModel.self) private var model
@Environment(\.dismiss) private var dismiss
@State private var name = ""
+ /// The canonical library the machine is created in.
+ @State private var location = VPhoneLaunchpadMachineLocations.defaultRoot
+ /// A folder chosen with Other… that is not one of the library's locations.
+ @State private var chosenLocation: String?
@State private var catalog: VPhoneLaunchpadFirmwareCatalog?
@State private var catalogError: String?
@State private var pairing: String?
@@ -36,6 +40,10 @@ struct VPhoneLaunchpadNewMachineView: View {
return selectedPairing.map { ($0.ios.url, $0.recommendedCloudOS.url) }
}
+ private var machine: VPhoneLaunchpadMachinePath {
+ VPhoneLaunchpadMachinePath(libraryRoot: location, name: name)
+ }
+
private var nameProblem: String? {
if name.isEmpty {
return nil
@@ -43,23 +51,34 @@ struct VPhoneLaunchpadNewMachineView: View {
if !VPhoneLaunchpadNames.isValidMachineName(name) {
return String(localized: "Use letters, digits, dots, dashes and underscores.")
}
- if model.machines.machines.contains(where: { $0.name == name }) {
+ if model.machines.machines.contains(where: { $0.path == machine }) || model.machines.creations[machine]?.isRunning == true {
return String(localized: "A machine with this name already exists.")
}
+ if FileManager.default.fileExists(atPath: machine.url.path) {
+ return String(localized: "A folder with this name already exists in this location.")
+ }
+ if !VPhoneLaunchpadMachineLocations.socketPathFits(root: location, name: name) {
+ return String(localized: "The path is too long. Use a shorter name, or a location with a shorter path.")
+ }
return nil
}
+ private var locationProblem: String? {
+ VPhoneLaunchpadMachineLocations.problem(with: location)
+ }
+
private var canCreate: Bool {
- !name.isEmpty && nameProblem == nil && sources != nil
+ !name.isEmpty && nameProblem == nil && locationProblem == nil && sources != nil
}
var body: some View {
Form {
Section {
TextField("Name", text: $name, prompt: Text(verbatim: "research-01"))
+ locationPicker
} footer: {
- if let nameProblem {
- Text(nameProblem).foregroundStyle(.red)
+ if let problem = nameProblem ?? locationProblem {
+ Text(problem).foregroundStyle(.red)
}
}
@@ -99,6 +118,67 @@ struct VPhoneLaunchpadNewMachineView: View {
}
}
.task { await loadCatalog() }
+ .onAppear { location = model.machines.preferredRoot }
+ }
+
+ // MARK: - Location
+
+ /// The library's locations that are mounted, the default one first, and
+ /// a folder chosen with Other….
+ private var locations: [String] {
+ var roots = model.machines.roots.filter { $0 == model.machines.libraryRoot || VPhoneLaunchpadMachineLocations.isAvailable($0) }
+ for root in [chosenLocation, location].compactMap(\.self) where !roots.contains(root) {
+ roots.append(root)
+ }
+ return roots
+ }
+
+ private var locationPicker: some View {
+ Picker("Location", selection: Binding(
+ get: { location },
+ set: { root in
+ if root.isEmpty {
+ // Let the menu close before the open panel runs.
+ Task { @MainActor in chooseLocation() }
+ } else {
+ location = root
+ }
+ },
+ )) {
+ ForEach(locations, id: \.self) { root in
+ Text(verbatim: VPhoneLaunchpadHostSetup.abbreviated(URL(fileURLWithPath: root, isDirectory: true)))
+ .tag(root)
+ }
+ Divider()
+ // Library roots are absolute, so an empty tag cannot be one.
+ Text("Other…").tag("")
+ }
+ .help(location)
+ }
+
+ private func chooseLocation() {
+ let panel = NSOpenPanel()
+ panel.title = String(localized: "Choose a Location")
+ panel.message = String(localized: "The machine is created in a folder with its name inside the folder you choose.")
+ panel.prompt = String(localized: "Choose")
+ panel.canChooseFiles = false
+ panel.canChooseDirectories = true
+ panel.canCreateDirectories = true
+ panel.allowsMultipleSelection = false
+ panel.directoryURL = URL(fileURLWithPath: location, isDirectory: true)
+ guard panel.runModal() == .OK, let url = panel.url else {
+ return
+ }
+ let root = VPhoneLaunchpadMachineLocations.canonical(url)
+ if !model.machines.roots.contains(root) {
+ chosenLocation = root
+ }
+ location = root
+ // Machines already in the folder join the list; a folder that cannot
+ // hold machines is only shown here, with the reason.
+ if VPhoneLaunchpadMachineLocations.problem(with: root) == nil {
+ model.machines.addLocation(root)
+ }
}
// MARK: - Firmware
@@ -158,7 +238,7 @@ struct VPhoneLaunchpadNewMachineView: View {
/// Disk plus roughly 20 GB of IPSWs and the prepared restore tree.
private var spaceNote: String {
- let root = VPhoneLaunchpadHostSetup.existingAncestor(of: model.libraryRoot)
+ let root = VPhoneLaunchpadHostSetup.existingAncestor(of: URL(fileURLWithPath: location, isDirectory: true))
let free = (try? root.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]))?
.volumeAvailableCapacityForImportantUsage ?? 0
return String(localized: "Needs about \(diskSizeGB + 20) GB; \(free / 1_000_000_000) GB free.")
@@ -197,6 +277,7 @@ struct VPhoneLaunchpadNewMachineView: View {
}
let options = VPhoneLaunchpadCreationPipeline.Options(
name: name,
+ libraryRoot: location,
iphoneSource: iphone,
cloudOSSource: cloudOS,
cpuCount: cpu,
@@ -207,9 +288,9 @@ struct VPhoneLaunchpadNewMachineView: View {
forceDyldSharedCacheMaxSlide: forceMaxSlide,
keepArtifacts: keepArtifacts,
)
- _ = model.machines.create(options)
- model.machines.selection = name
- onCreate(name)
+ let pipeline = model.machines.create(options)
+ model.machines.selection = pipeline.machine
+ onCreate(pipeline.machine)
}
}