Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Animate the turn: the panel and the window move together

Lakra16ea3b973b3
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
index 2be3ca18..0dfd2df9 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
@@ -48,16 +48,54 @@ final class VPhoneGuestControl {
@ObservationIgnored var onConnect: (([String]) -> Void)?
@ObservationIgnored var onDisconnect: (() -> Void)?
- /// The guest interface orientation the window last read; nil until it
- /// has read one, and again after a disconnect.
+ /// The guest interface orientation: the one the window last read, or the
+ /// one a menu rotation is turning to. Nil until one is known, and again
+ /// after a disconnect.
var interfaceOrientation: VPhoneDisplayOrientation? {
didSet {
guard interfaceOrientation != oldValue else { return }
- onInterfaceOrientationChange?(interfaceOrientation)
+ for observer in orientationObservers {
+ observer(interfaceOrientation)
+ }
}
}
- @ObservationIgnored var onInterfaceOrientationChange: ((VPhoneDisplayOrientation?) -> Void)?
+ /// True while a menu rotation waits for the guest, so the poll does not
+ /// turn the window back to an orientation read before the guest turned.
+ var isChangingOrientation: Bool {
+ pendingRotations > 0
+ }
+
+ @ObservationIgnored private var pendingRotations = 0
+ @ObservationIgnored private var orientationObservers: [(VPhoneDisplayOrientation?) -> Void] = []
+
+ func observeInterfaceOrientation(_ observer: @escaping (VPhoneDisplayOrientation?) -> Void) {
+ orientationObservers.append(observer)
+ }
+
+ /// Turns the guest to the first of `candidates` it accepts. Each is set
+ /// before the guest is asked, so the window turns with the guest instead
+ /// of after it, and a refused one moves straight on to the next. When
+ /// every one is refused, the orientation from before is restored and the
+ /// last refusal is thrown.
+ func rotate(toFirstOf candidates: [VPhoneDisplayOrientation]) async throws {
+ let previous = interfaceOrientation
+ pendingRotations += 1
+ defer { pendingRotations -= 1 }
+ var refusal: Error = ControlError.protocolError("no orientation to rotate to")
+ for orientation in candidates {
+ interfaceOrientation = orientation
+ do {
+ _ = try await call("display.rotation", params: ["orientation": String(orientation.rawValue)])
+ return
+ } catch {
+ print("[rotate] \(orientation) refused: \(error)")
+ refusal = error
+ }
+ }
+ interfaceOrientation = previous
+ throw refusal
+ }
var useGuestTouchInjection: Bool {
guard isConnected, guestCapabilities.contains("touch"),
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
index e0b25122..fdc880a1 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
@@ -45,7 +45,7 @@ extension VPhoneMenuController {
menu.addItem(rotate)
}
rotateMenuItems = [rotateLeft, rotateRight, orientationItem]
- control.onInterfaceOrientationChange = { [weak self] orientation in
+ control.observeInterfaceOrientation { [weak self] orientation in
self?.updateOrientationChecks(orientation)
}
menu.addItem(NSMenuItem.separator())
@@ -117,12 +117,13 @@ extension VPhoneMenuController {
}
@objc func chooseOrientation(_ sender: NSMenuItem) {
- guard let degrees = sender.representedObject as? Int else { return }
+ guard let degrees = sender.representedObject as? Int,
+ let orientation = VPhoneDisplayOrientation(degrees: degrees)
+ else { return }
Task {
do {
- _ = try await control.call("display.rotation", params: ["orientation": String(degrees)])
+ try await control.rotate(toFirstOf: [orientation])
} catch {
- print("[rotate] \(degrees) refused: \(error)")
VPhoneAlert.present(
title: "Unable to Rotate",
message: "The app in front does not support this orientation.",
@@ -140,28 +141,22 @@ extension VPhoneMenuController {
rotate(clockwise: true)
}
- /// Turns the guest a quarter turn from its current interface orientation.
- /// An orientation the foreground app refuses, such as upside down on the
- /// Home Screen, is skipped for the one after it. The window follows on
- /// its next orientation poll.
+ /// Turns the guest a quarter turn from its interface orientation, the
+ /// one already turning to when pressed again. An orientation the app in
+ /// front refuses, such as upside down on the Home Screen, is skipped for
+ /// the one after it. The window turns with the guest.
private func rotate(clockwise: Bool) {
Task {
- let method = control.guestCapabilities.contains("display_orientation")
- ? "display.orientation" : "display.rotation"
- guard let result = try? await control.call(method),
- let degrees = (result["degrees"] as? NSNumber)?.intValue,
- let current = VPhoneDisplayOrientation(degrees: degrees)
- else { return }
- var target = current.turned(clockwise: clockwise)
- for _ in 0 ..< 2 {
- do {
- _ = try await control.call("display.rotation", params: ["orientation": String(target.rawValue)])
- return
- } catch {
- print("[rotate] \(target) refused: \(error)")
- target = target.turned(clockwise: clockwise)
- }
+ var current = control.interfaceOrientation
+ if current == nil {
+ let method = control.guestCapabilities.contains("display_orientation")
+ ? "display.orientation" : "display.rotation"
+ let degrees = try? await (control.call(method)["degrees"] as? NSNumber)?.intValue
+ current = degrees.flatMap(VPhoneDisplayOrientation.init(degrees:))
}
+ guard let current else { return }
+ let next = current.turned(clockwise: clockwise)
+ try? await control.rotate(toFirstOf: [next, next.turned(clockwise: clockwise)])
}
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
index 75837fd0..79168a96 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
@@ -44,6 +44,7 @@ class VPhoneVirtualMachineWindowController: NSObject {
height: CGFloat(screenHeight) / scale,
)
panelSize = windowSize
+ container.panelSize = windowSize
let window = NSWindow(
contentRect: NSRect(origin: .zero, size: windowSize),
@@ -108,6 +109,12 @@ class VPhoneVirtualMachineWindowController: NSObject {
}
}
+ // The menu sets the orientation before the guest turns, and the poll
+ // after; either way the window follows it.
+ control.observeInterfaceOrientation { [weak self, weak window] orientation in
+ guard let self, let window else { return }
+ applyOrientation(orientation ?? .portrait, to: window)
+ }
_ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
Task { @MainActor in self?.pollOrientation() }
}
@@ -119,40 +126,42 @@ class VPhoneVirtualMachineWindowController: NSObject {
private var panelSize: NSSize = .zero
private var orientationPollInFlight = false
- /// Asks vphoned for the interface orientation once a second and turns the
- /// window to it. Guests without `display.orientation` stay portrait.
+ /// Asks vphoned for the interface orientation once a second. Guests
+ /// without `display.orientation` stay portrait. A read that overlaps a
+ /// rotation the menu started is dropped: it may predate the turn.
private func pollOrientation() {
guard !orientationPollInFlight,
- let control, control.isConnected,
+ let control, control.isConnected, !control.isChangingOrientation,
control.guestCapabilities.contains("display_orientation")
else { return }
orientationPollInFlight = true
Task {
defer { orientationPollInFlight = false }
guard let result = try? await control.call("display.orientation"),
+ !control.isChangingOrientation,
let degrees = (result["degrees"] as? NSNumber)?.intValue,
- let orientation = VPhoneDisplayOrientation(degrees: degrees),
- let window = windowController?.window
+ let orientation = VPhoneDisplayOrientation(degrees: degrees)
else { return }
control.interfaceOrientation = orientation
- applyOrientation(orientation, to: window)
}
}
/// Turns the VM view and gives the window the turned panel's aspect
- /// ratio. A windowed VM is resized around its center; a full-screen one
- /// keeps the screen and letterboxes the turned panel.
+ /// ratio, in one animation. A windowed VM reshapes around its center; a
+ /// full-screen one keeps the screen and letterboxes the turned panel.
private func applyOrientation(_ orientation: VPhoneDisplayOrientation, to window: NSWindow, force: Bool = false) {
guard let container = displayContainer, force || container.orientation != orientation else { return }
- container.orientation = orientation
- let displayed = orientation.displayedSize(panel: panelSize)
- window.contentAspectRatio = displayed
- guard !window.styleMask.contains(.fullScreen) else { return }
- let current = window.contentRect(forFrameRect: window.frame)
- let visible = window.screen.map { window.contentRect(forFrameRect: $0.visibleFrame) } ?? .zero
- let target = orientation.contentRect(from: current, panel: panelSize, within: visible)
- guard target != current else { return }
- window.setFrame(window.frameRect(forContentRect: target), display: true, animate: !force)
+ window.contentAspectRatio = orientation.displayedSize(panel: panelSize)
+ var frame: NSRect?
+ if !window.styleMask.contains(.fullScreen) {
+ let current = window.contentRect(forFrameRect: window.frame)
+ let visible = window.screen.map { window.contentRect(forFrameRect: $0.visibleFrame) } ?? .zero
+ let target = orientation.contentRect(from: current, panel: panelSize, within: visible)
+ if target != current {
+ frame = window.frameRect(forContentRect: target)
+ }
+ }
+ container.turn(to: orientation, windowFrame: frame, animated: !force)
}
// MARK: - Title
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneDisplayContainerView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneDisplayContainerView.swift
index 163dfc06..3346fefa 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneDisplayContainerView.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneDisplayContainerView.swift
@@ -1,28 +1,46 @@
import AppKit
+import QuartzCore
import VPhoneCoreKit
// MARK: - Display Container
/// The window's content view. It holds the VM view turned to the guest's
-/// interface orientation and fills itself with it.
+/// interface orientation, at the panel's aspect ratio, as large as fits.
///
/// The VM view keeps its portrait bounds under the turn, so touch mapping,
/// which converts window points into those bounds, needs no change: AppKit's
/// conversion undoes the rotation.
final class VPhoneDisplayContainerView: NSView {
let displayView: NSView
+ /// The guest panel's size in points, portrait.
+ var panelSize: NSSize = .zero {
+ didSet { needsLayout = true }
+ }
- var orientation: VPhoneDisplayOrientation = .portrait {
- didSet {
- guard orientation != oldValue else { return }
- needsLayout = true
- }
+ private(set) var orientation: VPhoneDisplayOrientation = .portrait
+ /// The drawn turn, counterclockwise in degrees. It differs from
+ /// `orientation.viewRotation` only during a turn, and may leave 0...360.
+ private var angle: CGFloat = 0
+ private var turn: Turn?
+ private var displayLink: CADisplayLink?
+
+ private static let turnDuration: CFTimeInterval = 0.35
+
+ /// One animated turn: the panel's angle and the window frame move
+ /// together, so the window reshapes as the panel turns.
+ private struct Turn {
+ let fromAngle: CGFloat
+ let toAngle: CGFloat
+ let fromFrame: NSRect?
+ let toFrame: NSRect?
+ let start: CFTimeInterval
}
init(displayView: NSView) {
self.displayView = displayView
super.init(frame: .zero)
wantsLayer = true
+ layer?.backgroundColor = NSColor.black.cgColor
displayView.autoresizingMask = []
addSubview(displayView)
}
@@ -32,11 +50,84 @@ final class VPhoneDisplayContainerView: NSView {
fatalError("init(coder:) is not supported")
}
+ // MARK: - Turning
+
+ /// Turns to `orientation`, moving the window to `windowFrame` alongside.
+ /// A turn already running continues from where it is drawn.
+ func turn(to orientation: VPhoneDisplayOrientation, windowFrame: NSRect?, animated: Bool) {
+ self.orientation = orientation
+ let target = VPhoneDisplayOrientation.turnTarget(from: angle, to: orientation.viewRotation)
+ guard animated, window?.isVisible == true else {
+ finishTurn(angle: target, windowFrame: windowFrame)
+ return
+ }
+ turn = Turn(
+ fromAngle: angle,
+ toAngle: target,
+ fromFrame: windowFrame == nil ? nil : window?.frame,
+ toFrame: windowFrame,
+ start: CACurrentMediaTime(),
+ )
+ if displayLink == nil {
+ let link = displayLink(target: self, selector: #selector(step(_:)))
+ link.add(to: .main, forMode: .common)
+ displayLink = link
+ }
+ }
+
+ @objc private func step(_ link: CADisplayLink) {
+ guard let turn else {
+ stopDisplayLink()
+ return
+ }
+ let progress = (link.targetTimestamp - turn.start) / Self.turnDuration
+ guard progress < 1 else {
+ self.turn = nil
+ stopDisplayLink()
+ finishTurn(angle: turn.toAngle, windowFrame: turn.toFrame)
+ return
+ }
+ let eased = CGFloat(VPhoneDisplayOrientation.easedProgress(progress))
+ angle = turn.fromAngle + (turn.toAngle - turn.fromAngle) * eased
+ if let from = turn.fromFrame, let to = turn.toFrame, let window {
+ window.setFrame(Self.interpolate(from, to, eased), display: false)
+ }
+ needsLayout = true
+ layoutSubtreeIfNeeded()
+ }
+
+ private func finishTurn(angle target: CGFloat, windowFrame: NSRect?) {
+ angle = target.truncatingRemainder(dividingBy: 360)
+ if angle < 0 { angle += 360 }
+ if let windowFrame, let window {
+ window.setFrame(windowFrame, display: true)
+ }
+ needsLayout = true
+ layoutSubtreeIfNeeded()
+ }
+
+ private func stopDisplayLink() {
+ displayLink?.invalidate()
+ displayLink = nil
+ }
+
+ private static func interpolate(_ from: NSRect, _ to: NSRect, _ t: CGFloat) -> NSRect {
+ NSRect(
+ x: (from.minX + (to.minX - from.minX) * t).rounded(),
+ y: (from.minY + (to.minY - from.minY) * t).rounded(),
+ width: (from.width + (to.width - from.width) * t).rounded(),
+ height: (from.height + (to.height - from.height) * t).rounded(),
+ )
+ }
+
+ // MARK: - Layout
+
override func layout() {
super.layout()
- // Sized unturned, then turned about its center: a quarter turn swaps
- // the frame's sides, so the turned view fills the container.
- let size = orientation.isSideways ? NSSize(width: bounds.height, height: bounds.width) : bounds.size
+ let size = panelSize.width > 0
+ ? VPhoneDisplayOrientation.fittedSize(panel: panelSize, angle: angle, in: bounds.size)
+ : bounds.size
+ // Sized unturned, then turned about its center.
displayView.frameCenterRotation = 0
displayView.frame = NSRect(
x: bounds.midX - size.width / 2,
@@ -44,6 +135,6 @@ final class VPhoneDisplayContainerView: NSView {
width: size.width,
height: size.height,
)
- displayView.frameCenterRotation = orientation.viewRotation
+ displayView.frameCenterRotation = angle
}
}
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneDisplayOrientation.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneDisplayOrientation.swift
index d74e488f..196d2bc7 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneDisplayOrientation.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneDisplayOrientation.swift
@@ -1,4 +1,5 @@
import CoreGraphics
+import Foundation
// MARK: - Display Orientation
@@ -44,6 +45,36 @@ public enum VPhoneDisplayOrientation: Int, CaseIterable, Sendable {
isSideways ? CGSize(width: panel.height, height: panel.width) : panel
}
+ // MARK: - Turning
+
+ /// The largest size with the panel's aspect ratio whose box, turned by
+ /// `angle` degrees, fits in `bounds`. Mid-turn the panel shrinks to stay
+ /// inside the window, as a phone turned in front of you does.
+ public static func fittedSize(panel: CGSize, angle: CGFloat, in bounds: CGSize) -> CGSize {
+ guard panel.width > 0, panel.height > 0, bounds.width > 0, bounds.height > 0 else { return bounds }
+ let radians = angle * .pi / 180
+ let cosine = abs(cos(radians)), sine = abs(sin(radians))
+ let boxWidth = panel.width * cosine + panel.height * sine
+ let boxHeight = panel.width * sine + panel.height * cosine
+ let scale = min(bounds.width / boxWidth, bounds.height / boxHeight)
+ return CGSize(width: panel.width * scale, height: panel.height * scale)
+ }
+
+ /// The angle to animate to from `current` so the panel takes the shorter
+ /// way round to `target`; a half turn goes counterclockwise.
+ public static func turnTarget(from current: CGFloat, to target: CGFloat) -> CGFloat {
+ var delta = (target - current).truncatingRemainder(dividingBy: 360)
+ if delta > 180 { delta -= 360 }
+ if delta <= -180 { delta += 360 }
+ return current + delta
+ }
+
+ /// Ease-in-out progress for a turn, 0 at the start and 1 at the end.
+ public static func easedProgress(_ progress: Double) -> Double {
+ let p = min(1, max(0, progress))
+ return p < 0.5 ? 4 * p * p * p : 1 - pow(-2 * p + 2, 3) / 2
+ }
+
/// The window content rect after turning to this orientation: the current
/// rect's long side becomes the side this orientation makes long, around
/// the same center, scaled down to fit `visible` when it would not.
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/DisplayOrientationTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/DisplayOrientationTests.swift
index 00d59ea4..7bd20adc 100644
--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/DisplayOrientationTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/DisplayOrientationTests.swift
@@ -45,6 +45,43 @@ struct DisplayOrientationTests {
#expect(VPhoneDisplayOrientation.landscapeRight.displayedSize(panel: Self.panel) == sideways)
}
+ // MARK: - Turning
+
+ @Test func `the panel fills the window at rest`() {
+ let upright = VPhoneDisplayOrientation.fittedSize(panel: Self.panel, angle: 0, in: Self.panel)
+ #expect(abs(upright.width - 393) < 1e-6 && abs(upright.height - 852) < 1e-6)
+ let sideways = VPhoneDisplayOrientation.fittedSize(
+ panel: Self.panel, angle: 90, in: CGSize(width: 852, height: 393),
+ )
+ #expect(abs(sideways.width - 393) < 1e-6 && abs(sideways.height - 852) < 1e-6)
+ }
+
+ @Test func `mid-turn the panel shrinks to stay inside and keeps its shape`() {
+ let bounds = CGSize(width: 622, height: 622)
+ let size = VPhoneDisplayOrientation.fittedSize(panel: Self.panel, angle: 45, in: bounds)
+ let root = 0.5.squareRoot()
+ #expect((size.width + size.height) * root <= 622 + 1e-6)
+ #expect(abs(size.width / size.height - 393.0 / 852.0) < 1e-9)
+ }
+
+ @Test func `turns take the short way round`() {
+ #expect(VPhoneDisplayOrientation.turnTarget(from: 0, to: 270) == -90)
+ #expect(VPhoneDisplayOrientation.turnTarget(from: 0, to: 90) == 90)
+ #expect(VPhoneDisplayOrientation.turnTarget(from: 270, to: 0) == 360)
+ #expect(VPhoneDisplayOrientation.turnTarget(from: 0, to: 180) == 180)
+ // A turn redirected halfway continues from where it is drawn.
+ #expect(VPhoneDisplayOrientation.turnTarget(from: -45, to: 90) == 90)
+ }
+
+ @Test func `easing starts and ends at rest`() {
+ #expect(VPhoneDisplayOrientation.easedProgress(0) == 0)
+ #expect(VPhoneDisplayOrientation.easedProgress(1) == 1)
+ #expect(VPhoneDisplayOrientation.easedProgress(0.5) == 0.5)
+ #expect(VPhoneDisplayOrientation.easedProgress(-1) == 0)
+ #expect(VPhoneDisplayOrientation.easedProgress(2) == 1)
+ #expect(VPhoneDisplayOrientation.easedProgress(0.1) < 0.1)
+ }
+
// MARK: - Window
@Test func `turning keeps the long side and the center`() {