Run a virtual iPhone on an Apple Silicon Mac.
Swift
Implement a battery sync between the VM and the host (#230)
Brandon Lekai9c90286b703d
diff --git a/scripts/vphoned/vphoned.m b/scripts/vphoned/vphoned.mindex b90f7d3e..c31049cc 100644--- a/scripts/vphoned/vphoned.m+++ b/scripts/vphoned/vphoned.m@@ -29,6 +29,7 @@#import "vphoned_install.h"#import "vphoned_keychain.h"#import "vphoned_location.h"+#import "vphoned_notify.h"#import "vphoned_protocol.h"#import "vphoned_settings.h"#import "vphoned_url.h"@@ -384,6 +385,14 @@ static BOOL handle_client(int fd) {continue;}+ // Low power mode sync+ if ([t isEqualToString:@"low_power_mode"]) {+ NSDictionary *resp = vp_handle_notify_command(msg);+ if (resp && !vp_write_message(fd, resp))+ break;+ continue;+ }+NSDictionary *resp = handle_command(msg);if (resp && !vp_write_message(fd, resp))break;diff --git a/scripts/vphoned/vphoned_notify.h b/scripts/vphoned/vphoned_notify.hnew file mode 100644index 00000000..4fce53d4--- /dev/null+++ b/scripts/vphoned/vphoned_notify.h@@ -0,0 +1,4 @@+#pragma once+#import <Foundation/Foundation.h>++NSDictionary *vp_handle_notify_command(NSDictionary *msg);diff --git a/scripts/vphoned/vphoned_notify.m b/scripts/vphoned/vphoned_notify.mnew file mode 100644index 00000000..76223b1a--- /dev/null+++ b/scripts/vphoned/vphoned_notify.m@@ -0,0 +1,32 @@+/*+ * vphoned_notify — Low power mode state sync.+ *+ * Sets LPM state via notify_set_state("com.apple.system.lowpowermode") + notify_post.+ * All registrations for a notification name share one state value, so this+ * updates what NSProcessInfo and SpringBoard read via notify_get_state —+ * mirroring what powerd does internally when the user toggles Low Power Mode.+ */++#import "vphoned_notify.h"+#import "vphoned_protocol.h"+#include <notify.h>++NSDictionary *vp_handle_notify_command(NSDictionary *msg) {+ id reqId = msg[@"id"];+ BOOL enabled = [msg[@"enabled"] boolValue];++ int token = 0;+ BOOL ok = (notify_register_check("com.apple.system.lowpowermode", &token) ==+ NOTIFY_STATUS_OK);+ if (ok) {+ notify_set_state(token, enabled ? 1 : 0);+ ok = (notify_post("com.apple.system.lowpowermode") == NOTIFY_STATUS_OK);+ notify_cancel(token);+ }++ NSLog(@"vphoned: low_power_mode %s -> %s", enabled ? "on" : "off",+ ok ? "ok" : "failed");+ NSMutableDictionary *r = vp_make_response(@"low_power_mode", reqId);+ r[@"ok"] = @(ok);+ return r;+}diff --git a/sources/vphone-cli/VPhoneAppDelegate.swift b/sources/vphone-cli/VPhoneAppDelegate.swiftindex afa9e736..9f663b67 100644--- a/sources/vphone-cli/VPhoneAppDelegate.swift+++ b/sources/vphone-cli/VPhoneAppDelegate.swift@@ -152,6 +152,8 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {} else {print("[location] guest does not support location simulation")}+ mc?.syncBatteryFromHost()+ mc?.syncLowPowerModeFromHost()}control.onDisconnect = { [weak mc, weak provider = locationProvider] inmc?.updateConnectAvailability(available: false)diff --git a/sources/vphone-cli/VPhoneControl.swift b/sources/vphone-cli/VPhoneControl.swiftindex 7f1f2d9d..aa23fbf9 100644--- a/sources/vphone-cli/VPhoneControl.swift+++ b/sources/vphone-cli/VPhoneControl.swift@@ -652,6 +652,14 @@ class VPhoneControl {_ = try await sendRequest(req)}+ func lowPowerMode(enabled: Bool) async throws {+ let (resp, _) = try await sendRequest(["t": "low_power_mode", "enabled": enabled])+ let ok = resp["ok"] as? Bool ?? false+ if !ok {+ throw ControlError.guestError("low_power_mode: failed to set state on guest")+ }+ }+// MARK: - Accessibilityfunc accessibilityTree(depth: Int = -1) async throws -> [String: Any] {diff --git a/sources/vphone-cli/VPhoneMenuBattery.swift b/sources/vphone-cli/VPhoneMenuBattery.swiftindex 0f22580b..863299b3 100644--- a/sources/vphone-cli/VPhoneMenuBattery.swift+++ b/sources/vphone-cli/VPhoneMenuBattery.swift@@ -1,4 +1,5 @@import AppKit+import IOKit.ps// MARK: - Battery Menu@@ -7,12 +8,28 @@ extension VPhoneMenuController {let item = NSMenuItem(title: "Battery", action: nil, keyEquivalent: "")let menu = NSMenu(title: "Battery")+ // Sync toggle+ let syncItem = makeItem("Sync with Host", action: #selector(toggleBatterySync(_:)))+ syncItem.state = .off+ menu.addItem(syncItem)++ // Status line (hidden until sync is active)+ let statusItem = NSMenuItem(title: "Status: —", action: nil, keyEquivalent: "")+ statusItem.isEnabled = false+ statusItem.isHidden = true+ menu.addItem(statusItem)+ batterySyncStatusItem = statusItem++ menu.addItem(NSMenuItem.separator())+// Charge level presets+ batteryLevelMenuItems = []for level in [100, 75, 50, 25, 10, 5] {let mi = makeItem("\(level)%", action: #selector(setBatteryLevel(_:)))mi.tag = levelmi.state = level == 100 ? .on : .offmenu.addItem(mi)+ batteryLevelMenuItems.append(mi)}menu.addItem(NSMenuItem.separator())@@ -26,8 +43,21 @@ extension VPhoneMenuController {menu.addItem(charging)menu.addItem(disconnected)+ batteryConnectivityMenuItems = [charging, disconnected]item.submenu = menu++ // Enable sync by default+ syncItem.state = .on+ batterySyncEnabled = true+ batterySyncStatusItem?.isHidden = false+ batteryLevelMenuItems.forEach { $0.isEnabled = false }+ batteryConnectivityMenuItems.forEach { $0.isEnabled = false }+ syncBatteryFromHost()+ syncLowPowerModeFromHost()+ startPowerSourceMonitoring()+ startLowPowerMonitoring()+return item}@@ -55,6 +85,133 @@ extension VPhoneMenuController {print("[battery] set \(Int(charge))%, connectivity=\(sender.tag)")}+ // MARK: - Host Sync++ @objc func toggleBatterySync(_ sender: NSMenuItem) {+ batterySyncEnabled.toggle()+ sender.state = batterySyncEnabled ? .on : .off+ batterySyncStatusItem?.isHidden = !batterySyncEnabled+ let manualEnabled = !batterySyncEnabled+ batteryLevelMenuItems.forEach { $0.isEnabled = manualEnabled }+ batteryConnectivityMenuItems.forEach { $0.isEnabled = manualEnabled }++ if batterySyncEnabled {+ syncBatteryFromHost()+ syncLowPowerModeFromHost()+ startPowerSourceMonitoring()+ startLowPowerMonitoring()+ } else {+ stopPowerSourceMonitoring()+ stopLowPowerMonitoring()+ }+ print("[battery] host sync \(batterySyncEnabled ? "enabled" : "disabled")")+ }++ // MARK: - Battery State Sync++ func syncBatteryFromHost() {+ guard batterySyncEnabled else { return }+ guard let (charge, connectivity) = hostBatteryState() else {+ batterySyncStatusItem?.title = "Status: no host battery"+ return+ }+ vm?.setBattery(charge: charge, connectivity: connectivity)+ updateStatusLabel(charge: charge, connectivity: connectivity)+ print("[battery] sync \(Int(charge))%, connectivity=\(connectivity)")+ }++ private func hostBatteryState() -> (charge: Double, connectivity: Int)? {+ let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()+ let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as [CFTypeRef]+ for source in sources {+ guard let info = IOPSGetPowerSourceDescription(snapshot, source)?+ .takeUnretainedValue() as? [String: Any] else { continue }+ guard let type = info[kIOPSTypeKey as String] as? String,+ type == kIOPSInternalBatteryType else { continue }+ let capacity = info[kIOPSCurrentCapacityKey as String] as? Int ?? 100+ let state = info[kIOPSPowerSourceStateKey as String] as? String ?? kIOPSACPowerValue+ let connectivity = (state == kIOPSACPowerValue) ? 1 : 2+ return (Double(capacity), connectivity)+ }+ return nil+ }++ // MARK: - Low Power Mode Sync++ func syncLowPowerModeFromHost() {+ guard batterySyncEnabled else { return }+ let enabled = ProcessInfo.processInfo.isLowPowerModeEnabled+ Task {+ do {+ try await control.lowPowerMode(enabled: enabled)+ syncBatteryFromHost() // refresh status label with updated LPM state+ print("[battery] sync LPM: \(enabled)")+ } catch {+ print("[battery] sync LPM failed: \(error)")+ }+ }+ }++ // MARK: - IOKit Power Source Monitoring++ private func startPowerSourceMonitoring() {+ stopPowerSourceMonitoring()+ let rawPtr = Unmanaged.passRetained(self).toOpaque()+ powerSourceRetainedPtr = rawPtr+ let source = IOPSNotificationCreateRunLoopSource({ rawContext in+ guard let ctx = rawContext else { return }+ Task { @MainActor in+ Unmanaged<VPhoneMenuController>.fromOpaque(ctx)+ .takeUnretainedValue()+ .syncBatteryFromHost()+ }+ }, rawPtr)+ guard let runLoopSource = source?.takeRetainedValue() else { return }+ powerSourceRunLoopSource = runLoopSource+ CFRunLoopAddSource(CFRunLoopGetMain(), runLoopSource, .defaultMode)+ }++ private func stopPowerSourceMonitoring() {+ if let source = powerSourceRunLoopSource {+ CFRunLoopRemoveSource(CFRunLoopGetMain(), source, .defaultMode)+ powerSourceRunLoopSource = nil+ }+ if let ptr = powerSourceRetainedPtr {+ Unmanaged<VPhoneMenuController>.fromOpaque(ptr).release()+ powerSourceRetainedPtr = nil+ }+ }++ // MARK: - Low Power Mode Monitoring++ private func startLowPowerMonitoring() {+ stopLowPowerMonitoring()+ lowPowerObserver = NotificationCenter.default.addObserver(+ forName: Notification.Name("NSProcessInfoPowerStateDidChangeNotification"),+ object: nil,+ queue: .main+ ) { [weak self] _ in+ Task { @MainActor in self?.syncLowPowerModeFromHost() }+ }+ }++ private func stopLowPowerMonitoring() {+ if let observer = lowPowerObserver {+ NotificationCenter.default.removeObserver(observer)+ lowPowerObserver = nil+ }+ }++ // MARK: - Status Label++ private func updateStatusLabel(charge: Double, connectivity: Int) {+ let connLabel = connectivity == 1 ? "charging" : "not charging"+ let lpmLabel = ProcessInfo.processInfo.isLowPowerModeEnabled ? ", low power" : ""+ batterySyncStatusItem?.title = "Status: \(Int(charge))% (\(connLabel)\(lpmLabel))"+ }++ // MARK: - Helpers+private func currentBatteryCharge(in menu: NSMenu) -> Double {for mi in menu.items {if mi.isSeparatorItem { break }diff --git a/sources/vphone-cli/VPhoneMenuController.swift b/sources/vphone-cli/VPhoneMenuController.swiftindex f32fdcd3..aa09e838 100644--- a/sources/vphone-cli/VPhoneMenuController.swift+++ b/sources/vphone-cli/VPhoneMenuController.swift@@ -36,6 +36,13 @@ class VPhoneMenuController {var screenRecorder: VPhoneScreenRecorder?var recordingItem: NSMenuItem?weak var captureView: VPhoneVirtualMachineView?+ var batterySyncEnabled = false+ var batterySyncStatusItem: NSMenuItem?+ var batteryLevelMenuItems: [NSMenuItem] = []+ var batteryConnectivityMenuItems: [NSMenuItem] = []+ var powerSourceRunLoopSource: CFRunLoopSource?+ var powerSourceRetainedPtr: UnsafeMutableRawPointer?+ var lowPowerObserver: (any NSObjectProtocol)?init(keyHelper: VPhoneKeyHelper, control: VPhoneControl) {self.keyHelper = keyHelper