Run a virtual iPhone on an Apple Silicon Mac.
Swift
Refine guest tools and browser controls
Lakr308df1a61832
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlApps.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlApps.swiftindex d6bd9fe2..73828fa1 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlApps.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlApps.swift@@ -3,7 +3,7 @@ import Foundationextension VPhoneGuestControl {// MARK: - App Management- struct AppInfo {+ struct AppInfo: Identifiable {let bundleId: Stringlet name: Stringlet version: String@@ -11,6 +11,8 @@ extension VPhoneGuestControl {let state: Stringlet pid: Intlet path: String++ var id: String { bundleId }}func appList(filter: String = "all") async throws -> [AppInfo] {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppBrowserModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppBrowserModel.swiftindex cceec438..24aaefc9 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppBrowserModel.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppBrowserModel.swift@@ -8,6 +8,8 @@ class VPhoneAppBrowserModel {var apps: [VPhoneGuestControl.AppInfo] = []var filter: AppFilter = .installedvar searchText = ""+ var selection = Set<VPhoneGuestControl.AppInfo.ID>()+ var sortOrder = [KeyPathComparator(\VPhoneGuestControl.AppInfo.name)]var isLoading = falsevar error: String?@@ -19,12 +21,12 @@ class VPhoneAppBrowserModel {}var filteredApps: [VPhoneGuestControl.AppInfo] {- guard !searchText.isEmpty else { return apps }let query = searchText.lowercased()- return apps.filter {+ let visible = query.isEmpty ? apps : apps.filter {$0.name.lowercased().contains(query)|| $0.bundleId.lowercased().contains(query)}+ return visible.sorted(using: sortOrder)}init(control: VPhoneGuestControl) {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppBrowserView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppBrowserView.swiftindex f659a719..a6b2041b 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppBrowserView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppBrowserView.swift@@ -5,41 +5,28 @@ struct VPhoneAppBrowserView: View {var body: some View {VStack(spacing: 0) {- filterBar- Divider()if model.isLoading, model.apps.isEmpty {ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)- } else if model.filteredApps.isEmpty {- ContentUnavailableView(- "No Apps",- systemImage: "app.dashed",- description: Text(- model.searchText.isEmpty- ? "No apps are installed on the guest."- : "No apps match your search.",- ),- )} else {appTable}++ statusBar}- .searchable(text: $model.searchText, prompt: "Filter by name or bundle ID").task { await model.refresh() }.onChange(of: model.control.isConnected) { _, connected inif connected {Task { await model.refresh() }}}+ .onChange(of: model.filter) { _, _ in model.selection.removeAll() }+ .onChange(of: model.searchText) { _, _ in model.selection.removeAll() }.alert("Error",isPresented: .init(get: { model.error != nil },- set: {- if !$0 {- model.error = nil- }- },+ set: { if !$0 { model.error = nil } },),) {Button("OK") { model.error = nil }@@ -48,99 +35,91 @@ struct VPhoneAppBrowserView: View {}}- // MARK: - Filter Bar+ // MARK: - Table- private var filterBar: some View {- HStack(spacing: 12) {- Picker("Filter", selection: $model.filter) {- ForEach(VPhoneAppBrowserModel.AppFilter.allCases, id: \.self) { f in- Text(f.rawValue.capitalized).tag(f)- }+ private var appTable: some View {+ Table(of: VPhoneGuestControl.AppInfo.self, selection: $model.selection, sortOrder: $model.sortOrder) {+ TableColumn("Name", value: \.name) { app in+ Text(app.name.isEmpty ? app.bundleId : app.name)+ .fontWeight(.medium)+ .lineLimit(1)}- .pickerStyle(.segmented)- .frame(maxWidth: 400)+ .width(min: 130, ideal: 190, max: .infinity)- Spacer()+ TableColumn("Bundle ID", value: \.bundleId) { app in+ Text(app.bundleId)+ .font(.system(.body, design: .monospaced))+ .lineLimit(1)+ .help(app.bundleId)+ }+ .width(min: 170, ideal: 260, max: .infinity)- Text(model.filteredApps.count == 1 ? "1 app" : "\(model.filteredApps.count) apps")- .font(.system(.body, design: .monospaced))- .foregroundStyle(.secondary)+ TableColumn("Version", value: \.version) { app in+ Text(app.version.isEmpty ? "—" : app.version)+ .font(.system(.body, design: .monospaced))+ }+ .width(min: 70, ideal: 90, max: 120)- Button {- Task { await model.refresh() }- } label: {- Image(systemName: "arrow.clockwise")+ TableColumn("Type", value: \.type) { app in+ Text(app.type.capitalized)+ }+ .width(min: 60, ideal: 80, max: 100)++ TableColumn("Status", value: \.pid) { app in+ Text(app.pid > 0 ? "Running · PID \(app.pid)" : "Not running")+ .foregroundStyle(app.pid > 0 ? .primary : .secondary)+ }+ .width(min: 120, ideal: 150, max: 180)+ } rows: {+ ForEach(model.filteredApps) { app in+ TableRow(app)}- .disabled(model.isLoading)}- .padding(.horizontal, 12)- .padding(.vertical, 8)- .onChange(of: model.filter) {- Task { await model.refresh() }+ .contextMenu(forSelectionType: VPhoneGuestControl.AppInfo.ID.self) { ids in+ Button("Copy Bundle ID") {+ let values = model.filteredApps+ .filter { ids.contains($0.id) }+ .map(\.bundleId)+ .joined(separator: "\n")+ guard !values.isEmpty else { return }+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(values, forType: .string)+ }}- }-- // MARK: - Table-- private var appTable: some View {- ScrollView {- LazyVStack(spacing: 0) {- ForEach(Array(model.filteredApps.enumerated()), id: \.element.bundleId) { index, app in- appRow(app)- .background(index % 2 == 0 ? Color.clear : Color.primary.opacity(0.03))- }+ .overlay {+ if model.filteredApps.isEmpty {+ ContentUnavailableView(+ "No Apps",+ systemImage: "app.dashed",+ description: Text(+ model.searchText.isEmpty+ ? "No apps are available for this filter."+ : "No apps match your search.",+ ),+ )}}}- private func appRow(_ app: VPhoneGuestControl.AppInfo) -> some View {- HStack(spacing: 10) {- VStack(alignment: .leading, spacing: 2) {- HStack(spacing: 6) {- Text(app.name.isEmpty ? app.bundleId : app.name)- .font(.system(.body, design: .monospaced))- .fontWeight(.medium)- .lineLimit(1)+ private var statusBar: some View {+ HStack {+ Circle()+ .fill(model.control.isConnected ? Color.green : Color.orange)+ .frame(width: 8, height: 8)- if !app.version.isEmpty {- Text("v\(app.version)")- .font(.system(.caption, design: .monospaced))- .foregroundStyle(.secondary)- }-- Text(app.type)- .font(.system(.caption2, design: .monospaced))- .padding(.horizontal, 4)- .padding(.vertical, 1)- .background(- app.type == "system"- ? Color.blue.opacity(0.15) : Color.green.opacity(0.15),- )- .cornerRadius(3)- }-- Text(app.bundleId)- .font(.system(.caption, design: .monospaced))- .foregroundStyle(.secondary)- .lineLimit(1)- .textSelection(.enabled)- }+ Text(model.filteredApps.count == 1 ? "1 app" : "\(model.filteredApps.count) apps")+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(.secondary)Spacer()- if app.pid > 0 {- HStack(spacing: 4) {- Circle()- .fill(.green)- .frame(width: 6, height: 6)- Text("pid \(app.pid)")- .font(.system(.caption, design: .monospaced))- .foregroundStyle(.secondary)- }+ if model.isLoading {+ ProgressView()+ .controlSize(.small)}}- .padding(.horizontal, 12)- .padding(.vertical, 6)- .contentShape(Rectangle())+ .padding(.horizontal, 8)+ .frame(height: 24)+ .background(.bar)}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppWindowController.swiftindex 3ea349a1..b2d28ca7 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppWindowController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Apps/VPhoneAppWindowController.swift@@ -2,37 +2,49 @@ import AppKitimport SwiftUI@MainActor-class VPhoneAppWindowController {+class VPhoneAppWindowController: NSObject, NSToolbarDelegate {+ private nonisolated static let filterItemID = NSToolbarItem.Identifier("apps-filter")+ private nonisolated static let searchItemID = NSToolbarItem.Identifier("apps-search")+ private nonisolated static let refreshItemID = NSToolbarItem.Identifier("apps-refresh")+private var window: NSWindow?+ private var model: VPhoneAppBrowserModel?+ private var searchItem: NSSearchToolbarItem?++ var isKeyWindow: Bool { window?.isKeyWindow == true }func showWindow(control: VPhoneGuestControl) {if let window {+ NSApp.activate(ignoringOtherApps: true)window.makeKeyAndOrderFront(nil)return}let model = VPhoneAppBrowserModel(control: control)let view = VPhoneAppBrowserView(model: model)- let hostingView = NSHostingView(rootView: view)+ self.model = modellet window = NSWindow(- contentRect: NSRect(x: 0, y: 0, width: 650, height: 500),+ contentRect: NSRect(x: 0, y: 0, width: 900, height: 500),styleMask: [.titled, .closable, .resizable, .miniaturizable],backing: .buffered,defer: false,)window.title = "Apps"- window.subtitle = "vphone"- window.contentView = hostingView- window.contentMinSize = NSSize(width: 450, height: 300)+ window.contentView = NSHostingView(rootView: view)+ window.contentMinSize = NSSize(width: 700, height: 300)window.center()window.toolbarStyle = .unifiedwindow.isReleasedWhenClosed = false+ window.level = .normallet toolbar = NSToolbar(identifier: "vphone-apps-toolbar")+ toolbar.delegate = selftoolbar.displayMode = .iconOnly+ toolbar.allowsUserCustomization = falsewindow.toolbar = toolbar+ NSApp.activate(ignoringOtherApps: true)window.makeKeyAndOrderFront(nil)self.window = window@@ -43,7 +55,101 @@ class VPhoneAppWindowController {) { [weak self] _ inTask { @MainActor inself?.window = nil+ self?.model = nil+ self?.searchItem = nil}}}++ func focusSearch() {+ searchItem?.beginSearchInteraction()+ }++ // MARK: - Toolbar++ nonisolated func toolbar(+ _: NSToolbar,+ itemForItemIdentifier identifier: NSToolbarItem.Identifier,+ willBeInsertedIntoToolbar _: Bool,+ ) -> NSToolbarItem? {+ MainActor.assumeIsolated {+ switch identifier {+ case Self.filterItemID: makeFilterItem()+ case Self.searchItemID: makeSearchItem()+ case Self.refreshItemID: makeRefreshItem()+ default: nil+ }+ }+ }++ nonisolated func toolbarDefaultItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {+ [Self.filterItemID, .flexibleSpace, Self.searchItemID, Self.refreshItemID]+ }++ nonisolated func toolbarAllowedItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {+ [Self.filterItemID, Self.searchItemID, Self.refreshItemID, .flexibleSpace, .space]+ }++ private func makeFilterItem() -> NSToolbarItem {+ let item = NSToolbarItem(itemIdentifier: Self.filterItemID)+ item.label = "App Type"+ item.toolTip = "Filter apps by type"+ item.visibilityPriority = .high++ let labels = VPhoneAppBrowserModel.AppFilter.allCases.map { $0.rawValue.capitalized }+ let control = NSSegmentedControl(+ labels: labels,+ trackingMode: .selectOne,+ target: self,+ action: #selector(filterChanged(_:)),+ )+ control.selectedSegment = 0+ control.frame.size = NSSize(width: 320, height: 28)+ item.view = control+ return item+ }++ private func makeSearchItem() -> NSToolbarItem {+ let item = NSSearchToolbarItem(itemIdentifier: Self.searchItemID)+ item.label = "Search Apps"+ item.visibilityPriority = .high+ item.preferredWidthForSearchField = 220++ let field = NSSearchField()+ field.placeholderString = "Search Apps"+ field.sendsSearchStringImmediately = true+ field.target = self+ field.action = #selector(searchChanged(_:))+ item.searchField = field+ searchItem = item+ return item+ }++ private func makeRefreshItem() -> NSToolbarItem {+ let item = NSToolbarItem(itemIdentifier: Self.refreshItemID)+ item.label = "Refresh"+ item.toolTip = "Refresh app list"+ item.image = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Refresh")+ item.target = self+ item.action = #selector(refresh)+ return item+ }++ // MARK: - Actions++ @objc private func filterChanged(_ sender: NSSegmentedControl) {+ let filters = VPhoneAppBrowserModel.AppFilter.allCases+ guard filters.indices.contains(sender.selectedSegment), let model else { return }+ model.filter = filters[sender.selectedSegment]+ Task { await model.refresh() }+ }++ @objc private func searchChanged(_ sender: NSSearchField) {+ model?.searchText = sender.stringValue+ }++ @objc private func refresh() {+ guard let model else { return }+ Task { await model.refresh() }+ }}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileWindowController.swiftindex e14bd32e..8f31adec 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileWindowController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileWindowController.swift@@ -9,6 +9,7 @@ class VPhoneFileWindowController {func showWindow(control: VPhoneGuestControl) {if let window {+ NSApp.activate(ignoringOtherApps: true)window.makeKeyAndOrderFront(nil)return}@@ -33,12 +34,14 @@ class VPhoneFileWindowController {window.center()window.toolbarStyle = .unifiedwindow.isReleasedWhenClosed = false+ window.level = .normal// Insert quickLookController at the window level so AppKit finds it// when walking the responder chain for QLPreviewPanel panel control.quickLookController.nextResponder = window.nextResponderwindow.nextResponder = quickLookController+ NSApp.activate(ignoringOtherApps: true)window.makeKeyAndOrderFront(nil)self.window = windowdiff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserModel.swiftindex 7a816414..6ebdceea 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserModel.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserModel.swift@@ -1,3 +1,4 @@+import AppKitimport Foundationimport Observation@@ -63,6 +64,17 @@ class VPhoneKeychainBrowserModel {("Keys", "keys"),]+ func copyRows(ids: Set<VPhoneKeychainItem.ID>) {+ let selected = filteredItems.filter { ids.contains($0.id) }+ guard !selected.isEmpty else { return }+ let header = "Class\tAccount\tService\tAccess Group\tProtection\tValue"+ let rows = selected.map { item in+ "\(item.displayClass)\t\(item.account)\t\(item.service)\t\(item.accessGroup)\t\(item.protection)\t\(item.displayValue)"+ }+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(([header] + rows).joined(separator: "\n"), forType: .string)+ }+// MARK: - Actionsfunc addTestItem() async {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserView.swiftindex 0e603406..d4156715 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserView.swift@@ -10,8 +10,6 @@ struct VPhoneKeychainBrowserView: View {tableView.padding(.bottom, controlBarHeight).overlay(controlBar.frame(maxHeight: .infinity, alignment: .bottom))- .searchable(text: $model.searchText, prompt: "Filter keychain items")- .toolbar { toolbarContent }if model.showDiagnostics {Divider()@@ -25,6 +23,8 @@ struct VPhoneKeychainBrowserView: View {Task { await model.refresh() }}}+ .onChange(of: model.filterClass) { _, _ in model.selection.removeAll() }+ .onChange(of: model.searchText) { _, _ in model.selection.removeAll() }.alert("Error",isPresented: .init(@@ -122,17 +122,6 @@ struct VPhoneKeychainBrowserView: View {Divider()- Picker("Class", selection: $model.filterClass) {- ForEach(VPhoneKeychainBrowserModel.classFilters, id: \.value) { filter in- Text(filter.label).tag(filter.value)- }- }- .pickerStyle(.menu)- .labelsHidden()- .frame(maxWidth: 120)-- Divider()-Text(model.statusText).font(.system(size: 11, design: .monospaced)).foregroundStyle(.secondary)@@ -209,52 +198,6 @@ struct VPhoneKeychainBrowserView: View {}}- // MARK: - Toolbar-- @ToolbarContentBuilder- var toolbarContent: some ToolbarContent {- ToolbarItem {- Button {- Task { await model.refresh() }- } label: {- Label("Refresh", systemImage: "arrow.clockwise")- }- .keyboardShortcut("r", modifiers: .command)- }- ToolbarItem {- Button {- Task { await model.addTestItem() }- } label: {- Label("Add Test", systemImage: "plus.circle")- }- .help("Add a test keychain item (debug)")- }- ToolbarItem {- Button {- Task { await model.removeTestItem() }- } label: {- Label("Remove Test", systemImage: "minus.circle")- }- .help("Remove the test keychain item")- }- ToolbarItem {- Button {- copySelected()- } label: {- Label("Copy", systemImage: "doc.on.doc")- }- .disabled(model.selection.isEmpty)- }- ToolbarItem {- Button {- model.showDiagnostics.toggle()- } label: {- Label("Diagnostics", systemImage: model.showDiagnostics ? "ladybug.fill" : "ladybug")- }- .help("Toggle diagnostics log panel")- }- }-// MARK: - Context Menu@ViewBuilder@@ -265,37 +208,13 @@ struct VPhoneKeychainBrowserView: View {Button("Copy Access Group") { copyField(ids: ids, keyPath: \.accessGroup) }Button("Copy Protection") { copyField(ids: ids, keyPath: \.protection) }Divider()- Button("Copy Row (TSV)") { copyRows(ids: ids) }+ Button("Copy Row (TSV)") { model.copyRows(ids: ids) }Divider()Button("Refresh") { Task { await model.refresh() } }}// MARK: - Copy Actions- func copySelected() {- let selected = model.filteredItems.filter { model.selection.contains($0.id) }- guard !selected.isEmpty else { return }- let header = "Class\tAccount\tService\tAccess Group\tProtection\tValue"- let rows = selected.map { item in- "\(item.displayClass)\t\(item.account)\t\(item.service)\t\(item.accessGroup)\t\(item.protection)\t\(item.displayValue)"- }- let text = ([header] + rows).joined(separator: "\n")- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(text, forType: .string)- }-- func copyRows(ids: Set<VPhoneKeychainItem.ID>) {- let selected = model.filteredItems.filter { ids.contains($0.id) }- guard !selected.isEmpty else { return }- let header = "Class\tAccount\tService\tAccess Group\tProtection\tValue"- let rows = selected.map { item in- "\(item.displayClass)\t\(item.account)\t\(item.service)\t\(item.accessGroup)\t\(item.protection)\t\(item.displayValue)"- }- let text = ([header] + rows).joined(separator: "\n")- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(text, forType: .string)- }-func copyField(ids: Set<VPhoneKeychainItem.ID>, keyPath: KeyPath<VPhoneKeychainItem, String>) {let values = model.filteredItems.filter { ids.contains($0.id) }diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainWindowController.swiftindex 38247c51..9cc9e4c2 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainWindowController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainWindowController.swift@@ -2,18 +2,27 @@ import AppKitimport SwiftUI@MainActor-class VPhoneKeychainWindowController {+class VPhoneKeychainWindowController: NSObject, NSToolbarDelegate {+ private nonisolated static let classItemID = NSToolbarItem.Identifier("keychain-class")+ private nonisolated static let searchItemID = NSToolbarItem.Identifier("keychain-search")+ private nonisolated static let actionsItemID = NSToolbarItem.Identifier("keychain-actions")+private var window: NSWindow?+ private var model: VPhoneKeychainBrowserModel?+ private var searchItem: NSSearchToolbarItem?++ var isKeyWindow: Bool { window?.isKeyWindow == true }func showWindow(control: VPhoneGuestControl) {if let window {+ NSApp.activate(ignoringOtherApps: true)window.makeKeyAndOrderFront(nil)return}let model = VPhoneKeychainBrowserModel(control: control)let view = VPhoneKeychainBrowserView(model: model)- let hostingView = NSHostingView(rootView: view)+ self.model = modellet window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 900, height: 500),@@ -22,17 +31,20 @@ class VPhoneKeychainWindowController {defer: false,)window.title = "Keychain"- window.subtitle = "vphone"- window.contentView = hostingView- window.contentMinSize = NSSize(width: 600, height: 300)+ window.contentView = NSHostingView(rootView: view)+ window.contentMinSize = NSSize(width: 700, height: 300)window.center()window.toolbarStyle = .unifiedwindow.isReleasedWhenClosed = false+ window.level = .normallet toolbar = NSToolbar(identifier: "vphone-keychain-toolbar")+ toolbar.delegate = selftoolbar.displayMode = .iconOnly+ toolbar.allowsUserCustomization = falsewindow.toolbar = toolbar+ NSApp.activate(ignoringOtherApps: true)window.makeKeyAndOrderFront(nil)self.window = window@@ -43,7 +55,130 @@ class VPhoneKeychainWindowController {) { [weak self] _ inTask { @MainActor inself?.window = nil+ self?.model = nil+ self?.searchItem = nil+ }+ }+ }++ func focusSearch() {+ searchItem?.beginSearchInteraction()+ }++ // MARK: - Toolbar++ nonisolated func toolbar(+ _: NSToolbar,+ itemForItemIdentifier identifier: NSToolbarItem.Identifier,+ willBeInsertedIntoToolbar _: Bool,+ ) -> NSToolbarItem? {+ MainActor.assumeIsolated {+ switch identifier {+ case Self.classItemID: makeClassItem()+ case Self.searchItemID: makeSearchItem()+ case Self.actionsItemID: makeActionsItem()+ default: nil}}}++ nonisolated func toolbarDefaultItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {+ [Self.classItemID, .flexibleSpace, Self.searchItemID, Self.actionsItemID]+ }++ nonisolated func toolbarAllowedItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {+ [Self.classItemID, Self.searchItemID, Self.actionsItemID, .flexibleSpace, .space]+ }++ private func makeClassItem() -> NSToolbarItem {+ let item = NSToolbarItem(itemIdentifier: Self.classItemID)+ item.label = "Item Type"+ item.toolTip = "Filter keychain items by type"+ item.visibilityPriority = .high++ let labels = VPhoneKeychainBrowserModel.classFilters.map(\.label)+ let control = NSSegmentedControl(+ labels: labels,+ trackingMode: .selectOne,+ target: self,+ action: #selector(classChanged(_:)),+ )+ control.selectedSegment = 0+ control.frame.size = NSSize(width: 420, height: 28)+ item.view = control+ return item+ }++ private func makeSearchItem() -> NSToolbarItem {+ let item = NSSearchToolbarItem(itemIdentifier: Self.searchItemID)+ item.label = "Search Keychain"+ item.visibilityPriority = .high+ item.preferredWidthForSearchField = 190++ let field = NSSearchField()+ field.placeholderString = "Search Keychain"+ field.sendsSearchStringImmediately = true+ field.target = self+ field.action = #selector(searchChanged(_:))+ item.searchField = field+ searchItem = item+ return item+ }++ private func makeActionsItem() -> NSToolbarItem {+ let item = NSMenuToolbarItem(itemIdentifier: Self.actionsItemID)+ item.label = "Actions"+ item.image = NSImage(systemSymbolName: "ellipsis.circle", accessibilityDescription: "Actions")++ let menu = NSMenu(title: "Keychain Actions")+ menu.addItem(actionItem("Refresh", action: #selector(refresh)))+ menu.addItem(actionItem("Copy Selected Rows", action: #selector(copySelectedRows)))+ menu.addItem(actionItem("Show Diagnostics", action: #selector(toggleDiagnostics)))+ menu.addItem(.separator())+ menu.addItem(actionItem("Add Test Item", action: #selector(addTestItem)))+ menu.addItem(actionItem("Remove Test Item", action: #selector(removeTestItem)))+ item.menu = menu+ return item+ }++ private func actionItem(_ title: String, action: Selector) -> NSMenuItem {+ let item = NSMenuItem(title: title, action: action, keyEquivalent: "")+ item.target = self+ return item+ }++ // MARK: - Actions++ @objc private func classChanged(_ sender: NSSegmentedControl) {+ guard VPhoneKeychainBrowserModel.classFilters.indices.contains(sender.selectedSegment) else { return }+ model?.filterClass = VPhoneKeychainBrowserModel.classFilters[sender.selectedSegment].value+ }++ @objc private func searchChanged(_ sender: NSSearchField) {+ model?.searchText = sender.stringValue+ }++ @objc private func refresh() {+ guard let model else { return }+ Task { await model.refresh() }+ }++ @objc private func copySelectedRows() {+ guard let model else { return }+ model.copyRows(ids: model.selection)+ }++ @objc private func toggleDiagnostics() {+ model?.showDiagnostics.toggle()+ }++ @objc private func addTestItem() {+ guard let model else { return }+ Task { await model.addTestItem() }+ }++ @objc private func removeTestItem() {+ guard let model else { return }+ Task { await model.removeTestItem() }+ }}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneGuestToolsWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneGuestToolsWindowController.swiftnew file mode 100644index 00000000..9f812de1--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneGuestToolsWindowController.swift@@ -0,0 +1,506 @@+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: "Get Clipboard"+ case .setClipboard: "Set Clipboard Text"+ case .readSetting: "Read Setting"+ case .writeSetting: "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 = "Guest Tools"+ window.subtitle = "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: "String"+ case .bool: "Boolean"+ case .int: "Integer"+ case .float: "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("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("Text set on the guest clipboard.")+ } catch {+ showError("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) } ?? "Not set"+ }+ showSuccess("Read \(domain)\(key.isEmpty ? "" : ".\(key)").")+ } catch {+ showError("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("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("Enter true or false for a Boolean value.")+ return+ }+ case .int:+ guard let number = Int64(rawValue) else {+ showError("Enter a valid integer.")+ return+ }+ value = number+ case .float:+ guard let number = Double(rawValue), number.isFinite else {+ showError("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("Wrote \(domain).\(key).")+ } catch {+ showError("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("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("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: "Inspect the guest clipboard and copy its text to your Mac."+ case .setClipboard: "Send text from your Mac to the guest clipboard."+ case .readSetting: "Read one preference key, or leave the key empty to read all keys in the domain."+ case .writeSetting: "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 ? "None" : model.clipboardTypes.joined(separator: ", "))+ metadata("Image", model.clipboardHasImage ? "Present" : "None")+ metadata("Change Count", String(model.clipboardChangeCount))+ }+ resultBox(model.clipboardText ?? "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("Characters: \(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: "Text"+ case .bool: "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(title).font(.headline)+ TextField(title, text: text, prompt: 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(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 c68313ab..6496767e 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuApps.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuApps.swift@@ -6,25 +6,30 @@ import VPhoneCoreKitextension VPhoneMenuController {func buildAppsMenu() -> NSMenuItem {- let item = NSMenuItem()+ let item = NSMenuItem(title: "Apps", action: nil, keyEquivalent: "")let menu = NSMenu(title: "Apps")menu.autoenablesItems = false- let browse = makeItem("App Browser", action: #selector(openAppBrowser))+ let browse = makeItem(+ "App Browser",+ action: #selector(openAppBrowser),+ keyEquivalent: "a",+ modifiers: [.command, .shift],+ )browse.isEnabled = falseappsListItem = browsemenu.addItem(browse)menu.addItem(NSMenuItem.separator())- let openURL = makeItem("Open URL...", action: #selector(openURL))+ let openURL = makeItem("Open URL…", action: #selector(openURL))openURL.isEnabled = falseappsOpenURLItem = openURLmenu.addItem(openURL)menu.addItem(NSMenuItem.separator())- let install = makeItem("Install IPA/TIPA...", action: #selector(installIPAFromDisk))+ let install = makeItem("Install App Package…", action: #selector(installIPAFromDisk))install.isEnabled = falseinstallPackageItem = installmenu.addItem(install)@@ -51,7 +56,7 @@ extension VPhoneMenuController {@objc func installIPAFromDisk() {guard control.isConnected else {- showAlert(title: "Install App Package", message: "Guest is not connected.", style: .warning)+ VPhoneAlert.run(title: "Install App Package", message: "The guest is not connected. Start a VM, then try again.", style: .warning)return}@@ -70,7 +75,7 @@ extension VPhoneMenuController {do {let result = try await control.installIPA(localURL: url)print("[install] \(result)")- showAlert(+ VPhoneAlert.run(title: "Install App Package",message: VPhoneInstallPackage.successMessage(for: url.lastPathComponent,@@ -79,63 +84,34 @@ extension VPhoneMenuController {style: .informational,)} catch {- showAlert(title: "Install App Package", message: "\(error)", style: .warning)+ VPhoneAlert.run(title: "Install App Package", message: "Unable to install the app package. Check the file and guest connection, then try again.", style: .warning)}}}@objc func openURL() {- let panel = NSPanel(- contentRect: NSRect(x: 0, y: 0, width: 420, height: 110),- styleMask: [.titled, .closable],- backing: .buffered,- defer: false,- )- panel.title = "Open URL"- panel.center()-- let lbl = NSTextField(labelWithString: "Enter URL to open on the guest:")- lbl.frame = NSRect(x: 20, y: 70, width: 380, height: 20)-- let field = NSTextField(frame: NSRect(x: 20, y: 42, width: 380, height: 24))+ let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 360, height: 24))field.placeholderString = "https://example.com"+ field.setAccessibilityLabel("URL to open on the guest")- let ok = NSButton(frame: NSRect(x: 310, y: 10, width: 90, height: 28))- ok.title = "Open"- ok.bezelStyle = .rounded- ok.keyEquivalent = "\r"- ok.target = self- ok.action = #selector(VPhoneMenuController.confirmModal)-- let cancel = NSButton(frame: NSRect(x: 210, y: 10, width: 90, height: 28))- cancel.title = "Cancel"- cancel.bezelStyle = .rounded- cancel.keyEquivalent = "\u{1b}"- cancel.target = NSApp- cancel.action = #selector(NSApplication.abortModal)-- panel.contentView?.addSubview(lbl)- panel.contentView?.addSubview(field)- panel.contentView?.addSubview(ok)- panel.contentView?.addSubview(cancel)-- let response = NSApp.runModal(for: panel)- panel.orderOut(nil)-- guard response == .OK, !field.stringValue.isEmpty else { return }- let url = field.stringValue+ let alert = NSAlert()+ alert.messageText = "Open URL"+ alert.informativeText = "Enter a URL to open on the guest."+ alert.accessoryView = field+ alert.addButton(withTitle: "Open")+ alert.addButton(withTitle: "Cancel")+ alert.window.initialFirstResponder = field+ guard alert.runModal() == .alertFirstButtonReturn, !field.stringValue.isEmpty else { return }+ let url = field.stringValueTask {do {try await control.openURL(url)- showAlert(title: "Open URL", message: "Opened \(url)", style: .informational)+ VPhoneAlert.run(title: "Open URL", message: "Opened \(url)", style: .informational)} catch {- showAlert(title: "Open URL", message: "\(error)", style: .warning)+ VPhoneAlert.run(title: "Open URL", message: "Unable to open the URL on the guest. Check the URL and guest connection, then try again.", style: .warning)}}}- @objc func confirmModal() {- NSApp.stopModal(withCode: .OK)- }}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swiftindex 34c985ae..71cb4899 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift@@ -4,11 +4,16 @@ import AppKitextension VPhoneMenuController {func buildConnectMenu() -> NSMenuItem {- let item = NSMenuItem()- let menu = NSMenu(title: "Connect")+ let item = NSMenuItem(title: "Guest", action: nil, keyEquivalent: "")+ let menu = NSMenu(title: "Guest")menu.autoenablesItems = false- let fileBrowser = makeItem("File Browser", action: #selector(openFiles))+ let fileBrowser = makeItem(+ "File Browser",+ action: #selector(openFiles),+ keyEquivalent: "f",+ modifiers: [.command, .shift],+ )fileBrowser.isEnabled = falseconnectFileBrowserItem = fileBrowsermenu.addItem(fileBrowser)@@ -20,52 +25,72 @@ extension VPhoneMenuController {menu.addItem(NSMenuItem.separator())- let devModeStatus = makeItem("Developer Mode Status", action: #selector(devModeStatus))- devModeStatus.isEnabled = false- connectDevModeStatusItem = devModeStatus- menu.addItem(devModeStatus)-- menu.addItem(NSMenuItem.separator())-- let ping = makeItem("Ping", action: #selector(sendPing))- ping.isEnabled = false- connectPingItem = ping- menu.addItem(ping)-- let guestHash = makeItem("Guest Agent Hash", action: #selector(queryGuestHash))- guestHash.isEnabled = false- connectGuestHashItem = guestHash- menu.addItem(guestHash)-- menu.addItem(NSMenuItem.separator())-- let clipGet = makeItem("Get Clipboard", action: #selector(getClipboard))+ let clipboardMenu = NSMenu(title: "Clipboard")+ clipboardMenu.autoenablesItems = false+ let clipGet = makeItem(+ "Get Clipboard",+ action: #selector(getClipboard),+ keyEquivalent: "c",+ modifiers: [.command, .shift],+ )clipGet.isEnabled = falseclipboardGetItem = clipGet- menu.addItem(clipGet)+ clipboardMenu.addItem(clipGet)let clipSet = makeItem("Set Clipboard Text…", action: #selector(setClipboardText))clipSet.isEnabled = falseclipboardSetItem = clipSet- menu.addItem(clipSet)-- menu.addItem(NSMenuItem.separator())+ clipboardMenu.addItem(clipSet)+ let clipboardItem = NSMenuItem(title: "Clipboard", action: nil, keyEquivalent: "")+ clipboardItem.submenu = clipboardMenu+ menu.addItem(clipboardItem)+ let settingsMenu = NSMenu(title: "Settings")+ settingsMenu.autoenablesItems = falselet settingsGet = makeItem("Read Setting…", action: #selector(readSetting))settingsGet.isEnabled = falsesettingsGetItem = settingsGet- menu.addItem(settingsGet)+ settingsMenu.addItem(settingsGet)let settingsSet = makeItem("Write Setting…", action: #selector(writeSetting))settingsSet.isEnabled = falsesettingsSetItem = settingsSet- menu.addItem(settingsSet)+ settingsMenu.addItem(settingsSet)+ let settingsItem = NSMenuItem(title: "Settings", action: nil, keyEquivalent: "")+ settingsItem.submenu = settingsMenu+ menu.addItem(settingsItem)menu.addItem(NSMenuItem.separator())- menu.addItem(buildLocationSubmenu())- menu.addItem(buildBatterySubmenu())- menu.addItem(buildCameraSubmenu())+ let diagnosticsMenu = NSMenu(title: "Diagnostics")+ diagnosticsMenu.autoenablesItems = false+ let devModeStatus = makeItem("Developer Mode Status", action: #selector(devModeStatus))+ devModeStatus.isEnabled = false+ connectDevModeStatusItem = devModeStatus+ diagnosticsMenu.addItem(devModeStatus)++ let ping = makeItem("Ping", action: #selector(sendPing))+ ping.isEnabled = false+ connectPingItem = ping+ diagnosticsMenu.addItem(ping)++ let guestHash = makeItem("Guest Agent Hash", action: #selector(queryGuestHash))+ guestHash.isEnabled = false+ connectGuestHashItem = guestHash+ diagnosticsMenu.addItem(guestHash)+ let diagnosticsItem = NSMenuItem(title: "Diagnostics", action: nil, keyEquivalent: "")+ diagnosticsItem.submenu = diagnosticsMenu+ menu.addItem(diagnosticsItem)++ menu.addItem(NSMenuItem.separator())++ let deviceMenu = NSMenu(title: "Device Overrides")+ deviceMenu.addItem(buildLocationSubmenu())+ deviceMenu.addItem(buildBatterySubmenu())+ deviceMenu.addItem(buildCameraSubmenu())+ let deviceItem = NSMenuItem(title: "Device Overrides", action: nil, keyEquivalent: "")+ deviceItem.submenu = deviceMenu+ menu.addItem(deviceItem)item.submenu = menureturn item@@ -96,13 +121,13 @@ extension VPhoneMenuController {Task {do {let enabled = try await control.isDeveloperModeEnabled()- showAlert(+ VPhoneAlert.run(title: "Developer Mode",message: enabled ? "Developer Mode is enabled." : "Developer Mode is disabled.",style: .informational,)} catch {- showAlert(+ VPhoneAlert.run(title: "Developer Mode",message: "Unable to read Developer Mode status. Check that the guest agent is connected, "+ "then try again.",@@ -116,9 +141,9 @@ extension VPhoneMenuController {Task {do {try await control.sendPing()- showAlert(title: "Ping", message: "The guest responded.", style: .informational)+ VPhoneAlert.run(title: "Ping", message: "The guest responded.", style: .informational)} catch {- showAlert(+ VPhoneAlert.run(title: "Ping",message: "The guest did not respond. Check that the guest agent is connected, then try again.",style: .warning,@@ -131,9 +156,9 @@ extension VPhoneMenuController {Task {do {let hash = try await control.guestBinaryHash()- showAlert(title: "Guest Agent Hash", message: "SHA-256: \(hash)", style: .informational)+ VPhoneAlert.run(title: "Guest Agent Hash", message: "SHA-256: \(hash)", style: .informational)} catch {- showAlert(+ VPhoneAlert.run(title: "Guest Agent Hash",message: "Unable to read the guest agent hash. Check that the guest agent is connected, "+ "then try again.",@@ -148,316 +173,22 @@ extension VPhoneMenuController {clipboardSetItem?.isEnabled = available}- // MARK: - Clipboard+ // MARK: - Clipboard & Settings@objc func getClipboard() {- Task {- do {- let content = try await control.clipboardGet()- var message = ""- if let text = content.text {- let truncated = text.count > 500 ? String(text.prefix(500)) + "…" : text- message += "Text: \(truncated)\n"- }- message += "Types: \(content.types.joined(separator: ", "))\n"- message += "Image: \(content.hasImage ? "Yes" : "No")\n"- message += "Change Count: \(content.changeCount)"- showAlert(title: "Clipboard Content", message: message, style: .informational)- } catch {- showAlert(- title: "Clipboard",- message: "Unable to read the guest clipboard. Try again.",- style: .warning,- )- }- }+ guestToolsWindowController.show(.getClipboard)}@objc func setClipboardText() {- let panel = NSPanel(- contentRect: NSRect(x: 0, y: 0, width: 420, height: 150),- styleMask: [.titled, .closable],- backing: .buffered,- defer: false,- )- panel.title = "Set Clipboard Text"- panel.center()-- let lbl = NSTextField(labelWithString: "Enter text to set on the guest clipboard:")- lbl.frame = NSRect(x: 20, y: 110, width: 380, height: 20)-- let field = NSTextField(frame: NSRect(x: 20, y: 50, width: 380, height: 50))- field.placeholderString = "Text to copy to clipboard"-- let ok = NSButton(frame: NSRect(x: 310, y: 12, width: 90, height: 28))- ok.title = "Set"- ok.bezelStyle = .rounded- ok.keyEquivalent = "\r"- ok.target = self- ok.action = #selector(VPhoneMenuController.confirmModal)-- let cancel = NSButton(frame: NSRect(x: 210, y: 12, width: 90, height: 28))- cancel.title = "Cancel"- cancel.bezelStyle = .rounded- cancel.keyEquivalent = "\u{1b}"- cancel.target = NSApp- cancel.action = #selector(NSApplication.abortModal)-- panel.contentView?.addSubview(lbl)- panel.contentView?.addSubview(field)- panel.contentView?.addSubview(ok)- panel.contentView?.addSubview(cancel)-- let response = NSApp.runModal(for: panel)- panel.orderOut(nil)-- guard response == .OK, !field.stringValue.isEmpty else { return }- let text = field.stringValue-- Task {- do {- try await control.clipboardSet(text: text)- showAlert(title: "Clipboard", message: "Text set successfully.", style: .informational)- } catch {- showAlert(- title: "Clipboard",- message: "Unable to set the guest clipboard. Try again.",- style: .warning,- )- }- }+ guestToolsWindowController.show(.setClipboard)}- // MARK: - Settings-@objc func readSetting() {- let panel = NSPanel(- contentRect: NSRect(x: 0, y: 0, width: 420, height: 160),- styleMask: [.titled, .closable],- backing: .buffered,- defer: false,- )- panel.title = "Read Setting"- panel.center()-- let lbl1 = NSTextField(labelWithString: "Domain:")- lbl1.frame = NSRect(x: 20, y: 118, width: 380, height: 18)- let domainField = NSTextField(frame: NSRect(x: 20, y: 92, width: 380, height: 22))- domainField.placeholderString = "com.apple.springboard"-- let lbl2 = NSTextField(labelWithString: "Key (leave empty for all keys):")- lbl2.frame = NSRect(x: 20, y: 68, width: 380, height: 18)- let keyField = NSTextField(frame: NSRect(x: 20, y: 42, width: 380, height: 22))- keyField.placeholderString = "Key (leave empty for all keys)"-- let ok = NSButton(frame: NSRect(x: 310, y: 10, width: 90, height: 28))- ok.title = "Read"- ok.bezelStyle = .rounded- ok.keyEquivalent = "\r"- ok.target = self- ok.action = #selector(VPhoneMenuController.confirmModal)-- let cancel = NSButton(frame: NSRect(x: 210, y: 10, width: 90, height: 28))- cancel.title = "Cancel"- cancel.bezelStyle = .rounded- cancel.keyEquivalent = "\u{1b}"- cancel.target = NSApp- cancel.action = #selector(NSApplication.abortModal)-- panel.contentView?.addSubview(lbl1)- panel.contentView?.addSubview(domainField)- panel.contentView?.addSubview(lbl2)- panel.contentView?.addSubview(keyField)- panel.contentView?.addSubview(ok)- panel.contentView?.addSubview(cancel)-- let response = NSApp.runModal(for: panel)- panel.orderOut(nil)-- guard response == .OK else { return }- let domain = domainField.stringValue- guard !domain.isEmpty else { return }- let key: String? = keyField.stringValue.isEmpty ? nil : keyField.stringValue-- Task {- do {- let value = try await control.settingsGet(domain: domain, key: key)- let display: String- if let dict = value as? [String: Any] {- let data = try JSONSerialization.data(- withJSONObject: dict,- options: [.prettyPrinted, .sortedKeys],- )- display = String(data: data, encoding: .utf8) ?? "\(dict)"- } else {- display = "\(value ?? "Not set")"- }- let truncated = display.count > 2000 ? String(display.prefix(2000)) + "\n…" : display- showAlert(- title: "Setting: \(domain)\(key.map { ".\($0)" } ?? "")",- message: truncated,- style: .informational,- )- } catch {- showAlert(- title: "Read Setting",- message: "Unable to read that setting. Check the domain and key, then try again.",- style: .warning,- )- }- }+ guestToolsWindowController.show(.readSetting)}@objc func writeSetting() {- let panel = NSPanel(- contentRect: NSRect(x: 0, y: 0, width: 420, height: 240),- styleMask: [.titled, .closable],- backing: .buffered,- defer: false,- )- panel.title = "Write Setting"- panel.center()-- let lbl1 = NSTextField(labelWithString: "Domain:")- lbl1.frame = NSRect(x: 20, y: 198, width: 380, height: 18)- let domainField = NSTextField(frame: NSRect(x: 20, y: 172, width: 380, height: 22))- domainField.placeholderString = "com.apple.springboard"-- let lbl2 = NSTextField(labelWithString: "Key:")- lbl2.frame = NSRect(x: 20, y: 148, width: 380, height: 18)- let keyField = NSTextField(frame: NSRect(x: 20, y: 122, width: 380, height: 22))- keyField.placeholderString = "Key"-- let lbl3 = NSTextField(labelWithString: "Type:")- lbl3.frame = NSRect(x: 20, y: 98, width: 380, height: 18)- let typeField = NSTextField(frame: NSRect(x: 20, y: 72, width: 380, height: 22))- typeField.placeholderString = "bool | string | int | float"-- let lbl4 = NSTextField(labelWithString: "Value:")- lbl4.frame = NSRect(x: 20, y: 48, width: 380, height: 18)- let valueField = NSTextField(frame: NSRect(x: 20, y: 42, width: 220, height: 22))- valueField.placeholderString = "Value"-- let ok = NSButton(frame: NSRect(x: 310, y: 10, width: 90, height: 28))- ok.title = "Write"- ok.bezelStyle = .rounded- ok.keyEquivalent = "\r"- ok.target = self- ok.action = #selector(VPhoneMenuController.confirmModal)-- let cancel = NSButton(frame: NSRect(x: 210, y: 10, width: 90, height: 28))- cancel.title = "Cancel"- cancel.bezelStyle = .rounded- cancel.keyEquivalent = "\u{1b}"- cancel.target = NSApp- cancel.action = #selector(NSApplication.abortModal)-- panel.contentView?.addSubview(lbl1)- panel.contentView?.addSubview(domainField)- panel.contentView?.addSubview(lbl2)- panel.contentView?.addSubview(keyField)- panel.contentView?.addSubview(lbl3)- panel.contentView?.addSubview(typeField)- panel.contentView?.addSubview(lbl4)- panel.contentView?.addSubview(valueField)- panel.contentView?.addSubview(ok)- panel.contentView?.addSubview(cancel)-- let response = NSApp.runModal(for: panel)- panel.orderOut(nil)-- guard response == .OK else { return }- let domain = domainField.stringValue- let key = keyField.stringValue- let type = typeField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()- let rawValue = valueField.stringValue- guard !domain.isEmpty, !key.isEmpty else { return }-- let value: Any- let valueType: String- switch type {- case "", "string":- value = rawValue- valueType = "string"- case "boolean", "bool":- switch rawValue.lowercased() {- case "true", "yes", "1": value = true- case "false", "no", "0": value = false- default:- showAlert(title: "Write Setting", message: "Enter true or false for a boolean value.", style: .warning)- return- }- valueType = "bool"- case "integer", "int":- guard let number = Int64(rawValue) else {- showAlert(title: "Write Setting", message: "Enter a valid integer.", style: .warning)- return- }- value = number- valueType = "int"- case "float", "double":- guard let number = Double(rawValue), number.isFinite else {- showAlert(title: "Write Setting", message: "Enter a finite number.", style: .warning)- return- }- value = number- valueType = "float"- default:- showAlert(title: "Write Setting", message: "Type must be string, bool, int, or float.", style: .warning)- return- }-- Task {- do {- try await control.settingsSet(- domain: domain,- key: key,- value: value,- type: valueType,- )- showAlert(- title: "Write Setting",- message: "Set \(domain).\(key) = \(rawValue)",- style: .informational,- )- } catch {- showAlert(- title: "Write Setting",- message: "Unable to write that setting. Check the domain, key and type, then try again.",- style: .warning,- )- }- }+ guestToolsWindowController.show(.writeSetting)}- // MARK: - Alert-- func showAlert(title: String, message: String, style _: NSAlert.Style) {- let panel = NSPanel(- contentRect: NSRect(x: 0, y: 0, width: 380, height: 120),- styleMask: [.titled, .closable],- backing: .buffered,- defer: false,- )- panel.title = title- panel.center()-- let msg = NSTextField(labelWithString: message)- msg.frame = NSRect(x: 20, y: 50, width: 340, height: 50)- msg.lineBreakMode = .byWordWrapping- msg.maximumNumberOfLines = 3-- let ok = NSButton(frame: NSRect(x: 280, y: 12, width: 80, height: 28))- ok.title = "OK"- ok.bezelStyle = .rounded- ok.keyEquivalent = "\r"- ok.target = NSApp- ok.action = #selector(NSApplication.stopModal(withCode:))-- panel.contentView?.addSubview(msg)- panel.contentView?.addSubview(ok)-- NSApp.runModal(for: panel)- panel.orderOut(nil)- }}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swiftindex 785b2ace..8824b70b 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift@@ -7,10 +7,12 @@ import Foundationclass VPhoneMenuController {let keySender: VPhoneVirtualMachineKeySenderlet control: VPhoneGuestControl+ let guestToolsWindowController: VPhoneGuestToolsWindowControllerweak var vm: VPhoneVirtualMachine?var onFilesPressed: (() -> Void)?var onKeychainPressed: (() -> Void)?+ var onFindPressed: (() -> Void)?var onAppsPressed: (() -> Void)?var connectFileBrowserItem: NSMenuItem?var connectKeychainBrowserItem: NSMenuItem?@@ -54,6 +56,7 @@ class VPhoneMenuController {init(keySender: VPhoneVirtualMachineKeySender, control: VPhoneGuestControl) {self.keySender = keySenderself.control = control+ guestToolsWindowController = VPhoneGuestToolsWindowController(control: control)setupMenuBar()}@@ -79,6 +82,23 @@ class VPhoneMenuController {appMenuItem.submenu = appMenumainMenu.addItem(appMenuItem)+ let editMenuItem = NSMenuItem()+ let editMenu = NSMenu(title: "Edit")+ editMenu.addItem(withTitle: "Cut", action: #selector(NSText.cut(_:)), keyEquivalent: "x")+ editMenu.addItem(withTitle: "Copy", action: #selector(NSText.copy(_:)), keyEquivalent: "c")+ editMenu.addItem(withTitle: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v")+ editMenu.addItem(NSMenuItem.separator())+ editMenu.addItem(withTitle: "Select All", action: #selector(NSText.selectAll(_:)), keyEquivalent: "a")+ editMenu.addItem(NSMenuItem.separator())+ let findItem = editMenu.addItem(+ withTitle: "Find…",+ action: #selector(findKeychain),+ keyEquivalent: "f",+ )+ findItem.target = self+ editMenuItem.submenu = editMenu+ mainMenu.addItem(editMenuItem)+mainMenu.addItem(buildConnectMenu())mainMenu.addItem(buildKeysMenu())mainMenu.addItem(buildAppsMenu())@@ -104,9 +124,19 @@ class VPhoneMenuController {NSApp.mainMenu = mainMenu}- func makeItem(_ title: String, action: Selector) -> NSMenuItem {- let item = NSMenuItem(title: title, action: action, keyEquivalent: "")+ func makeItem(+ _ title: String,+ action: Selector,+ keyEquivalent: String = "",+ modifiers: NSEvent.ModifierFlags = .command,+ ) -> NSMenuItem {+ let item = NSMenuItem(title: title, action: action, keyEquivalent: keyEquivalent)+ item.keyEquivalentModifierMask = modifiersitem.target = selfreturn item}++ @objc private func findKeychain() {+ onFindPressed?()+ }}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuKeys.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuKeys.swiftindex f7abfba1..980d456f 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuKeys.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuKeys.swift@@ -5,16 +5,21 @@ import LocalAuthenticationextension VPhoneMenuController {func buildKeysMenu() -> NSMenuItem {- let item = NSMenuItem()+ let item = NSMenuItem(title: "Keys", action: nil, keyEquivalent: "")let menu = NSMenu(title: "Keys")- menu.addItem(makeItem("Home Screen", action: #selector(sendHome)))+ menu.addItem(makeItem(+ "Home Screen",+ action: #selector(sendHome),+ keyEquivalent: "h",+ modifiers: [.command, .shift],+ ))menu.addItem(makeItem("Power", action: #selector(sendPower)))menu.addItem(makeItem("Volume Up", action: #selector(sendVolumeUp)))menu.addItem(makeItem("Volume Down", action: #selector(sendVolumeDown)))menu.addItem(NSMenuItem.separator())- menu.addItem(makeItem("Spotlight (Cmd+Space)", action: #selector(sendSpotlight)))+ menu.addItem(makeItem("Open Guest Spotlight", action: #selector(sendSpotlight)))menu.addItem(NSMenuItem.separator())- menu.addItem(makeItem("Type ASCII from Clipboard", action: #selector(typeFromClipboard)))+ menu.addItem(makeItem("Type ASCII from Mac Clipboard", action: #selector(typeFromClipboard)))menu.addItem(NSMenuItem.separator())let tidItem = makeItem("Touch ID Home Forwarding", action: #selector(toggleTouchIDForwarding))if hasTouchID {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swiftindex e3c2a81f..38dcbcdc 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swift@@ -4,13 +4,18 @@ import AppKitextension VPhoneMenuController {func buildRecordMenu() -> NSMenuItem {- let item = NSMenuItem()- let menu = NSMenu(title: "Record")- let toggle = makeItem("Start Recording", action: #selector(toggleRecording))+ let item = NSMenuItem(title: "Capture", action: nil, keyEquivalent: "")+ let menu = NSMenu(title: "Capture")+ let toggle = makeItem(+ "Start Recording",+ action: #selector(toggleRecording),+ keyEquivalent: "r",+ modifiers: [.command, .shift],+ )recordingItem = togglemenu.addItem(toggle)menu.addItem(NSMenuItem.separator())- menu.addItem(makeItem("Copy Screenshot to Clipboard", action: #selector(copyScreenshotToClipboard)))+ menu.addItem(makeItem("Copy Screenshot to Mac Clipboard", action: #selector(copyScreenshotToClipboard)))menu.addItem(makeItem("Save Screenshot to File", action: #selector(saveScreenshotToFile)))item.submenu = menureturn item@@ -27,7 +32,7 @@ extension VPhoneMenuController {}} else {guard let view = activeCaptureView() else {- showAlert(+ showCaptureAlert(title: "Recording",message: "No VM window is open. Start a VM, then try again.",style: .warning,@@ -38,7 +43,7 @@ extension VPhoneMenuController {try screenRecorder?.startRecording(view: view)recordingItem?.title = "Stop Recording"} catch {- showAlert(title: "Recording", message: "Unable to start recording. Try again.", style: .warning)+ showCaptureAlert(title: "Recording", message: "Unable to start recording. Try again.", style: .warning)}}}@@ -46,7 +51,7 @@ extension VPhoneMenuController {@objc func copyScreenshotToClipboard() {guard let recorder = screenRecorder else { return }guard control.isConnected else {- showAlert(+ showCaptureAlert(title: "Screenshot",message: "The guest is not connected. Start a VM, then try again.",style: .warning,@@ -58,9 +63,9 @@ extension VPhoneMenuController {do {let image = try await control.screenshotJPEG()try recorder.copyScreenshotToPasteboard(jpegData: image)- showAlert(title: "Screenshot", message: "Copied to clipboard.", style: .informational)+ showCaptureAlert(title: "Screenshot", message: "Screenshot copied to the Mac clipboard.", style: .informational)} catch {- showAlert(title: "Screenshot", message: "Unable to copy the screenshot. Try again.", style: .warning)+ showCaptureAlert(title: "Screenshot", message: "Unable to copy the screenshot. Try again.", style: .warning)}}}@@ -68,7 +73,7 @@ extension VPhoneMenuController {@objc func saveScreenshotToFile() {guard let recorder = screenRecorder else { return }guard control.isConnected else {- showAlert(+ showCaptureAlert(title: "Screenshot",message: "The guest is not connected. Start a VM, then try again.",style: .warning,@@ -80,9 +85,9 @@ extension VPhoneMenuController {do {let image = try await control.screenshotJPEG()let url = try recorder.saveScreenshot(jpegData: image)- showAlert(title: "Screenshot", message: "Saved to \(url.path)", style: .informational)+ showCaptureAlert(title: "Screenshot", message: "Saved to \(url.path)", style: .informational)} catch {- showAlert(title: "Screenshot", message: "Unable to save the screenshot. Try again.", style: .warning)+ showCaptureAlert(title: "Screenshot", message: "Unable to save the screenshot. Try again.", style: .warning)}}}@@ -92,57 +97,26 @@ extension VPhoneMenuController {return captureView.window == nil ? nil : captureView}- private func showRecordingSavedAlert(url: URL) {- let panel = NSPanel(- contentRect: NSRect(x: 0, y: 0, width: 420, height: 110),- styleMask: [.titled, .closable],- backing: .buffered,- defer: false,+ private func showCaptureAlert(title: String, message: String, style: NSAlert.Style) {+ VPhoneAlert.present(+ title: title,+ message: message,+ style: style,+ attachedTo: NSApp.keyWindow ?? activeCaptureView()?.window,)- panel.title = "Recording"- panel.center()-- let msg = NSTextField(labelWithString: "Saved to \(url.path)")- msg.frame = NSRect(x: 20, y: 60, width: 380, height: 30)- msg.lineBreakMode = .byTruncatingMiddle-- let reveal = NSButton(frame: NSRect(x: 20, y: 12, width: 150, height: 28))- reveal.title = "Reveal in Finder"- reveal.bezelStyle = .rounded-- let ok = NSButton(frame: NSRect(x: 310, y: 12, width: 90, height: 28))- ok.title = "OK"- ok.bezelStyle = .rounded- ok.keyEquivalent = "\r"- ok.target = self- ok.action = #selector(VPhoneMenuController.confirmModal)-- panel.contentView?.addSubview(msg)- panel.contentView?.addSubview(reveal)- panel.contentView?.addSubview(ok)-- // Use a custom approach: reveal button stops modal with code 100- class RecordingRevealAction: NSObject {- var action: () -> Void- init(_ action: @escaping () -> Void) {- self.action = action- }+ }- @objc func clicked() {- action()+ private func showRecordingSavedAlert(url: URL) {+ VPhoneAlert.present(+ title: "Recording",+ message: "Saved to \(url.path)",+ style: .informational,+ attachedTo: NSApp.keyWindow ?? activeCaptureView()?.window,+ buttons: ["OK", "Reveal in Finder"],+ ) { response in+ if response == .alertSecondButtonReturn {+ NSWorkspace.shared.activateFileViewerSelecting([url])}}- let helper = RecordingRevealAction {- NSApp.stopModal(withCode: NSApplication.ModalResponse(rawValue: 100))- }- reveal.target = helper- reveal.action = #selector(RecordingRevealAction.clicked)-- let response = NSApp.runModal(for: panel)- panel.orderOut(nil)-- if response.rawValue == 100 {- NSWorkspace.shared.activateFileViewerSelecting([url])- }}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneAlert.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneAlert.swiftnew file mode 100644index 00000000..d165c05b--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneAlert.swift@@ -0,0 +1,46 @@+import AppKit++@MainActor+enum VPhoneAlert {+ @discardableResult+ static func run(+ title: String,+ message: String,+ style: NSAlert.Style,+ buttons: [String] = ["OK"],+ ) -> NSApplication.ModalResponse {+ makeAlert(title: title, message: message, style: style, buttons: buttons).runModal()+ }++ static func present(+ title: String,+ message: String,+ style: NSAlert.Style,+ attachedTo window: NSWindow?,+ buttons: [String] = ["OK"],+ completion: ((NSApplication.ModalResponse) -> Void)? = nil,+ ) {+ let alert = makeAlert(title: title, message: message, style: style, buttons: buttons)+ if let window {+ alert.beginSheetModal(for: window) { response in completion?(response) }+ } else {+ completion?(alert.runModal())+ }+ }++ private static func makeAlert(+ title: String,+ message: String,+ style: NSAlert.Style,+ buttons: [String],+ ) -> NSAlert {+ let alert = NSAlert()+ alert.messageText = title+ alert.informativeText = message+ alert.alertStyle = style+ for button in buttons {+ alert.addButton(withTitle: button)+ }+ return alert+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swiftindex 2d5d91ff..c81f6eae 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift@@ -29,35 +29,11 @@ class VPhoneVirtualMachineKeySender {return true}- let panel = NSPanel(- contentRect: NSRect(x: 0, y: 0, width: 380, height: 110),- styleMask: [.titled, .closable],- backing: .buffered,- defer: false,+ VPhoneAlert.run(+ title: "Guest Agent Not Connected",+ message: "The guest agent is not connected. Wait for it to connect, then try again.",+ style: .warning,)- panel.title = "Guest Agent Not Connected"- panel.center()-- let msg = NSTextField(- labelWithString: "The guest agent is not connected. Wait for it to connect, then try again.",- )- msg.frame = NSRect(x: 20, y: 50, width: 340, height: 44)- msg.lineBreakMode = .byWordWrapping- msg.maximumNumberOfLines = 3-- let ok = NSButton(frame: NSRect(x: 280, y: 12, width: 80, height: 28))- ok.title = "OK"- ok.bezelStyle = .rounded- ok.keyEquivalent = "\r"- ok.target = NSApp- ok.action = #selector(NSApplication.stopModal(withCode:))-- panel.contentView?.addSubview(msg)- panel.contentView?.addSubview(ok)-- NSApp.runModal(for: panel)- panel.orderOut(nil)-return false}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swiftindex 41da159c..fe239752 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift@@ -50,6 +50,7 @@ class VPhoneVirtualMachineWindowController: NSObject, NSToolbarDelegate {)window.isReleasedWhenClosed = false+ window.level = .normalwindow.contentAspectRatio = windowSizewindow.title = "vphone — Starting…"window.subtitle = makeSubtitle(ip: nil)@@ -74,9 +75,9 @@ class VPhoneVirtualMachineWindowController: NSObject, NSToolbarDelegate {windowController = controllerkeySender.window = window+ NSApp.activate(ignoringOtherApps: true)window.makeKeyAndOrderFront(nil)window.makeFirstResponder(view)- NSApp.activate(ignoringOtherApps: true)let monitor = VPhoneTouchIDMonitor()monitor.start(control: control, window: window)diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex fe0608bc..c04e1b22 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -142,6 +142,16 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {guard let keychainWC, let control else { return }keychainWC.showWindow(control: control)}+ mc.onFindPressed = { [weak keychainWC, weak appWC, weak control] in+ if appWC?.isKeyWindow == true {+ appWC?.focusSearch()+ } else if keychainWC?.isKeyWindow == true {+ keychainWC?.focusSearch()+ } else if let appWC, let control {+ appWC.showWindow(control: control)+ appWC.focusSearch()+ }+ }mc.onAppsPressed = { [weak appWC, weak control] inguard let appWC, let control else { return }appWC.showWindow(control: control)diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swiftindex 3154ff29..b0413dc6 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift@@ -81,10 +81,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {}override func performKeyEquivalent(with event: NSEvent) -> Bool {- if event.modifierFlags.contains(.command),- event.charactersIgnoringModifiers == "h"- {- keySender?.sendHome()+ if NSApp.mainMenu?.performKeyEquivalent(with: event) == true {return true}return super.performKeyEquivalent(with: event)@@ -112,14 +109,14 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {Task { @MainActor inguard let control, control.isConnected else {- showAlert(title: "Install App Package", message: "Guest is not connected.", style: .warning)+ VPhoneAlert.run(title: "Install App Package", message: "Guest is not connected.", style: .warning)return}do {let result = try await control.installIPA(localURL: url)print("[install] \(result)")- showAlert(+ VPhoneAlert.run(title: "Install App Package",message: VPhoneInstallPackage.successMessage(for: url.lastPathComponent,@@ -128,7 +125,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {style: .informational,)} catch {- showAlert(title: "Install App Package", message: "\(error)", style: .warning)+ VPhoneAlert.run(title: "Install App Package", message: "\(error)", style: .warning)}}return true@@ -155,18 +152,6 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {layer?.borderColor = visible ? NSColor.systemGreen.cgColor : NSColor.clear.cgColor}- private func showAlert(title: String, message: String, style: NSAlert.Style) {- let alert = NSAlert()- alert.messageText = title- alert.informativeText = message- alert.alertStyle = style- if let window {- alert.beginSheetModal(for: window)- } else {- alert.runModal()- }- }-// MARK: - Programmatic Touch (for automation)/// Convert screenshot pixel coordinates to NSView local coordinates.