Run a virtual iPhone on an Apple Silicon Mac.
Swift
Add attached attitude dials to the guest display
Phineas Guo5632674c13e8
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstringsindex 2a20ebf5..9d6843c6 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings@@ -1,6 +1,20 @@{"sourceLanguage" : "en","strings" : {+ "Show Attitude Dials" : {+ "extractionState" : "manual",+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Show Attitude Dials" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "显示姿态刻度盘" } }+ }+ },+ "Drag or scroll a dial to adjust its angle. Hover to show its rotation axis." : {+ "extractionState" : "manual",+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Drag or scroll a dial to adjust its angle. Hover to show its rotation axis." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "按住拖动或滚动刻度盘可调整角度,悬停时显示对应旋转轴。" } }+ }+ },"Angles describe a stationary pose. Zero is face up. Enable simulation before launching the guest app." : {"extractionState" : "manual","localizations" : {@@ -32564,4 +32578,4 @@}},"version" : "1.3"-}\ No newline at end of file+}diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/AttitudeDialTests.swift b/VPhoneExecutable/VPhoneVirtualization/Tests/AttitudeDialTests.swiftnew file mode 100644index 00000000..7c9a1cf8--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/AttitudeDialTests.swift@@ -0,0 +1,128 @@+import AppKit+import SwiftUI++@main+struct AttitudeDialTests {+ @MainActor static func main() {+ let preview = CommandLine.arguments.contains("--preview")+ let windows = preview || CommandLine.arguments.contains("--windows")+ if windows {+ _ = NSApplication.shared+ NSApp.setActivationPolicy(.regular)+ }+ Task { @MainActor in+ let model = VPhoneMotionModel(ranges: [-180 ... 180, -90 ... 90, -180 ... 180], read: {+ VPhoneMotionReply(configuration: .init(enabled: true), providerRunning: true)+ }, write: { VPhoneMotionReply(configuration: $0, providerRunning: true) })+ await model.connectionChanged(true)+ VPhoneAttitudeAxis.roll.adjust(300, in: model)+ assert(model.xValue == 180 && model.yValue == 0 && model.zValue == 0)+ VPhoneAttitudeAxis.pitch.adjust(-300, in: model)+ assert(model.yValue == -90)+ VPhoneAttitudeAxis.yaw.adjust(-300, in: model)+ assert(model.zValue == -180)+ VPhoneAttitudeAxis.yaw.adjust(.infinity, in: model)+ assert(model.zValue == -180)+ await model.connectionChanged(false)+ VPhoneAttitudeAxis.roll.adjust(-10, in: model)+ assert(model.xValue == 180)+ await model.connectionChanged(true)+ model.reset()+ assert(abs(VPhoneAttitudeAxis.angularDelta(from: 179 * .pi / 180, to: -179 * .pi / 180) - 2) < 0.001)+ assert(abs(VPhoneAttitudeAxis.angularDelta(from: -179 * .pi / 180, to: 179 * .pi / 180) + 2) < 0.001)+ assert(VPhoneAttitudeAxis.roll.scrollDelta(x: 8, y: 1, precise: true) == -2)+ assert(VPhoneAttitudeAxis.pitch.scrollDelta(x: 8, y: -2, precise: false) == -4)+ assert(VPhoneAttitudeAxis.pitch.scrollDelta(x: 0, y: 4, precise: true) == 1)+ assert(VPhoneAttitudeAxis.yaw.scrollDelta(x: 0, y: 4, precise: true) == -1)+ let screen = NSRect(x: -1440, y: 0, width: 1440, height: 900)+ for parent in [NSRect(x: -1000, y: 240, width: 360, height: 420), screen] {+ for axis in VPhoneAttitudeAxis.allCases {+ assert(screen.contains(VPhoneAttitudeDialsWindowController.dialFrame(axis: axis, around: parent, within: screen)))+ }+ }+ print("Attitude dials: angle bounds, axis isolation, disconnected input, wheel deltas, circular seam and screen-edge layout passed")+ guard windows else { exit(0) }+ await checkWindows(model: model, preview: preview)+ }+ if windows { NSApp.run() } else { dispatchMain() }+ }++ @MainActor static func checkWindows(model: VPhoneMotionModel, preview: Bool) async {+ let parent = NSWindow(contentRect: NSRect(x: 600, y: 270, width: 320, height: 440), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false)+ parent.title = "Attitude Dial Preview"+ parent.isReleasedWhenClosed = false+ parent.contentView?.wantsLayer = true+ parent.contentView?.layer?.backgroundColor = NSColor(white: 0.08, alpha: 1).cgColor+ parent.makeKeyAndOrderFront(nil)+ let controller = VPhoneAttitudeDialsWindowController(model: model)+ controller.attach(to: parent)+ controller.isShown = true+ try? await Task.sleep(for: .milliseconds(300))+ assert(parent.childWindows?.count == 4 && controller.isPresented)+ let roll = parent.childWindows!.first { $0.title == VPhoneLocalization.text("Roll") }!+ assert(!roll.canBecomeKey && roll.parent == parent)+ let original = roll.frame+ parent.setFrameOrigin(NSPoint(x: parent.frame.minX - 40, y: parent.frame.minY))+ assert(abs(roll.frame.minX - original.minX + 40) < 1)+ parent.setContentSize(NSSize(width: 360, height: 480))+ assert(abs(roll.frame.midX - parent.frame.midX) < 1)+ let overlay = parent.childWindows!.first { $0.ignoresMouseEvents }!+ assert(overlay.frame.size == parent.contentView!.frame.size)+ controller.setHovered(.yaw)+ assert(controller.hoveredAxis == .yaw)+ controller.isShown = false+ controller.isShown = true // An old hide completion must not hide a reopened dial.+ try? await Task.sleep(for: .milliseconds(300))+ assert(controller.isPresented && parent.childWindows!.allSatisfy(\.isVisible))++ // Exercise the real NSView drag handler, including the atan2 seam.+ let input = VPhoneAttitudeDialInputView(frame: NSRect(x: 0, y: 0, width: 144, height: 144))+ input.axis = .yaw+ input.enabled = true+ input.adjust = { VPhoneAttitudeAxis.yaw.adjust($0, in: model) }+ let inputWindow = NSWindow(contentRect: input.frame, styleMask: .borderless, backing: .buffered, defer: false)+ inputWindow.isReleasedWhenClosed = false+ inputWindow.contentView = input+ func event(_ type: NSEvent.EventType, angle: Double) -> NSEvent {+ NSEvent.mouseEvent(with: type, location: NSPoint(x: 72 + cos(angle) * 50, y: 72 + sin(angle) * 50), modifierFlags: [], timestamp: 0, windowNumber: inputWindow.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)!+ }+ input.mouseDown(with: event(.leftMouseDown, angle: 179 * .pi / 180))+ input.mouseDragged(with: event(.leftMouseDragged, angle: -179 * .pi / 180))+ assert(abs(model.zValue + 2) < 0.001)+ input.mouseUp(with: event(.leftMouseUp, angle: -179 * .pi / 180))+ func linearEvent(_ type: NSEvent.EventType, point: NSPoint) -> NSEvent {+ NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: 0, windowNumber: inputWindow.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)!+ }+ for axis in [VPhoneAttitudeAxis.roll, .pitch] {+ input.axis = axis+ input.adjust = { axis.adjust($0, in: model) }+ input.mouseDown(with: linearEvent(.leftMouseDown, point: NSPoint(x: 72, y: 72)))+ input.mouseDragged(with: linearEvent(.leftMouseDragged, point: NSPoint(x: 92, y: 92)))+ assert(axis.value(in: model) == -10)+ input.mouseUp(with: linearEvent(.leftMouseUp, point: NSPoint(x: 92, y: 92)))+ }+ inputWindow.close()+ print("Attitude dials: real circular drag, child attachment, focus, movement, resize, hover and rapid toggle passed")+ if preview {+ let editor = NSWindow(contentRect: NSRect(x: 100, y: 230, width: 480, height: 520), styleMask: [.titled, .closable], backing: .buffered, defer: false)+ editor.title = "Device Attitude"+ editor.isReleasedWhenClosed = false+ editor.contentView = NSHostingView(rootView: VPhoneMotionEditor(model: model, sensor: .attitude, attitudeDials: controller))+ editor.makeKeyAndOrderFront(nil)+ NSApp.activate(ignoringOtherApps: true)+ while parent.isVisible, editor.isVisible {+ try? await Task.sleep(for: .seconds(1))+ }+ controller.close()+ exit(0)+ }+ controller.isShown = false+ try? await Task.sleep(for: .milliseconds(300))+ assert(parent.childWindows!.allSatisfy { !$0.isVisible })+ controller.close()+ assert(parent.childWindows?.isEmpty != false)+ parent.close()+ print("Attitude dials: animated dismissal and child-window cleanup passed")+ exit(0)+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/run-attitude-dial-tests.sh b/VPhoneExecutable/VPhoneVirtualization/Tests/run-attitude-dial-tests.shnew file mode 100644index 00000000..c9586c3b--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/run-attitude-dial-tests.sh@@ -0,0 +1,12 @@+#!/bin/zsh+# vphone-tier: build+set -euo pipefail+root="$(cd "${0:a:h}/../../.." && pwd)"+out="$root/.build/attitude-dial-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/VPhoneLocalization.swift" \+ "$root/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/"*.swift \+ "${0:a:h}/AttitudeDialTests.swift" -o "$out/AttitudeDialTests"+"$out/AttitudeDialTests" "$@"diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swiftindex dc29abcf..0b2c8a15 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swift@@ -72,6 +72,7 @@ extension VPhoneMenuController {/// Enables the panels the connected agent can serve. An empty list, as on/// disconnect, disables them all.func updatePanelAvailability(capabilities: [String]) {+ guestPanelsWindowController.attitudeConnectionChanged()for (panel, item) in panelMenuItems {item.isEnabled = capabilities.contains(panel.capability)}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneAttitudeDial.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneAttitudeDial.swiftnew file mode 100644index 00000000..1bc57806--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneAttitudeDial.swift@@ -0,0 +1,310 @@+import AppKit+import SwiftUI++// MARK: - Axes and Interaction++enum VPhoneAttitudeAxis: String, CaseIterable, Identifiable {+ case roll, pitch, yaw++ var id: Self { self }+ var title: String {+ switch self {+ case .roll: "Roll"+ case .pitch: "Pitch"+ case .yaw: "Yaw"+ }+ }++ var range: ClosedRange<Double> { self == .pitch ? -90 ... 90 : -180 ... 180 }+ var color: Color {+ switch self {+ case .roll: .green+ case .pitch: .red+ case .yaw: .blue+ }+ }++ var size: NSSize {+ switch self {+ case .roll: NSSize(width: 248, height: 80)+ case .pitch: NSSize(width: 80, height: 248)+ case .yaw: NSSize(width: 144, height: 144)+ }+ }++ @MainActor func value(in model: VPhoneMotionModel) -> Double {+ switch self {+ case .roll: model.xValue+ case .pitch: model.yValue+ case .yaw: model.zValue+ }+ }++ @MainActor func adjust(_ delta: Double, in model: VPhoneMotionModel) {+ guard model.canEdit, delta.isFinite else { return }+ let value = min(range.upperBound, max(range.lowerBound, value(in: model) + delta))+ switch self {+ case .roll: model.xValue = value+ case .pitch: model.yValue = value+ case .yaw: model.zValue = value+ }+ }++ /// The shortest signed turn avoids a jump when a circular drag crosses ±π.+ static func angularDelta(from: Double, to: Double) -> Double {+ atan2(sin(to - from), cos(to - from)) * 180 / .pi+ }++ func scrollDelta(x: Double, y: Double, precise: Bool) -> Double {+ let delta = self == .roll && abs(x) > abs(y) ? x : y+ let direction = self == .pitch ? 1.0 : -1.0+ return direction * delta * (precise ? 0.25 : 2)+ }+}++/// AppKit supplies wheel deltas and incremental circular drags without+/// intercepting any of the guest display's mouse or trackpad events.+struct VPhoneAttitudeDialInput: NSViewRepresentable {+ let axis: VPhoneAttitudeAxis+ let enabled: Bool+ let adjust: @MainActor (Double) -> Void+ let hover: @MainActor (Bool) -> Void++ func makeNSView(context _: Context) -> VPhoneAttitudeDialInputView {+ let view = VPhoneAttitudeDialInputView()+ view.setAccessibilityElement(false)+ return view+ }++ func updateNSView(_ view: VPhoneAttitudeDialInputView, context _: Context) {+ view.axis = axis+ view.enabled = enabled+ view.adjust = adjust+ view.hover = hover+ }+}++@MainActor+final class VPhoneAttitudeDialInputView: NSView {+ var axis = VPhoneAttitudeAxis.roll+ var enabled = false+ var adjust: (@MainActor (Double) -> Void)?+ var hover: (@MainActor (Bool) -> Void)?+ private var lastPoint: NSPoint?+ private var tracking: NSTrackingArea?++ override func acceptsFirstMouse(for _: NSEvent?) -> Bool { true }++ override func updateTrackingAreas() {+ super.updateTrackingAreas()+ if let tracking { removeTrackingArea(tracking) }+ let area = NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self)+ addTrackingArea(area)+ tracking = area+ }++ override func resetCursorRects() {+ addCursorRect(bounds, cursor: enabled ? .openHand : .arrow)+ }++ override func mouseEntered(with _: NSEvent) { hover?(true) }+ override func mouseExited(with _: NSEvent) { hover?(false) }+ override func mouseDown(with event: NSEvent) {+ guard enabled else { return }+ lastPoint = convert(event.locationInWindow, from: nil)+ }++ override func mouseDragged(with event: NSEvent) {+ let point = convert(event.locationInWindow, from: nil)+ defer { lastPoint = point }+ guard enabled, let lastPoint else { return }+ let delta: Double+ switch axis {+ case .roll: delta = -Double(point.x - lastPoint.x) * 0.5+ case .pitch: delta = -Double(point.y - lastPoint.y) * 0.5+ case .yaw:+ let center = NSPoint(x: bounds.midX, y: bounds.midY)+ // Near the hub an angle is undefined; rebase instead of jumping.+ guard hypot(point.x - center.x, point.y - center.y) > 12,+ hypot(lastPoint.x - center.x, lastPoint.y - center.y) > 12 else { return }+ delta = -VPhoneAttitudeAxis.angularDelta(+ from: atan2(lastPoint.y - center.y, lastPoint.x - center.x),+ to: atan2(point.y - center.y, point.x - center.x),+ )+ }+ adjust?(delta)+ }++ override func mouseUp(with _: NSEvent) { lastPoint = nil }++ override func scrollWheel(with event: NSEvent) {+ guard enabled else { return }+ adjust?(axis.scrollDelta(x: event.scrollingDeltaX, y: event.scrollingDeltaY, precise: event.hasPreciseScrollingDeltas))+ }+}++// MARK: - Dial Faces++struct VPhoneAttitudeDial: View {+ let axis: VPhoneAttitudeAxis+ let controller: VPhoneAttitudeDialsWindowController+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ var body: some View {+ let value = axis.value(in: controller.model)+ ZStack {+ if axis == .yaw {+ VPhoneAttitudeCircularScale(color: axis.color)+ .rotationEffect(.degrees(value))+ Rectangle().fill(axis.color).frame(width: 2, height: 16).offset(y: -55)+ } else {+ VPhoneAttitudeLinearScale(vertical: axis == .pitch, value: value, color: axis.color)+ }+ VStack(spacing: 4) {+ Text(VPhoneLocalization.text(axis.title)).foregroundStyle(.secondary)+ Text(verbatim: value.formatted(.number.precision(.fractionLength(0 ... 1))) + "°")+ .contentTransition(.numericText(value: value))+ .foregroundStyle(axis.color)+ }+ .font(.system(.caption, design: .monospaced))+ .padding(4)+ .background(Color(red: 0.102, green: 0.102, blue: 0.102))+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .background(Color(red: 0.102, green: 0.102, blue: 0.102))+ .clipShape(RoundedRectangle(cornerRadius: axis == .yaw ? 72 : 8))+ .overlay {+ RoundedRectangle(cornerRadius: axis == .yaw ? 72 : 8)+ .stroke(controller.hoveredAxis == axis ? axis.color : Color(white: 0.2), lineWidth: 1)+ }+ .opacity(controller.model.canEdit ? 1 : 0.5)+ .animation(reduceMotion ? nil : .easeOut(duration: 0.12), value: value)+ .overlay {+ VPhoneAttitudeDialInput(axis: axis, enabled: controller.model.canEdit, adjust: {+ axis.adjust($0, in: controller.model)+ }, hover: { controller.setHovered($0 ? axis : nil) })+ }+ .accessibilityElement(children: .ignore)+ .accessibilityLabel(VPhoneLocalization.text(axis.title))+ .accessibilityValue(value.formatted(.number.precision(.fractionLength(0 ... 1))) + "°")+ .accessibilityIdentifier("attitude-dial-" + axis.rawValue)+ .accessibilityAdjustableAction { direction in+ switch direction {+ case .increment: axis.adjust(1, in: controller.model)+ case .decrement: axis.adjust(-1, in: controller.model)+ @unknown default: break+ }+ }+ .scaleEffect(controller.isPresented ? 1 : 0.85)+ .opacity(controller.isPresented ? 1 : 0)+ .animation(reduceMotion ? nil : .easeOut(duration: 0.2), value: controller.isPresented)+ .animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: controller.hoveredAxis)+ .environment(\.colorScheme, .dark)+ .padding(2)+ }+}++struct VPhoneAttitudeCircularScale: View {+ let color: Color++ var body: some View {+ Canvas { context, size in+ let center = CGPoint(x: size.width / 2, y: size.height / 2)+ let radius = min(size.width, size.height) / 2 - 12+ for tick in 0 ..< 72 {+ let angle = Double(tick) * .pi / 36+ let inner = radius - (tick.isMultiple(of: 6) ? 12 : 6)+ var path = Path()+ path.move(to: CGPoint(x: center.x + sin(angle) * inner, y: center.y - cos(angle) * inner))+ path.addLine(to: CGPoint(x: center.x + sin(angle) * radius, y: center.y - cos(angle) * radius))+ context.stroke(path, with: .color(tick == 0 ? color : .gray), lineWidth: tick == 0 ? 2 : 1)+ if tick.isMultiple(of: 6) {+ let degrees = (tick > 36 ? tick - 72 : tick) * 5+ let labelRadius = radius - 24+ context.draw(+ Text(verbatim: "\(degrees)").font(.system(size: 9, design: .monospaced)).foregroundStyle(.gray),+ at: CGPoint(x: center.x + sin(angle) * labelRadius, y: center.y - cos(angle) * labelRadius),+ )+ }+ }+ }+ .accessibilityHidden(true)+ }+}++struct VPhoneAttitudeLinearScale: View {+ let vertical: Bool+ let value: Double+ let color: Color++ var body: some View {+ GeometryReader { geometry in+ // Static scale, moved by a standard animatable offset. One degree+ // is two points; the center marker stays fixed as the ticks move.+ Canvas { context, size in+ for degrees in stride(from: -180, through: 180, by: 5) {+ let position = CGFloat(vertical ? 180 - degrees : degrees + 180) * 2+ let length: CGFloat = degrees.isMultiple(of: 30) ? 16 : 8+ var path = Path()+ if vertical {+ path.move(to: CGPoint(x: 8, y: position))+ path.addLine(to: CGPoint(x: 8 + length, y: position))+ } else {+ path.move(to: CGPoint(x: position, y: 8))+ path.addLine(to: CGPoint(x: position, y: 8 + length))+ }+ context.stroke(path, with: .color(degrees == 0 ? color : .gray), lineWidth: degrees == 0 ? 2 : 1)+ if degrees.isMultiple(of: 30) {+ context.draw(+ Text(verbatim: "\(degrees)").font(.system(.caption2, design: .monospaced)).foregroundStyle(.gray),+ at: CGPoint(x: vertical ? size.width - 20 : position, y: vertical ? position : size.height - 16),+ )+ }+ }+ }+ .frame(width: vertical ? geometry.size.width : 720, height: vertical ? 720 : geometry.size.height)+ .offset(+ x: vertical ? 0 : geometry.size.width / 2 - 360 - value * 2,+ y: vertical ? geometry.size.height / 2 - 360 + value * 2 : 0,+ )+ Rectangle().fill(color)+ .frame(width: vertical ? 20 : 2, height: vertical ? 2 : 20)+ .position(x: vertical ? 18 : geometry.size.width / 2, y: vertical ? geometry.size.height / 2 : 18)+ }+ .clipped()+ .accessibilityHidden(true)+ }+}++// MARK: - Hover Axes++struct VPhoneAttitudeAxesOverlay: View {+ let controller: VPhoneAttitudeDialsWindowController+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ var body: some View {+ GeometryReader { geometry in+ ZStack {+ Rectangle().fill(VPhoneAttitudeAxis.roll.color)+ .frame(width: 2, height: geometry.size.height - 24)+ .opacity(controller.hoveredAxis == .roll ? 0.85 : 0)+ Rectangle().fill(VPhoneAttitudeAxis.pitch.color)+ .frame(width: geometry.size.width - 24, height: 2)+ .opacity(controller.hoveredAxis == .pitch ? 0.85 : 0)+ Circle().stroke(VPhoneAttitudeAxis.yaw.color, lineWidth: 2)+ .frame(width: min(geometry.size.width, geometry.size.height) - 24,+ height: min(geometry.size.width, geometry.size.height) - 24)+ .overlay(alignment: .top) {+ Circle().fill(VPhoneAttitudeAxis.yaw.color).frame(width: 6, height: 6)+ }+ .rotationEffect(.degrees(controller.model.zValue))+ .opacity(controller.hoveredAxis == .yaw ? 0.85 : 0)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ .animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: controller.hoveredAxis)+ .animation(reduceMotion ? nil : .easeOut(duration: 0.12), value: controller.model.zValue)+ .accessibilityHidden(true)+ .allowsHitTesting(false)+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneAttitudeDialsWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneAttitudeDialsWindowController.swiftnew file mode 100644index 00000000..75ed470b--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneAttitudeDialsWindowController.swift@@ -0,0 +1,179 @@+import AppKit+import Observation+import SwiftUI++// MARK: - Attached Windows++@MainActor+@Observable+final class VPhoneAttitudeDialsWindowController: NSObject {+ let model: VPhoneMotionModel+ var isShown = false {+ didSet {+ guard isShown != oldValue else { return }+ updateVisibility()+ }+ }++ private(set) var isPresented = false+ private(set) var hoveredAxis: VPhoneAttitudeAxis?+ @ObservationIgnored private weak var parent: NSWindow?+ @ObservationIgnored private var dials: [VPhoneAttitudeAxis: NSPanel] = [:]+ @ObservationIgnored private var axesWindow: NSPanel?+ @ObservationIgnored private var visibilityTask: Task<Void, Never>?+ @ObservationIgnored private var connectionTask: Task<Void, Never>?++ init(model: VPhoneMotionModel) {+ self.model = model+ super.init()+ }++ func connectionChanged(_ connected: Bool) {+ connectionTask?.cancel()+ connectionTask = Task { await model.connectionChanged(connected) }+ }++ func attach(to window: NSWindow?) {+ removeWindows()+ NotificationCenter.default.removeObserver(self)+ parent = window+ guard let window else { return }+ for name in [NSWindow.didMoveNotification, NSWindow.didResizeNotification, NSWindow.didChangeScreenNotification] {+ NotificationCenter.default.addObserver(self, selector: #selector(layoutWindows), name: name, object: window)+ }+ for name in [NSWindow.didMiniaturizeNotification, NSWindow.didDeminiaturizeNotification] {+ NotificationCenter.default.addObserver(self, selector: #selector(updateVisibility), name: name, object: window)+ }+ for name in [NSWindow.didEnterFullScreenNotification, NSWindow.didExitFullScreenNotification] {+ NotificationCenter.default.addObserver(self, selector: #selector(updateVisibility), name: name, object: window)+ }+ NotificationCenter.default.addObserver(self, selector: #selector(close), name: NSWindow.willCloseNotification, object: window)+ NotificationCenter.default.addObserver(self, selector: #selector(clearHover), name: NSApplication.didResignActiveNotification, object: nil)+ updateVisibility()+ }++ func setHovered(_ axis: VPhoneAttitudeAxis?) {+ hoveredAxis = isShown && isPresented ? axis : nil+ }++ @objc private func clearHover() { hoveredAxis = nil }++ @objc private func updateVisibility() {+ visibilityTask?.cancel()+ hoveredAxis = nil+ guard let parent, isShown, !parent.isMiniaturized else {+ isPresented = false+ dials.values.forEach { $0.ignoresMouseEvents = true }+ visibilityTask = Task { [weak self] in+ try? await Task.sleep(for: .milliseconds(220))+ guard !Task.isCancelled, let self else { return }+ self.dials.values.forEach { $0.orderOut(nil) }+ self.axesWindow?.orderOut(nil)+ }+ return+ }+ if dials.isEmpty { makeWindows() }+ layoutWindows()+ for dial in dials.values {+ dial.ignoresMouseEvents = false+ dial.orderFront(nil)+ dial.contentView?.layoutSubtreeIfNeeded()+ }+ axesWindow?.orderFront(nil)+ visibilityTask = Task { [weak self] in+ // Give the hosting views a first frame before animating them in.+ try? await Task.sleep(for: .milliseconds(16))+ guard !Task.isCancelled else { return }+ self?.isPresented = true+ }+ }++ private func makeWindows() {+ guard let parent else { return }+ for axis in VPhoneAttitudeAxis.allCases {+ let panel = makePanel(size: axis.size)+ panel.title = VPhoneLocalization.text(axis.title)+ panel.contentView = NSHostingView(rootView: VPhoneAttitudeDial(axis: axis, controller: self))+ parent.addChildWindow(panel, ordered: .above)+ dials[axis] = panel+ }+ let overlay = makePanel(size: parent.frame.size)+ overlay.ignoresMouseEvents = true+ overlay.contentView = NSHostingView(rootView: VPhoneAttitudeAxesOverlay(controller: self))+ parent.addChildWindow(overlay, ordered: .above)+ axesWindow = overlay+ }++ private func makePanel(size: NSSize) -> NSPanel {+ let panel = VPhoneAttitudeDialPanel(+ contentRect: NSRect(origin: .zero, size: size),+ styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false,+ )+ panel.isReleasedWhenClosed = false+ panel.isOpaque = false+ panel.backgroundColor = .clear+ panel.hasShadow = false+ panel.hidesOnDeactivate = true+ panel.isMovable = false+ panel.collectionBehavior = [.fullScreenAuxiliary]+ panel.animationBehavior = .none+ return panel+ }++ @objc private func layoutWindows() {+ guard let parent else { return }+ let frame = parent.frame+ let visible = parent.screen?.visibleFrame ?? frame.insetBy(dx: -300, dy: -300)+ for (axis, panel) in dials {+ panel.setFrame(Self.dialFrame(axis: axis, around: frame, within: visible), display: true)+ }+ if let content = parent.contentView {+ axesWindow?.setFrame(parent.convertToScreen(content.convert(content.bounds, to: nil)), display: true)+ }+ }++ /// Keep controls reachable at screen edges and in full screen. Child-window+ /// attachment handles movement; resize/screen notifications recompute anchors.+ static func dialFrame(axis: VPhoneAttitudeAxis, around parent: NSRect, within visible: NSRect) -> NSRect {+ let size = axis.size+ let origin: NSPoint+ switch axis {+ case .yaw: origin = NSPoint(x: parent.midX - size.width / 2, y: parent.maxY + 8)+ case .roll: origin = NSPoint(x: parent.midX - size.width / 2, y: parent.minY - size.height - 8)+ case .pitch: origin = NSPoint(x: parent.maxX + 8, y: parent.midY - size.height / 2)+ }+ return NSRect(+ x: min(max(origin.x, visible.minX), max(visible.minX, visible.maxX - size.width)),+ y: min(max(origin.y, visible.minY), max(visible.minY, visible.maxY - size.height)),+ width: size.width, height: size.height,+ )+ }++ private func removeWindows() {+ visibilityTask?.cancel()+ isPresented = false+ hoveredAxis = nil+ for window in Array(dials.values) + [axesWindow].compactMap({ $0 }) {+ parent?.removeChildWindow(window)+ // Hosting views retain this controller; clear them when tearing down.+ window.contentView = nil+ window.close()+ }+ dials.removeAll()+ axesWindow = nil+ }++ @objc func close() {+ connectionTask?.cancel()+ isShown = false+ removeWindows()+ NotificationCenter.default.removeObserver(self)+ parent = nil+ }+}++@MainActor+final class VPhoneAttitudeDialPanel: NSPanel {+ override var canBecomeKey: Bool { false }+ override var canBecomeMain: Bool { false }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swiftindex 81978b98..98f3cfbf 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift@@ -28,16 +28,20 @@ struct VPhoneMotionView: View {let model: VPhoneMotionModellet sensor: VPhoneMotionSensorlet connected: @MainActor () -> Bool+ var attitudeDials: VPhoneAttitudeDialsWindowController? = nilvar body: some View {- VPhoneMotionEditor(model: model, sensor: sensor)- .task(id: connected()) { await model.connectionChanged(connected()) }+ VPhoneMotionEditor(model: model, sensor: sensor, attitudeDials: attitudeDials)+ .task(id: connected()) {+ if attitudeDials == nil { await model.connectionChanged(connected()) }+ }}}struct VPhoneMotionEditor: View {@Bindable var model: VPhoneMotionModellet sensor: VPhoneMotionSensor+ var attitudeDials: VPhoneAttitudeDialsWindowController? = nilvar body: some View {VStack(spacing: 0) {@@ -79,12 +83,34 @@ struct VPhoneMotionEditor: View {}.formStyle(.grouped).disabled(!model.canEdit)+ if let attitudeDials {+ VPhoneAttitudeDialsToggle(controller: attitudeDials)+ .padding(12)+ }Divider()VPhoneMotionSyncStatus(model: model, sensor: sensor)}}}+struct VPhoneAttitudeDialsToggle: View {+ @Bindable var controller: VPhoneAttitudeDialsWindowController++ var body: some View {+ VStack(alignment: .leading, spacing: 8) {+ Toggle(isOn: $controller.isShown) {+ Text("Show Attitude Dials", bundle: VPhoneLocalization.bundle)+ }+ .toggleStyle(.checkbox)+ .accessibilityIdentifier("attitude-show-dials")+ Text("Drag or scroll a dial to adjust its angle. Hover to show its rotation axis.", bundle: VPhoneLocalization.bundle)+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+}+struct VPhoneMotionAxisRow: View {let sensor: VPhoneMotionSensorlet index: Intdiff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhoneGuestPanelsWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhoneGuestPanelsWindowController.swiftindex 1f27cdf2..ff12e86d 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhoneGuestPanelsWindowController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhoneGuestPanelsWindowController.swift@@ -38,6 +38,10 @@ enum VPhoneGuestPanel: CaseIterable {final class VPhoneGuestPanelsWindowController {private let control: VPhoneGuestControlprivate var windows: [VPhoneGuestPanel: VPhoneGuestToolWindow] = [:]+ private var attitudeDials: VPhoneAttitudeDialsWindowController?+ weak var displayWindow: NSWindow? {+ didSet { attitudeDials?.attach(to: displayWindow) }+ }init(control: VPhoneGuestControl) {self.control = control@@ -49,6 +53,14 @@ final class VPhoneGuestPanelsWindowController {window.show()}+ func attitudeConnectionChanged() {+ attitudeDials?.connectionChanged(control.isConnected && control.guestCapabilities.contains("motion_attitude"))+ }++ func closeAttitudeDials() {+ attitudeDials?.close()+ }+private func makeWindow(_ panel: VPhoneGuestPanel) -> VPhoneGuestToolWindow {let control = controlswitch panel {@@ -118,12 +130,16 @@ final class VPhoneGuestPanelsWindowController {read: { try await control.readAttitude() },write: { try await control.setAttitude($0) },)+ let dials = VPhoneAttitudeDialsWindowController(model: model)+ attitudeDials = dials+ dials.attach(to: displayWindow)+ attitudeConnectionChanged()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 }) }+ size: NSSize(width: 480, height: 520),+ minSize: NSSize(width: 440, height: 480),+ ) { VPhoneMotionView(model: model, sensor: .attitude, connected: { control.isConnected }, attitudeDials: dials) }}}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swiftindex 68deb8ca..1b164503 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift@@ -22,6 +22,8 @@ class VPhoneVirtualMachineWindowController: NSObject, NSWindowDelegate {virtualMachineView}+ var displayWindow: NSWindow? { windowController?.window }+func showWindow(for vm: VZVirtualMachine,screenWidth: Int,diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex e72e1289..07fb8db6 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -181,6 +181,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {}let mc = VPhoneMenuController(keySender: keySender, control: control)+ mc.guestPanelsWindowController.displayWindow = wc.displayWindowmc.vm = vmmc.onHardwareKeyboardChange = { [weak self] enabled inguard let self else { return }@@ -469,6 +470,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {hostAudioLatencySync?.stop()cameraServer?.disconnect()menuController?.stopBatteryMonitoring()+ menuController?.guestPanelsWindowController.closeAttitudeDials()windowController?.closeForRestart()// Tool windows belong to the old guest connection too.for window in NSApp.windows {