Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Add live device attitude controls to the VM display app

Phineas Guo193f57543486
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 6f931b8c..694423bf 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -243,7 +243,7 @@
> change. Disabling the patch removes the added library; live environment
> sync cannot reinstall an absent selected library. A provider/library update
> needs a reboot, without silently restarting backboardd. The VM display app's
-> Motion Sensors → 3D Gyroscope panel sends valid three-axis edits immediately,
+> Features → Motion Sensors → 3D Gyroscope panel sends valid three-axis edits immediately,
> with a simulation checkbox that retains values and a reset that zeros all
> axes. `motion.gyroscope.set` accepts an optional Boolean `enabled` (default
> true); the panel checks `motion_gyroscope_toggle` support. Writes serialize
@@ -262,8 +262,9 @@
> notify state; apps receive radians, quaternion, matrix and matching gravity.
> Disabling restores the native path; removing the library and relaunching apps
> reverts injection. Live sync cannot reinstall an absent selected library.
-> Native host subscription tests and guest cross-compilation passed;
-> manual guest acceptance remains.
+> Features → Motion Sensors → Device Attitude provides live angle editing,
+> a simulation checkbox and zero reset. Native host subscription tests and
+> guest cross-compilation passed; manual guest acceptance remains.
> Contract and validation: `Research/Guest/virtual_attitude.md`.
> **Current launchd hook (2026-09-25; isolated VM verification):**
diff --git a/Research/Guest/virtual_attitude.md b/Research/Guest/virtual_attitude.md
index 63200cbf..ef765f0a 100644
--- a/Research/Guest/virtual_attitude.md
+++ b/Research/Guest/virtual_attitude.md
@@ -1,6 +1,6 @@
# Device attitude simulation
-## Core contract
+## Contract and panel
vphoned capability `motion_attitude` exposes `motion.attitude.get`,
`motion.attitude.set {roll,pitch,yaw,enabled?}` and `motion.attitude.clear`.
@@ -9,7 +9,11 @@ Set requires finite JSON numbers: roll/yaw in [-180,180] degrees, pitch in
`enabled` must be a Boolean and defaults to true. Clear disables and zeros;
set with enabled=false retains angles.
-RPC uses degrees; Core Motion uses radians. Zero is face-up, gravity (0,0,-1)
+**Features → Motion Sensors → Device Attitude** (Chinese:
+**功能 → 运动传感器 → 设备姿态**) offers immediate edits, a simulation checkbox
+and zero reset preserving the checkbox. The gyro panel is in the same submenu.
+Both share the serialized/coalesced writer and retry/reconnect model.
+UI/RPC use degrees; Core Motion uses radians. Zero is face-up, gravity (0,0,-1)
g. Pitch is about X, roll about Y, yaw about Z: R = Rz(yaw) Rx(pitch) Ry(roll).
Pitch ±90° makes Euler roll/yaw singular; quaternion/matrix remain well-defined.
@@ -67,12 +71,15 @@ configuration, packed-state boundaries, quaternion/matrix/gravity, copy,
relative attitude and secure coding. Its real host Core Motion runtime test
covers all start overloads, polling, callback delivery, live toggle, snapshots,
interval setting, bounded backlog and suppression after stop, using a separate
-Darwin notification name. Catalogue tests cover version gating, blocking,
-preset reachability and manifest invariants.
-
-2026-10-08: sample and live hook tests passed, and 55 catalogue/model tests
-in seven suites passed. The complete bundle built successfully; bundle
-admission and strict deep signature verification passed.
+Darwin notification name. The shared editor harness
+`zsh VPhoneExecutable/VPhoneVirtualization/Tests/run-gyroscope-tests.sh` covers
+sequencing/retry/reconnect and attitude-specific bounds. Catalogue tests cover
+version gating, blocking, preset reachability and manifest invariants.
+
+2026-10-08: sample and live hook tests passed, shared editor tests passed,
+55 catalogue/model tests in seven suites passed, and the full VPhone Debug
+bundle built successfully. Bundle admission and strict deep signature verification
+passed; the built zh-Hans strings include 设备姿态 and 俯仰.
Guest acceptance is manual, as requested: update guest, relaunch a consumer,
enable simulation, compare polling/callback Euler radians, quaternion and
diff --git a/Research/Guest/virtual_gyroscope.md b/Research/Guest/virtual_gyroscope.md
index 50bb6c97..76ceefd4 100644
--- a/Research/Guest/virtual_gyroscope.md
+++ b/Research/Guest/virtual_gyroscope.md
@@ -47,8 +47,8 @@ provider. **Enumeration and dispatch do not prove CoreMotion acceptance.**
## Host panel
-The VM display app's **Motion Sensors → 3D Gyroscope** menu opens a native
-SwiftUI panel (Chinese: **运动传感器 → 3D 陀螺仪**). Each axis has a text field
+The VM display app's **Features → Motion Sensors → 3D Gyroscope** menu opens a native
+SwiftUI panel (Chinese: **功能 → 运动传感器 → 3D 陀螺仪**). Each axis has a text field
and a 0.1 rad/s stepper. Valid edits are sent immediately; partial, non-finite
and out-of-range text stays in the field with a validation message and is not
sent. The checkbox enables/disables simulation without discarding axis values.
@@ -65,6 +65,10 @@ remain unsynced with a retry action. Closing the panel does not drop a write
already accepted by the UI. The existing window controller retains the model
and uses `isReleasedWhenClosed = false`.
+The shared `VPhoneMotionModel` / `VPhoneMotionView` also powers the independent
+degree-based attitude editor; see `virtual_attitude.md`. Gyro configuration
+remains raw rad/s and does not drive the attitude simulation.
+
The model test harness (`zsh VPhoneExecutable/VPhoneVirtualization/Tests/run-gyroscope-tests.sh`)
exercises delayed acknowledgements, coalescing, reset/disable while a write is
pending, invalid text, retry, reconnect, stale reads and decimal-comma input.
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
index 7dddadd1..2a20ebf5 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
@@ -1,6 +1,142 @@
{
"sourceLanguage" : "en",
"strings" : {
+ "Angles describe a stationary pose. Zero is face up. Enable simulation before launching the guest app." : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Angles describe a stationary pose. Zero is face up. Enable simulation before launching the guest app."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "角度表示静止姿态。归零时屏幕朝上。请在启动来宾 App 前启用模拟。"
+ }
+ }
+ }
+ },
+ "Device Attitude" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Device Attitude"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "设备姿态"
+ }
+ }
+ }
+ },
+ "Enable the device attitude patch and relaunch the guest app." : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Enable the device attitude patch and relaunch the guest app."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "请启用设备姿态补丁并重新启动来宾 App。"
+ }
+ }
+ }
+ },
+ "Guest did not apply the attitude configuration" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Guest did not apply the attitude configuration"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "来宾未应用设备姿态设定"
+ }
+ }
+ }
+ },
+ "Pitch" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Pitch"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "俯仰"
+ }
+ }
+ }
+ },
+ "Roll" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Roll"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "横滚"
+ }
+ }
+ }
+ },
+ "Roll and yaw: -180 to 180°. Pitch: -90 to 90°." : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Roll and yaw: -180 to 180°. Pitch: -90 to 90°."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "横滚和偏航:-180 到 180°。俯仰:-90 到 90°。"
+ }
+ }
+ }
+ },
+ "Yaw" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Yaw"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "偏航"
+ }
+ }
+ }
+ },
"%@ axis" : {
"extractionState" : "manual",
"localizations" : {
diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/GyroscopeModelTests.swift b/VPhoneExecutable/VPhoneVirtualization/Tests/GyroscopeModelTests.swift
index 32e96e9e..455cd12c 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Tests/GyroscopeModelTests.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/GyroscopeModelTests.swift
@@ -2,12 +2,12 @@ import Foundation
@MainActor
final class VPhoneGyroscopeTestGuest {
- var reply = VPhoneGyroscopeReply(configuration: VPhoneGyroscopeConfiguration(), providerRunning: true)
- var writes: [VPhoneGyroscopeConfiguration] = []
- var completions: [CheckedContinuation<VPhoneGyroscopeReply, any Error>] = []
+ var reply = VPhoneMotionReply(configuration: VPhoneMotionConfiguration(), providerRunning: true)
+ var writes: [VPhoneMotionConfiguration] = []
+ var completions: [CheckedContinuation<VPhoneMotionReply, any Error>] = []
private var completed = 0
- func write(_ value: VPhoneGyroscopeConfiguration) async throws -> VPhoneGyroscopeReply {
+ func write(_ value: VPhoneMotionConfiguration) async throws -> VPhoneMotionReply {
writes.append(value)
return try await withCheckedThrowingContinuation { completions.append($0) }
}
@@ -28,7 +28,7 @@ final class VPhoneGyroscopeTestGuest {
}
@main
-struct VPhoneGyroscopeModelTests {
+struct VPhoneMotionModelTests {
@MainActor static func waitFor(_ predicate: () -> Bool) async {
for _ in 0 ..< 10000 {
if predicate() { return }
@@ -39,7 +39,7 @@ struct VPhoneGyroscopeModelTests {
@MainActor static func main() async {
let guest = VPhoneGyroscopeTestGuest()
- let model = VPhoneGyroscopeModel(locale: Locale(identifier: "en_US"), read: { guest.reply }, write: {
+ let model = VPhoneMotionModel(locale: Locale(identifier: "en_US"), read: { guest.reply }, write: {
try await guest.write($0)
})
await model.connectionChanged(true)
@@ -55,13 +55,13 @@ struct VPhoneGyroscopeModelTests {
assert(guest.writes.count == 1)
guest.finish()
await waitFor { guest.writes.count == 2 }
- assert(guest.writes[1] == VPhoneGyroscopeConfiguration(enabled: true, x: 1, y: 2, z: -3))
+ assert(guest.writes[1] == VPhoneMotionConfiguration(enabled: true, x: 1, y: 2, z: -3))
assert(model.xText == "1" && model.yText == "2" && model.zText == "-3")
model.reset()
assert(model.enabled && model.xText == "0" && model.yText == "0" && model.zText == "0")
guest.finish()
await waitFor { guest.writes.count == 3 }
- assert(guest.writes[2] == VPhoneGyroscopeConfiguration(enabled: true))
+ assert(guest.writes[2] == VPhoneMotionConfiguration(enabled: true))
guest.finish()
await waitFor { !model.isSending }
assert(!model.hasLocalChanges && model.error == nil)
@@ -93,7 +93,7 @@ struct VPhoneGyroscopeModelTests {
await waitFor { !model.isSending }
model.reset()
await waitFor { guest.writes.count == 8 }
- assert(guest.writes[7] == VPhoneGyroscopeConfiguration())
+ assert(guest.writes[7] == VPhoneMotionConfiguration())
assert(!model.hasInvalidAxes)
guest.finish()
await waitFor { !model.isSending }
@@ -118,7 +118,7 @@ struct VPhoneGyroscopeModelTests {
await waitFor { guest.writes.count == 11 }
await model.connectionChanged(false)
assert(!model.canEdit && !model.providerRunning)
- guest.reply.configuration = VPhoneGyroscopeConfiguration()
+ guest.reply.configuration = VPhoneMotionConfiguration()
await model.connectionChanged(true)
assert(model.zText == "9" && guest.writes.count == 11)
guest.finish()
@@ -140,8 +140,8 @@ struct VPhoneGyroscopeModelTests {
// A cancelled/stale initial read cannot replace the new connection's
// values, nor can reading the guest itself trigger a write.
- var reads: [CheckedContinuation<VPhoneGyroscopeReply, any Error>] = []
- let reconnect = VPhoneGyroscopeModel(read: {
+ var reads: [CheckedContinuation<VPhoneMotionReply, any Error>] = []
+ let reconnect = VPhoneMotionModel(read: {
try await withCheckedThrowingContinuation { reads.append($0) }
}, write: { _ in fatalError("A read unexpectedly triggered a write") })
let first = Task { await reconnect.connectionChanged(true) }
@@ -149,23 +149,45 @@ struct VPhoneGyroscopeModelTests {
await reconnect.connectionChanged(false)
let second = Task { await reconnect.connectionChanged(true) }
await waitFor { reads.count == 2 }
- reads[1].resume(returning: VPhoneGyroscopeReply(
- configuration: VPhoneGyroscopeConfiguration(enabled: true, x: 3), providerRunning: true,
+ reads[1].resume(returning: VPhoneMotionReply(
+ configuration: VPhoneMotionConfiguration(enabled: true, x: 3), providerRunning: true,
))
await second.value
- reads[0].resume(returning: VPhoneGyroscopeReply(
- configuration: VPhoneGyroscopeConfiguration(x: 99), providerRunning: false,
+ reads[0].resume(returning: VPhoneMotionReply(
+ configuration: VPhoneMotionConfiguration(x: 99), providerRunning: false,
))
await first.value
assert(reconnect.enabled && reconnect.xValue == 3 && reconnect.providerRunning)
- let decimal = VPhoneGyroscopeModel(locale: Locale(identifier: "de_DE"), read: { guest.reply }, write: {
- VPhoneGyroscopeReply(configuration: $0, providerRunning: true)
+ let decimal = VPhoneMotionModel(locale: Locale(identifier: "de_DE"), read: { guest.reply }, write: {
+ VPhoneMotionReply(configuration: $0, providerRunning: true)
})
await decimal.connectionChanged(true)
decimal.xText = "1,25"
await waitFor { !decimal.hasLocalChanges }
assert(decimal.configuration.x == 1.25)
- print("Gyroscope model tests passed: ordered/coalesced writes, toggle, reset, invalid input, retry, reconnect, stale reads, locale")
+
+ let attitude = VPhoneMotionModel(
+ ranges: [-180 ... 180, -90 ... 90, -180 ... 180],
+ read: { VPhoneMotionReply(configuration: VPhoneMotionConfiguration(), providerRunning: true) },
+ write: { VPhoneMotionReply(configuration: $0, providerRunning: true) },
+ )
+ await attitude.connectionChanged(true)
+ attitude.yText = "91"
+ assert(attitude.hasInvalidAxes && attitude.configuration.y == 0)
+ attitude.enabled = true // Still works with invalid pitch text.
+ await waitFor { !attitude.hasLocalChanges }
+ assert(attitude.configuration.enabled && attitude.configuration.y == 0)
+ attitude.reset()
+ await waitFor { !attitude.hasLocalChanges }
+ assert(attitude.enabled && !attitude.hasInvalidAxes && attitude.yText == "0")
+ attitude.xText = "180"
+ attitude.yText = "-90"
+ attitude.zText = "-180"
+ await waitFor { !attitude.hasLocalChanges }
+ assert(attitude.configuration == VPhoneMotionConfiguration(enabled: true, x: 180, y: -90, z: -180))
+ attitude.xText = "181"
+ assert(attitude.hasInvalidAxes && attitude.configuration.x == 180)
+ print("Motion model tests passed: ordered/coalesced writes, toggle, reset, invalid input, retry, reconnect, stale reads, locale and attitude bounds")
}
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/run-gyroscope-tests.sh b/VPhoneExecutable/VPhoneVirtualization/Tests/run-gyroscope-tests.sh
index 499a8e48..8cecd614 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Tests/run-gyroscope-tests.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/run-gyroscope-tests.sh
@@ -7,6 +7,6 @@ out="$root/.build/gyroscope-tests"
mkdir -p "$out"
xcrun --sdk macosx swiftc -swift-version 6 -parse-as-library \
-target arm64-apple-macos15.0 -module-cache-path "$out/module-cache" \
- "$root/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Gyroscope/VPhoneGyroscopeModel.swift" \
+ "$root/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionModel.swift" \
"${0:a:h}/GyroscopeModelTests.swift" -o "$out/GyroscopeModelTests"
"$out/GyroscopeModelTests"
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlAttitude.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlAttitude.swift
new file mode 100644
index 00000000..0bc7876c
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlAttitude.swift
@@ -0,0 +1,35 @@
+import CoreFoundation
+import Foundation
+
+// MARK: - Attitude RPC
+
+extension VPhoneGuestControl {
+ func readAttitude() async throws -> VPhoneMotionReply {
+ guard guestCapabilities.contains("motion_attitude") else {
+ throw ControlError.unsupportedCapability("motion_attitude")
+ }
+ return try attitudeReply(await call("motion.attitude.get"))
+ }
+
+ func setAttitude(_ value: VPhoneMotionConfiguration) async throws -> VPhoneMotionReply {
+ guard guestCapabilities.contains("motion_attitude") else {
+ throw ControlError.unsupportedCapability("motion_attitude")
+ }
+ return try attitudeReply(await call("motion.attitude.set", params: [
+ "enabled": value.enabled, "roll": value.x, "pitch": value.y, "yaw": value.z,
+ ]))
+ }
+
+ private func attitudeReply(_ result: [String: Any]) throws -> VPhoneMotionReply {
+ guard let enabled = result["enabled"] as? NSNumber, CFGetTypeID(enabled) == CFBooleanGetTypeID(),
+ let roll = result["roll"] as? NSNumber, let pitch = result["pitch"] as? NSNumber,
+ let yaw = result["yaw"] as? NSNumber,
+ [roll, pitch, yaw].allSatisfy({ CFGetTypeID($0) != CFBooleanGetTypeID() && $0.doubleValue.isFinite }),
+ abs(roll.doubleValue) <= 180, abs(pitch.doubleValue) <= 90, abs(yaw.doubleValue) <= 180
+ else { throw ControlError.protocolError("invalid attitude configuration") }
+ return VPhoneMotionReply(
+ configuration: VPhoneMotionConfiguration(enabled: enabled.boolValue, x: roll.doubleValue, y: pitch.doubleValue, z: yaw.doubleValue),
+ providerRunning: result.bool("provider_installed") ?? false,
+ )
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlGyroscope.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlGyroscope.swift
index 3d0c0f43..c5187912 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlGyroscope.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlGyroscope.swift
@@ -4,7 +4,7 @@ import Foundation
// MARK: - Gyroscope RPC
extension VPhoneGuestControl {
- func readGyroscope() async throws -> VPhoneGyroscopeReply {
+ func readGyroscope() async throws -> VPhoneMotionReply {
guard guestCapabilities.contains("motion_gyroscope_toggle") else {
throw ControlError.unsupportedCapability("motion_gyroscope_toggle")
}
@@ -12,7 +12,7 @@ extension VPhoneGuestControl {
return try gyroscopeReply(result)
}
- func setGyroscope(_ value: VPhoneGyroscopeConfiguration) async throws -> VPhoneGyroscopeReply {
+ func setGyroscope(_ value: VPhoneMotionConfiguration) async throws -> VPhoneMotionReply {
guard guestCapabilities.contains("motion_gyroscope_toggle") else {
throw ControlError.unsupportedCapability("motion_gyroscope_toggle")
}
@@ -22,7 +22,7 @@ extension VPhoneGuestControl {
return try gyroscopeReply(result)
}
- private func gyroscopeReply(_ result: [String: Any]) throws -> VPhoneGyroscopeReply {
+ private func gyroscopeReply(_ result: [String: Any]) throws -> VPhoneMotionReply {
guard let enabled = result["enabled"] as? NSNumber,
CFGetTypeID(enabled) == CFBooleanGetTypeID(),
let x = result["x"] as? NSNumber, let y = result["y"] as? NSNumber, let z = result["z"] as? NSNumber,
@@ -30,8 +30,8 @@ extension VPhoneGuestControl {
CFGetTypeID($0) != CFBooleanGetTypeID() && $0.doubleValue.isFinite && abs($0.doubleValue) <= 1000
})
else { throw ControlError.protocolError("invalid gyroscope configuration") }
- return VPhoneGyroscopeReply(
- configuration: VPhoneGyroscopeConfiguration(enabled: enabled.boolValue, x: x.doubleValue, y: y.doubleValue, z: z.doubleValue),
+ return VPhoneMotionReply(
+ configuration: VPhoneMotionConfiguration(enabled: enabled.boolValue, x: x.doubleValue, y: y.doubleValue, z: z.doubleValue),
providerRunning: result.bool("provider_running") ?? false,
)
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
index 54ed2205..0f26855c 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
@@ -142,7 +142,6 @@ class VPhoneMenuController {
// inspection and capture.
mainMenu.addItem(buildDeviceMenu())
mainMenu.addItem(buildFeaturesMenu())
- mainMenu.addItem(buildMotionSensorsMenu())
mainMenu.addItem(buildDataMenu())
mainMenu.addItem(buildAppsMenu())
mainMenu.addItem(buildDiagnosticsMenu())
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuFeatures.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuFeatures.swift
index 50a3b1e3..2abe5676 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuFeatures.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuFeatures.swift
@@ -2,9 +2,7 @@ import AppKit
// MARK: - Features Menu
-/// Sensors the host simulates for the guest: location, battery and camera.
-/// Each is a titled section of this menu rather than a submenu, so every
-/// control is one level down from the menu bar.
+/// Host sensor controls, with the motion panels grouped in their own submenu.
extension VPhoneMenuController {
func buildFeaturesMenu() -> NSMenuItem {
let item = NSMenuItem(title: "Features", action: nil, keyEquivalent: "")
@@ -22,6 +20,8 @@ extension VPhoneMenuController {
menu.addItem(child)
}
}
+ menu.addItem(NSMenuItem.separator())
+ menu.addItem(buildMotionSensorsMenu())
item.submenu = menu
return item
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuMotion.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuMotion.swift
index 3e9c7aa8..6fc79aef 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuMotion.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuMotion.swift
@@ -8,6 +8,7 @@ extension VPhoneMenuController {
let menu = NSMenu(title: "Motion Sensors")
menu.autoenablesItems = false
menu.addItem(makePanelItem(.gyroscope, "3D Gyroscope", keyEquivalent: "", symbol: "gyroscope"))
+ menu.addItem(makePanelItem(.attitude, "Device Attitude", keyEquivalent: "", symbol: "rotate.3d"))
item.submenu = menu
return item
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Gyroscope/VPhoneGyroscopeView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Gyroscope/VPhoneGyroscopeView.swift
deleted file mode 100644
index ffa5053e..00000000
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Gyroscope/VPhoneGyroscopeView.swift
+++ /dev/null
@@ -1,120 +0,0 @@
-import SwiftUI
-
-struct VPhoneGyroscopeView: View {
- let model: VPhoneGyroscopeModel
- let connected: @MainActor () -> Bool
-
- var body: some View {
- VPhoneGyroscopeEditor(model: model)
- .task(id: connected()) { await model.connectionChanged(connected()) }
- }
-}
-
-struct VPhoneGyroscopeEditor: View {
- @Bindable var model: VPhoneGyroscopeModel
-
- var body: some View {
- VStack(spacing: 0) {
- Form {
- Section {
- Toggle(isOn: $model.enabled) {
- Text("Enable Simulation", bundle: VPhoneLocalization.bundle)
- }
- .toggleStyle(.checkbox)
- .accessibilityIdentifier("gyroscope-enabled")
- Text("Changes sync to the guest immediately. Disabling keeps your axis values.", bundle: VPhoneLocalization.bundle)
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- Section {
- VPhoneGyroscopeAxisRow(axis: "X", text: $model.xText, value: $model.xValue)
- VPhoneGyroscopeAxisRow(axis: "Y", text: $model.yText, value: $model.yValue)
- VPhoneGyroscopeAxisRow(axis: "Z", text: $model.zText, value: $model.zValue)
- if model.hasInvalidAxes {
- Text("Enter a number from -1000 to 1000 for each axis.", bundle: VPhoneLocalization.bundle)
- .font(.caption)
- .foregroundStyle(.orange)
- }
- Button { model.reset() } label: {
- Label {
- Text("Reset", bundle: VPhoneLocalization.bundle)
- } icon: { Image(systemName: "arrow.counterclockwise") }
- }
- .accessibilityIdentifier("gyroscope-reset")
- .help(Text("Set all three axes to zero", bundle: VPhoneLocalization.bundle))
- } header: {
- Text("Angular Velocity", bundle: VPhoneLocalization.bundle)
- }
- }
- .formStyle(.grouped)
- .disabled(!model.canEdit)
- Divider()
- VPhoneGyroscopeSyncStatus(model: model)
- }
- }
-}
-
-struct VPhoneGyroscopeAxisRow: View {
- let axis: String
- @Binding var text: String
- @Binding var value: Double
-
- var body: some View {
- HStack(spacing: 8) {
- Text(verbatim: axis)
- .font(.system(.body, design: .monospaced))
- TextField(axis, text: $text)
- .textFieldStyle(.roundedBorder)
- .font(.system(.body, design: .monospaced))
- .accessibilityLabel(VPhoneLocalization.format("%@ axis", axis))
- .accessibilityIdentifier("gyroscope-axis-" + axis.lowercased())
- Text(verbatim: "rad/s").foregroundStyle(.secondary)
- Stepper(axis, value: $value, in: -1000 ... 1000, step: 0.1)
- .labelsHidden()
- .accessibilityLabel(VPhoneLocalization.format("%@ axis", axis))
- }
- }
-}
-
-struct VPhoneGyroscopeSyncStatus: View {
- let model: VPhoneGyroscopeModel
-
- var body: some View {
- HStack(spacing: 8) {
- if !model.isConnected {
- Text("Guest not connected", bundle: VPhoneLocalization.bundle)
- } else if model.isReading || model.isSending {
- ProgressView().controlSize(.small)
- Text("Syncing…", bundle: VPhoneLocalization.bundle)
- } else if let error = model.error {
- Image(systemName: "exclamationmark.triangle").foregroundStyle(.orange)
- Text(VPhoneLocalization.text(error)).textSelection(.enabled)
- } else if model.hasLoaded {
- Text(model.providerRunning ? "Synced" : "Waiting for sensor service…", bundle: VPhoneLocalization.bundle)
- }
- Spacer(minLength: 0)
- if model.canRetry {
- Button { model.retry() } label: { Text("Retry", bundle: VPhoneLocalization.bundle) }
- } else if model.isConnected && !model.hasLoaded && !model.isReading {
- Button { Task { await model.connectionChanged(true) } } label: {
- Text("Retry", bundle: VPhoneLocalization.bundle)
- }
- }
- }
- .font(.system(.caption, design: .monospaced))
- .padding(8)
- .background(.bar)
- }
-}
-
-#Preview {
- let sample = VPhoneGyroscopeReply(
- configuration: VPhoneGyroscopeConfiguration(enabled: true, x: 1.25, y: 0, z: -0.75),
- providerRunning: true,
- )
- let model = VPhoneGyroscopeModel(read: { sample }, write: {
- VPhoneGyroscopeReply(configuration: $0, providerRunning: true)
- })
- return VPhoneGyroscopeView(model: model, connected: { true })
- .frame(width: 440, height: 380)
-}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Gyroscope/VPhoneGyroscopeModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionModel.swift
similarity index 72%
rename from VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Gyroscope/VPhoneGyroscopeModel.swift
rename to VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionModel.swift
index 7326c283..1f026522 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Gyroscope/VPhoneGyroscopeModel.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionModel.swift
@@ -1,23 +1,23 @@
import Foundation
import Observation
-struct VPhoneGyroscopeConfiguration: Equatable, Sendable {
+struct VPhoneMotionConfiguration: Equatable, Sendable {
var enabled = false
var x = 0.0
var y = 0.0
var z = 0.0
}
-struct VPhoneGyroscopeReply: Sendable {
- var configuration: VPhoneGyroscopeConfiguration
+struct VPhoneMotionReply: Sendable {
+ var configuration: VPhoneMotionConfiguration
var providerRunning: Bool
}
-// MARK: - Live Gyroscope Controls
+// MARK: - Live Motion Controls
@MainActor
@Observable
-final class VPhoneGyroscopeModel {
+final class VPhoneMotionModel {
var enabled = false {
didSet {
guard !applyingGuest, enabled != oldValue else { return }
@@ -38,22 +38,29 @@ final class VPhoneGyroscopeModel {
private(set) var providerRunning = false
private(set) var error: String?
private(set) var hasLocalChanges = false
- private(set) var configuration = VPhoneGyroscopeConfiguration()
+ private(set) var configuration = VPhoneMotionConfiguration()
- @ObservationIgnored private let read: @MainActor () async throws -> VPhoneGyroscopeReply
- @ObservationIgnored private let write: @MainActor (VPhoneGyroscopeConfiguration) async throws -> VPhoneGyroscopeReply
+ @ObservationIgnored private let read: @MainActor () async throws -> VPhoneMotionReply
+ @ObservationIgnored private let write: @MainActor (VPhoneMotionConfiguration) async throws -> VPhoneMotionReply
@ObservationIgnored private let locale: Locale
+ @ObservationIgnored private let ranges: [ClosedRange<Double>]
+ @ObservationIgnored private let rejectionMessage: String
@ObservationIgnored private var applyingGuest = false
@ObservationIgnored private var generation = 0
- @ObservationIgnored private var pending: VPhoneGyroscopeConfiguration?
+ @ObservationIgnored private var pending: VPhoneMotionConfiguration?
@ObservationIgnored private var writer: Task<Void, Never>?
init(
locale: Locale = .current,
- read: @escaping @MainActor () async throws -> VPhoneGyroscopeReply,
- write: @escaping @MainActor (VPhoneGyroscopeConfiguration) async throws -> VPhoneGyroscopeReply,
+ ranges: [ClosedRange<Double>] = [-1000 ... 1000, -1000 ... 1000, -1000 ... 1000],
+ rejectionMessage: String = "Guest did not apply the gyroscope configuration",
+ read: @escaping @MainActor () async throws -> VPhoneMotionReply,
+ write: @escaping @MainActor (VPhoneMotionConfiguration) async throws -> VPhoneMotionReply,
) {
self.locale = locale
+ precondition(ranges.count == 3)
+ self.ranges = ranges
+ self.rejectionMessage = rejectionMessage
self.read = read
self.write = write
}
@@ -64,22 +71,22 @@ final class VPhoneGyroscopeModel {
// Computed key-path bindings let the steppers repair a partially typed axis.
var xValue: Double {
- get { number(xText) ?? configuration.x }
+ get { number(xText, range: ranges[0]) ?? configuration.x }
set { xText = formatted(newValue) }
}
var yValue: Double {
- get { number(yText) ?? configuration.y }
+ get { number(yText, range: ranges[1]) ?? configuration.y }
set { yText = formatted(newValue) }
}
var zValue: Double {
- get { number(zText) ?? configuration.z }
+ get { number(zText, range: ranges[2]) ?? configuration.z }
set { zText = formatted(newValue) }
}
- private func number(_ text: String) -> Double? {
+ private func number(_ text: String, range: ClosedRange<Double>) -> Double? {
let normalized = text.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: locale.decimalSeparator ?? ".", with: ".")
- guard let value = Double(normalized), value.isFinite, abs(value) <= 1000 else { return nil }
+ guard let value = Double(normalized), value.isFinite, range.contains(value) else { return nil }
return value
}
@@ -87,9 +94,10 @@ final class VPhoneGyroscopeModel {
value.formatted(.number.grouping(.never).precision(.fractionLength(0 ... 6)).locale(locale))
}
- private var parsedConfiguration: VPhoneGyroscopeConfiguration? {
- guard let x = number(xText), let y = number(yText), let z = number(zText) else { return nil }
- return VPhoneGyroscopeConfiguration(enabled: enabled, x: x, y: y, z: z)
+ private var parsedConfiguration: VPhoneMotionConfiguration? {
+ guard let x = number(xText, range: ranges[0]), let y = number(yText, range: ranges[1]),
+ let z = number(zText, range: ranges[2]) else { return nil }
+ return VPhoneMotionConfiguration(enabled: enabled, x: x, y: y, z: z)
}
private func axesChanged() {
@@ -97,7 +105,7 @@ final class VPhoneGyroscopeModel {
enqueue(value)
}
- private func applyFields(_ value: VPhoneGyroscopeConfiguration) {
+ private func applyFields(_ value: VPhoneMotionConfiguration) {
applyingGuest = true
defer { applyingGuest = false }
enabled = value.enabled
@@ -109,7 +117,7 @@ final class VPhoneGyroscopeModel {
func reset() {
guard canEdit else { return }
- let zero = VPhoneGyroscopeConfiguration(enabled: enabled)
+ let zero = VPhoneMotionConfiguration(enabled: enabled)
applyFields(zero)
enqueue(zero)
}
@@ -145,7 +153,7 @@ final class VPhoneGyroscopeModel {
}
}
- private func enqueue(_ value: VPhoneGyroscopeConfiguration) {
+ private func enqueue(_ value: VPhoneMotionConfiguration) {
guard canEdit else { return }
configuration = value
pending = value
@@ -175,7 +183,7 @@ final class VPhoneGyroscopeModel {
// The guest returns the persisted configuration, not merely
// transport success. Keep newer edits in the fields untouched.
guard reply.configuration == value else {
- error = "Guest did not apply the gyroscope configuration"
+ error = rejectionMessage
pending = configuration
break
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift
new file mode 100644
index 00000000..4b22a414
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift
@@ -0,0 +1,147 @@
+import SwiftUI
+
+enum VPhoneMotionSensor {
+ case gyroscope, attitude
+
+ var identifier: String { self == .gyroscope ? "gyroscope" : "attitude" }
+ var axes: [String] { self == .gyroscope ? ["X", "Y", "Z"] : ["Roll", "Pitch", "Yaw"] }
+ var ranges: [ClosedRange<Double>] {
+ self == .gyroscope ? [-1000 ... 1000, -1000 ... 1000, -1000 ... 1000] : [-180 ... 180, -90 ... 90, -180 ... 180]
+ }
+ var units: String { self == .gyroscope ? "rad/s" : "°" }
+ var step: Double { self == .gyroscope ? 0.1 : 1 }
+}
+
+struct VPhoneMotionView: View {
+ let model: VPhoneMotionModel
+ let sensor: VPhoneMotionSensor
+ let connected: @MainActor () -> Bool
+
+ var body: some View {
+ VPhoneMotionEditor(model: model, sensor: sensor)
+ .task(id: connected()) { await model.connectionChanged(connected()) }
+ }
+}
+
+struct VPhoneMotionEditor: View {
+ @Bindable var model: VPhoneMotionModel
+ let sensor: VPhoneMotionSensor
+
+ var body: some View {
+ VStack(spacing: 0) {
+ Form {
+ Section {
+ Toggle(isOn: $model.enabled) {
+ Text("Enable Simulation", bundle: VPhoneLocalization.bundle)
+ }
+ .toggleStyle(.checkbox)
+ .accessibilityIdentifier(sensor.identifier + "-enabled")
+ Text("Changes sync to the guest immediately. Disabling keeps your axis values.", bundle: VPhoneLocalization.bundle)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ if sensor == .attitude {
+ Text("Angles describe a stationary pose. Zero is face up. Enable simulation before launching the guest app.", bundle: VPhoneLocalization.bundle)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ Section {
+ VPhoneMotionAxisRow(sensor: sensor, index: 0, text: $model.xText, value: $model.xValue)
+ VPhoneMotionAxisRow(sensor: sensor, index: 1, text: $model.yText, value: $model.yValue)
+ VPhoneMotionAxisRow(sensor: sensor, index: 2, text: $model.zText, value: $model.zValue)
+ if model.hasInvalidAxes {
+ Text(sensor == .gyroscope ? "Enter a number from -1000 to 1000 for each axis." : "Roll and yaw: -180 to 180°. Pitch: -90 to 90°.", bundle: VPhoneLocalization.bundle)
+ .font(.caption)
+ .foregroundStyle(.orange)
+ }
+ Button { model.reset() } label: {
+ Label {
+ Text("Reset", bundle: VPhoneLocalization.bundle)
+ } icon: { Image(systemName: "arrow.counterclockwise") }
+ }
+ .accessibilityIdentifier(sensor.identifier + "-reset")
+ .help(Text("Set all three axes to zero", bundle: VPhoneLocalization.bundle))
+ } header: {
+ Text(sensor == .gyroscope ? "Angular Velocity" : "Device Attitude", bundle: VPhoneLocalization.bundle)
+ }
+ }
+ .formStyle(.grouped)
+ .disabled(!model.canEdit)
+ Divider()
+ VPhoneMotionSyncStatus(model: model, sensor: sensor)
+ }
+ }
+}
+
+struct VPhoneMotionAxisRow: View {
+ let sensor: VPhoneMotionSensor
+ let index: Int
+ @Binding var text: String
+ @Binding var value: Double
+
+ var body: some View {
+ HStack(spacing: 8) {
+ Text(VPhoneLocalization.text(sensor.axes[index]))
+ .font(.system(.body, design: .monospaced))
+ TextField(VPhoneLocalization.text(sensor.axes[index]), text: $text)
+ .textFieldStyle(.roundedBorder)
+ .font(.system(.body, design: .monospaced))
+ .accessibilityLabel(VPhoneLocalization.text(sensor.axes[index]))
+ .accessibilityIdentifier(sensor.identifier + "-axis-" + sensor.axes[index].lowercased())
+ Text(verbatim: sensor.units).foregroundStyle(.secondary)
+ Stepper(VPhoneLocalization.text(sensor.axes[index]), value: $value, in: sensor.ranges[index], step: sensor.step)
+ .labelsHidden()
+ .accessibilityLabel(VPhoneLocalization.text(sensor.axes[index]))
+ }
+ }
+}
+
+struct VPhoneMotionSyncStatus: View {
+ let model: VPhoneMotionModel
+ let sensor: VPhoneMotionSensor
+
+ var body: some View {
+ HStack(spacing: 8) {
+ if !model.isConnected {
+ Text("Guest not connected", bundle: VPhoneLocalization.bundle)
+ } else if model.isReading || model.isSending {
+ ProgressView().controlSize(.small)
+ Text("Syncing…", bundle: VPhoneLocalization.bundle)
+ } else if let error = model.error {
+ Image(systemName: "exclamationmark.triangle").foregroundStyle(.orange)
+ Text(VPhoneLocalization.text(error)).textSelection(.enabled)
+ } else if model.hasLoaded {
+ if model.providerRunning {
+ Text("Synced", bundle: VPhoneLocalization.bundle)
+ } else if sensor == .attitude {
+ Text("Enable the device attitude patch and relaunch the guest app.", bundle: VPhoneLocalization.bundle)
+ } else {
+ Text("Waiting for sensor service…", bundle: VPhoneLocalization.bundle)
+ }
+ }
+ Spacer(minLength: 0)
+ if model.canRetry {
+ Button { model.retry() } label: { Text("Retry", bundle: VPhoneLocalization.bundle) }
+ } else if model.isConnected && !model.hasLoaded && !model.isReading {
+ Button { Task { await model.connectionChanged(true) } } label: {
+ Text("Retry", bundle: VPhoneLocalization.bundle)
+ }
+ }
+ }
+ .font(.system(.caption, design: .monospaced))
+ .padding(8)
+ .background(.bar)
+ }
+}
+
+#Preview {
+ let sample = VPhoneMotionReply(
+ configuration: VPhoneMotionConfiguration(enabled: true, x: 1.25, y: 0, z: -0.75),
+ providerRunning: true,
+ )
+ let model = VPhoneMotionModel(read: { sample }, write: {
+ VPhoneMotionReply(configuration: $0, providerRunning: true)
+ })
+ return VPhoneMotionView(model: model, sensor: .gyroscope, connected: { true })
+ .frame(width: 440, height: 380)
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhoneGuestPanelsWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhoneGuestPanelsWindowController.swift
index 9b92ba84..1f27cdf2 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhoneGuestPanelsWindowController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhoneGuestPanelsWindowController.swift
@@ -13,6 +13,7 @@ enum VPhoneGuestPanel: CaseIterable {
case services
case controls
case gyroscope
+ case attitude
/// The `/v1/health` capability an agent must report before the panel can
/// talk to it. Older agents answer "Unknown method" for everything else.
@@ -24,6 +25,7 @@ enum VPhoneGuestPanel: CaseIterable {
case .services: "services"
case .controls: "display"
case .gyroscope: "motion_gyroscope_toggle"
+ case .attitude: "motion_attitude"
}
}
}
@@ -99,7 +101,7 @@ final class VPhoneGuestPanelsWindowController {
minSize: NSSize(width: 460, height: 400),
) { VPhoneControlsView(model: model) }
case .gyroscope:
- let model = VPhoneGyroscopeModel(
+ let model = VPhoneMotionModel(
read: { try await control.readGyroscope() },
write: { try await control.setGyroscope($0) },
)
@@ -108,7 +110,20 @@ final class VPhoneGuestPanelsWindowController {
autosaveName: "vphone-panel-gyroscope",
size: NSSize(width: 440, height: 380),
minSize: NSSize(width: 400, height: 340),
- ) { VPhoneGyroscopeView(model: model, connected: { control.isConnected }) }
+ ) { VPhoneMotionView(model: model, sensor: .gyroscope, connected: { control.isConnected }) }
+ case .attitude:
+ let model = VPhoneMotionModel(
+ ranges: VPhoneMotionSensor.attitude.ranges,
+ rejectionMessage: "Guest did not apply the attitude configuration",
+ read: { try await control.readAttitude() },
+ write: { try await control.setAttitude($0) },
+ )
+ return VPhoneGuestToolWindow(
+ title: String(localized: "Device Attitude", bundle: VPhoneLocalization.bundle),
+ autosaveName: "vphone-panel-attitude",
+ size: NSSize(width: 480, height: 440),
+ minSize: NSSize(width: 440, height: 400),
+ ) { VPhoneMotionView(model: model, sensor: .attitude, connected: { control.isConnected }) }
}
}
}