Run a virtual iPhone on an Apple Silicon Mac.
Swift
Split Guest Tools into Clipboard and Preferences windows
Lakr2331e9350a69c11
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swiftindex 88516d9d..a75c8a7e 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swift@@ -9,6 +9,7 @@ struct VPhoneFileBrowserView: View {@State private var newFolderName = ""@State private var fileToRename: VPhoneRemoteFile?@State private var renameName = ""+ @State private var isDropTargeted = falseprivate let controlBarHeight: CGFloat = 24@@ -19,7 +20,6 @@ struct VPhoneFileBrowserView: View {.overlay(controlBar.frame(maxHeight: .infinity, alignment: .bottom)).opacity(model.isTransferring ? 0.25 : 1).searchable(text: $model.searchText, prompt: "Filter files")- .onDrop(of: [.fileURL], isTargeted: nil, perform: dropFiles).disabled(model.isTransferring).toolbar { toolbarContent }if model.isTransferring {@@ -28,8 +28,12 @@ struct VPhoneFileBrowserView: View {.background(.thickMaterial).zIndex(100)}+ if isDropTargeted {+ dropHighlight+ }}.frame(maxWidth: .infinity, maxHeight: .infinity)+ .onDrop(of: [.fileURL], isTargeted: $isDropTargeted, perform: dropFiles).task { await model.refresh() }.alert("Error",@@ -335,8 +339,11 @@ struct VPhoneFileBrowserView: View {panel.allowsMultipleSelection = truepanel.canChooseFiles = truepanel.canChooseDirectories = false- guard panel.runModal() == .OK else { return }- Task { await model.uploadFiles(urls: panel.urls) }+ // Toolbar and context menu actions come from the Files window, which is key.+ VPhoneAlert.present(panel, on: NSApp.keyWindow) { response in+ guard response == .OK else { return }+ Task { await model.uploadFiles(urls: panel.urls) }+ }}func downloadAction() {@@ -345,8 +352,10 @@ struct VPhoneFileBrowserView: View {panel.canChooseFiles = falsepanel.canChooseDirectories = truepanel.prompt = VPhoneLocalization.text("Save Here")- guard panel.runModal() == .OK, let url = panel.url else { return }- Task { await model.downloadSelected(to: url) }+ VPhoneAlert.present(panel, on: NSApp.keyWindow) { response in+ guard response == .OK, let url = panel.url else { return }+ Task { await model.downloadSelected(to: url) }+ }}func createFolder() {@@ -369,7 +378,25 @@ struct VPhoneFileBrowserView: View {&& !trimmed.contains("/") && !trimmed.contains("\0")}+ /// Shown over the whole window while files are dragged in from Finder.+ var dropHighlight: some View {+ RoundedRectangle(cornerRadius: 8)+ .strokeBorder(Color.accentColor, lineWidth: 2)+ .background(Color.accentColor.opacity(0.08))+ .overlay {+ Label("Drop to Upload to \(model.currentPath)", systemImage: "square.and.arrow.up")+ .font(.headline)+ .padding(.horizontal, 14)+ .padding(.vertical, 8)+ .background(.regularMaterial, in: Capsule())+ }+ .padding(4)+ .allowsHitTesting(false)+ .accessibilityHidden(true)+ }+func dropFiles(_ providers: [NSItemProvider]) -> Bool {+ guard !model.isTransferring else { return false }let validProviders = providers.filter { $0.canLoadObject(ofClass: URL.self) }guard !validProviders.isEmpty else { return false }Task { @MainActor indiff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestClipboardModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestClipboardModel.swiftnew file mode 100644index 00000000..483f9eff--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestClipboardModel.swift@@ -0,0 +1,105 @@+import AppKit+import Foundation++@MainActor+@Observable+final class VPhoneGuestClipboardModel {+ enum Activity {+ case reading+ case sending++ var title: String {+ switch self {+ case .reading: "Reading guest clipboard…"+ case .sending: "Sending text to guest…"+ }+ }+ }++ let control: VPhoneGuestControl+ var mode: VPhoneGuestToolMode = .read+ /// Set to move focus to the compose editor the next time the view updates.+ var focusComposeRequested = false+ private(set) var activity: Activity?+ private(set) var status: VPhoneGuestToolStatus?+ private(set) var clipboard: VPhoneGuestControl.ClipboardContent?+ private(set) var readDate: Date?+ var composeText = ""++ var isBusy: Bool { activity != nil }+ var canCopyText: Bool { clipboard?.text != nil }+ var canCopyImage: Bool { clipboard?.imageData != nil }+ var canSend: Bool { !composeText.isEmpty && !isBusy }++ init(control: VPhoneGuestControl) {+ self.control = control+ }++ // MARK: - Read++ func refresh() async {+ guard activity == nil else { return }+ activity = .reading+ defer { activity = nil }+ do {+ clipboard = try await control.clipboardGet()+ readDate = .now+ status = nil+ } catch {+ fail("Unable to read the guest clipboard. Check the connection, then try again.")+ }+ }++ func copyTextToMac() {+ guard let text = clipboard?.text else { return }+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ succeed("Copied guest text to the Mac clipboard.")+ }++ func copyImageToMac() {+ guard let data = clipboard?.imageData, let image = NSImage(data: data) else { return }+ NSPasteboard.general.clearContents()+ NSPasteboard.general.writeObjects([image])+ succeed("Copied guest image to the Mac clipboard.")+ }++ // MARK: - Write++ func send() async {+ let text = composeText+ guard !text.isEmpty, activity == nil else { return }+ activity = .sending+ do {+ try await control.clipboardSet(text: text)+ } catch {+ activity = nil+ fail("Unable to set the guest clipboard. Check the connection, then try again.")+ return+ }+ activity = nil++ // Read it back so Read mode shows what the guest now holds.+ await refresh()+ succeed("Sent \(text.count == 1 ? "1 character" : "\(text.count) characters") to the guest clipboard.")+ }++ func pasteFromMac() {+ guard let text = NSPasteboard.general.string(forType: .string) else {+ fail("The Mac clipboard has no text.")+ return+ }+ composeText = text+ status = nil+ }++ // MARK: - Status++ private func succeed(_ message: String) {+ status = VPhoneGuestToolStatus(message: message, isError: false)+ }++ private func fail(_ message: String) {+ status = VPhoneGuestToolStatus(message: message, isError: true)+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestClipboardView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestClipboardView.swiftnew file mode 100644index 00000000..1f508140--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestClipboardView.swift@@ -0,0 +1,175 @@+import SwiftUI++struct VPhoneGuestClipboardView: View {+ @Bindable var model: VPhoneGuestClipboardModel+ @FocusState private var composeFocused: Bool++ var body: some View {+ VStack(spacing: 0) {+ Group {+ switch model.mode {+ case .read: readPane+ case .write: writePane+ }+ }+ .padding(16)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)++ Divider()+ VPhoneGuestToolStatusBar(+ isConnected: model.control.isConnected,+ activity: model.activity?.title,+ status: model.status,+ )+ }+ .toolbar { toolbar }+ .guestToolShortcuts([+ VPhoneGuestToolShortcut(key: "1") { model.mode = .read },+ VPhoneGuestToolShortcut(key: "2") { model.mode = .write },+ VPhoneGuestToolShortcut(key: "r", isEnabled: model.mode == .read && !model.isBusy) {+ Task { await model.refresh() }+ },+ VPhoneGuestToolShortcut(key: .return, isEnabled: model.mode == .write && model.canSend) {+ Task { await model.send() }+ },+ ])+ .onAppear(perform: applyFocusRequest)+ .onChange(of: model.focusComposeRequested) { _, _ in applyFocusRequest() }+ .onChange(of: model.mode) { _, mode in+ if mode == .read, model.clipboard == nil {+ Task { await model.refresh() }+ } else if mode == .write {+ composeFocused = true+ }+ }+ }++ // MARK: - Toolbar++ @ToolbarContentBuilder+ private var toolbar: some ToolbarContent {+ ToolbarItem(placement: .principal) {+ VPhoneGuestToolModePicker(mode: $model.mode)+ }++ switch model.mode {+ case .read:+ ToolbarItemGroup(placement: .primaryAction) {+ Button("Copy Text", systemImage: "doc.on.doc") { model.copyTextToMac() }+ .help("Copy the guest text to the Mac clipboard")+ .disabled(!model.canCopyText)+ Button("Copy Image", systemImage: "photo.on.rectangle") { model.copyImageToMac() }+ .help("Copy the guest image to the Mac clipboard")+ .disabled(!model.canCopyImage)+ Button("Refresh", systemImage: "arrow.clockwise") { Task { await model.refresh() } }+ .help("Read the guest clipboard again (⌘R)")+ .disabled(model.isBusy)+ }+ case .write:+ ToolbarItemGroup(placement: .primaryAction) {+ Button("Paste from Mac", systemImage: "doc.on.clipboard") { model.pasteFromMac() }+ .help("Replace the text below with the Mac clipboard text")+ Button("Send", systemImage: "paperplane") { Task { await model.send() } }+ .help("Set the guest clipboard to this text (⌘↩)")+ .disabled(!model.canSend)+ }+ }+ }++ // MARK: - Read++ @ViewBuilder+ private var readPane: some View {+ if let clipboard = model.clipboard {+ VStack(alignment: .leading, spacing: 12) {+ HStack(alignment: .top, spacing: 24) {+ VPhoneGuestToolsField(title: "Change Count", value: String(clipboard.changeCount))+ VPhoneGuestToolsField(+ title: "Read At",+ value: model.readDate?.formatted(date: .omitted, time: .standard) ?? "—",+ )+ VPhoneGuestToolsField(+ title: "Types",+ value: clipboard.types.isEmpty ? "None" : clipboard.types.joined(separator: ", "),+ )+ }+ content(clipboard)+ }+ } else if model.activity == .reading {+ ProgressView()+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ ContentUnavailableView {+ Label("Clipboard Not Read", systemImage: "doc.on.clipboard")+ } description: {+ Text("Choose Refresh to read the guest clipboard's text, image and types.")+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ }++ @ViewBuilder+ private func content(_ clipboard: VPhoneGuestControl.ClipboardContent) -> some View {+ let image = clipboard.imageData.flatMap(NSImage.init(data:))+ if clipboard.text == nil, image == nil {+ ContentUnavailableView(+ "Clipboard Empty",+ systemImage: "clipboard",+ description: Text("The guest clipboard holds no text or image. Copy something in the guest, then refresh."),+ )+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ HStack(alignment: .top, spacing: 12) {+ if let text = clipboard.text {+ ScrollView {+ Text(text)+ .font(.system(.body, design: .monospaced))+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(10)+ }+ .background(Color(nsColor: .textBackgroundColor))+ .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(nsColor: .separatorColor)))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ .accessibilityLabel("Guest clipboard text")+ }+ if let image {+ Image(nsImage: image)+ .resizable()+ .scaledToFit()+ .frame(maxWidth: clipboard.text == nil ? .infinity : 220, maxHeight: .infinity)+ .background(Color(nsColor: .textBackgroundColor))+ .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(nsColor: .separatorColor)))+ .accessibilityLabel("Guest clipboard image")+ }+ }+ .frame(maxHeight: .infinity)+ }+ }++ // MARK: - Write++ private var writePane: some View {+ VStack(alignment: .leading, spacing: 8) {+ TextEditor(text: $model.composeText)+ .font(.system(.body, design: .monospaced))+ .scrollContentBackground(.hidden)+ .padding(6)+ .background(Color(nsColor: .textBackgroundColor))+ .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(nsColor: .separatorColor)))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ .focused($composeFocused)+ .accessibilityLabel("Text to send to the guest clipboard")++ Text(model.composeText.count == 1 ? "1 character" : "\(model.composeText.count) characters")+ .font(.system(.caption, design: .monospaced))+ .foregroundStyle(.secondary)+ }+ }++ private func applyFocusRequest() {+ guard model.focusComposeRequested else { return }+ composeFocused = true+ model.focusComposeRequested = false+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestPreferenceEntry.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestPreferenceEntry.swiftnew file mode 100644index 00000000..9edb31d3--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestPreferenceEntry.swift@@ -0,0 +1,202 @@+import Foundation++// MARK: - Value Type++/// The scalar types `settings.set` accepts. The raw value is the wire name.+enum VPhoneGuestPreferenceType: String, CaseIterable, Identifiable {+ case string+ case bool+ case int+ case float++ var id: Self { self }++ var title: String {+ switch self {+ case .string: "String"+ case .bool: "Boolean"+ case .int: "Integer"+ case .float: "Float"+ }+ }++ var prompt: String {+ switch self {+ case .string: "Text"+ case .bool: "true or false"+ case .int: "42"+ case .float: "3.14"+ }+ }++ /// Parses text typed by the user into the value sent to the guest.+ func parse(_ text: String) -> Result<Any, VPhoneGuestPreferenceParseError> {+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ switch self {+ case .string:+ return .success(text)+ case .bool:+ switch trimmed.lowercased() {+ case "true", "yes", "1": return .success(true)+ case "false", "no", "0": return .success(false)+ default: return .failure(.init(message: "Enter true or false for a Boolean value."))+ }+ case .int:+ guard let number = Int64(trimmed) else {+ return .failure(.init(message: "Enter a whole number for an Integer value."))+ }+ return .success(number)+ case .float:+ guard let number = Double(trimmed), number.isFinite else {+ return .failure(.init(message: "Enter a finite number for a Float value."))+ }+ return .success(number)+ }+ }+}++struct VPhoneGuestPreferenceParseError: Error {+ let message: String+}++// MARK: - Entry++/// One node of a preference value as the guest returned it. Dictionaries and+/// arrays carry children so the result reads as an outline.+struct VPhoneGuestPreferenceEntry: Identifiable {+ enum Kind {+ case string+ case bool+ case int+ case float+ case date+ case data+ case array+ case dictionary+ case null+ }++ let id: String+ let key: String+ let kind: Kind+ let summary: String+ let children: [VPhoneGuestPreferenceEntry]?++ var typeTitle: String {+ switch kind {+ case .string: "String"+ case .bool: "Boolean"+ case .int: "Integer"+ case .float: "Float"+ case .date: "Date"+ case .data: "Data"+ case .array: "Array"+ case .dictionary: "Dictionary"+ case .null: "Null"+ }+ }++ /// The write type that round-trips this entry, when it is a scalar.+ var writableType: VPhoneGuestPreferenceType? {+ switch kind {+ case .string: .string+ case .bool: .bool+ case .int: .int+ case .float: .float+ default: nil+ }+ }++ init(key: String, value: Any?, path: String? = nil) {+ let path = path ?? key+ id = path+ self.key = key++ switch value {+ case nil, is NSNull:+ kind = .null+ summary = "—"+ children = nil+ case let number as NSNumber where CFGetTypeID(number) == CFBooleanGetTypeID():+ kind = .bool+ summary = number.boolValue ? "true" : "false"+ children = nil+ case let number as NSNumber:+ let isFloat = CFNumberIsFloatType(number)+ kind = isFloat ? .float : .int+ summary = isFloat ? String(number.doubleValue) : String(number.int64Value)+ children = nil+ case let string as String:+ kind = .string+ summary = string+ children = nil+ case let date as Date:+ kind = .date+ summary = date.ISO8601Format()+ children = nil+ case let data as Data:+ kind = .data+ summary = ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: .binary)+ children = nil+ case let array as [Any]:+ kind = .array+ summary = array.count == 1 ? "1 item" : "\(array.count) items"+ children = array.enumerated().map { index, element in+ VPhoneGuestPreferenceEntry(key: "[\(index)]", value: element, path: "\(path)/\(index)")+ }+ case let dictionary as [String: Any]:+ kind = .dictionary+ summary = dictionary.count == 1 ? "1 key" : "\(dictionary.count) keys"+ children = Self.entries(from: dictionary, path: path)+ default:+ kind = .string+ summary = String(describing: value!)+ children = nil+ }+ }++ static func entries(from dictionary: [String: Any], path: String = "") -> [VPhoneGuestPreferenceEntry] {+ dictionary.keys+ .sorted { $0.localizedStandardCompare($1) == .orderedAscending }+ .map { VPhoneGuestPreferenceEntry(key: $0, value: dictionary[$0], path: "\(path)/\($0)") }+ }+}++// MARK: - Read Result++struct VPhoneGuestPreferenceReadResult {+ let domain: String+ /// Nil when the whole domain was read.+ let key: String?+ let entries: [VPhoneGuestPreferenceEntry]+ /// Pretty-printed JSON, or a plain description for scalars.+ let text: String++ init(domain: String, key: String?, value: Any?) {+ self.domain = domain+ self.key = key++ if key == nil, let dictionary = value as? [String: Any] {+ entries = VPhoneGuestPreferenceEntry.entries(from: dictionary)+ } else if let key, value != nil, !(value is NSNull) {+ entries = [VPhoneGuestPreferenceEntry(key: key, value: value)]+ } else {+ entries = []+ }++ if let value, JSONSerialization.isValidJSONObject(value),+ let data = try? JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .sortedKeys]),+ let string = String(data: data, encoding: .utf8)+ {+ text = string+ } else if let value, !(value is NSNull) {+ text = String(describing: value)+ } else {+ text = ""+ }+ }++ var title: String {+ key.map { "\(domain) › \($0)" } ?? domain+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestPreferencesModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestPreferencesModel.swiftnew file mode 100644index 00000000..232f5951--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestPreferencesModel.swift@@ -0,0 +1,166 @@+import AppKit+import Foundation++@MainActor+@Observable+final class VPhoneGuestPreferencesModel {+ enum Activity {+ case reading+ case writing++ var title: String {+ switch self {+ case .reading: "Reading preference…"+ case .writing: "Writing preference…"+ }+ }+ }++ enum Field: Hashable {+ case domain+ case readKey+ case writeKey+ case value+ }++ enum ResultStyle: String, CaseIterable, Identifiable {+ case outline+ case json++ var id: Self { self }+ var title: String { self == .outline ? "Outline" : "JSON" }+ var symbol: String { self == .outline ? "list.bullet.indent" : "curlybraces" }+ }++ static let suggestedDomains = [+ "com.apple.springboard",+ "com.apple.Preferences",+ "com.apple.UIKit",+ ".GlobalPreferences",+ "com.apple.mobilesafari",+ ]++ let control: VPhoneGuestControl+ var mode: VPhoneGuestToolMode = .read+ /// A field the view should focus the next time it updates.+ var focusRequest: Field?+ private(set) var activity: Activity?+ private(set) var status: VPhoneGuestToolStatus?++ var domain = ""+ var readKey = ""+ var resultStyle: ResultStyle = .outline+ private(set) var readResult: VPhoneGuestPreferenceReadResult?+ var writeKey = ""+ var writeType: VPhoneGuestPreferenceType = .string+ var writeValue = ""++ var isBusy: Bool { activity != nil }+ var trimmedDomain: String { domain.trimmingCharacters(in: .whitespacesAndNewlines) }+ var trimmedWriteKey: String { writeKey.trimmingCharacters(in: .whitespacesAndNewlines) }+ var canRead: Bool { !trimmedDomain.isEmpty && !isBusy }+ var canWrite: Bool { !trimmedDomain.isEmpty && !trimmedWriteKey.isEmpty && !isBusy }+ var canCopyResult: Bool { !(readResult?.text.isEmpty ?? true) }++ /// The last value read for the key in the write form, if any.+ var currentWriteValue: VPhoneGuestPreferenceEntry? {+ guard let readResult, readResult.domain == trimmedDomain else { return nil }+ return readResult.entries.first { $0.key == trimmedWriteKey }+ }++ init(control: VPhoneGuestControl) {+ self.control = control+ }++ // MARK: - Read++ func read() async {+ let domain = trimmedDomain+ let key = readKey.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !domain.isEmpty, activity == nil else { return }+ activity = .reading+ defer { activity = nil }+ do {+ let value = try await control.settingsGet(domain: domain, key: key.isEmpty ? nil : key)+ let result = VPhoneGuestPreferenceReadResult(domain: domain, key: key.isEmpty ? nil : key, value: value)+ readResult = result+ if result.entries.isEmpty, result.text.isEmpty {+ succeed(key.isEmpty ? "\(domain) has no values." : "\(key) is not set in \(domain).")+ } else {+ status = nil+ }+ } catch {+ fail("Unable to read that preference. Check the domain and key, then try again.")+ }+ }++ func copyResult() {+ guard let text = readResult?.text, !text.isEmpty else { return }+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ succeed("Copied the result as JSON.")+ }++ /// Whether an entry is a top-level scalar the write form can round-trip.+ func canEdit(_ entry: VPhoneGuestPreferenceEntry) -> Bool {+ entry.writableType != nil && readResult?.entries.contains { $0.id == entry.id } == true+ }++ /// Loads a top-level scalar into the write form. With `switchToWrite`,+ /// the window also moves to Write mode with the value focused.+ func edit(_ entry: VPhoneGuestPreferenceEntry, switchToWrite: Bool) {+ guard canEdit(entry), let type = entry.writableType else { return }+ writeKey = entry.key+ writeType = type+ writeValue = entry.summary+ if switchToWrite {+ mode = .write+ focusRequest = .value+ }+ }++ // MARK: - Write++ func write() async {+ let domain = trimmedDomain+ let key = trimmedWriteKey+ guard !domain.isEmpty, !key.isEmpty else {+ fail("Enter a domain and key.")+ return+ }+ let value: Any+ switch writeType.parse(writeValue) {+ case let .success(parsed): value = parsed+ case let .failure(error):+ fail(error.message)+ return+ }++ guard activity == nil else { return }+ activity = .writing+ do {+ try await control.settingsSet(domain: domain, key: key, value: value, type: writeType.rawValue)+ } catch {+ activity = nil+ fail("Unable to write that preference. Check the connection, then try again.")+ return+ }+ activity = nil++ // Read the domain back so Read mode shows what the guest stored.+ if readResult?.domain == domain {+ await read()+ }+ succeed("Wrote \(key) to \(domain).")+ }++ // MARK: - Status++ private func succeed(_ message: String) {+ status = VPhoneGuestToolStatus(message: message, isError: false)+ }++ private func fail(_ message: String) {+ status = VPhoneGuestToolStatus(message: message, isError: true)+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestPreferencesView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestPreferencesView.swiftnew file mode 100644index 00000000..19c04dd4--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestPreferencesView.swift@@ -0,0 +1,272 @@+import SwiftUI++struct VPhoneGuestPreferencesView: View {+ @Bindable var model: VPhoneGuestPreferencesModel+ @FocusState private var focus: VPhoneGuestPreferencesModel.Field?+ @State private var selection: VPhoneGuestPreferenceEntry.ID?++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ domainBar+ .padding(12)+ Divider()+ Group {+ switch model.mode {+ case .read: resultPane+ case .write: writeForm+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ Divider()+ VPhoneGuestToolStatusBar(+ isConnected: model.control.isConnected,+ activity: model.activity?.title,+ status: model.status,+ )+ }+ .toolbar { toolbar }+ .guestToolShortcuts([+ VPhoneGuestToolShortcut(key: "1") { model.mode = .read },+ VPhoneGuestToolShortcut(key: "2") { model.mode = .write },+ VPhoneGuestToolShortcut(key: "r", isEnabled: model.mode == .read && model.canRead) {+ Task { await model.read() }+ },+ VPhoneGuestToolShortcut(key: .return, isEnabled: model.mode == .write && model.canWrite) {+ Task { await model.write() }+ },+ ])+ .onAppear(perform: applyFocusRequest)+ .onChange(of: model.focusRequest) { _, _ in applyFocusRequest() }+ .onChange(of: selection) { _, id in+ // A single click fills the write form; double-click also opens it.+ guard let id, let entry = entry(for: id) else { return }+ model.edit(entry, switchToWrite: false)+ }+ }++ // MARK: - Toolbar++ @ToolbarContentBuilder+ private var toolbar: some ToolbarContent {+ ToolbarItem(placement: .principal) {+ VPhoneGuestToolModePicker(mode: $model.mode)+ }++ switch model.mode {+ case .read:+ ToolbarItemGroup(placement: .primaryAction) {+ Picker("Result Style", selection: $model.resultStyle) {+ ForEach(VPhoneGuestPreferencesModel.ResultStyle.allCases) { style in+ Label(style.title, systemImage: style.symbol).tag(style)+ }+ }+ .pickerStyle(.segmented)+ .help("Show the result as an outline or as JSON")+ .disabled(model.readResult == nil)+ Button("Copy JSON", systemImage: "doc.on.doc") { model.copyResult() }+ .help("Copy the result as JSON")+ .disabled(!model.canCopyResult)+ Button("Read", systemImage: "arrow.clockwise") { Task { await model.read() } }+ .help("Read the key, or every key in the domain when Key is empty (⌘R)")+ .disabled(!model.canRead)+ }+ case .write:+ ToolbarItem(placement: .primaryAction) {+ Button("Write", systemImage: "square.and.arrow.down") { Task { await model.write() } }+ .help("Write this value to the guest (⌘↩)")+ .disabled(!model.canWrite)+ }+ }+ }++ // MARK: - Domain++ private var domainBar: some View {+ HStack(alignment: .firstTextBaseline, spacing: 8) {+ Text("Domain")+ .foregroundStyle(.secondary)+ TextField("Domain", text: $model.domain, prompt: Text("com.apple.springboard"))+ .focused($focus, equals: .domain)+ .onSubmit(submit)+ Menu {+ ForEach(VPhoneGuestPreferencesModel.suggestedDomains, id: \.self) { domain in+ Button(domain) { model.domain = domain }+ }+ } label: {+ Image(systemName: "chevron.down")+ }+ .menuStyle(.borderlessButton)+ .menuIndicator(.hidden)+ .fixedSize()+ .help("Common preference domains")+ .accessibilityLabel("Common domains")++ if model.mode == .read {+ Text("Key")+ .foregroundStyle(.secondary)+ TextField("Key", text: $model.readKey, prompt: Text("All keys"))+ .focused($focus, equals: .readKey)+ .onSubmit(submit)+ .frame(maxWidth: 220)+ }+ }+ .textFieldStyle(.roundedBorder)+ .font(.system(.body, design: .monospaced))+ .labelsHidden()+ }++ // MARK: - Read++ @ViewBuilder+ private var resultPane: some View {+ if let result = model.readResult {+ if model.resultStyle == .json || result.entries.isEmpty {+ jsonView(result)+ } else {+ outline(result)+ }+ } else if model.activity == .reading {+ ProgressView()+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ ContentUnavailableView(+ "No Preference Read",+ systemImage: "list.bullet.rectangle",+ description: Text("Enter a domain, then choose Read. Leave Key empty to read every key in the domain."),+ )+ }+ }++ private func outline(_ result: VPhoneGuestPreferenceReadResult) -> some View {+ Table(result.entries, children: \.children, selection: $selection) {+ TableColumn("Key") { entry in+ Text(entry.key)+ .font(.system(.body, design: .monospaced))+ .help(entry.key)+ }+ .width(min: 140, ideal: 220)++ TableColumn("Type") { entry in+ Text(entry.typeTitle)+ .foregroundStyle(.secondary)+ }+ .width(min: 70, ideal: 90, max: 110)++ TableColumn("Value") { entry in+ Text(entry.summary)+ .font(.system(.body, design: .monospaced))+ .foregroundStyle(entry.children == nil ? .primary : .secondary)+ .lineLimit(1)+ .help(entry.summary)+ }+ }+ .contextMenu(forSelectionType: VPhoneGuestPreferenceEntry.ID.self) { ids in+ if let id = ids.first, let entry = entry(for: id) {+ Button("Edit Value…") { model.edit(entry, switchToWrite: true) }+ .disabled(!model.canEdit(entry))+ Divider()+ Button("Copy Key") { copy(entry.key) }+ Button("Copy Value") { copy(entry.summary) }+ .disabled(entry.children != nil)+ }+ } primaryAction: { ids in+ if let id = ids.first, let entry = entry(for: id) {+ model.edit(entry, switchToWrite: true)+ }+ }+ .accessibilityLabel("Preference values for \(result.title)")+ }++ private func jsonView(_ result: VPhoneGuestPreferenceReadResult) -> some View {+ ScrollView {+ Text(result.text.isEmpty ? "No value." : result.text)+ .font(.system(.body, design: .monospaced))+ .foregroundStyle(result.text.isEmpty ? .secondary : .primary)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(12)+ }+ .background(Color(nsColor: .textBackgroundColor))+ .accessibilityLabel("Preference value for \(result.title)")+ }++ // MARK: - Write++ private var writeForm: some View {+ Form {+ TextField("Key", text: $model.writeKey, prompt: Text("Preference key"))+ .focused($focus, equals: .writeKey)+ .onSubmit(submit)++ Picker("Type", selection: $model.writeType) {+ ForEach(VPhoneGuestPreferenceType.allCases) { type in+ Text(type.title).tag(type)+ }+ }++ valueField++ if let current = model.currentWriteValue {+ LabeledContent("Current Value") {+ Text("\(current.summary) (\(current.typeTitle))")+ .foregroundStyle(.secondary)+ .textSelection(.enabled)+ }+ }+ }+ .formStyle(.grouped)+ .font(.system(.body, design: .monospaced))+ }++ @ViewBuilder+ private var valueField: some View {+ if model.writeType == .bool {+ Picker("Value", selection: $model.writeValue) {+ Text("true").tag("true")+ Text("false").tag("false")+ }+ .pickerStyle(.segmented)+ .focused($focus, equals: .value)+ .onAppear {+ if case .failure = model.writeType.parse(model.writeValue) {+ model.writeValue = "true"+ }+ }+ } else {+ TextField("Value", text: $model.writeValue, prompt: Text(model.writeType.prompt))+ .focused($focus, equals: .value)+ .onSubmit(submit)+ }+ }++ // MARK: - Helpers++ private func submit() {+ switch model.mode {+ case .read: Task { await model.read() }+ case .write: Task { await model.write() }+ }+ }++ private func entry(for id: VPhoneGuestPreferenceEntry.ID) -> VPhoneGuestPreferenceEntry? {+ func find(_ entries: [VPhoneGuestPreferenceEntry]) -> VPhoneGuestPreferenceEntry? {+ for entry in entries {+ if entry.id == id { return entry }+ if let match = entry.children.flatMap(find) { return match }+ }+ return nil+ }+ return model.readResult.flatMap { find($0.entries) }+ }++ private func copy(_ text: String) {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ }++ private func applyFocusRequest() {+ guard let request = model.focusRequest else { return }+ focus = request+ model.focusRequest = nil+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestToolsShared.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestToolsShared.swiftnew file mode 100644index 00000000..2f4e2845--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestToolsShared.swift@@ -0,0 +1,139 @@+import SwiftUI++// MARK: - Mode++/// The toolbar switch each guest tool window shows.+enum VPhoneGuestToolMode: String, CaseIterable, Identifiable {+ case read+ case write++ var id: Self { self }++ var title: String {+ switch self {+ case .read: "Read"+ case .write: "Write"+ }+ }++ var shortcut: KeyEquivalent {+ switch self {+ case .read: "1"+ case .write: "2"+ }+ }+}++struct VPhoneGuestToolModePicker: View {+ @Binding var mode: VPhoneGuestToolMode++ var body: some View {+ Picker("Mode", selection: $mode) {+ ForEach(VPhoneGuestToolMode.allCases) { mode in+ Text(mode.title).tag(mode)+ }+ }+ .pickerStyle(.segmented)+ .labelsHidden()+ .fixedSize()+ .help("Switch between reading from and writing to the guest (⌘1, ⌘2)")+ }+}++// MARK: - Status++struct VPhoneGuestToolStatus {+ let message: String+ let isError: Bool+}++/// The bottom bar shared by the guest windows: connection, activity, result.+struct VPhoneGuestToolStatusBar: View {+ let isConnected: Bool+ let activity: String?+ let status: VPhoneGuestToolStatus?++ var body: some View {+ HStack(spacing: 8) {+ Circle()+ .fill(isConnected ? Color.green : Color.orange)+ .frame(width: 8, height: 8)+ .accessibilityLabel(isConnected ? "Guest connected" : "Guest disconnected")++ if let activity {+ ProgressView()+ .controlSize(.small)+ Text(activity)+ .foregroundStyle(.secondary)+ } else if let status {+ Image(systemName: status.isError ? "exclamationmark.triangle.fill" : "checkmark.circle.fill")+ .foregroundStyle(status.isError ? .orange : .green)+ Text(status.message)+ .foregroundStyle(status.isError ? .primary : .secondary)+ .textSelection(.enabled)+ } else {+ Text(isConnected ? "Connected" : "Guest not connected")+ .foregroundStyle(.secondary)+ }++ Spacer(minLength: 0)+ }+ .font(.system(size: 11, design: .monospaced))+ .lineLimit(1)+ .padding(.horizontal, 8)+ .frame(height: 24)+ .background(.bar)+ .accessibilityElement(children: .combine)+ .accessibilityAddTraits(.updatesFrequently)+ }+}++// MARK: - Shortcuts++/// A keyboard shortcut for a toolbar action.+struct VPhoneGuestToolShortcut {+ let key: KeyEquivalent+ var modifiers: EventModifiers = .command+ var isEnabled = true+ let action: () -> Void+}++extension View {+ /// Adds keyboard shortcuts for toolbar actions. The buttons are invisible+ /// but stay in the hosting view, where AppKit routes key equivalents.+ func guestToolShortcuts(_ shortcuts: [VPhoneGuestToolShortcut]) -> some View {+ background {+ ForEach(shortcuts.indices, id: \.self) { index in+ let shortcut = shortcuts[index]+ Button("", action: shortcut.action)+ .keyboardShortcut(shortcut.key, modifiers: shortcut.modifiers)+ .disabled(!shortcut.isEnabled)+ .opacity(0)+ .frame(width: 0, height: 0)+ .accessibilityHidden(true)+ }+ }+ }+}++// MARK: - Metadata++/// A small caption label above a value.+struct VPhoneGuestToolsField: View {+ let title: String+ let value: String++ var body: some View {+ VStack(alignment: .leading, spacing: 2) {+ Text(title)+ .font(.caption)+ .foregroundStyle(.secondary)+ Text(value)+ .font(.system(.body, design: .monospaced))+ .lineLimit(1)+ .truncationMode(.middle)+ .textSelection(.enabled)+ .help(value)+ }+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestToolsWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestToolsWindowController.swiftnew file mode 100644index 00000000..a77a262a--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/GuestTools/VPhoneGuestToolsWindowController.swift@@ -0,0 +1,130 @@+import AppKit+import SwiftUI++// MARK: - Entry Points++/// The Guest menu items that open a guest tool window.+enum VPhoneGuestToolAction {+ case getClipboard+ case setClipboard+ case readSetting+ case writeSetting+}++// MARK: - Window Controller++/// Owns the Clipboard and Preferences windows. They are separate windows+/// with their own models; this type only routes the Guest menu to them.+@MainActor+final class VPhoneGuestToolsWindowController {+ let clipboardModel: VPhoneGuestClipboardModel+ let preferencesModel: VPhoneGuestPreferencesModel+ private let clipboardWindow: VPhoneGuestToolWindow+ private let preferencesWindow: VPhoneGuestToolWindow++ init(control: VPhoneGuestControl) {+ let clipboardModel = VPhoneGuestClipboardModel(control: control)+ let preferencesModel = VPhoneGuestPreferencesModel(control: control)+ self.clipboardModel = clipboardModel+ self.preferencesModel = preferencesModel+ clipboardWindow = VPhoneGuestToolWindow(+ title: "Clipboard",+ autosaveName: "vphone-guest-clipboard",+ size: NSSize(width: 640, height: 480),+ minSize: NSSize(width: 480, height: 320),+ ) { VPhoneGuestClipboardView(model: clipboardModel) }+ preferencesWindow = VPhoneGuestToolWindow(+ title: "Preferences",+ autosaveName: "vphone-guest-preferences",+ size: NSSize(width: 760, height: 540),+ minSize: NSSize(width: 560, height: 360),+ ) { VPhoneGuestPreferencesView(model: preferencesModel) }+ }++ func show(_ action: VPhoneGuestToolAction) {+ switch action {+ case .getClipboard:+ clipboardModel.mode = .read+ clipboardWindow.show()+ Task { await clipboardModel.refresh() }+ case .setClipboard:+ clipboardModel.mode = .write+ clipboardModel.focusComposeRequested = true+ clipboardWindow.show()+ case .readSetting:+ preferencesModel.mode = .read+ preferencesModel.focusRequest = .domain+ preferencesWindow.show()+ case .writeSetting:+ preferencesModel.mode = .write+ preferencesModel.focusRequest = preferencesModel.trimmedDomain.isEmpty ? .domain : .writeKey+ preferencesWindow.show()+ }+ }+}++// MARK: - Window++/// One guest tool window. The SwiftUI content supplies the toolbar, which+/// the hosting controller bridges into the window.+@MainActor+final class VPhoneGuestToolWindow: NSObject, NSWindowDelegate {+ private let title: String+ private let autosaveName: String+ private let size: NSSize+ private let minSize: NSSize+ private let makeContent: () -> AnyView+ private var window: NSWindow?++ init(+ title: String,+ autosaveName: String,+ size: NSSize,+ minSize: NSSize,+ @ViewBuilder content: @escaping () -> some View,+ ) {+ self.title = title+ self.autosaveName = autosaveName+ self.size = size+ self.minSize = minSize+ makeContent = { AnyView(content()) }+ super.init()+ }++ func show() {+ let window = window ?? makeWindow()+ NSApp.activate(ignoringOtherApps: true)+ window.makeKeyAndOrderFront(nil)+ }++ private func makeWindow() -> NSWindow {+ let hostingController = NSHostingController(rootView: makeContent())+ hostingController.sceneBridgingOptions = [.toolbars]++ let window = NSWindow(+ contentRect: NSRect(origin: .zero, size: size),+ styleMask: [.titled, .closable, .resizable, .miniaturizable],+ backing: .buffered,+ defer: false,+ )+ window.title = title+ window.subtitle = "Guest"+ window.contentViewController = hostingController+ window.contentMinSize = minSize+ window.setContentSize(size)+ window.toolbarStyle = .unified+ window.isReleasedWhenClosed = false+ window.level = .normal+ window.delegate = self+ window.setFrameAutosaveName(autosaveName)+ if window.frame.origin == .zero {+ window.center()+ }+ self.window = window+ return window+ }++ nonisolated func windowWillClose(_: Notification) {+ MainActor.assumeIsolated { window = nil }+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneGuestToolsWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneGuestToolsWindowController.swiftdeleted file mode 100644index 375a9301..00000000--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneGuestToolsWindowController.swift+++ /dev/null@@ -1,520 +0,0 @@-import AppKit-import SwiftUI--enum VPhoneGuestToolPage: String, CaseIterable, Identifiable {- case getClipboard- case setClipboard- case readSetting- case writeSetting-- var id: Self {- self- }-- var title: String {- switch self {- case .getClipboard: VPhoneLocalization.text("Get Clipboard")- case .setClipboard: VPhoneLocalization.text("Set Clipboard Text")- case .readSetting: VPhoneLocalization.text("Read Setting")- case .writeSetting: VPhoneLocalization.text("Write Setting")- }- }-- var symbol: String {- switch self {- case .getClipboard: "doc.on.clipboard"- case .setClipboard: "square.and.pencil"- case .readSetting: "list.bullet.rectangle"- case .writeSetting: "slider.horizontal.3"- }- }-}--@MainActor-final class VPhoneGuestToolsWindowController: NSObject, NSWindowDelegate {- private var window: NSWindow?- private let model: VPhoneGuestToolsModel-- init(control: VPhoneGuestControl) {- model = VPhoneGuestToolsModel(control: control)- super.init()- }-- func show(_ page: VPhoneGuestToolPage) {- model.page = page-- if window == nil {- let window = NSWindow(- contentRect: NSRect(x: 0, y: 0, width: 840, height: 560),- styleMask: [.titled, .closable, .resizable, .miniaturizable],- backing: .buffered,- defer: false,- )- window.title = VPhoneLocalization.text("Guest Tools")- window.subtitle = VPhoneLocalization.text("Clipboard & Settings")- window.contentViewController = NSHostingController(rootView: VPhoneGuestToolsView(model: model))- window.contentMinSize = NSSize(width: 680, height: 440)- window.setContentSize(NSSize(width: 840, height: 560))- window.isReleasedWhenClosed = false- window.level = .normal- window.delegate = self- window.center()- self.window = window- }-- NSApp.activate(ignoringOtherApps: true)- window?.makeKeyAndOrderFront(nil)-- if page == .getClipboard {- Task { await model.refreshClipboard() }- }- }-- nonisolated func windowWillClose(_: Notification) {- MainActor.assumeIsolated { window = nil }- }-}--@MainActor-@Observable-final class VPhoneGuestToolsModel {- enum ValueType: String, CaseIterable, Identifiable {- case string- case bool- case int- case float-- var id: Self {- self- }-- var title: String {- switch self {- case .string: VPhoneLocalization.text("String")- case .bool: VPhoneLocalization.text("Boolean")- case .int: VPhoneLocalization.text("Integer")- case .float: VPhoneLocalization.text("Float")- }- }- }-- let control: VPhoneGuestControl- var page: VPhoneGuestToolPage = .getClipboard- var isBusy = false- var clipboardText: String?- var clipboardTypes: [String] = []- var clipboardHasImage = false- var clipboardImageData: Data?- var clipboardChangeCount = 0- var hasClipboardResult = false- var clipboardInput = ""- var readDomain = ""- var readKey = ""- var settingResult: String?- var writeDomain = ""- var writeKey = ""- var writeType: ValueType = .string- var writeValue = ""- var status: String?- var isError = false-- init(control: VPhoneGuestControl) {- self.control = control- }-- func refreshClipboard() async {- guard !isBusy else { return }- isBusy = true- defer { isBusy = false }- status = nil- do {- let content = try await control.clipboardGet()- clipboardText = content.text- clipboardTypes = content.types- clipboardHasImage = content.hasImage- clipboardImageData = content.imageData- clipboardChangeCount = content.changeCount- hasClipboardResult = true- } catch {- showError(- VPhoneLocalization.text("Unable to read the guest clipboard. Check the connection and try again."))- }- }-- func setClipboard() async {- guard !clipboardInput.isEmpty, !isBusy else { return }- isBusy = true- defer { isBusy = false }- do {- try await control.clipboardSet(text: clipboardInput)- showSuccess(VPhoneLocalization.text("Text set on the guest clipboard."))- } catch {- showError(VPhoneLocalization.text("Unable to set the guest clipboard. Check the connection and try again."))- }- }-- func readSetting() async {- let domain = readDomain.trimmingCharacters(in: .whitespacesAndNewlines)- let key = readKey.trimmingCharacters(in: .whitespacesAndNewlines)- guard !domain.isEmpty, !isBusy else { return }- isBusy = true- defer { isBusy = false }- status = nil- settingResult = nil- do {- let value = try await control.settingsGet(domain: domain, key: key.isEmpty ? nil : key)- if let value, JSONSerialization.isValidJSONObject(value) {- let data = try JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .sortedKeys])- settingResult = String(data: data, encoding: .utf8) ?? String(describing: value)- } else {- settingResult = value.map { String(describing: $0) } ?? VPhoneLocalization.text("Not set")- }- showSuccess(VPhoneLocalization.format("Read %@.", domain + (key.isEmpty ? "" : ".\(key)")))- } catch {- showError(VPhoneLocalization.text("Unable to read that setting. Check the domain and key, then try again."))- }- }-- func writeSetting() async {- let domain = writeDomain.trimmingCharacters(in: .whitespacesAndNewlines)- let key = writeKey.trimmingCharacters(in: .whitespacesAndNewlines)- guard !isBusy else { return }- guard !domain.isEmpty, !key.isEmpty else {- showError(VPhoneLocalization.text("Enter a domain and key."))- return- }-- let rawValue = writeValue.trimmingCharacters(in: .whitespacesAndNewlines)- let value: Any- switch writeType {- case .string:- value = writeValue- case .bool:- switch rawValue.lowercased() {- case "true", "yes", "1": value = true- case "false", "no", "0": value = false- default:- showError(VPhoneLocalization.text("Enter true or false for a Boolean value."))- return- }- case .int:- guard let number = Int64(rawValue) else {- showError(VPhoneLocalization.text("Enter a valid integer."))- return- }- value = number- case .float:- guard let number = Double(rawValue), number.isFinite else {- showError(VPhoneLocalization.text("Enter a finite number."))- return- }- value = number- }-- isBusy = true- defer { isBusy = false }- do {- try await control.settingsSet(domain: domain, key: key, value: value, type: writeType.rawValue)- showSuccess(VPhoneLocalization.format("Wrote %@.", "\(domain).\(key)"))- } catch {- showError(VPhoneLocalization.text("Unable to write that setting. Check the connection and try again."))- }- }-- func copy(_ text: String) {- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(text, forType: .string)- showSuccess(VPhoneLocalization.text("Copied to the Mac clipboard."))- }-- func copyImage() {- guard let clipboardImageData, let image = NSImage(data: clipboardImageData) else { return }- NSPasteboard.general.clearContents()- NSPasteboard.general.writeObjects([image])- showSuccess(VPhoneLocalization.text("Image copied to the Mac clipboard."))- }-- private func showSuccess(_ message: String) {- status = message- isError = false- }-- private func showError(_ message: String) {- status = message- isError = true- }-}--struct VPhoneGuestToolsView: View {- @Bindable var model: VPhoneGuestToolsModel- @FocusState private var focusedField: FocusedField?-- private enum FocusedField: Hashable {- case clipboardInput- case readDomain- case writeDomain- }-- var body: some View {- HStack(spacing: 0) {- sidebar- Divider()- VStack(alignment: .leading, spacing: 20) {- header- pageContent- Spacer(minLength: 0)- if let status = model.status {- Label(status, systemImage: model.isError ? "exclamationmark.triangle" : "checkmark.circle")- .foregroundStyle(model.isError ? .orange : .green)- .accessibilityAddTraits(.updatesFrequently)- }- }- .padding(24)- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)- }- .frame(maxWidth: .infinity, maxHeight: .infinity)- .onAppear(perform: focusCurrentPage)- .onChange(of: model.page) { _, _ in- model.status = nil- focusCurrentPage()- }- }-- private var sidebar: some View {- VStack(alignment: .leading, spacing: 8) {- Text("GUEST TOOLS")- .font(.system(.caption, design: .monospaced, weight: .semibold))- .foregroundStyle(.secondary)- .padding(.horizontal, 12)- .padding(.bottom, 8)-- ForEach(VPhoneGuestToolPage.allCases) { page in- Button {- model.page = page- if page == .getClipboard, !model.hasClipboardResult {- Task { await model.refreshClipboard() }- }- } label: {- Label(page.title, systemImage: page.symbol)- .frame(maxWidth: .infinity, alignment: .leading)- .padding(.horizontal, 12)- .padding(.vertical, 9)- .background(model.page == page ? Color.accentColor.opacity(0.18) : .clear)- .clipShape(RoundedRectangle(cornerRadius: 6))- }- .buttonStyle(.plain)- .accessibilityAddTraits(model.page == page ? .isSelected : [])- }- Spacer()- }- .padding(16)- .frame(width: 220)- .frame(maxHeight: .infinity)- .background(Color(nsColor: .windowBackgroundColor))- }-- private var header: some View {- VStack(alignment: .leading, spacing: 6) {- Text(model.page.title)- .font(.system(size: 22, weight: .semibold))- Text(pageDescription)- .foregroundStyle(.secondary)- }- }-- private var pageDescription: String {- switch model.page {- case .getClipboard: VPhoneLocalization.text("Inspect the guest clipboard and copy its text to your Mac.")- case .setClipboard: VPhoneLocalization.text("Send text from your Mac to the guest clipboard.")- case .readSetting:- VPhoneLocalization.text("Read one preference key, or leave the key empty to read all keys in the domain.")- case .writeSetting: VPhoneLocalization.text("Write a typed value to a guest preference key.")- }- }-- @ViewBuilder- private var pageContent: some View {- switch model.page {- case .getClipboard: clipboardReadPage- case .setClipboard: clipboardWritePage- case .readSetting: settingReadPage- case .writeSetting: settingWritePage- }- }-- private var clipboardReadPage: some View {- VStack(alignment: .leading, spacing: 16) {- HStack {- Button("Refresh") { Task { await model.refreshClipboard() } }- .disabled(model.isBusy)- Spacer()- Button("Copy Text") { model.copy(model.clipboardText ?? "") }- .disabled(model.clipboardText == nil)- Button("Copy Image") { model.copyImage() }- .disabled(model.clipboardImageData == nil)- }- if model.hasClipboardResult {- HStack(spacing: 24) {- metadata(- "Types",- model.clipboardTypes.isEmpty- ? VPhoneLocalization.text("None") : model.clipboardTypes.joined(separator: ", "))- metadata(- "Image",- model.clipboardHasImage ? VPhoneLocalization.text("Present") : VPhoneLocalization.text("None"))- metadata("Change Count", String(model.clipboardChangeCount))- }- resultBox(- model.clipboardText- ?? VPhoneLocalization.text(- "No text in the guest clipboard. Copy text in the guest, then refresh."))- if let data = model.clipboardImageData, let image = NSImage(data: data) {- Image(nsImage: image)- .resizable()- .scaledToFit()- .frame(maxHeight: 180)- .accessibilityLabel("Guest clipboard image")- }- } else if model.isBusy {- ProgressView("Reading guest clipboard…")- } else {- Text("Choose Refresh to read the guest clipboard.")- .foregroundStyle(.secondary)- }- }- }-- private var clipboardWritePage: some View {- VStack(alignment: .leading, spacing: 12) {- Text("Text")- .font(.headline)- TextEditor(text: $model.clipboardInput)- .font(.system(.body, design: .monospaced))- .focused($focusedField, equals: .clipboardInput)- .frame(minHeight: 180)- .accessibilityLabel("Text for guest clipboard")- .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(nsColor: .separatorColor)))- HStack {- Text(VPhoneLocalization.format("Characters: %@", String(model.clipboardInput.count)))- .font(.system(.caption, design: .monospaced))- .foregroundStyle(.secondary)- Spacer()- Button("Set Clipboard Text") { Task { await model.setClipboard() } }- .buttonStyle(.borderedProminent)- .disabled(model.clipboardInput.isEmpty || model.isBusy)- }- }- }-- private var settingReadPage: some View {- VStack(alignment: .leading, spacing: 16) {- HStack(spacing: 12) {- field("Domain", text: $model.readDomain, prompt: "com.apple.springboard")- .focused($focusedField, equals: .readDomain)- field("Key (Optional)", text: $model.readKey, prompt: "Leave empty for all keys")- }- HStack {- Button("Read Setting") { Task { await model.readSetting() } }- .buttonStyle(.borderedProminent)- .disabled(model.readDomain.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.isBusy)- Spacer()- if let result = model.settingResult {- Button("Copy Result") { model.copy(result) }- }- }- if let result = model.settingResult {- resultBox(result)- } else {- Text("Enter a domain and choose Read Setting.")- .foregroundStyle(.secondary)- }- }- }-- private var settingWritePage: some View {- VStack(alignment: .leading, spacing: 16) {- HStack(spacing: 12) {- field("Domain", text: $model.writeDomain, prompt: "com.apple.springboard")- .focused($focusedField, equals: .writeDomain)- field("Key", text: $model.writeKey, prompt: "Preference key")- }- HStack(alignment: .top, spacing: 12) {- VStack(alignment: .leading, spacing: 6) {- Text("Type").font(.headline)- Picker("Type", selection: $model.writeType) {- ForEach(VPhoneGuestToolsModel.ValueType.allCases) { type in- Text(type.title).tag(type)- }- }- .labelsHidden()- }- .frame(width: 150)- field("Value", text: $model.writeValue, prompt: valuePrompt)- }- Text("Boolean accepts true or false. Numeric values use decimal notation.")- .font(.caption)- .foregroundStyle(.secondary)- HStack {- Spacer()- Button("Write Setting") { Task { await model.writeSetting() } }- .buttonStyle(.borderedProminent)- .disabled(model.writeDomain.isEmpty || model.writeKey.isEmpty || model.isBusy)- }- }- }-- private var valuePrompt: String {- switch model.writeType {- case .string: VPhoneLocalization.text("Text")- case .bool: VPhoneLocalization.text("true or false")- case .int: "42"- case .float: "3.14"- }- }-- private func field(_ title: String, text: Binding<String>, prompt: String) -> some View {- VStack(alignment: .leading, spacing: 6) {- Text(VPhoneLocalization.text(title)).font(.headline)- TextField(VPhoneLocalization.text(title), text: text, prompt: Text(VPhoneLocalization.text(prompt)))- .textFieldStyle(.roundedBorder)- .font(.system(.body, design: .monospaced))- }- .frame(maxWidth: .infinity, alignment: .leading)- }-- private func metadata(_ title: String, _ value: String) -> some View {- VStack(alignment: .leading, spacing: 4) {- Text(VPhoneLocalization.text(title).uppercased())- .font(.system(.caption, design: .monospaced, weight: .semibold))- .foregroundStyle(.secondary)- Text(value)- .font(.system(.body, design: .monospaced))- .lineLimit(2)- .textSelection(.enabled)- }- .frame(maxWidth: .infinity, alignment: .leading)- }-- private func resultBox(_ result: String) -> some View {- ScrollView {- Text(result)- .font(.system(.body, design: .monospaced))- .textSelection(.enabled)- .frame(maxWidth: .infinity, alignment: .leading)- .padding(14)- }- .frame(maxWidth: .infinity, maxHeight: .infinity)- .background(Color(nsColor: .textBackgroundColor))- .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(nsColor: .separatorColor)))- .accessibilityLabel("Result")- }-- private func focusCurrentPage() {- switch model.page {- case .getClipboard: focusedField = nil- case .setClipboard: focusedField = .clipboardInput- case .readSetting: focusedField = .readDomain- case .writeSetting: focusedField = .writeDomain- }- }-}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuApps.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuApps.swiftindex 16aee6ed..f79ec93c 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuApps.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuApps.swift@@ -56,7 +56,7 @@ extension VPhoneMenuController {@objc func installIPAFromDisk() {guard control.isConnected else {- VPhoneAlert.run(+ VPhoneAlert.present(title: "Install App Package", message: "The guest is not connected. Start a VM, then try again.",style: .warning)return@@ -70,14 +70,18 @@ extension VPhoneMenuController {panel.prompt = VPhoneLocalization.text("Install")panel.message = VPhoneLocalization.text("Choose an IPA or TIPA package to install in the guest.")- let response = panel.runModal()- guard response == .OK, let url = panel.url else { return }+ VPhoneAlert.present(panel) { [weak self] response in+ guard response == .OK, let url = panel.url else { return }+ self?.installIPA(from: url)+ }+ }+ private func installIPA(from url: URL) {Task {do {let result = try await control.installIPA(localURL: url)print("[install] \(result)")- VPhoneAlert.run(+ VPhoneAlert.present(title: "Install App Package",message: VPhoneLocalization.installedMessage(for: url.lastPathComponent,@@ -86,7 +90,7 @@ extension VPhoneMenuController {style: .informational,)} catch {- VPhoneAlert.run(+ VPhoneAlert.present(title: "Install App Package",message: "Unable to install the app package. Check the file and guest connection, then try again.",style: .warning)@@ -107,15 +111,20 @@ extension VPhoneMenuController {alert.addButton(withTitle: VPhoneLocalization.text("Cancel"))alert.window.initialFirstResponder = field- guard alert.runModal() == .alertFirstButtonReturn, !field.stringValue.isEmpty else { return }- let url = field.stringValue+ VPhoneAlert.present(alert) { [weak self] response in+ guard response == .alertFirstButtonReturn, !field.stringValue.isEmpty else { return }+ self?.openOnGuest(field.stringValue)+ }+ }++ private func openOnGuest(_ url: String) {Task {do {try await control.openURL(url)- VPhoneAlert.run(+ VPhoneAlert.present(title: "Open URL", message: VPhoneLocalization.format("Opened %@", url), style: .informational)} catch {- VPhoneAlert.run(+ VPhoneAlert.present(title: "Open URL",message: "Unable to open the URL on the guest. Check the URL and guest connection, then try again.",style: .warning)diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuCamera.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuCamera.swiftindex 6ba1b66e..2e13116f 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuCamera.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuCamera.swift@@ -97,12 +97,14 @@ extension VPhoneMenuController {]panel.prompt = VPhoneLocalization.text("Use as Camera Source")panel.title = VPhoneLocalization.text("Choose Video File")- panel.runModal()- guard let url = panel.url else { return }- cameraServer?.setSource(.videoFile, videoURL: url)- refreshCameraSourceCheckmarks()- cameraStartStopItem?.isEnabled =- (cameraServer?.isConnected ?? false) && (cameraServer?.sourceKind ?? .off) == .videoFile+ VPhoneAlert.present(panel) { [weak self] response in+ guard let self, response == .OK, let url = panel.url else { return }+ cameraServer?.setSource(.videoFile, videoURL: url)+ refreshCameraSourceCheckmarks()+ cameraStartStopItem?.isEnabled =+ (cameraServer?.isConnected ?? false) &&+ (cameraServer?.sourceKind ?? .off) == .videoFile+ }}@objc func toggleCameraStreaming() {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swiftindex de8c847b..b69c24db 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift@@ -121,13 +121,13 @@ extension VPhoneMenuController {Task {do {let enabled = try await control.isDeveloperModeEnabled()- VPhoneAlert.run(+ VPhoneAlert.present(title: "Developer Mode",message: enabled ? "Developer Mode is enabled." : "Developer Mode is disabled.",style: .informational,)} catch {- VPhoneAlert.run(+ VPhoneAlert.present(title: "Developer Mode",message: "Unable to read Developer Mode status. Check that the guest agent is connected, "+ "then try again.",@@ -141,9 +141,9 @@ extension VPhoneMenuController {Task {do {try await control.sendPing()- VPhoneAlert.run(title: "Ping", message: "The guest responded.", style: .informational)+ VPhoneAlert.present(title: "Ping", message: "The guest responded.", style: .informational)} catch {- VPhoneAlert.run(+ VPhoneAlert.present(title: "Ping",message: "The guest did not respond. Check that the guest agent is connected, then try again.",style: .warning,@@ -156,9 +156,9 @@ extension VPhoneMenuController {Task {do {let hash = try await control.guestBinaryHash()- VPhoneAlert.run(title: "Guest Agent Hash", message: "SHA-256: \(hash)", style: .informational)+ VPhoneAlert.present(title: "Guest Agent Hash", message: "SHA-256: \(hash)", style: .informational)} catch {- VPhoneAlert.run(+ VPhoneAlert.present(title: "Guest Agent Hash",message: "Unable to read the guest agent hash. Check that the guest agent is connected, "+ "then try again.",diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swiftindex 339fcb16..07bcc891 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swift@@ -107,7 +107,6 @@ extension VPhoneMenuController {title: title,message: message,style: style,- attachedTo: NSApp.keyWindow ?? activeCaptureView()?.window,)}@@ -116,7 +115,6 @@ extension VPhoneMenuController {title: "Recording",message: VPhoneLocalization.format("Saved to %@", url.path),style: .informational,- attachedTo: NSApp.keyWindow ?? activeCaptureView()?.window,buttons: ["OK", "Reveal in Finder"],) { response inif response == .alertSecondButtonReturn {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneAlert.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneAlert.swiftindex 2acc2071..eeee7af3 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneAlert.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneAlert.swift@@ -1,31 +1,58 @@import AppKit+/// Presents alerts and open panels as sheets on the window they belong to:+/// the window passed in, or the VM display window for menu actions. When+/// neither is available, for example with --no-graphics, they run app-modal.@MainActorenum VPhoneAlert {- @discardableResult- static func run(+ /// The VM display window. Set when it is created.+ static weak var hostWindow: NSWindow?++ static func present(title: String,message: String,style: NSAlert.Style,buttons: [String] = ["OK"],- ) -> NSApplication.ModalResponse {- makeAlert(title: title, message: message, style: style, buttons: buttons).runModal()+ on window: NSWindow? = nil,+ completion: ((NSApplication.ModalResponse) -> Void)? = nil,+ ) {+ present(makeAlert(title: title, message: message, style: style, buttons: buttons), on: window, completion: completion)}static func present(- title: String,- message: String,- style: NSAlert.Style,- attachedTo window: NSWindow?,- buttons: [String] = ["OK"],+ _ alert: NSAlert,+ on window: NSWindow? = nil,completion: ((NSApplication.ModalResponse) -> Void)? = nil,) {- let alert = makeAlert(title: title, message: message, style: style, buttons: buttons)- if let window {+ if let window = presentingWindow(window) {+ // AppKit queues the sheet if another one is already showing.alert.beginSheetModal(for: window) { response in completion?(response) }} else {- completion?(alert.runModal())+ let response = alert.runModal()+ completion?(response)+ }+ }++ static func present(+ _ panel: NSSavePanel,+ on window: NSWindow? = nil,+ completion: @escaping (NSApplication.ModalResponse) -> Void,+ ) {+ if let window = presentingWindow(window) {+ panel.beginSheetModal(for: window) { response in completion(response) }+ } else {+ completion(panel.runModal())+ }+ }++ private static func presentingWindow(_ preferred: NSWindow?) -> NSWindow? {+ guard let window = preferred ?? hostWindow, window.isVisible || window.isMiniaturized else { return nil }+ if window.isMiniaturized {+ window.deminiaturize(nil)}+ NSApp.activate(ignoringOtherApps: true)+ window.makeKeyAndOrderFront(nil)+ return window}private static func makeAlert(diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swiftindex c81f6eae..c8744efc 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift@@ -29,7 +29,7 @@ class VPhoneVirtualMachineKeySender {return true}- VPhoneAlert.run(+ VPhoneAlert.present(title: "Guest Agent Not Connected",message: "The guest agent is not connected. Wait for it to connect, then try again.",style: .warning,diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swiftindex b4d2fcd2..490c6d17 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift@@ -51,6 +51,7 @@ class VPhoneVirtualMachineWindowController: NSObject, NSToolbarDelegate {window.isReleasedWhenClosed = falsewindow.level = .normal+ VPhoneAlert.hostWindow = windowwindow.contentAspectRatio = windowSizewindow.title = VPhoneLocalization.text("vphone — Starting…")window.subtitle = makeSubtitle(ip: nil)diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swiftindex 4094c4b5..1555f7e0 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift@@ -109,14 +109,14 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {Task { @MainActor inguard let control, control.isConnected else {- VPhoneAlert.run(title: "Install App Package", message: "Guest is not connected.", style: .warning)+ VPhoneAlert.present(title: "Install App Package", message: "Guest is not connected.", style: .warning)return}do {let result = try await control.installIPA(localURL: url)print("[install] \(result)")- VPhoneAlert.run(+ VPhoneAlert.present(title: "Install App Package",message: VPhoneLocalization.installedMessage(for: url.lastPathComponent,@@ -125,7 +125,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {style: .informational,)} catch {- VPhoneAlert.run(title: "Install App Package", message: "\(error)", style: .warning)+ VPhoneAlert.present(title: "Install App Package", message: "\(error)", style: .warning)}}return true