Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Save files dropped on the window to the Files app

Lakr6e1b0cfe411c
diff --git a/VPhoneDaemon/Daemon/GuestAPI+FileTool.swift b/VPhoneDaemon/Daemon/GuestAPI+FileTool.swift
index 2817377d..d8f266b5 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+FileTool.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+FileTool.swift
@@ -36,6 +36,8 @@ extension GuestAPI {
return try changeMode(string(params, "path"), mode: string(params, "mode"))
case "files.chown":
return try changeOwner(string(params, "path"), owner: string(params, "owner"))
+ case "files.save_to_files_app":
+ return try saveToFilesApp(string(params, "path"), name: string(params, "name"))
case "files.plist":
return try readPlist(string(params, "path"))
case "files.plist_set":
diff --git a/VPhoneDaemon/Daemon/GuestAPI+FilesApp.swift b/VPhoneDaemon/Daemon/GuestAPI+FilesApp.swift
new file mode 100644
index 00000000..fd072fad
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+FilesApp.swift
@@ -0,0 +1,59 @@
+import Foundation
+
+// MARK: - Files App
+
+extension GuestAPI {
+ static let filesAppGroup = "group.com.apple.FileProvider.LocalStorage"
+ static let filesAppDropFolder = "vphone-drop"
+
+ /// The folder the Files app shows as On My iPhone: `File Provider Storage`
+ /// in the LocalStorage app group, whose container UUID differs per device.
+ static func filesAppRoot() throws -> String {
+ let groups = "/var/mobile/Containers/Shared/AppGroup"
+ for name in try FileManager.default.contentsOfDirectory(atPath: groups) {
+ let container = groups + "/" + name
+ let metadata = NSDictionary(
+ contentsOfFile: container + "/.com.apple.mobile_container_manager.metadata.plist",
+ )
+ if metadata?["MCMMetadataIdentifier"] as? String == filesAppGroup {
+ return container + "/File Provider Storage"
+ }
+ }
+ throw GuestAPIError.operationFailed("The Files app storage container was not found")
+ }
+
+ /// Moves an uploaded file into On My iPhone › vphone-drop. Items there are
+ /// shown by the Files app at once when they look like the ones it creates:
+ /// owned by mobile, folders 755 and files 644, no extended attributes. A
+ /// name already taken is kept; the new file gets " 2", " 3", … before its
+ /// extension.
+ static func saveToFilesApp(_ source: String, name: String) throws -> [String: Any] {
+ guard !name.isEmpty, !name.contains("/"), name != ".", name != ".." else {
+ throw GuestAPIError.invalidRequest("name must be a single file name")
+ }
+ let manager = FileManager.default
+ let root = try filesAppRoot()
+ let directory = root + "/" + filesAppDropFolder
+ let mobile: [FileAttributeKey: Any] = [.ownerAccountID: 501, .groupOwnerAccountID: 501]
+ for path in [root, directory] where !manager.fileExists(atPath: path) {
+ var attributes = mobile
+ attributes[.posixPermissions] = 0o755
+ try manager.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: attributes)
+ }
+
+ let stem = (name as NSString).deletingPathExtension
+ let suffix = (name as NSString).pathExtension
+ var candidate = name
+ var number = 2
+ while manager.fileExists(atPath: directory + "/" + candidate) {
+ candidate = suffix.isEmpty ? "\(stem) \(number)" : "\(stem) \(number).\(suffix)"
+ number += 1
+ }
+ let destination = directory + "/" + candidate
+ try manager.moveItem(atPath: source, toPath: destination)
+ var attributes = mobile
+ attributes[.posixPermissions] = 0o644
+ try manager.setAttributes(attributes, ofItemAtPath: destination)
+ return ["path": destination, "name": candidate, "folder": filesAppDropFolder]
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index 73d481ca..48f5be9c 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -88,6 +88,7 @@ enum GuestAPI {
"app_details",
"system_control",
"file_tools",
+ "files_app_drop",
"packages",
"environment_update",
],
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
index c31481bb..bdd97fa1 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
@@ -8019,6 +8019,40 @@
}
}
},
+ "Dropped Files" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dropped Files"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ドロップしたファイル"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "놓은 파일"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tệp đã thả"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "拖入的文件"
+ }
+ }
+ }
+ },
"Edit" : {
"localizations" : {
"en" : {
@@ -19279,6 +19313,40 @@
}
}
},
+ "Saved “%@” to On My iPhone › %@ in Files." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Saved “%1$@” to On My iPhone › %2$@ in Files."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "「%1$@」を“ファイル”の「このiPhone内 › %2$@」に保存しました。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "“%1$@”을(를) 파일 앱의 ‘나의 iPhone › %2$@’에 저장했습니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Đã lưu “%1$@” vào Trên iPhone › %2$@ trong ứng dụng Tệp."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已将“%1$@”保存到“文件”App 的“我的 iPhone › %2$@”。"
+ }
+ }
+ }
+ },
"Save…" : {
"localizations" : {
"ja" : {
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
index a17ab50b..b416aa27 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
@@ -323,6 +323,32 @@ final class VPhoneGuestControl {
return result["msg"] as? String ?? "Installed \(localURL.lastPathComponent)."
}
+ /// Where the Files app shows a dropped file: On My iPhone › vphone-drop.
+ static let dropFolder = "vphone-drop"
+
+ /// Uploads a file dropped on the window, then has vphoned move it into
+ /// the Files app's On My iPhone › vphone-drop. vphoned finds that storage,
+ /// keeps a name already taken by numbering the new one, and gives the
+ /// file the owner and mode the Files app uses. Returns the name used.
+ func saveDroppedFile(localURL: URL) async throws -> String {
+ guard guestCapabilities.contains("files_app_drop") else {
+ throw ControlError.unsupportedCapability("files_app_drop")
+ }
+ let data = try Data(contentsOf: localURL, options: .mappedIfSafe)
+ let path = "/var/root/Library/Caches/vphoned-drop-\(UUID().uuidString)"
+ try await createDirectory(path: "/var/root/Library/Caches")
+ try await uploadFile(path: path, data: data)
+ do {
+ let result = try await call(
+ "files.save_to_files_app", params: ["path": path, "name": localURL.lastPathComponent],
+ )
+ return result["name"] as? String ?? localURL.lastPathComponent
+ } catch {
+ try? await deleteFile(path: path)
+ throw error
+ }
+ }
+
func installBootstrap(layout: String, localURL: URL? = nil) async throws -> [String: Any] {
guard guestCapabilities.contains("bootstrap_install") else {
throw ControlError.unsupportedCapability("bootstrap_install")
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift
index b9d97af3..402e2ba1 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift
@@ -80,10 +80,13 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {
keySender.sendHome()
}
- // MARK: - Drag and Drop Install
+ // MARK: - Drag and Drop
+ /// Every dropped file goes through vphoned: an .ipa or .tipa is installed,
+ /// anything else is saved to the Files app's On My iPhone › vphone-drop.
+ /// Folders are not taken.
override func draggingEntered(_ sender: any NSDraggingInfo) -> NSDragOperation {
- guard droppedInstallPackageURL(from: sender) != nil else { return [] }
+ guard !droppedFileURLs(from: sender).isEmpty else { return [] }
updateDragHighlight(true)
return .copy
}
@@ -93,58 +96,69 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {
}
override func prepareForDragOperation(_ sender: any NSDraggingInfo) -> Bool {
- droppedInstallPackageURL(from: sender) != nil
+ !droppedFileURLs(from: sender).isEmpty
}
override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool {
updateDragHighlight(false)
- guard let url = droppedInstallPackageURL(from: sender) else { return false }
+ let urls = droppedFileURLs(from: sender)
+ guard !urls.isEmpty else { return false }
+ let packagesOnly = urls.allSatisfy(VPhoneInstallPackage.isSupportedFile)
+ let title = packagesOnly ? "Install App Package" : "Dropped Files"
Task { @MainActor in
guard let control, control.isConnected else {
VPhoneAlert.present(
- title: "Install App Package",
+ title: title,
message: "The guest agent is not connected. Wait for it to connect, then try again.",
style: .warning,
)
return
}
- do {
- let result = try await control.installIPA(localURL: url)
- print("[install] \(result)")
- VPhoneAlert.present(
- title: "Install App Package",
- message: VPhoneLocalization.installedMessage(
- for: url.lastPathComponent,
- detail: result,
- ),
- style: .informational,
- )
- } catch {
- VPhoneAlert.present(
- title: "Install App Package",
- message: "Unable to install the app package. Check the file and guest connection, then try again.",
- style: .warning,
- )
+ var lines: [String] = []
+ var failed = false
+ for url in urls {
+ let name = url.lastPathComponent
+ if VPhoneInstallPackage.isSupportedFile(url) {
+ do {
+ let result = try await control.installIPA(localURL: url)
+ print("[install] \(result)")
+ lines.append(VPhoneLocalization.installedMessage(for: name, detail: result))
+ } catch {
+ failed = true
+ lines.append(VPhoneLocalization.format("Unable to install %@.", name))
+ }
+ } else {
+ do {
+ let saved = try await control.saveDroppedFile(localURL: url)
+ print("[drop] saved \(name) as \(saved)")
+ lines.append(VPhoneLocalization.format(
+ "Saved “%@” to On My iPhone › %@ in Files.", saved, VPhoneGuestControl.dropFolder,
+ ))
+ } catch {
+ failed = true
+ lines.append(VPhoneLocalization.format(
+ "Unable to upload “%@”. Check the connection, then try again.", name,
+ ))
+ }
+ }
}
+ VPhoneAlert.present(
+ title: title,
+ message: lines.joined(separator: "\n"),
+ style: failed ? .warning : .informational,
+ )
}
return true
}
- private func droppedInstallPackageURL(from sender: any NSDraggingInfo) -> URL? {
+ private func droppedFileURLs(from sender: any NSDraggingInfo) -> [URL] {
let options: [NSPasteboard.ReadingOptionKey: Any] = [
.urlReadingFileURLsOnly: true,
]
- guard
- let urls = sender.draggingPasteboard.readObjects(
- forClasses: [NSURL.self],
- options: options,
- ) as? [URL]
- else {
- return nil
- }
- return urls.first(where: VPhoneInstallPackage.isSupportedFile)
+ let urls = sender.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: options) as? [URL] ?? []
+ return urls.filter { (try? $0.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true }
}
private func updateDragHighlight(_ visible: Bool) {