Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

feat: 新增每台 VM 的 hardware keyboard 切換選單

Wing CHAN6f058bc86998
diff --git a/Research/hardware_keyboard_toggle.md b/Research/hardware_keyboard_toggle.md
new file mode 100644
index 00000000..2d22360c
--- /dev/null
+++ b/Research/hardware_keyboard_toggle.md
@@ -0,0 +1,77 @@
+# Hardware keyboard toggle(Issue #332)
+
+日期:2026-10-03。狀態:已實作;bundle、unit tests 與真實 guest 核心功能驗證通過。人工驗證限制見下文。
+
+VM 視窗的 **Device → Use Hardware Keyboard** 提供勾選選單及 **⇧⌘K**。
+勾選代表這個 VM 實際啟動時使用的 keyboard configuration。
+選單要求先保存 guest 工作,再選 **Restart and Apply**。
+取消不改動設定或 VM。套用會保存該 VM 的 `config.plist`,停止 VM,
+再在同一個 `NSApplication` 內重建 VM 與視窗。PID 及 console streams 保持不變。
+這是完整的 VM 重啟,不是 guest OS reboot,也不是即時 hot-plug。
+
+關閉時,VM 使用 `keyboards = []`,並停止從 Mac keyboard
+經 guest agent 轉送特殊鍵。開啟時恢復 `VZUSBKeyboardConfiguration`。
+`hardwareKeyboardEnabled` 未出現在舊 manifest 時,維持原有的開啟狀態。
+設定跟隨 VM。其他 VM 不受影響。
+
+## Framework 限制與依據
+
+Apple 的 [init(configuration:),Parameters](https://developer.apple.com/documentation/virtualization/vzvirtualmachine/init(configuration:))
+寫道:「The VM stores a copy of the configuration.」
+這直接支持:修改建立 VM 前的 configuration,不能當作運行中 VM 已更新的證據。
+
+Apple 的 [VZUSBDeviceConfiguration,Overview](https://developer.apple.com/documentation/virtualization/vzusbdeviceconfiguration)
+寫道:「Classes that conform to this protocol represent hot-pluggable USB device configurations.」
+同頁 Conforming Types 只列出 mass storage 與 passthrough configuration。
+[VZUSBKeyboardConfiguration,Inherits From](https://developer.apple.com/documentation/virtualization/vzusbkeyboardconfiguration)
+列出「VZKeyboardConfiguration」,Conforms To 沒有 `VZUSBDeviceConfiguration`。
+根據兩頁及 macOS SDK 宣告推論:public USB hot-plug API 不適用於這個虛擬 keyboard。
+因此實作使用完整 VM 重啟,沒有把忽略 key events 當作拔除 guest keyboard。
+
+本機 macOS 27.0.1 framework 的 Objective-C method inventory 顯示 `_VZKeyboard`
+有 `sendKeyEvents:`,但沒有 keyboard attach/detach selector。
+這是本機版本的觀察,不是所有 macOS 版本或 private API 的保證。
+
+## 驗證(2026-10-03)
+
+環境:macOS 27.0.1 (26A434)、Xcode 27.0 RC、Swift 6.4、
+真實 VPhone guest iOS 26.6.2 (23G90)。
+測試使用官方 VM 的 APFS 副本及隔離 local bundle。
+
+- 完整 `VPhone` Debug bundle build、`Bundle admission passed`、ad-hoc signature verification、Launchpad policy 與 Host preflight 均通過。
+- `VPhoneCoreKitTests/ManifestTests`:10 tests 通過。涵蓋舊 manifest、開/關 plist round-trip、其他欄位更新及 guest device 更新時保留 preference。
+- 官方 2.3.1 基線:Settings 搜尋欄已有 caret,但 software keyboard 沒有出現。
+- 關閉後,系統 software keyboard 出現。點按 numeric keys 後,搜尋欄讀回輸入值。
+- 開啟後,CUA 的原生 macOS `pressKey("a")` 經 window server 與 VM window,guest 搜尋欄讀回 `ㄇ`(注音輸入法)。
+- 關閉時,host `a`、Delete、fn、Ctrl+Space、Esc 事件沒有改變搜尋文字或 keyboard layout。
+- UI lifecycle 修正版完成關閉 → 開啟 → 關閉 → 開啟 → 關閉。最後交付 binary 再完成關閉 → 開啟 → 關閉及完全重新 launch。Host PID 在選單切換中保持,每次 guest 重啟後都取得新的 agent/UI read-back,選單與快捷鍵持續可操作。
+- 實際讀取 AppKit `NSMenuItem.state` 及 Virtualization runtime keyboard array,log 原句依序包含 `[keyboard] Menu checked: false, active keyboards: 0`、`[keyboard] Menu checked: true, active keyboards: 1`。兩種狀態與保存設定相符。
+- `Cancel` 保持 config SHA、Host PID 與 process 啟動時間不變。
+- 完全停止並重新 launch VM 後,false 設定保留,software keyboard 再次出現並能點按輸入。
+
+最後交付版的 VM binary SHA-256:
+`aee60324dad1889c956397a57b0053c1a6575a034d28b934bfc8f8acd021dbc2`。
+這個 binary 已通過關閉、開啟、再次關閉及重新 launch 的驗證。local bundle 的安裝 receipt、guest screenshot、UI tree 與 log 保留在本機驗證紀錄。
+
+測試沒有執行 Flutter Golden tests。第三方 keyboard extension 的安裝或註冊不屬於本功能驗收。
+
+## 限制
+
+- 這個版本需要完整 VM restart。Public API 的限制見上述依據。未宣稱可以即時 hot-plug。
+- 目前直接核對的是執行中的 AppKit menu state。CUA 未提供 menu checkmark 屬性,menu screenshot 無法取得,因此未直接核對畫面上的勾號像素。
+- Mac keyboard 路徑使用原生 macOS 事件自動化驗證。沒有真人手按實體鍵盤的觀察紀錄。
+- 實測僅涵蓋上述 host/guest 版本。其他 macOS 與 iPadOS guest 未測。
+
+## 重現命令
+
+```sh
+xcodebuild -workspace VPhone.xcworkspace -scheme VPhone -configuration Debug \
+ -destination 'platform=macOS,arch=arm64' -derivedDataPath .build/XcodeBundle build
+xcodebuild -project VPhoneKit/VPhoneKit.xcodeproj -scheme VPhoneCoreKitTests \
+ -destination 'platform=macOS,arch=arm64' -only-testing:VPhoneCoreKitTests/ManifestTests test
+```
+
+在隔離 VM 開啟 Settings 搜尋欄。使用 **Device → Use Hardware Keyboard**,
+分別取消及選擇 **Restart and Apply**。每次重啟後重新開啟搜尋欄,核對
+software keyboard 點按輸入及 Mac keyboard 輸入。最後停止並重新 launch VM,
+再核對選單 state、`config.plist` 與 guest 輸入。
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
index a109ed18..e1dfd59c 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
@@ -1,6 +1,193 @@
{
"sourceLanguage" : "en",
"strings" : {
+ "Use Hardware Keyboard" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Use Hardware Keyboard"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "使用硬件键盘"
+ }
+ }
+ }
+ },
+ "Changing the hardware keyboard requires restarting the virtual machine." : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Changing the hardware keyboard requires restarting the virtual machine."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "更改硬件键盘需要重新启动虚拟机。"
+ }
+ }
+ }
+ },
+ "Enable Hardware Keyboard?" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Enable Hardware Keyboard?"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "启用硬件键盘?"
+ }
+ }
+ }
+ },
+ "Disable Hardware Keyboard?" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Disable Hardware Keyboard?"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "停用硬件键盘?"
+ }
+ }
+ }
+ },
+ "Changing the hardware keyboard requires restarting the virtual machine. Save your work in the guest first. The setting is saved for this machine. With the hardware keyboard disabled, tap a text field to use the guest's software keyboard." : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Changing the hardware keyboard requires restarting the virtual machine. Save your work in the guest first. The setting is saved for this machine. With the hardware keyboard disabled, tap a text field to use the guest's software keyboard."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "更改硬件键盘需要重新启动虚拟机。请先保存客体系统中的工作。设置会保存在这台虚拟机中。停用硬件键盘后,点击文本框即可使用客体系统的软件键盘。"
+ }
+ }
+ }
+ },
+ "Restart and Apply" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Restart and Apply"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "重新启动并应用"
+ }
+ }
+ }
+ },
+ "Unable to Change Hardware Keyboard" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Unable to Change Hardware Keyboard"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "无法更改硬件键盘"
+ }
+ }
+ }
+ },
+ "Unable to Restart Virtual Machine" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Unable to Restart Virtual Machine"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "无法重新启动虚拟机"
+ }
+ }
+ }
+ },
+ "The virtual machine stopped and the keyboard setting was saved. Launch this machine again. Unable to restart: %@" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "The virtual machine stopped and the keyboard setting was saved. Launch this machine again. Unable to restart: %@"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "虚拟机已停止,键盘设置已保存。请再次启动这台虚拟机。无法重新启动:%@"
+ }
+ }
+ }
+ },
+ "Recording in Progress" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Recording in Progress"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在录制"
+ }
+ }
+ }
+ },
+ "Stop the screen recording before changing the hardware keyboard." : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Stop the screen recording before changing the hardware keyboard."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "请先停止屏幕录制,再更改硬件键盘。"
+ }
+ }
+ }
+ },
"%@ / %@" : {
"localizations" : {
"en" : {
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBattery.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBattery.swift
index 25805515..84a15538 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBattery.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBattery.swift
@@ -79,6 +79,13 @@ extension VPhoneMenuController {
// MARK: - Host Sync
+ /// Release the run-loop context before replacing this VM's controllers.
+ func stopBatteryMonitoring() {
+ batterySyncEnabled = false
+ stopPowerSourceMonitoring()
+ stopLowPowerMonitoring()
+ }
+
@objc func toggleBatterySync(_ sender: NSMenuItem) {
batterySyncEnabled.toggle()
sender.state = batterySyncEnabled ? .on : .off
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
index a4e70c5d..339a0682 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
@@ -1,4 +1,5 @@
import AppKit
+import Dynamic
import Foundation
// MARK: - Menu Controller
@@ -9,7 +10,18 @@ class VPhoneMenuController {
let control: VPhoneGuestControl
let guestToolsWindowController: VPhoneGuestToolsWindowController
let guestPanelsWindowController: VPhoneGuestPanelsWindowController
- weak var vm: VPhoneVirtualMachine?
+ weak var vm: VPhoneVirtualMachine? {
+ didSet {
+ hardwareKeyboardItem?.state = vm?.usesHardwareKeyboard == true ? .on : .off
+ hardwareKeyboardItem?.isEnabled = vm != nil
+ if let vm, let item = hardwareKeyboardItem {
+ let count = (Dynamic(vm.virtualMachine)._keyboards.asObject as? NSArray)?.count
+ print("[keyboard] Menu checked: \(item.state == .on), active keyboards: \(count.map(String.init) ?? "unknown")")
+ }
+ }
+ }
+ var hardwareKeyboardItem: NSMenuItem?
+ var onHardwareKeyboardChange: ((Bool) async throws -> Void)?
var onFilesPressed: (() -> Void)?
var onKeychainPressed: (() -> Void)?
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
index f6f920df..4c08355c 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
@@ -63,6 +63,17 @@ extension VPhoneMenuController {
menu.addItem(NSMenuItem.separator())
menu.addItem(makeItem("Open Guest Spotlight", action: #selector(sendSpotlight), symbol: "magnifyingglass"))
menu.addItem(makeItem("Switch Guest Input Source", action: #selector(sendGlobe), symbol: "globe"))
+ let keyboardItem = makeItem(
+ "Use Hardware Keyboard",
+ action: #selector(toggleHardwareKeyboard),
+ keyEquivalent: "k",
+ modifiers: [.command, .shift],
+ symbol: "keyboard",
+ )
+ keyboardItem.isEnabled = false
+ keyboardItem.toolTip = VPhoneLocalization.text("Changing the hardware keyboard requires restarting the virtual machine.")
+ hardwareKeyboardItem = keyboardItem
+ menu.addItem(keyboardItem)
// Trackpad scroll and pinch arrive as ordinary NSEvents; the view turns
// them into guest touches. Off hands both back to AppKit untouched.
let trackpadItem = makeItem(
@@ -126,6 +137,45 @@ extension VPhoneMenuController {
keySender.sendGlobe()
}
+ @objc func toggleHardwareKeyboard() {
+ guard let vm, let change = onHardwareKeyboardChange,
+ hardwareKeyboardItem?.isEnabled == true else { return }
+ guard screenRecorder?.isRecording != true else {
+ VPhoneAlert.present(
+ title: "Recording in Progress",
+ message: "Stop the screen recording before changing the hardware keyboard.",
+ style: .warning,
+ )
+ return
+ }
+ let enabled = !vm.usesHardwareKeyboard
+ hardwareKeyboardItem?.isEnabled = false
+ VPhoneAlert.present(
+ title: enabled ? "Enable Hardware Keyboard?" : "Disable Hardware Keyboard?",
+ message: "Changing the hardware keyboard requires restarting the virtual machine. Save your work in the guest first. The setting is saved for this machine. With the hardware keyboard disabled, tap a text field to use the guest's software keyboard.",
+ style: .warning,
+ buttons: ["Restart and Apply", "Cancel"],
+ ) { [weak self] response in
+ guard let self else { return }
+ guard response == .alertFirstButtonReturn else {
+ hardwareKeyboardItem?.isEnabled = true
+ return
+ }
+ Task { [weak self] in
+ do {
+ try await change(enabled)
+ } catch {
+ self?.hardwareKeyboardItem?.isEnabled = true
+ VPhoneAlert.present(
+ title: "Unable to Change Hardware Keyboard",
+ message: error.localizedDescription,
+ style: .warning,
+ )
+ }
+ }
+ }
+ }
+
// MARK: - Rotate
/// The four interface orientations, checked by the one the window last
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift
index 0be6edb1..e0dad034 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift
@@ -51,6 +51,16 @@ final class VPhoneApplication: NSApplication {
/// it goes on to the virtual keyboard, which `VPhoneHostKeyEvents` then
/// delivers to the view itself.
func takeKeyEvent(_ event: NSEvent, view: VPhoneVirtualMachineView) -> Bool {
+ if !view.hardwareKeyboardEnabled {
+ // Keep host menu shortcuts available, including the keyboard toggle.
+ // Do not synthesize dropped keys through vphoned while disconnected.
+ if event.type == .keyDown, mainMenu?.performKeyEquivalent(with: event) == true {
+ menuKeyCodes.insert(event.keyCode)
+ } else if event.type == .keyUp {
+ menuKeyCodes.remove(event.keyCode)
+ }
+ return true
+ }
if event.type == .flagsChanged {
forwardGlobe(event, view: view)
return false
@@ -81,6 +91,13 @@ final class VPhoneApplication: NSApplication {
// MARK: - Keys the Virtual Keyboard Drops
+ /// A rebuilt VM must not inherit keys or a guest connection from the old one.
+ func resetGuestKeyState() {
+ releaseGlobe(leavingWindow: true)
+ forwardedKeys.removeAll()
+ menuKeyCodes.removeAll()
+ }
+
/// fn / 🌐 reaches AppKit only as a flags change, and the virtual USB
/// keyboard has no field for it. vphoned presses the guest's 🌐 for it, held
/// for as long as fn is, so 🌐 alone switches the input source and 🌐
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
index 3703dfac..05d278c4 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
@@ -11,6 +11,8 @@ class VPhoneVirtualMachineWindowController: NSObject {
private(set) var touchIDMonitor: VPhoneTouchIDMonitor?
private var homeButton: NSButton?
private var subtitleLabel: NSTextField?
+ private var timers: [Timer] = []
+ private var keyStateObservers: [NSObjectProtocol] = []
var captureView: VPhoneVirtualMachineView? {
virtualMachineView
@@ -21,6 +23,7 @@ class VPhoneVirtualMachineWindowController: NSObject {
screenWidth: Int,
screenHeight: Int,
screenScale: Double,
+ hardwareKeyboardEnabled: Bool,
keySender: VPhoneVirtualMachineKeySender,
control: VPhoneGuestControl,
name: String,
@@ -30,7 +33,8 @@ class VPhoneVirtualMachineWindowController: NSObject {
let view = VPhoneVirtualMachineView()
view.virtualMachine = vm
- view.capturesSystemKeys = true
+ view.hardwareKeyboardEnabled = hardwareKeyboardEnabled
+ view.capturesSystemKeys = hardwareKeyboardEnabled
view.keySender = keySender
view.control = control
view.clipboardSync = VPhoneClipboardSync(control: control)
@@ -102,13 +106,13 @@ class VPhoneVirtualMachineWindowController: NSObject {
touchIDMonitor = monitor
// Poll vphoned status for the Home button and the subtitle
- _ = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] _ in
+ timers.append(Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] _ in
Task { @MainActor in
guard let self, let control = self.control else { return }
self.updateHomeButton(connected: control.isConnected)
self.updateSubtitle(control: control)
}
- }
+ })
// The menu sets the orientation before the guest turns, and the poll
// after; either way the window follows it.
@@ -116,9 +120,27 @@ class VPhoneVirtualMachineWindowController: NSObject {
guard let self, let window else { return }
applyOrientation(orientation ?? .portrait, to: window)
}
- _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
+ timers.append(Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
Task { @MainActor in self?.pollOrientation() }
- }
+ })
+ }
+
+ /// Disconnect the old display and input devices before rebuilding the VM.
+ func closeForRestart() {
+ timers.forEach { $0.invalidate() }
+ timers.removeAll()
+ keyStateObservers.forEach { NotificationCenter.default.removeObserver($0) }
+ keyStateObservers.removeAll()
+ NotificationCenter.default.removeObserver(self)
+ touchIDMonitor?.stop()
+ touchIDMonitor = nil
+ captureView?.virtualMachine = nil
+ captureView?.keySender = nil
+ captureView?.control = nil
+ captureView?.clipboardSync = nil
+ windowController?.close()
+ windowController = nil
+ VPhoneHostHotKeys.shared.resume()
}
// MARK: - Orientation
@@ -171,15 +193,19 @@ class VPhoneVirtualMachineWindowController: NSObject {
/// is key; see `VPhoneHostHotKeys`.
private func observeKeyState(of window: NSWindow) {
let center = NotificationCenter.default
- center.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: .main) { _ in
- MainActor.assumeIsolated { VPhoneHostHotKeys.shared.suspend() }
- }
+ keyStateObservers.append(center.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: .main) { [weak self] _ in
+ MainActor.assumeIsolated {
+ if self?.captureView?.hardwareKeyboardEnabled == true {
+ VPhoneHostHotKeys.shared.suspend()
+ }
+ }
+ })
for name in [NSWindow.didResignKeyNotification, NSWindow.willCloseNotification] {
- center.addObserver(forName: name, object: window, queue: .main) { _ in
+ keyStateObservers.append(center.addObserver(forName: name, object: window, queue: .main) { _ in
MainActor.assumeIsolated { VPhoneHostHotKeys.shared.resume() }
- }
+ })
}
- if window.isKeyWindow {
+ if window.isKeyWindow, captureView?.hardwareKeyboardEnabled == true {
VPhoneHostHotKeys.shared.suspend()
}
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift
index f3ea2b46..2e690f16 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift
@@ -147,6 +147,8 @@ class VPhoneHostAutomationServer {
func stop() {
if listenFD >= 0 {
+ // Wake the blocked accept before a VM restart creates a new socket.
+ shutdown(listenFD, SHUT_RDWR)
close(listenFD)
listenFD = -1
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
index 2763d640..6350d7c6 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
@@ -18,6 +18,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
private var apiProxy: VPhoneAPIProxy?
private var sigintSource: DispatchSourceSignal?
private var didAttemptAutoInstall = false
+ private var isRestartingVirtualMachine = false
init(command: VPhoneBootCommand) {
self.command = command
@@ -123,6 +124,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
screenWidth: options.screenWidth,
screenHeight: options.screenHeight,
screenScale: options.screenScale,
+ hardwareKeyboardEnabled: vm.usesHardwareKeyboard,
keySender: keySender,
control: control,
name: VPhoneDockName.name(forConfig: options.configURL),
@@ -150,6 +152,10 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
let mc = VPhoneMenuController(keySender: keySender, control: control)
mc.vm = vm
+ mc.onHardwareKeyboardChange = { [weak self] enabled in
+ guard let self else { return }
+ try await restartWithHardwareKeyboard(enabled)
+ }
mc.captureView = wc.captureView
mc.touchIDMonitor = wc.touchIDMonitor
mc.onFilesPressed = { [weak fileWC, weak control] in
@@ -311,13 +317,83 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
}
}
- func applicationWillTerminate(_: Notification) {
+ @MainActor
+ private func stopControlServices() {
hostAutomationServer?.stop()
apiProxy?.stop()
control?.stop()
}
+ /// Virtualization copies the keyboard configuration when creating the VM.
+ /// A guest reboot leaves the USB device in place. Rebuild the VM's devices
+ /// inside the same NSApplication so the menu remains registered with macOS.
+ @MainActor
+ private func restartWithHardwareKeyboard(_ enabled: Bool) async throws {
+ guard !isRestartingVirtualMachine else { return }
+ isRestartingVirtualMachine = true
+ defer { isRestartingVirtualMachine = false }
+ try await stopForHardwareKeyboardChange(enabled)
+
+ vm?.stopHostDevices()
+ (NSApp as? VPhoneApplication)?.resetGuestKeyState()
+ stopControlServices()
+ locationProvider?.stopForwarding()
+ locationProvider?.stopReplay()
+ cameraServer?.disconnect()
+ menuController?.stopBatteryMonitoring()
+ windowController?.closeForRestart()
+ // Tool windows belong to the old guest connection too.
+ for window in NSApp.windows { window.close() }
+ NSApp.mainMenu = nil
+ windowController = nil
+ menuController = nil
+ fileWindowController = nil
+ keychainWindowController = nil
+ appWindowController = nil
+ locationProvider = nil
+ cameraServer = nil
+ hostAutomationServer = nil
+ apiProxy = nil
+ control = nil
+ vm = nil
+
+ print("[vphone] Restarting with hardware keyboard \(enabled ? "enabled" : "disabled")")
+ do {
+ try await startVirtualMachine()
+ } catch {
+ VPhoneAlert.present(
+ title: "Unable to Restart Virtual Machine",
+ message: VPhoneLocalization.format("The virtual machine stopped and the keyboard setting was saved. Launch this machine again. Unable to restart: %@", error.localizedDescription),
+ style: .warning,
+ ) { _ in NSApp.terminate(nil) }
+ }
+ }
+
+ @MainActor
+ private func stopForHardwareKeyboardChange(_ enabled: Bool) async throws {
+ guard let vm else { return }
+ let manifest = try VPhoneVirtualMachineManifest.load(from: command.config)
+ try manifest.updating(hardwareKeyboardEnabled: enabled).write(to: command.config)
+
+ // An intentional stop must not go through guestDidStop's exit handler.
+ vm.virtualMachine.delegate = nil
+ do {
+ nonisolated(unsafe) let machine = vm.virtualMachine
+ try await machine.stop()
+ } catch {
+ vm.virtualMachine.delegate = vm
+ // Preserve any other edits made while stop was in flight.
+ let current = try VPhoneVirtualMachineManifest.load(from: command.config)
+ try current.updating(hardwareKeyboardEnabled: vm.usesHardwareKeyboard).write(to: command.config)
+ throw error
+ }
+ }
+
+ func applicationWillTerminate(_: Notification) {
+ stopControlServices()
+ }
+
func applicationShouldTerminateAfterLastWindowClosed(_: NSApplication) -> Bool {
- !command.noGraphics
+ !command.noGraphics && !isRestartingVirtualMachine
}
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift
index 0d4b59b2..1f824cef 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift
@@ -7,10 +7,13 @@ import VPhoneCoreKit
@MainActor
class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
let virtualMachine: VZVirtualMachine
+ /// The configuration actually used by this VM, rather than a pending preference.
+ let usesHardwareKeyboard: Bool
/// ECID hex string resolved from machineIdentifier (e.g. "0x0012345678ABCDEF").
let ecidHex: String?
/// Read handle for VM serial output.
private var serialOutputReadHandle: FileHandle?
+ private var serialInputSource: DispatchSourceRead?
/// Synthetic battery source for runtime charge/connectivity updates.
private var batterySource: AnyObject?
/// The in-process network backing `.tunnel` mode; nil for every other mode.
@@ -64,19 +67,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
let newID = VZMacMachineIdentifier()
machineIdentifier = newID
- manifest = VPhoneVirtualMachineManifest(
- platformType: manifest.platformType,
- platformFusing: manifest.platformFusing,
- machineIdentifier: newID.dataRepresentation,
- cpuCount: manifest.cpuCount,
- memorySize: manifest.memorySize,
- screenConfig: manifest.screenConfig,
- networkConfig: manifest.networkConfig,
- diskImage: manifest.diskImage,
- nvramStorage: manifest.nvramStorage,
- romImages: manifest.romImages,
- sepStorage: manifest.sepStorage,
- )
+ manifest = manifest.updating(machineIdentifier: newID.dataRepresentation)
try manifest.write(to: options.configURL)
try VPhoneHostFilePermissions.makeAccessible(at: options.configURL)
@@ -198,16 +189,21 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
// Forward host stdin -> VM serial input
let writeHandle = inputPipe.fileHandleForWriting
let stdinFD = FileHandle.standardInput.fileDescriptor
- DispatchQueue.global(qos: .userInteractive).async {
+ let inputSource = DispatchSource.makeReadSource(
+ fileDescriptor: stdinFD, queue: .global(qos: .userInteractive),
+ )
+ inputSource.setEventHandler { @Sendable [weak inputSource] in
var buf = [UInt8](repeating: 0, count: 4096)
- while true {
- let n = read(stdinFD, &buf, buf.count)
- if n <= 0 {
- break
- }
- writeHandle.write(Data(buf[..<n]))
+ let n = read(stdinFD, &buf, buf.count)
+ if n > 0 {
+ try? writeHandle.write(contentsOf: Data(buf[..<n]))
+ } else if n == 0 || errno != EINTR {
+ inputSource?.cancel()
}
}
+ inputSource.setCancelHandler { @Sendable in try? writeHandle.close() }
+ inputSource.activate()
+ serialInputSource = inputSource
serialOutputReadHandle = outputPipe.fileHandleForReading
@@ -233,7 +229,9 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
config.entropyDevices = [obj]
print("[vphone] Entropy device configured")
- config.keyboards = [VZUSBKeyboardConfiguration()]
+ usesHardwareKeyboard = manifest.usesHardwareKeyboard
+ config.keyboards = usesHardwareKeyboard ? [VZUSBKeyboardConfiguration()] : []
+ print("[vphone] Hardware keyboard: \(usesHardwareKeyboard ? "enabled" : "disabled")")
// Vsock (host <-> guest control channel, no IP/TCP involved)
config.socketDevices = [VZVirtioSocketDeviceConfiguration()]
@@ -302,6 +300,14 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
// MARK: - Bundle Files
+ /// Cancel serial forwarding before another VM takes the same host stdin.
+ func stopHostDevices() {
+ serialInputSource?.cancel()
+ serialInputSource = nil
+ serialOutputReadHandle?.readabilityHandler = nil
+ serialOutputReadHandle = nil
+ }
+
/// Every file below is opened, created or overwritten by this process or
/// by Virtualization, and neither refuses a symbolic link. A bundle can
/// come from someone else's export, so an entry that exists must be a
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift
index 2f3efd3d..3b5b9bed 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift
@@ -10,6 +10,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {
/// Whether Esc replays the back gesture (an iPhone, which has no Esc key)
/// or reaches the guest as Esc (an iPad). See `VPhoneApplication`.
var escapeIsBackGesture = true
+ var hardwareKeyboardEnabled = true
/// Whether trackpad scroll/pinch gestures are replayed as guest touches.
var trackpadGesturesEnabled = VPhoneTrackpadGestures.isEnabled {
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift
index 57134fdd..04a07ae7 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift
@@ -92,6 +92,11 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
/// Memory size in bytes
public let memorySize: UInt64
+ /// Missing in older manifests, which keep the original USB keyboard.
+ public let hardwareKeyboardEnabled: Bool?
+
+ public var usesHardwareKeyboard: Bool { hardwareKeyboardEnabled ?? true }
+
// MARK: - Display
/// Screen configuration
@@ -224,6 +229,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
romImages: ROMImages?,
sepStorage: String = "SEPStorage",
guestProductType: String? = nil,
+ hardwareKeyboardEnabled: Bool? = nil,
) {
schemaVersion = Self.currentSchemaVersion
self.platformType = platformType
@@ -238,6 +244,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
self.romImages = romImages
self.sepStorage = sepStorage
self.guestProductType = guestProductType
+ self.hardwareKeyboardEnabled = hardwareKeyboardEnabled
}
// MARK: - Creation
@@ -405,6 +412,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
memorySize: UInt64? = nil,
machineIdentifier: Data? = nil,
networkConfig: NetworkConfig? = nil,
+ hardwareKeyboardEnabled: Bool? = nil,
) -> VPhoneVirtualMachineManifest {
VPhoneVirtualMachineManifest(
platformType: platformType,
@@ -419,6 +427,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
romImages: romImages,
sepStorage: sepStorage,
guestProductType: guestProductType,
+ hardwareKeyboardEnabled: hardwareKeyboardEnabled ?? self.hardwareKeyboardEnabled,
)
}
@@ -439,6 +448,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
romImages: romImages,
sepStorage: sepStorage,
guestProductType: device == .default ? nil : device.productType,
+ hardwareKeyboardEnabled: hardwareKeyboardEnabled,
)
}
}
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ManifestTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ManifestTests.swift
index a0c6aa2e..31bf56d0 100644
--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ManifestTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ManifestTests.swift
@@ -34,6 +34,32 @@ struct ManifestTests {
#expect(updated.networkConfig.mode == .nat)
}
+ @Test func `old manifests keep the hardware keyboard enabled`() throws {
+ let encoder = PropertyListEncoder()
+ let data = try encoder.encode(sampleManifest())
+ let plist = try #require(PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any])
+ #expect(plist["hardwareKeyboardEnabled"] == nil)
+ let loaded = try PropertyListDecoder().decode(VPhoneVirtualMachineManifest.self, from: data)
+ #expect(loaded.usesHardwareKeyboard)
+ }
+
+ @Test(arguments: [true, false])
+ func `keyboard setting survives plist and unrelated edits`(enabled: Bool) throws {
+ let original = sampleManifest().updating(hardwareKeyboardEnabled: enabled)
+ let data = try PropertyListEncoder().encode(original)
+ let loaded = try PropertyListDecoder().decode(VPhoneVirtualMachineManifest.self, from: data)
+ #expect(loaded.usesHardwareKeyboard == enabled)
+ #expect(loaded.hardwareKeyboardEnabled == enabled)
+ let edited = loaded.updating(cpuCount: 4, machineIdentifier: Data([1, 2, 3]))
+ #expect(edited.usesHardwareKeyboard == enabled)
+ #expect(edited.cpuCount == 4)
+ #expect(edited.machineIdentifier == Data([1, 2, 3]))
+ #expect(edited.diskImage == original.diskImage)
+ #expect(edited.networkConfig == original.networkConfig)
+ #expect(edited.updating(guestDevice: .default).usesHardwareKeyboard == enabled)
+ #expect(edited.updating(hardwareKeyboardEnabled: !enabled).usesHardwareKeyboard == !enabled)
+ }
+
@Test func `network config round trips through plist`() throws {
let dir = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)