From e6e0dfd1d7e85d6a0a85b44f5cb1bd61d30083f2 Mon Sep 17 00:00:00 2001 From: osy Date: Tue, 17 Nov 2026 09:49:29 -0800 Subject: [PATCH 1/4] display(macOS): revert "keep Retina displays sharp when the display link draws" This reverts commit 9f1068802eb2e578e9aaa0dd5139d6154c38b90e (#8195). The CAMetalDisplayLink it fixed is reverted next and replaced by a display link that lets MTKView keep handling its drawables, which does not need this fix. Assisted-by: Claude:claude-opus-5-5 --- .../VMDisplayQemuMetalWindowController.swift | 7 ---- Platform/macOS/Display/VMMetalView.swift | 39 ------------------- 2 files changed, 46 deletions(-) diff --git a/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift b/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift index 4d05211465..1e4c926ff4 100644 --- a/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift +++ b/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift @@ -795,13 +795,6 @@ extension VMDisplayQemuMetalWindowController { @available(macOS 14, *) extension VMDisplayQemuMetalWindowController: CAMetalDisplayLinkDelegate { func metalDisplayLink(_ link: CAMetalDisplayLink, needsUpdate update: CAMetalDisplayLink.Update) { - let texture = update.drawable.texture - if let layer = metalView.layer as? CAMetalLayer, - CGFloat(texture.width) != layer.drawableSize.width || CGFloat(texture.height) != layer.drawableSize.height { - // taken before the view was resized: the renderer's viewport already has the new size, so - // draw into the next drawable, which has it too - return - } metalView.displayLinkDrawable = update.drawable renderer.draw(in: metalView) metalView.displayLinkDrawable = nil diff --git a/Platform/macOS/Display/VMMetalView.swift b/Platform/macOS/Display/VMMetalView.swift index db60d89f9f..8b14a04e1d 100644 --- a/Platform/macOS/Display/VMMetalView.swift +++ b/Platform/macOS/Display/VMMetalView.swift @@ -50,45 +50,6 @@ class VMMetalView: MTKView { return descriptor } - override var drawableSize: CGSize { - didSet { - updateLayerDrawableSize() - } - } - - override func setFrameSize(_ newSize: NSSize) { - super.setFrameSize(newSize) - updateLayerDrawableSize() - } - - override func setBoundsSize(_ newSize: NSSize) { - super.setBoundsSize(newSize) - updateLayerDrawableSize() - } - - override func viewDidChangeBackingProperties() { - super.viewDidChangeBackingProperties() - updateLayerDrawableSize() - } - - /// Gives the layer the view's drawable size as soon as it changes, while a display link draws. - /// - /// MTKView applies `drawableSize` to its layer only from its own draw loop, which is paused while a - /// display link draws. The layer would otherwise keep the size it had when the window opened, and - /// every frame would be scaled into the view, blurring it. The size is the view's `drawableSize` - /// because that is the one the renderer's viewport is given. - private func updateLayerDrawableSize() { - guard isPaused else { - // MTKView's own draw loop keeps the layer's size - return - } - let size = drawableSize - guard size.width > 0, size.height > 0, let layer = layer as? CAMetalLayer, layer.drawableSize != size else { - return - } - layer.drawableSize = size - } - private enum ModifierKeySwap { case none case ctrlCmd From bf21fcf861d432e1a8d099345f8c5d8e01185290 Mon Sep 17 00:00:00 2001 From: osy Date: Tue, 17 Nov 2026 09:49:30 -0800 Subject: [PATCH 2/4] display(macOS): revert "fix 60 Hz cap on ProMotion screens" This reverts commit 216660f0 (#7983). Its CAMetalDisplayLink hands out the layer's drawables itself, so VMMetalView had to replace MTKView's drawable, render pass descriptor and drawable sizing, and frames were drawn at a stale size (#8191). The next commit fixes the 60 Hz cap without changing how MTKView draws. Assisted-by: Claude:claude-opus-5-5 --- .../VMDisplayQemuMetalWindowController.swift | 59 +++---------------- Platform/macOS/Display/VMMetalView.swift | 20 ------- 2 files changed, 7 insertions(+), 72 deletions(-) diff --git a/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift b/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift index 1e4c926ff4..e159444626 100644 --- a/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift +++ b/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift @@ -45,8 +45,6 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { private var globalEventMonitor: Any? = nil private var ctrlKeyDown: Bool = false private var screenChangedToken: Any? - /// `CAMetalDisplayLink` on macOS 14 and later - private var displayLink: AnyObject? private var displayConfig: UTMQemuConfigurationDisplay? { vmQemuConfig?.displays[id] @@ -99,16 +97,9 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { logger.critical("Failed to create renderer.") return } - if #available(macOS 14, *), let layer = metalView.layer as? CAMetalLayer { - // A CAMetalDisplayLink paces the layer at the rate it requests; MTKView's own - // timer can stay at 60 Hz on a ProMotion display. - let link = CAMetalDisplayLink(metalLayer: layer) - link.delegate = self - link.add(to: .main, forMode: .common) - metalView.isPaused = true - displayLink = link + if let fps = preferredFramesPerSecond { + metalView.preferredFramesPerSecond = fps } - updateFrameRate() renderer.changeUpscaler(displayConfig?.upscalingFilter.metalSamplerMinMagFilter ?? .linear, downscaler: displayConfig?.downscalingFilter.metalSamplerMinMagFilter ?? .linear) vmDisplay?.addRenderer(renderer) // can be nil if primary metalView.delegate = renderer @@ -131,26 +122,7 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { super.windowDidLoad() } - /// Refresh at the rate of the screen the window is on, unless the user set a limit. - @discardableResult - private func updateFrameRate() -> Int? { - guard let fps = preferredFramesPerSecond else { - return nil - } - if #available(macOS 14, *), let link = displayLink as? CAMetalDisplayLink { - let rate = Float(fps) - link.preferredFrameRateRange = CAFrameRateRange(minimum: rate, maximum: rate, preferred: rate) - } else { - metalView.preferredFramesPerSecond = fps - } - return fps - } - override func windowWillClose(_ notification: Notification) { - if #available(macOS 14, *), let link = displayLink as? CAMetalDisplayLink { - link.invalidate() - } - displayLink = nil vmDisplay?.removeRenderer(renderer!) stopAllCapture() if let screenChangedToken = screenChangedToken { @@ -186,11 +158,6 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { displaySizeDidChange(size: vmDisplay.displaySize) } super.enterLive() - // pick up an FPS limit changed while the window was open - updateFrameRate() - if #available(macOS 14, *), let link = displayLink as? CAMetalDisplayLink { - link.isPaused = false - } setControl(.resize, isEnabled: false) // disable item if isWindowFocusAutoCapture { captureMouse() @@ -199,9 +166,6 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { override func enterSuspended(isBusy busy: Bool) { if !busy { - if #available(macOS 14, *), let link = displayLink as? CAMetalDisplayLink { - link.isPaused = true - } metalView.isHidden = true screenshotView.image = vm.screenshot?.image screenshotView.isHidden = false @@ -217,7 +181,11 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { override func virtualMachineDisplayRefreshRate(_ vm: any UTMVirtualMachine) -> Int? { // the window may have moved screens since it was loaded - return updateFrameRate() + guard let fps = preferredFramesPerSecond else { + return nil + } + metalView.preferredFramesPerSecond = fps + return fps } /// Frame rate the display is rendered at on the current screen, respecting the user's limit @@ -351,8 +319,6 @@ extension VMDisplayQemuMetalWindowController { func windowDidChangeScreen(_ notification: Notification) { logger.debug("screen changed") - // the new screen can refresh at a different rate - updateFrameRate() if let vmDisplay = self.vmDisplay { displaySizeDidChange(size: vmDisplay.displaySize) } @@ -789,14 +755,3 @@ extension VMDisplayQemuMetalWindowController { window.beginSheet(sheetWindow) } } - -// MARK: - Display link - -@available(macOS 14, *) -extension VMDisplayQemuMetalWindowController: CAMetalDisplayLinkDelegate { - func metalDisplayLink(_ link: CAMetalDisplayLink, needsUpdate update: CAMetalDisplayLink.Update) { - metalView.displayLinkDrawable = update.drawable - renderer.draw(in: metalView) - metalView.displayLinkDrawable = nil - } -} diff --git a/Platform/macOS/Display/VMMetalView.swift b/Platform/macOS/Display/VMMetalView.swift index 8b14a04e1d..6ac9c2c1c8 100644 --- a/Platform/macOS/Display/VMMetalView.swift +++ b/Platform/macOS/Display/VMMetalView.swift @@ -30,26 +30,6 @@ class VMMetalView: MTKView { @Setting("IsISOKeySwapped") private var isISOKeySwapped = false @Setting("IsCapsLockKey") private var isCapsLockKey: Bool = false - /// Drawable supplied by a display link for the frame being drawn, used instead of one - /// acquired from the layer. - var displayLinkDrawable: CAMetalDrawable? - - override var currentDrawable: CAMetalDrawable? { - displayLinkDrawable ?? super.currentDrawable - } - - override var currentRenderPassDescriptor: MTLRenderPassDescriptor? { - guard let drawable = displayLinkDrawable else { - return super.currentRenderPassDescriptor - } - let descriptor = MTLRenderPassDescriptor() - descriptor.colorAttachments[0].texture = drawable.texture - descriptor.colorAttachments[0].loadAction = .clear - descriptor.colorAttachments[0].storeAction = .store - descriptor.colorAttachments[0].clearColor = clearColor - return descriptor - } - private enum ModifierKeySwap { case none case ctrlCmd From 5aa74c39830a565c02be3c7701ec397c318df6ce Mon Sep 17 00:00:00 2001 From: osy Date: Tue, 17 Nov 2026 10:09:26 -0800 Subject: [PATCH 3/4] display(macOS): draw on the view's display link at the screen's rate MTKView's own timer can stay at 60 Hz for a window on a 120 Hz ProMotion panel while the main display is a 60 Hz one (#7983). On macOS 14 and later, draw from the display link NSView makes instead: it follows the screen the view is on, and each tick only asks MTKView to draw, so MTKView keeps acquiring and sizing its drawables as it does with its own timer, and a frame always has the view's pixel size (#8191). macOS 12 and 13 keep MTKView's own timer. Without an FPS limit the link keeps its default rate range, the native rate of whichever screen it is on, so the rate follows the window to another screen and a change of the screen's refresh rate. A range pinned to the screen's rate when it was read stayed at 60 Hz for a window that opened on a 60 Hz screen. With a limit, the link is pinned to the limit. Assisted-by: Claude:claude-opus-5-5 --- .../VMDisplayQemuMetalWindowController.swift | 81 +++++++++++++++++-- Platform/macOS/Display/VMMetalView.swift | 5 ++ 2 files changed, 78 insertions(+), 8 deletions(-) diff --git a/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift b/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift index e159444626..6a095b3502 100644 --- a/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift +++ b/Platform/macOS/Display/VMDisplayQemuMetalWindowController.swift @@ -45,6 +45,13 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { private var globalEventMonitor: Any? = nil private var ctrlKeyDown: Bool = false private var screenChangedToken: Any? + /// `CADisplayLink` of the view on macOS 14 and later + private var displayLink: AnyObject? + + @available(macOS 14, *) + private var viewDisplayLink: CADisplayLink? { + displayLink as? CADisplayLink + } private var displayConfig: UTMQemuConfigurationDisplay? { vmQemuConfig?.displays[id] @@ -97,9 +104,17 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { logger.critical("Failed to create renderer.") return } - if let fps = preferredFramesPerSecond { - metalView.preferredFramesPerSecond = fps - } + if #available(macOS 14, *) { + // MTKView's own timer can stay at 60 Hz on a ProMotion display when the main display is a + // 60 Hz one; the view's display link follows the screen the view is on + let target = DisplayLinkTarget(view: metalView) + let link = metalView.displayLink(target: target, selector: #selector(DisplayLinkTarget.displayLinkDidFire(_:))) + link.isPaused = true // until the VM is live + link.add(to: .main, forMode: .common) + metalView.isPaused = true + displayLink = link + } + updateFrameRate() renderer.changeUpscaler(displayConfig?.upscalingFilter.metalSamplerMinMagFilter ?? .linear, downscaler: displayConfig?.downscalingFilter.metalSamplerMinMagFilter ?? .linear) vmDisplay?.addRenderer(renderer) // can be nil if primary metalView.delegate = renderer @@ -122,7 +137,31 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { super.windowDidLoad() } + /// Refresh at the rate of the screen the window is on, unless the user set a limit. + /// - Returns: The rate on the current screen, if it is known + @discardableResult + private func updateFrameRate() -> Int? { + if #available(macOS 14, *), let link = viewDisplayLink { + if rendererFpsLimit > 0 { + // a screen slower than the limit lowers the rate by itself + let limit = Float(rendererFpsLimit) + link.preferredFrameRateRange = CAFrameRateRange(minimum: limit, maximum: limit, preferred: limit) + } else { + // the link runs at the rate of whichever screen the view is on, also after the + // window moves to another screen or the screen's refresh rate is changed + link.preferredFrameRateRange = .default + } + } else if let fps = preferredFramesPerSecond { + metalView.preferredFramesPerSecond = fps + } + return preferredFramesPerSecond + } + override func windowWillClose(_ notification: Notification) { + if #available(macOS 14, *), let link = viewDisplayLink { + link.invalidate() + } + displayLink = nil vmDisplay?.removeRenderer(renderer!) stopAllCapture() if let screenChangedToken = screenChangedToken { @@ -158,6 +197,11 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { displaySizeDidChange(size: vmDisplay.displaySize) } super.enterLive() + // pick up an FPS limit changed while the window was open + updateFrameRate() + if #available(macOS 14, *), let link = viewDisplayLink { + link.isPaused = false + } setControl(.resize, isEnabled: false) // disable item if isWindowFocusAutoCapture { captureMouse() @@ -166,6 +210,9 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { override func enterSuspended(isBusy busy: Bool) { if !busy { + if #available(macOS 14, *), let link = viewDisplayLink { + link.isPaused = true + } metalView.isHidden = true screenshotView.image = vm.screenshot?.image screenshotView.isHidden = false @@ -181,11 +228,7 @@ class VMDisplayQemuMetalWindowController: VMDisplayQemuWindowController { override func virtualMachineDisplayRefreshRate(_ vm: any UTMVirtualMachine) -> Int? { // the window may have moved screens since it was loaded - guard let fps = preferredFramesPerSecond else { - return nil - } - metalView.preferredFramesPerSecond = fps - return fps + return updateFrameRate() } /// Frame rate the display is rendered at on the current screen, respecting the user's limit @@ -319,6 +362,8 @@ extension VMDisplayQemuMetalWindowController { func windowDidChangeScreen(_ notification: Notification) { logger.debug("screen changed") + // the new screen can refresh at a different rate + updateFrameRate() if let vmDisplay = self.vmDisplay { displaySizeDidChange(size: vmDisplay.displaySize) } @@ -755,3 +800,23 @@ extension VMDisplayQemuMetalWindowController { window.beginSheet(sheetWindow) } } + +// MARK: - Display link + +/// Target of the view's display link, which keeps the view alive only while it is in use. +@available(macOS 14, *) +private final class DisplayLinkTarget: NSObject { + private weak var view: VMMetalView? + + init(view: VMMetalView) { + self.view = view + } + + @objc func displayLinkDidFire(_ link: CADisplayLink) { + guard let view = view else { + link.invalidate() + return + } + view.drawDisplayLinkFrame() + } +} diff --git a/Platform/macOS/Display/VMMetalView.swift b/Platform/macOS/Display/VMMetalView.swift index 6ac9c2c1c8..ccc2e4bcb0 100644 --- a/Platform/macOS/Display/VMMetalView.swift +++ b/Platform/macOS/Display/VMMetalView.swift @@ -30,6 +30,11 @@ class VMMetalView: MTKView { @Setting("IsISOKeySwapped") private var isISOKeySwapped = false @Setting("IsCapsLockKey") private var isCapsLockKey: Bool = false + /// Draws a frame for a tick of the display link that drives this view on macOS 14 and later. + func drawDisplayLinkFrame() { + draw() + } + private enum ModifierKeySwap { case none case ctrlCmd From 7fe8ee7a49f7e0f23ceb417bb0b3bba26b591dbd Mon Sep 17 00:00:00 2001 From: osy Date: Tue, 17 Nov 2026 08:08:46 -0800 Subject: [PATCH 4/4] tests: check that a VM display frame keeps the guest's pixels A QEMU display window drawn at another size than the view's pixels is scaled, which blurred every guest in 5.0.9 (#8191). Draw frames through VMMetalView.drawDisplayLinkFrame(), as the window's display link does, without a VM: after each resize the drawable must have the view's pixel size, and a one-pixel checkerboard drawn by CSMetalRenderer at 1:1 must come back unchanged. With drawDisplayLinkFrame() doing what 5.0.9's display link did (hand the renderer the layer's next drawable), both fail: the drawable keeps the size the view had first. Assisted-by: Claude:claude-opus-5-5 --- Tests/macOS/VMMetalViewDrawableTests.swift | 196 +++++++++++++++++++++ UTM.xcodeproj/project.pbxproj | 4 + 2 files changed, 200 insertions(+) create mode 100644 Tests/macOS/VMMetalViewDrawableTests.swift diff --git a/Tests/macOS/VMMetalViewDrawableTests.swift b/Tests/macOS/VMMetalViewDrawableTests.swift new file mode 100644 index 0000000000..9ff3ee4d09 --- /dev/null +++ b/Tests/macOS/VMMetalViewDrawableTests.swift @@ -0,0 +1,196 @@ +// +// Copyright © 2026 Turing Software, LLC. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import XCTest +import MetalKit +import CocoaSpiceRenderer +@testable import UTM + +/// A QEMU display window draws each frame from `VMMetalView.drawDisplayLinkFrame()` (macOS 14 and later). +/// A frame drawn into a drawable of another size than the view's pixels is scaled into the window, which +/// blurs the guest's display (#8191). These tests draw frames the way the window does, without a VM. +@MainActor +final class VMMetalViewDrawableTests: XCTestCase { + /// Records the drawable of each frame, then lets `renderer` draw it (or clears it). + private final class RecordingDelegate: NSObject, MTKViewDelegate { + let commandQueue: MTLCommandQueue + weak var renderer: CSMetalRenderer? + /// Pixel size of each frame's drawable + var sizes: [CGSize] = [] + /// Pixels of the last frame `renderer` drew + var lastPixels: [UInt32] = [] + + init(device: MTLDevice, renderer: CSMetalRenderer? = nil) { + commandQueue = device.makeCommandQueue()! + self.renderer = renderer + } + + func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { + renderer?.mtkView(view, drawableSizeWillChange: size) + } + + func draw(in view: MTKView) { + guard let drawable = view.currentDrawable else { + return + } + sizes.append(CGSize(width: drawable.texture.width, height: drawable.texture.height)) + if let renderer = renderer { + renderer.draw(in: view) + lastPixels = copyPixels(of: drawable.texture, behindWorkOn: renderer.commandQueue) + } else if let pass = view.currentRenderPassDescriptor, + let commandBuffer = commandQueue.makeCommandBuffer(), + let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass) { + encoder.endEncoding() + commandBuffer.present(drawable) + commandBuffer.commit() + } + } + + /// Copies a drawable's texture out on the queue the renderer drew it on, so the copy runs after that + /// draw, while the drawable is still held here + private func copyPixels(of texture: MTLTexture, behindWorkOn queue: MTLCommandQueue) -> [UInt32] { + let count = texture.width * texture.height + guard let buffer = queue.device.makeBuffer(length: count * 4, options: .storageModeShared), + let commandBuffer = queue.makeCommandBuffer(), + let blit = commandBuffer.makeBlitCommandEncoder() else { + return [] + } + blit.copy(from: texture, sourceSlice: 0, sourceLevel: 0, sourceOrigin: MTLOriginMake(0, 0, 0), + sourceSize: MTLSizeMake(texture.width, texture.height, 1), + to: buffer, destinationOffset: 0, destinationBytesPerRow: texture.width * 4, destinationBytesPerImage: 0) + blit.endEncoding() + commandBuffer.commit() + commandBuffer.waitUntilCompleted() + return Array(UnsafeBufferPointer(start: buffer.contents().assumingMemoryBound(to: UInt32.self), count: count)) + } + } + + /// A guest display: a texture and the quad CocoaSpice builds for it (`CSDisplay.rebuildDisplayVertices`). + private final class TestRenderSource: NSObject, CSRenderSource { + let texture: MTLTexture? + let vertices: MTLBuffer? + let numVertices: UInt = 6 + let isVisible = true + let offset = CGPoint.zero + let hasAlpha = false + let isInverted = false + weak var cursor: CSRenderSource? + + init(device: MTLDevice, width: Int, height: Int, pixels: [UInt32]) { + let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false) + let texture = device.makeTexture(descriptor: descriptor)! + pixels.withUnsafeBytes { bytes in + texture.replace(region: MTLRegionMake2D(0, 0, width, height), mipmapLevel: 0, withBytes: bytes.baseAddress!, bytesPerRow: width * 4) + } + self.texture = texture + let w = Float(width) / 2, h = Float(height) / 2 + let quad: [CSRenderVertex] = [ + CSRenderVertex(position: [ w, h], textureCoordinate: [1, 0]), + CSRenderVertex(position: [-w, h], textureCoordinate: [0, 0]), + CSRenderVertex(position: [-w, -h], textureCoordinate: [0, 1]), + CSRenderVertex(position: [ w, h], textureCoordinate: [1, 0]), + CSRenderVertex(position: [-w, -h], textureCoordinate: [0, 1]), + CSRenderVertex(position: [ w, -h], textureCoordinate: [1, 1]), + ] + vertices = device.makeBuffer(bytes: quad, length: MemoryLayout.stride * quad.count) + } + } + + private var window: NSWindow? + + override func tearDown() { + window?.close() + window = nil + super.tearDown() + } + + /// A view set up as `VMDisplayQemuMetalWindowController` sets it up when a display link draws it. + private func makeView(points: CGSize) throws -> VMMetalView { + guard let device = MTLCreateSystemDefaultDevice() else { + throw XCTSkip("This host has no Metal device.") + } + let window = NSWindow(contentRect: CGRect(origin: .zero, size: points), styleMask: .borderless, backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + self.window = window + let view = VMMetalView(frame: window.contentView!.bounds, device: device) + view.autoresizingMask = [.width, .height] + view.framebufferOnly = false + view.isPaused = true + window.contentView!.addSubview(view) + return view + } + + /// Draws one frame, or skips the test on a host that gives the view no drawable. + private func drawFrame(_ view: VMMetalView, recordedBy delegate: RecordingDelegate) throws { + let count = delegate.sizes.count + view.drawDisplayLinkFrame() + if delegate.sizes.count == count { + throw XCTSkip("This host gives the view no drawable.") + } + } + + private func pixelSize(of view: NSView) -> CGSize { + view.convertToBacking(view.bounds).size + } + + /// Runs the main queue until the blocks queued on it so far have run. + private func drainMainQueue() { + let drained = expectation(description: "main queue") + DispatchQueue.main.async { drained.fulfill() } + wait(for: [drained], timeout: 5) + } + + func testFramesAreDrawnAtTheViewsPixelSizeAfterResizing() throws { + let view = try makeView(points: CGSize(width: 400, height: 300)) + let delegate = RecordingDelegate(device: view.device!) + view.delegate = delegate + for points in [CGSize(width: 400, height: 300), CGSize(width: 640, height: 400), CGSize(width: 320, height: 200)] { + window!.setContentSize(points) + try drawFrame(view, recordedBy: delegate) + XCTAssertEqual(delegate.sizes.last, pixelSize(of: view), "frame after resizing to \(points) points") + } + } + + /// The guest's pixels reach the window unchanged at 1:1 (Retina mode on a Retina screen, or any mode + /// at scale 1): a one-pixel checkerboard comes back exactly, so any resampling on the way fails. + func testOneToOneFrameKeepsEveryGuestPixel() throws { + let (width, height) = (64, 48) + // the window opens at another size and is then fitted to the guest, as a VM window is + let view = try makeView(points: CGSize(width: 400, height: 300)) + let scale = window!.backingScaleFactor + let device = view.device! + let renderer = CSMetalRenderer(metalKitView: view) + let delegate = RecordingDelegate(device: device, renderer: renderer) + view.delegate = delegate + try drawFrame(view, recordedBy: delegate) + window!.setContentSize(CGSize(width: CGFloat(width) / scale, height: CGFloat(height) / scale)) + XCTAssertEqual(pixelSize(of: view), CGSize(width: width, height: height)) + renderer.viewportScale = 1.0 + + let white: UInt32 = 0xFFFF_FFFF, black: UInt32 = 0xFF00_0000 + let pattern = (0..