Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qnsview_drawing.mm
Go to the documentation of this file.
1// Copyright (C) 2018 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5// This file is included from qnsview.mm, and only used to organize the code
6
7@implementation QContainerLayer {
8 CALayer *m_contentLayer;
9}
10- (instancetype)initWithContentLayer:(CALayer *)contentLayer
11{
12 if ((self = [super init])) {
13 m_contentLayer = contentLayer;
14 [self addSublayer:contentLayer];
15 }
16 return self;
17}
18
19- (CALayer*)contentLayer
20{
21 return m_contentLayer;
22}
23
24- (void)layoutSublayers
25{
26 // Layout the content layer explicitly, as using a autoresizingMask
27 // of kCALayerWidthSizable | kCALayerHeightSizable has been seen to
28 // drift out of sync, resulting in a content layer larger than its
29 // container layer.
30 m_contentLayer.frame = self.bounds;
31}
32
33- (void)setNeedsDisplay
34{
35 [self setNeedsDisplayInRect:CGRectInfinite];
36}
37
38- (void)setNeedsDisplayInRect:(CGRect)rect
39{
40 [super setNeedsDisplayInRect:rect];
41 [self.contentLayer setNeedsDisplayInRect:rect];
42}
43@end
44
45@implementation QNSView (Drawing)
46
47- (void)initDrawing
48{
49 // Pick up and persist requested color space from surface format
50 const QSurfaceFormat surfaceFormat = m_platformWindow->format();
51 if (QColorSpace colorSpace = surfaceFormat.colorSpace(); colorSpace.isValid()) {
52 NSData *iccData = colorSpace.iccProfile().toNSData();
53 self.colorSpace = [[[NSColorSpace alloc] initWithICCProfileData:iccData] autorelease];
54 }
55
56 // Trigger creation of the layer
57 self.wantsLayer = YES;
58}
59
60- (BOOL)isOpaque
61{
62 if (!m_platformWindow)
63 return true;
64 return m_platformWindow->isOpaque();
65}
66
67- (BOOL)isFlipped
68{
69 return YES;
70}
71
72- (NSColorSpace*)colorSpace
73{
74 // If no explicit color space was set, use the NSWindow's color space
75 return m_colorSpace ? m_colorSpace : self.window.colorSpace;
76}
77
78// ----------------------- Layer setup -----------------------
79
80- (BOOL)shouldUseMetalLayer
81{
82 if (!m_platformWindow)
83 return false;
84
85 // MetalSurface needs a layer, and so does VulkanSurface (via MoltenVK)
86 QSurface::SurfaceType surfaceType = m_platformWindow->window()->surfaceType();
87 return surfaceType == QWindow::MetalSurface || surfaceType == QWindow::VulkanSurface;
88}
89
90/*
91 This method is called by AppKit when layer-backing is requested by
92 setting wantsLayer too YES (via -[NSView _updateLayerBackedness]),
93 or in cases where AppKit itself decides that a view should be
94 layer-backed.
95
96 Note however that some code paths in AppKit will not go via this
97 method for creating the backing layer, and will instead create the
98 layer manually, and just call setLayer. An example of this is when
99 an NSOpenGLContext is attached to a view, in which case AppKit will
100 create a new layer in NSOpenGLContextSetLayerOnViewIfNecessary.
101
102 For this reason we leave the implementation of this override as
103 minimal as possible, only focusing on creating the appropriate
104 layer type, and then leave it up to setLayer to do the work of
105 making sure the layer is set up correctly.
106*/
107- (CALayer *)makeBackingLayer
108{
109 if ([self shouldUseMetalLayer]) {
110 // Check if Metal is supported. If it isn't then it's most likely
111 // too late at this point and the QWindow will be non-functional,
112 // but we can at least print a warning.
113 if ([MTLCreateSystemDefaultDevice() autorelease]) {
114 static bool allowPresentsWithTransaction =
115 !qEnvironmentVariableIsSet("QT_MTL_NO_TRANSACTION");
116 return allowPresentsWithTransaction ?
117 [QMetalLayer layer] : [CAMetalLayer layer];
118 } else {
119 qCWarning(lcQpaDrawing) << "Failed to create QWindow::MetalSurface."
120 << "Metal is not supported by any of the GPUs in this system.";
121 }
122 }
123
124 // We handle drawing via displayLayer instead of drawRect or updateLayer,
125 // as the latter two do not work for CAMetalLayer. And we handle content
126 // scale manually for the same reason. Which means we don't really need
127 // NSViewBackingLayer. In fact it just gets in the way, by assuming that
128 // if we don't have a drawRect function we "draw nothing".
129 return [CALayer layer];
130}
131
132/*
133 This method is called by AppKit whenever the view is asked to change
134 its layer, which can happen both as a result of enabling layer-backing,
135 or when a layer is set explicitly. The latter can happen both when a
136 view is layer-hosting, or when AppKit internals are switching out the
137 layer-backed view, as described above for makeBackingLayer.
138*/
139- (void)setLayer:(CALayer *)layer
140{
141 if (!m_platformWindow) {
142 [super setLayer:layer];
143 return;
144 }
145
146 qCDebug(lcQpaDrawing) << "Making" << self
147 << (self.wantsLayer ? "layer-backed" : "layer-hosted")
148 << "with" << layer;
149
150 if (layer.delegate && layer.delegate != self) {
151 qCWarning(lcQpaDrawing) << "Layer already has delegate" << layer.delegate
152 << "This delegate is responsible for all view updates for" << self;
153 } else {
154 layer.delegate = self;
155 }
156
157 layer.name = @"Qt content layer";
158
159 static const bool containerLayerOptOut = qEnvironmentVariableIsSet("QT_MAC_NO_CONTAINER_LAYER");
160 if (m_platformWindow->window()->surfaceType() != QSurface::OpenGLSurface && !containerLayerOptOut) {
161 qCDebug(lcQpaDrawing) << "Wrapping content layer" << layer << "in container layer";
162 auto *containerLayer = [[[QContainerLayer alloc] initWithContentLayer:layer] autorelease];
163 containerLayer.name = @"Qt container layer";
164 containerLayer.delegate = self;
165 layer = containerLayer;
166 }
167
168 [super setLayer:layer];
169
170 [self propagateBackingProperties];
171
172 if (self.opaque && lcQpaDrawing().isDebugEnabled()) {
173 // If the view claims to be opaque we expect it to fill the entire
174 // layer with content, in which case we want to detect any areas
175 // where it doesn't.
176 layer.backgroundColor = NSColor.magentaColor.CGColor;
177 }
178}
179
180// ----------------------- Layer updates -----------------------
181
182- (NSViewLayerContentsRedrawPolicy)layerContentsRedrawPolicy
183{
184 // We need to set this explicitly since the super implementation
185 // returns LayerContentsRedrawNever for custom layers like CAMetalLayer.
186 return NSViewLayerContentsRedrawDuringViewResize;
187}
188
189- (NSViewLayerContentsPlacement)layerContentsPlacement
190{
191 // Always place the layer at top left without any automatic scaling.
192 // This will highlight situations where we're missing content for the
193 // layer by not responding to the displayLayer: request synchronously.
194 // It also allows us to re-use larger layers when resizing a window down.
195 return NSViewLayerContentsPlacementTopLeft;
196}
197
198- (void)viewDidChangeBackingProperties
199{
200 qCDebug(lcQpaDrawing) << "Backing properties changed for" << self;
201
202 if (!m_platformWindow)
203 return;
204
205 [self propagateBackingProperties];
206
207 // Ideally we would plumb this situation through QPA in a way that lets
208 // clients invalidate their own caches, recreate QBackingStore, etc.
209
210 // QPA supports DPR (scale) change notifications. We are not sure
211 // based on this event that it is the scale that has changed (it
212 // could be the color space), however QPA will determine if it has
213 // actually changed.
214 QWindowSystemInterface::handleWindowDevicePixelRatioChanged
215 <QWindowSystemInterface::SynchronousDelivery>(m_platformWindow->window());
216
217 // Trigger an expose, and let QCocoaBackingStore deal with
218 // buffer invalidation internally.
219 [self setNeedsDisplay:YES];
220}
221
222- (void)propagateBackingProperties
223{
224 if (!self.layer)
225 return;
226
227 // We expect clients to fill the layer with retina aware content,
228 // based on the devicePixelRatio of the QWindow, so we set the
229 // layer's content scale to match that. By going via devicePixelRatio
230 // instead of applying the NSWindow's backingScaleFactor, we also take
231 // into account OpenGL views with wantsBestResolutionOpenGLSurface set
232 // to NO. In this case the window will have a backingScaleFactor of 2,
233 // but the QWindow will have a devicePixelRatio of 1.
234 auto devicePixelRatio = m_platformWindow->devicePixelRatio();
235 auto *contentLayer = m_platformWindow->contentLayer();
236 qCDebug(lcQpaDrawing) << "Updating" << contentLayer << "content scale to" << devicePixelRatio;
237 contentLayer.contentsScale = devicePixelRatio;
238
239 if ([contentLayer isKindOfClass:CAMetalLayer.class]) {
240 CAMetalLayer *metalLayer = static_cast<CAMetalLayer *>(contentLayer);
241 metalLayer.colorspace = self.colorSpace.CGColorSpace;
242 qCDebug(lcQpaDrawing) << "Set" << metalLayer << "color space to" << metalLayer.colorspace;
243 }
244}
245
246/*
247 This method is called by AppKit to determine whether it should update
248 the contentScale of the layer to match the window backing scale.
249
250 We always return NO since we're updating the contents scale manually.
251*/
252- (BOOL)layer:(CALayer *)layer shouldInheritContentsScale:(CGFloat)scale fromWindow:(NSWindow *)window
253{
254 Q_UNUSED(layer);
255 Q_UNUSED(scale);
256 Q_UNUSED(window);
257 return NO;
258}
259
260// ----------------------- Draw callbacks -----------------------
261
262/*
263 We set our view up as the layer's delegate, which means we get
264 first dibs on displaying the layer, without needing to go through
265 updateLayer or drawRect.
266*/
267- (void)displayLayer:(CALayer *)layer
268{
269 if (auto *containerLayer = qt_objc_cast<QContainerLayer*>(layer)) {
270 qCDebug(lcQpaDrawing) << "Skipping display of" << containerLayer
271 << "as display is handled by content layer" << containerLayer.contentLayer;
272 return;
273 }
274
275 if (!m_platformWindow)
276 return;
277
278 auto *qtMetalLayer = qt_objc_cast<QMetalLayer *>(layer);
279
280 if (qtMetalLayer) {
281 // Once we're done with display, even if we exit early below, we need to
282 // unlock the display lock. But we must wait to unlock the display lock
283 // until the display cycle finishes, as otherwise the render thread may
284 // step in and present before the transaction commits. The display lock
285 // is recursive, so setNeedsDisplay can be safely called in the meantime
286 // without any issue.
287 QMetaObject::invokeMethod(m_platformWindow, [qtMetalLayer]{
288 qCDebug(lcMetalLayer) << "Unlocking" << qtMetalLayer << "after finishing display-cycle";
289 qtMetalLayer.displayLock.unlock();
290 }, Qt::QueuedConnection);
291 }
292
293 if (!NSThread.isMainThread) {
294 // Qt is calling AppKit APIs such as -[NSOpenGLContext setView:] on secondary threads,
295 // which we shouldn't do. This may result in AppKit (wrongly) triggering a display on
296 // the thread where we made the call, so block it here and defer to the main thread.
297 qCWarning(lcQpaDrawing) << "Display non non-main thread! Deferring to main thread";
298 dispatch_async(dispatch_get_main_queue(), ^{ self.needsDisplay = YES; });
299 return;
300 }
301
302 if (m_platformWindow->m_deliveringUpdateRequest) {
303 // In rare cases delivering an update request might trigger a synchronous display,
304 // for example when calling -[NSOpenGLContext update] as part of rendering a frame,
305 // if using the software GL backend on macOS 26. Our rendering stack does not deal
306 // well with this reentrancy, and it also causes crashes the macOS GL driver.
307 qCWarning(lcQpaDrawing) << "Asked to display during update-request delivery. Deferring.";
308 dispatch_async(dispatch_get_main_queue(), ^{ self.needsDisplay = YES; });
309 return;
310 }
311
312 auto *currentScreen = static_cast<QCocoaScreen*>(m_platformWindow->screen());
313 if (!currentScreen || !currentScreen->isOnline()) {
314 qCWarning(lcQpaDrawing) << "Display requested for non-online display" << currentScreen
315 << "Deferring to next runloop pass";
316 dispatch_async(dispatch_get_main_queue(), ^{ self.needsDisplay = YES; });
317 return;
318 }
319
320 const auto handleExposeEvent = [&]{
321 const auto bounds = QRectF::fromCGRect(self.bounds).toRect();
322 qCDebug(lcQpaDrawing) << "[QNSView displayLayer]" << m_platformWindow->window() << bounds;
323 m_platformWindow->handleExposeEvent(bounds);
324 };
325
326 if (qtMetalLayer) {
327 const bool presentedWithTransaction = qtMetalLayer.presentsWithTransaction;
328 qtMetalLayer.presentsWithTransaction = YES;
329
330 handleExposeEvent();
331
332 {
333 // Clearing the mainThreadPresentation below will auto-release the
334 // block held by the property, which in turn holds on to drawables,
335 // so we want to clean up as soon as possible, to prevent stalling
336 // when requesting new drawables. But merely referencing the block
337 // below for the nil-check will make another auto-released copy of
338 // the block, so the scope of the auto-release pool needs to include
339 // that check as well.
340 QMacAutoReleasePool pool;
341
342 // If the expose event resulted in a secondary thread requesting that its
343 // drawable should be presented on the main thread with transaction, do so.
344 if (auto mainThreadPresentation = qtMetalLayer.mainThreadPresentation) {
345 mainThreadPresentation();
346 qtMetalLayer.mainThreadPresentation = nil;
347 }
348 }
349
350 qtMetalLayer.presentsWithTransaction = presentedWithTransaction;
351 } else {
352 handleExposeEvent();
353 }
354}
355
356@end