Run a virtual iPhone on an Apple Silicon Mac.
Swift
Scroll iPad guests natively through a virtual pointing device
Jacky427df2632a83
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex a74fa9a5..1b75ae44 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -324,7 +324,7 @@ request carries `"force": true`.| --- | --- || Device | `device.snapshot`, `device.info` (snapshot plus network, screen, rotation, brightness, volume, low power, Developer Mode, agent, `device_name` `{name, own_name}`: the pinned name and the guest's own ComputerName), `device.screen`, `device.network`, `device.ioreg {plane}`, `device.environment`, `device.basebin {archive?}` || Display, audio | `display.brightness {value?}`, `display.rotation {orientation?}`, `display.orientation` (`{degrees, source}`: SpringBoard's interface orientation without a screen capture, for polling; `degrees` is null while SpringBoard has no answer; capability `display_orientation`), `display.rotation_lock {locked}`, `display.auto_lock` (`{auto_lock_seconds, never, lock_screen_minimum_seconds}`: Auto-Lock and the Lock Screen timeout vphoned keeps in step with it, see below; capability `display_auto_lock`), `screen.unlock {passcode?, timeout?}` (`{locked, screen_off, was_locked, was_screen_off}`: the display on and the Lock Screen passed, see below; capability `screen_unlock`), `audio.volume {value?, category?}`, `audio.state` |-| Input | `input.touch`, `input.hid`, `input.button {name}`, `input.key {name}`, `input.type {text, delay_ms?}`, `input.paste {text}`, `input.tap`, `input.double_tap`, `input.long_press`, `input.swipe`, `input.drag {points}`, `input.touch_sequence {events}` — gesture coordinates are screen points |+| Input | `input.touch`, `input.hid`, `input.button {name}`, `input.key {name}`, `input.type {text, delay_ms?}`, `input.paste {text}`, `input.tap`, `input.double_tap`, `input.long_press`, `input.swipe`, `input.drag {points}`, `input.touch_sequence {events}` — gesture coordinates are screen points; `input.pointer {x, y}`, `input.scroll {phase, dx?, dy?, x?, y?}` (capability `pointer_scroll`, see below) || UI | `ui.tree` (alias `accessibility.tree`), `ui.element_at`, `ui.tap_element`, `ui.wait`, `ui.wait_gone`, `ui.ocr {languages?, min_confidence?}`, `ui.describe`, `screen.screenshot` || Processes | `processes.list {filter?}`, `processes.kill {pid, signal?}` **force**, `memory.jetsam`, `memory.pressure` (only the three kernel memory sysctls, for polling) || launchd | `services.list`, `status`, `print`, `dump`, `disabled`, `start`, `enable`, `load`, `profile` (see below); `services.stop`, `disable`, `remove`, `signal`, `unload`, `profile.apply {profile, groups?, allow?}` **force**; `launchd.getenv`, `setenv`, `unsetenv`. On tvOS, which never enables user sessions, they read the system domain alone; before icli 0.8.6 the foreground-user lookup trapped there and killed vphoned |@@ -416,6 +416,29 @@ offers the last fix again every 10 s until the guest takes it, since the Macsends a new one only when it moves. A preset or a replay pauses sync for thatrun without changing the setting.+`input.pointer` and `input.scroll` (capability `pointer_scroll`, iPad guests+only; REST `POST /v1/input/pointer`, `POST /v1/input/scroll`) scroll the way an+iPad with a trackpad does, instead of with a dragging finger. On first use+vphoned creates a virtual pointing device (a HID user device with an absolute+position, `VPhoneDaemon/Native/vphoned_pointer.m`); iPadOS then shows a pointer,+which hides itself after a few seconds without movement.++- `input.pointer {x, y}` puts the pointer at x, y: 0...1 from the top-left+ corner of the interface as it is shown, in any orientation.+- `input.scroll {phase, dx?, dy?, x?, y?}` sends one scroll event to the view+ under the pointer, after moving the pointer to x, y when they are given.+ `phase` is `began`, `changed`, `ended` or `cancelled`: `began` first, a+ `changed` per delta, then `ended`. `dx` and `dy` are interface points with a+ browser wheel event's signs, positive `dy` toward the end of the content,+ under the guest's natural scrolling setting (on by default); each is at most+ 10000.++The view moves by the deltas and by nothing else: iPadOS does not run on+after `ended`, so a client that wants a trackpad's momentum sends it as more+`changed` deltas first. The first few points of a scroll start the gesture+and do not move the view (about 15 points on iPadOS 26). Both answer+`invalid_operation` when the device cannot be made or is not ready yet.+`time.timezone` (capability `timezone`; REST `GET/PUT /v1/timezone`) returns`{identifier, automatic, seconds_from_gmt}`: the Olson name`/var/db/timezone/localtime` points to under `/var/db/timezone/zoneinfo`, anddiff --git a/Skills/vphone-guest-control/references/rpc-methods.md b/Skills/vphone-guest-control/references/rpc-methods.mdindex d5f29b19..3d9ac3c5 100644--- a/Skills/vphone-guest-control/references/rpc-methods.md+++ b/Skills/vphone-guest-control/references/rpc-methods.md@@ -73,6 +73,8 @@ invalid-request error, read the source named there instead of guessing keys.| `input.key` | `name` (`return`, `cmd+v`, …) || `input.type` | `text`, `delay_ms?` (30) || `input.paste` | `text` |+| `input.pointer` | `x`, `y` (0...1 of the interface as shown; iPad, capability `pointer_scroll`) |+| `input.scroll` | `phase` (`began`/`changed`/`ended`/`cancelled`), `dx?`, `dy?` (points, wheel signs), `x?`, `y?` |## UI inspectiondiff --git a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlementsindex 2aa98f56..02b954ba 100644--- a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements+++ b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements@@ -53,6 +53,8 @@<true/><key>com.apple.backboardd.launchapplications</key><true/>+ <key>com.apple.developer.hid.virtual.device</key>+ <true/><key>com.apple.developer.networking.HotspotHelper</key><true/><key>com.apple.developer.networking.vpn.api</key>@@ -525,6 +527,7 @@<string>IOGPUDeviceUserClient</string><string>IOHIDEventServiceFastPathUserClient</string><string>IOHIDLibUserClient</string>+ <string>IOHIDResourceDeviceUserClient</string><string>IOMobileFramebufferUserClient</string><string>IOReportUserClient</string><string>IOSurfaceAcceleratorClient</string>diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex bda43785..bf3edfb9 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -148,10 +148,16 @@ enum GuestAPI {"motion_gyroscope","motion_gyroscope_toggle","motion_attitude",- ],+ ] + pointerCapabilities(),]}+ /// iPadOS takes a pointing device as it is; iOS on an iPhone only through+ /// AssistiveTouch, so `input.pointer` and `input.scroll` are an iPad's.+ private static func pointerCapabilities() -> [String] {+ GuestVirtualAudioProduct.machine().hasPrefix("iPad") ? ["pointer_scroll"] : []+ }+static func execute(method: String, params: [String: Any]) throws -> [String: Any] {switch method {case "device.snapshot":@@ -328,6 +334,27 @@ enum GuestAPI {number(params, "x2"), number(params, "y2"),)return ["phase": phase.rawValue, "fingers": 2]+ case "input.pointer":+ let point: GuestPointerScroll.Point+ do {+ point = try GuestPointerScroll.point(params)+ } catch {+ throw GuestAPIError.invalidRequest(error.message)+ }+ try pointerResult(vp_pointer_move(point.x, point.y))+ return ["x": point.x, "y": point.y]+ case "input.scroll":+ let scroll: GuestPointerScroll.Scroll+ do {+ scroll = try GuestPointerScroll.scroll(params)+ } catch {+ throw GuestAPIError.invalidRequest(error.message)+ }+ if let point = scroll.pointer {+ try pointerResult(vp_pointer_move(point.x, point.y))+ }+ try pointerResult(vp_pointer_scroll(scroll.phase.bits, scroll.dx, scroll.dy))+ return ["phase": scroll.phase.rawValue]case "input.hid":let page = try integer(params, "page")let usage = try integer(params, "usage")@@ -591,6 +618,17 @@ enum GuestAPI {/// Digitizer phase codes for vphoned's own multi-finger injection path./// icli keeps its equivalent mapping module-internal, and these are the/// values the private digitizer entry points take: 0 down, 1 move, 3 up.+ /// A pointer call's result as an error, nothing when it worked.+ static func pointerResult(_ code: Int32) throws {+ switch Int(code) {+ case Int(VP_POINTER_OK): return+ case Int(VP_POINTER_UNAVAILABLE): throw GuestAPIError.operationFailed("this base has no virtual pointing device")+ case Int(VP_POINTER_REFUSED): throw GuestAPIError.operationFailed("the guest refused to create the virtual pointing device")+ case Int(VP_POINTER_NOT_READY): throw GuestAPIError.operationFailed("the virtual pointing device is not ready yet")+ default: throw GuestAPIError.operationFailed("the pointer event could not be delivered")+ }+ }+static func touchPhaseCode(_ phase: TouchPhase) -> Int32 {switch phase {case .down: 0diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swiftindex 2fcb9ba6..6706ad66 100644--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift@@ -237,6 +237,8 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandlecase (.POST, "/v1/bootstrap/firmware"): "bootstrap.firmware"case (.POST, "/v1/input/touch"): "input.touch"case (.POST, "/v1/input/touch2"): "input.touch2"+ case (.POST, "/v1/input/pointer"): "input.pointer"+ case (.POST, "/v1/input/scroll"): "input.scroll"case (.POST, "/v1/input/hid"): "input.hid"case (.GET, "/v1/location"): "location.current"case (.PUT, "/v1/location"): "location.set"diff --git a/VPhoneDaemon/Daemon/GuestPointerScroll.swift b/VPhoneDaemon/Daemon/GuestPointerScroll.swiftnew file mode 100644index 00000000..1fe5847b--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestPointerScroll.swift@@ -0,0 +1,96 @@+import Foundation++// MARK: - Pointer Scroll++/// The parameters of `input.pointer` and `input.scroll`.+///+/// A scroll goes in phases, the way a trackpad's does: `began` before the+/// first delta, `changed` for each delta, then `ended` or `cancelled`. iPadOS+/// moves the view under the pointer by each delta, in interface points, and+/// does not decelerate by itself after `ended`: a client that wants the+/// content to run on (a trackpad's momentum) sends that as more `changed`+/// deltas before it ends the scroll.+///+/// Nothing here touches the guest, so `VPhoneDaemon/Tests/run-logic-tests.sh`+/// builds this file on the Mac.+enum GuestPointerScroll {+ enum Phase: String {+ case began+ case changed+ case ended+ case cancelled++ /// The `IOHIDEventPhaseBits` value the scroll event carries.+ var bits: Int32 {+ switch self {+ case .began: 1+ case .changed: 2+ case .ended: 4+ case .cancelled: 8+ }+ }+ }++ /// A position in the interface as it is shown, 0...1 from the top-left+ /// corner, so the same in every orientation.+ struct Point: Equatable {+ var x: Double+ var y: Double+ }++ struct Scroll: Equatable {+ var phase: Phase+ var dx: Double+ var dy: Double+ /// Where to put the pointer first; the scroll goes to the view under it.+ var pointer: Point?+ }++ struct Problem: Error, Equatable {+ let message: String+ }++ /// The largest delta one event may carry, in points. A trackpad's are a+ /// few dozen; this only refuses nonsense.+ static let maximumDelta = 10000.0++ static func point(_ params: [String: Any]) throws(Problem) -> Point {+ guard let x = number(params["x"]), let y = number(params["y"]),+ (0 ... 1).contains(x), (0 ... 1).contains(y)+ else {+ throw Problem(message: "x and y must be numbers within 0...1")+ }+ return Point(x: x, y: y)+ }++ static func scroll(_ params: [String: Any]) throws(Problem) -> Scroll {+ guard let name = params["phase"] as? String, let phase = Phase(rawValue: name) else {+ throw Problem(message: "phase must be began, changed, ended or cancelled")+ }+ var deltas: [Double] = []+ for key in ["dx", "dy"] {+ guard let value = params[key] else {+ deltas.append(0)+ continue+ }+ guard let delta = number(value), abs(delta) <= maximumDelta else {+ throw Problem(message: "\(key) must be a number within ±\(Int(maximumDelta))")+ }+ deltas.append(delta)+ }+ var pointer: Point?+ if params["x"] != nil || params["y"] != nil {+ pointer = try point(params)+ }+ return Scroll(phase: phase, dx: deltas[0], dy: deltas[1], pointer: pointer)+ }++ /// A finite JSON number; a boolean is not one.+ private static func number(_ value: Any?) -> Double? {+ guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else {+ return nil+ }+ let double = number.doubleValue+ return double.isFinite ? double : nil+ }+}diff --git a/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift b/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swiftindex b9f7b53a..ab0becd0 100644--- a/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift+++ b/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift@@ -62,7 +62,7 @@ enum GuestVirtualAudioProduct {return (value as? NSNumber)?.intValue}- private static func machine() -> String {+ static func machine() -> String {var size = 0guard sysctlbyname("hw.machine", nil, &size, nil, 0) == 0, size > 0 else { return "" }var bytes = [CChar](repeating: 0, count: size + 1)diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex 07a07561..ddf96c22 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -27,6 +27,27 @@ bool vp_hid_load(void);/// `touchSequence` can carry two fingers at once, which is why this exists.void vp_hid_touch2(int phase, double x1, double y1, double x2, double y2);+/// What vp_pointer_move and vp_pointer_scroll return.+enum {+ VP_POINTER_OK = 0,+ /// The base does not have the private IOKit symbols.+ VP_POINTER_UNAVAILABLE = 1,+ /// IOHIDUserDeviceCreate refused to make the device.+ VP_POINTER_REFUSED = 2,+ /// The device exists but iOS has not put an event service over it yet.+ VP_POINTER_NOT_READY = 3,+ /// The report or the event could not be made or delivered.+ VP_POINTER_FAILED = 4,+};++/// Put the virtual pointer at x, y: 0...1 from the top-left corner of the+/// interface as it is shown. Creates the pointing device on first use.+int vp_pointer_move(double x, double y);++/// One scroll event at the pointer. `phase` is an IOHIDEventPhaseBits value;+/// dx and dy are interface points, with a browser wheel event's signs.+int vp_pointer_scroll(int phase, double dx, double dy);+/// Turn the display on without pressing a button. False when/// SpringBoardServices has no SBSUndimScreen.bool vp_screen_undim(void);diff --git a/VPhoneDaemon/Native/vphoned_pointer.m b/VPhoneDaemon/Native/vphoned_pointer.mnew file mode 100644index 00000000..c6f7a0fb--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_pointer.m@@ -0,0 +1,187 @@+/*+ * vphoned_pointer — a virtual pointing device, for native scrolling.+ *+ * A scroll made of touches is a finger that drags and lets go, and how far the+ * content runs on afterwards is the guest's guess at the finger's speed from+ * the times the moves arrive. Over a network those times bunch up, so the+ * run-on changes from one swipe to the next. A pointing device scrolls the way+ * an iPad with a trackpad does: the view under the pointer moves by exactly+ * the deltas given, and nothing runs on that the client did not send.+ *+ * The device is a HID user device that reports an absolute position, so+ * iPadOS shows its pointer and puts it where a report says, in the interface's+ * own orientation (measured on iPadOS 26 in portrait and landscape); the+ * pointer hides itself when it has been still for a few seconds. Scroll+ * events are dispatched with that device's event service as their sender:+ * with any other sender (the touchscreen's included) they reach nothing, or+ * the view at the top-left corner. The device is created on first use and+ * lives as long as vphoned.+ *+ * Every entry point is resolved with dlsym, like vphoned_touch.m.+ */++#import "Include/VphonedNative.h"++#include <dlfcn.h>+#include <mach/mach_time.h>+#include <math.h>+#include <unistd.h>++typedef void *IOHIDEventSystemClientRef;+typedef void *IOHIDEventRef;+typedef void *IOHIDUserDeviceRef;+typedef double IOHIDFloat;+typedef unsigned int vp_io_object_t;++static IOHIDEventSystemClientRef (*pClientCreate)(CFAllocatorRef);+static void (*pDispatch)(IOHIDEventSystemClientRef, IOHIDEventRef);+static void (*pSetSender)(IOHIDEventRef, uint64_t);+static IOHIDEventRef (*pScroll)(CFAllocatorRef, uint64_t, IOHIDFloat, IOHIDFloat, IOHIDFloat, uint32_t);+static void (*pSetPhase)(IOHIDEventRef, uint32_t);+static IOHIDUserDeviceRef (*pDeviceCreate)(CFAllocatorRef, CFDictionaryRef);+static int (*pHandleReport)(IOHIDUserDeviceRef, const uint8_t *, CFIndex);+static CFMutableDictionaryRef (*pMatching)(const char *);+static int (*pMatchingServices)(unsigned int, CFDictionaryRef, vp_io_object_t *);+static vp_io_object_t (*pNext)(vp_io_object_t);+static CFTypeRef (*pSearchProperty)(vp_io_object_t, const char *, CFStringRef, CFAllocatorRef, uint32_t);+static int (*pEntryID)(vp_io_object_t, uint64_t *);+static int (*pRelease)(vp_io_object_t);++static dispatch_queue_t gPointerQueue;+static bool gPointerLoaded;+static IOHIDEventSystemClientRef gPointerClient;+static IOHIDUserDeviceRef gPointerDevice;+static uint64_t gPointerSender;++static NSString *const kPointerProduct = @"vphone pointer";++// Three buttons (never pressed), an absolute X and Y within 0...32767, a wheel+// and a horizontal pan (never turned). Without the wheel and the pan iPadOS+// shows the pointer but sends the scroll events nowhere.+static const uint8_t kPointerDescriptor[] = {+ 0x05, 0x01, 0x09, 0x02, 0xA1, 0x01, 0x09, 0x01, 0xA1, 0x00,+ 0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02,+ 0x95, 0x01, 0x75, 0x05, 0x81, 0x03,+ 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x15, 0x00, 0x26, 0xFF, 0x7F, 0x75, 0x10, 0x95, 0x02, 0x81, 0x02,+ 0x09, 0x38, 0x15, 0x81, 0x25, 0x7F, 0x75, 0x08, 0x95, 0x01, 0x81, 0x06,+ 0x05, 0x0C, 0x0A, 0x38, 0x02, 0x15, 0x81, 0x25, 0x7F, 0x75, 0x08, 0x95, 0x01, 0x81, 0x06,+ 0xC0, 0xC0,+};+static const double kPointerMaximum = 32767;++// kIORegistryIterateRecursively | kIORegistryIterateParents+#define VP_SEARCH_UP 3u++static bool load_symbols(void) {+ if (gPointerLoaded) return true;+ void *ioKit = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);+ if (!ioKit) return false;+ pClientCreate = dlsym(ioKit, "IOHIDEventSystemClientCreate");+ pDispatch = dlsym(ioKit, "IOHIDEventSystemClientDispatchEvent");+ pSetSender = dlsym(ioKit, "IOHIDEventSetSenderID");+ pScroll = dlsym(ioKit, "IOHIDEventCreateScrollEvent");+ pSetPhase = dlsym(ioKit, "IOHIDEventSetPhase");+ pDeviceCreate = dlsym(ioKit, "IOHIDUserDeviceCreate");+ pHandleReport = dlsym(ioKit, "IOHIDUserDeviceHandleReport");+ pMatching = dlsym(ioKit, "IOServiceMatching");+ pMatchingServices = dlsym(ioKit, "IOServiceGetMatchingServices");+ pNext = dlsym(ioKit, "IOIteratorNext");+ pSearchProperty = dlsym(ioKit, "IORegistryEntrySearchCFProperty");+ pEntryID = dlsym(ioKit, "IORegistryEntryGetRegistryEntryID");+ pRelease = dlsym(ioKit, "IOObjectRelease");+ gPointerLoaded = pClientCreate && pDispatch && pSetSender && pScroll && pSetPhase && pDeviceCreate &&+ pHandleReport && pMatching && pMatchingServices && pNext && pSearchProperty && pEntryID &&+ pRelease;+ return gPointerLoaded;+}++// The registry ID of the event service iOS put over the device, which is the+// sender its own events carry.+static uint64_t find_sender(void) {+ vp_io_object_t iterator = 0;+ if (pMatchingServices(0, pMatching("IOHIDEventService"), &iterator) != 0) return 0;+ uint64_t found = 0;+ vp_io_object_t service;+ while ((service = pNext(iterator))) {+ CFTypeRef product = pSearchProperty(service, "IOService", CFSTR("Product"), kCFAllocatorDefault, VP_SEARCH_UP);+ if (!found && product && CFGetTypeID(product) == CFStringGetTypeID() &&+ CFStringCompare(product, (__bridge CFStringRef)kPointerProduct, 0) == kCFCompareEqualTo) {+ pEntryID(service, &found);+ }+ if (product) CFRelease(product);+ pRelease(service);+ }+ pRelease(iterator);+ return found;+}++// On gPointerQueue. The event service appears a moment after the device;+// waits up to a second for it.+static int ensure_device(void) {+ if (gPointerSender) return VP_POINTER_OK;+ if (!load_symbols()) return VP_POINTER_UNAVAILABLE;+ if (!gPointerClient) gPointerClient = pClientCreate(kCFAllocatorDefault);+ if (!gPointerClient) return VP_POINTER_UNAVAILABLE;+ if (!gPointerDevice) {+ NSDictionary *properties = @{+ @"ReportDescriptor": [NSData dataWithBytes:kPointerDescriptor length:sizeof(kPointerDescriptor)],+ @"VendorID": @0x05AC,+ @"ProductID": @0x7650,+ @"Product": kPointerProduct,+ @"Transport": @"USB",+ @"PrimaryUsagePage": @1,+ @"PrimaryUsage": @2,+ };+ gPointerDevice = pDeviceCreate(kCFAllocatorDefault, (__bridge CFDictionaryRef)properties);+ if (!gPointerDevice) {+ NSLog(@"vphoned: IOHIDUserDeviceCreate refused the pointer device");+ return VP_POINTER_REFUSED;+ }+ }+ for (int attempt = 0; attempt < 50 && !gPointerSender; attempt++) {+ gPointerSender = find_sender();+ if (!gPointerSender) usleep(20000);+ }+ return gPointerSender ? VP_POINTER_OK : VP_POINTER_NOT_READY;+}++static dispatch_queue_t pointer_queue(void) {+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ dispatch_queue_attr_t attributes = dispatch_queue_attr_make_with_qos_class(+ DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0);+ gPointerQueue = dispatch_queue_create("com.vphone.vphoned.pointer", attributes);+ });+ return gPointerQueue;+}++int vp_pointer_move(double x, double y) {+ __block int result;+ dispatch_sync(pointer_queue(), ^{+ result = ensure_device();+ if (result != VP_POINTER_OK) return;+ uint16_t px = (uint16_t)lround(fmin(fmax(x, 0), 1) * kPointerMaximum);+ uint16_t py = (uint16_t)lround(fmin(fmax(y, 0), 1) * kPointerMaximum);+ const uint8_t report[7] = {0, px & 0xFF, px >> 8, py & 0xFF, py >> 8, 0, 0};+ if (pHandleReport(gPointerDevice, report, sizeof(report)) != 0) result = VP_POINTER_FAILED;+ });+ return result;+}++int vp_pointer_scroll(int phase, double dx, double dy) {+ __block int result;+ dispatch_sync(pointer_queue(), ^{+ result = ensure_device();+ if (result != VP_POINTER_OK) return;+ IOHIDEventRef event = pScroll(kCFAllocatorDefault, mach_absolute_time(), dx, dy, 0, 0);+ if (!event) {+ result = VP_POINTER_FAILED;+ return;+ }+ pSetPhase(event, (uint32_t)phase);+ pSetSender(event, gPointerSender);+ pDispatch(gPointerClient, event);+ CFRelease(event);+ });+ return result;+}diff --git a/VPhoneDaemon/Tests/LogicTests.swift b/VPhoneDaemon/Tests/LogicTests.swiftindex f1b89dbd..00fd0e06 100644--- a/VPhoneDaemon/Tests/LogicTests.swift+++ b/VPhoneDaemon/Tests/LogicTests.swift@@ -4,7 +4,8 @@ import Foundation/// Checks the guest-independent parts of vphoned on the Mac: the service/// profile lists and bookkeeping, the first-boot settle verdict (data-/// migration included) and the device name rule. `run-logic-tests.sh` builds+/// migration included), the device name rule and the pointer scroll+/// parameters. `run-logic-tests.sh` builds/// this file with those sources.nonisolated(unsafe) var failures = 0nonisolated(unsafe) var checks = 0@@ -34,6 +35,7 @@ enum LogicTests {settleVerdicts()dataMigrationRecord()deviceNameRule()+ pointerScroll()print("\(checks) checks, \(failures) failures")exit(failures == 0 ? 0 : 1)}@@ -343,4 +345,44 @@ enum LogicTests {expect(GuestDeviceNameRule.problem(String(repeating: "测", count: 85)) == nil, "255 bytes of CJK")expect(GuestDeviceNameRule.problem(String(repeating: "测", count: 86)) != nil, "258 bytes of CJK")}++ // MARK: - Pointer Scroll++ static func scrollProblem(_ params: [String: Any]) -> String? {+ do {+ _ = try GuestPointerScroll.scroll(params)+ return nil+ } catch {+ return error.message+ }+ }++ static func pointerScroll() {+ typealias Scroll = GuestPointerScroll.Scroll+ expectEqual(try? GuestPointerScroll.scroll(["phase": "changed", "dx": 1.5, "dy": -20]),+ Scroll(phase: .changed, dx: 1.5, dy: -20, pointer: nil))+ expectEqual(try? GuestPointerScroll.scroll(["phase": "began"]),+ Scroll(phase: .began, dx: 0, dy: 0, pointer: nil), "deltas default to 0")+ expectEqual(try? GuestPointerScroll.scroll(["phase": "began", "x": 0, "y": 1]),+ Scroll(phase: .began, dx: 0, dy: 0, pointer: .init(x: 0, y: 1)), "a pointer position comes with it")+ expectEqual(GuestPointerScroll.Phase.began.bits, 1)+ expectEqual(GuestPointerScroll.Phase.changed.bits, 2)+ expectEqual(GuestPointerScroll.Phase.ended.bits, 4)+ expectEqual(GuestPointerScroll.Phase.cancelled.bits, 8)+ let phase = "phase must be began, changed, ended or cancelled"+ expectEqual(scrollProblem([:]), phase)+ expectEqual(scrollProblem(["phase": "move"]), phase)+ expectEqual(scrollProblem(["phase": 2]), phase)+ let delta = "must be a number within ±10000"+ expectEqual(scrollProblem(["phase": "changed", "dy": "20"]), "dy \(delta)")+ expectEqual(scrollProblem(["phase": "changed", "dx": true]), "dx \(delta)", "a boolean is not a number")+ expectEqual(scrollProblem(["phase": "changed", "dy": 10001]), "dy \(delta)")+ expectEqual(scrollProblem(["phase": "changed", "dy": Double.infinity]), "dy \(delta)")+ let point = "x and y must be numbers within 0...1"+ expectEqual(scrollProblem(["phase": "began", "x": 0.5]), point, "x without y")+ expectEqual(scrollProblem(["phase": "began", "x": 0.5, "y": 1.01]), point)+ expectEqual(scrollProblem(["phase": "began", "x": -0.1, "y": 0.5]), point)+ expectEqual(try? GuestPointerScroll.point(["x": 0.25, "y": 0.75]), GuestPointerScroll.Point(x: 0.25, y: 0.75))+ expect((try? GuestPointerScroll.point(["x": false, "y": 0])) == nil, "a boolean is not a coordinate")+ }}diff --git a/VPhoneDaemon/Tests/run-logic-tests.sh b/VPhoneDaemon/Tests/run-logic-tests.shindex 04e1c7cd..597bba25 100755--- a/VPhoneDaemon/Tests/run-logic-tests.sh+++ b/VPhoneDaemon/Tests/run-logic-tests.sh@@ -3,7 +3,8 @@ set -euo pipefail# Builds the guest-independent vphoned sources with LogicTests.swift for the# Mac and runs them: service profile lists and bookkeeping, the first-boot-# settle verdict, the device name rule. No guest is needed.+# settle verdict, the device name rule, the pointer scroll parameters. No+# guest is needed.daemon="${0:a:h:h}"temporary="$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/vphone-logic-tests.XXXXXX")"@@ -14,6 +15,7 @@ trap '/bin/rm -rf "$temporary"' EXIT"$daemon/Daemon/GuestServiceProfile.swift" \"$daemon/Daemon/GuestFirstBootSettle.swift" \"$daemon/Daemon/GuestDeviceNameRule.swift" \+ "$daemon/Daemon/GuestPointerScroll.swift" \"$daemon/Tests/LogicTests.swift" \-o "$temporary/logic-tests"