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
qcocoascreen.mm
Go to the documentation of this file.
1// Copyright (C) 2017 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#include <AppKit/AppKit.h>
6#include <ScreenCaptureKit/ScreenCaptureKit.h>
7
8#include "qcocoascreen.h"
9
10#include "qcocoawindow.h"
11#include "qcocoahelpers.h"
13
14#include <QtCore/qcoreapplication.h>
15#include <QtGui/private/qcoregraphics_p.h>
16
17#include <IOKit/graphics/IOGraphicsLib.h>
18
19#include <QtGui/qpainter.h>
20#include <QtGui/private/qwindow_p.h>
21#include <QtGui/private/qhighdpiscaling_p.h>
22
23#include <QtCore/private/qcore_mac_p.h>
24#include <QtCore/private/qeventdispatcher_cf_p.h>
25
26QT_BEGIN_NAMESPACE
27
45
46QMacNotificationObserver QCocoaScreen::s_screenParameterObserver;
47CGDisplayReconfigurationCallBack QCocoaScreen::s_displayReconfigurationCallBack = nullptr;
48
49void QCocoaScreen::initializeScreens()
50{
51 updateScreens();
52
53 s_displayReconfigurationCallBack = [](CGDirectDisplayID displayId, CGDisplayChangeSummaryFlags flags, void *userInfo) {
54 Q_UNUSED(userInfo);
55
56 const bool beforeReconfigure = flags & kCGDisplayBeginConfigurationFlag;
57 qCDebug(lcQpaScreen).verbosity(0) << "Display" << displayId
58 << (beforeReconfigure ? "beginning" : "finished") << "reconfigure"
59 << QFlags<CoreGraphics::DisplayChange>(flags);
60
61 if (!beforeReconfigure)
62 updateScreens();
63 };
64 CGDisplayRegisterReconfigurationCallback(s_displayReconfigurationCallBack, nullptr);
65
66 s_screenParameterObserver = QMacNotificationObserver(NSApplication.sharedApplication,
67 NSApplicationDidChangeScreenParametersNotification, [&]() {
68 qCDebug(lcQpaScreen) << "Received screen parameter change notification";
69 updateScreens();
70
71 // The notification is posted when the EDR headroom of a display changes,
72 // which might affect the rendering of windows that opt in to EDR.
73 updateHdrWindows();
74 });
75}
76
77/*
78 Update the list of available QScreens, and the properties of existing screens.
79
80 At this point we rely on the NSScreen.screens to be up to date.
81*/
82void QCocoaScreen::updateScreens()
83{
84 // Adding, updating, or removing a screen below might trigger
85 // Qt or the application to move a window to a different screen,
86 // recursing back here via QCocoaWindow::windowDidChangeScreen.
87 // The update code is not re-entrant, so bail out if we end up
88 // in this situation. The screens will stabilize eventually.
89 static bool updatingScreens = false;
90 if (updatingScreens) {
91 qCInfo(lcQpaScreen) << "Skipping screen update, already updating";
92 return;
93 }
94 QScopedValueRollback recursionGuard(updatingScreens, true);
95
96 uint32_t displayCount = 0;
97 if (CGGetOnlineDisplayList(0, nullptr, &displayCount) != kCGErrorSuccess)
98 qFatal("Failed to get number of online displays");
99
100 QVector<CGDirectDisplayID> onlineDisplays(displayCount);
101 if (CGGetOnlineDisplayList(displayCount, onlineDisplays.data(), &displayCount) != kCGErrorSuccess)
102 qFatal("Failed to get online displays");
103
104 qCInfo(lcQpaScreen) << "Updating screens with" << displayCount
105 << "online displays:" << onlineDisplays;
106
107 // TODO: Verify whether we can always assume the main display is first
108 int mainDisplayIndex = onlineDisplays.indexOf(CGMainDisplayID());
109 if (mainDisplayIndex < 0) {
110 qCWarning(lcQpaScreen) << "Main display not in list of online displays!";
111 } else if (mainDisplayIndex > 0) {
112 qCWarning(lcQpaScreen) << "Main display not first display, making sure it is";
113 onlineDisplays.move(mainDisplayIndex, 0);
114 }
115
116 for (CGDirectDisplayID displayId : onlineDisplays) {
117 Q_ASSERT(CGDisplayIsOnline(displayId));
118
119 if (CGDisplayMirrorsDisplay(displayId))
120 continue;
121
122 // A single physical screen can map to multiple displays IDs,
123 // depending on which GPU is in use or which physical port the
124 // screen is connected to. By mapping the display ID to a UUID,
125 // which are shared between displays that target the same screen,
126 // we can pick an existing QScreen to update instead of needlessly
127 // adding and removing QScreens.
128 QCFType<CFUUIDRef> uuid = CGDisplayCreateUUIDFromDisplayID(displayId);
129 Q_ASSERT(uuid);
130
131 if (QCocoaScreen *existingScreen = QCocoaScreen::get(uuid)) {
132 existingScreen->update(displayId);
133 qCInfo(lcQpaScreen) << "Updated" << existingScreen;
134 if (CGDisplayIsMain(displayId) && existingScreen != qGuiApp->primaryScreen()->handle()) {
135 qCInfo(lcQpaScreen) << "Primary screen changed to" << existingScreen;
136 QWindowSystemInterface::handlePrimaryScreenChanged(existingScreen);
137 }
138 } else {
139 QCocoaScreen::add(displayId);
140 }
141 }
142
143 for (QScreen *screen : QGuiApplication::screens()) {
144 QCocoaScreen *platformScreen = static_cast<QCocoaScreen*>(screen->handle());
145 if (!platformScreen->isOnline() || platformScreen->isMirroring())
146 platformScreen->remove();
147 }
148}
149
150void QCocoaScreen::add(CGDirectDisplayID displayId)
151{
152 const bool isPrimary = CGDisplayIsMain(displayId);
153 QCocoaScreen *cocoaScreen = new QCocoaScreen(displayId);
154 qCInfo(lcQpaScreen) << "Adding" << cocoaScreen
155 << (isPrimary ? "as new primary screen" : "");
156 QWindowSystemInterface::handleScreenAdded(cocoaScreen, isPrimary);
157}
158
159QCocoaScreen::QCocoaScreen(CGDirectDisplayID displayId)
160 : QPlatformScreen(), m_displayId(displayId)
161{
162 update(m_displayId);
163 m_cursor = new QCocoaCursor;
164}
165
166void QCocoaScreen::cleanupScreens()
167{
168 // Remove screens in reverse order to avoid crash in case of multiple screens
169 for (QScreen *screen : backwards(QGuiApplication::screens()))
170 static_cast<QCocoaScreen*>(screen->handle())->remove();
171
172 Q_ASSERT(s_displayReconfigurationCallBack);
173 CGDisplayRemoveReconfigurationCallback(s_displayReconfigurationCallBack, nullptr);
174 s_displayReconfigurationCallBack = nullptr;
175
176 s_screenParameterObserver.remove();
177}
178
179void QCocoaScreen::remove()
180{
181 // This may result in the application responding to QGuiApplication::screenRemoved
182 // by moving the window to another screen, either by setGeometry, or by setScreen.
183 // If the window isn't moved by the application, Qt will as a fallback move it to
184 // the primary screen via setScreen. Due to the way setScreen works, this won't
185 // actually recreate the window on the new screen, it will just assign the new
186 // QScreen to the window. The associated NSWindow will have an NSScreen determined
187 // by AppKit. AppKit will then move the window to another screen by changing the
188 // geometry, and we will get a callback in QCocoaWindow::windowDidMove and then
189 // QCocoaWindow::windowDidChangeScreen. At that point the window will appear to have
190 // already changed its screen, but that's only true if comparing the Qt screens,
191 // not when comparing the NSScreens.
192 qCInfo(lcQpaScreen) << "Removing " << this;
193 QWindowSystemInterface::handleScreenRemoved(this);
194}
195
197{
198 Q_ASSERT_X(!screen(), "QCocoaScreen", "QScreen should be deleted first");
199
200 delete m_cursor;
201
202 CVDisplayLinkRelease(m_displayLink);
203 if (m_displayLinkSource)
204 dispatch_release(m_displayLinkSource);
205}
206
207void QCocoaScreen::update(CGDirectDisplayID displayId)
208{
209 if (displayId != m_displayId) {
210 qCDebug(lcQpaScreen) << "Reconnecting" << this << "as display" << displayId;
211 m_displayId = displayId;
212 }
213
214 Q_ASSERT(isOnline());
215
216 // Some properties are only available via NSScreen
217 NSScreen *nsScreen = nativeScreen();
218 if (!nsScreen) {
219 qCDebug(lcQpaScreen) << "Corresponding NSScreen not yet available. Deferring update";
220 return;
221 }
222
223 const QRect previousGeometry = m_geometry;
224 const QRect previousAvailableGeometry = m_availableGeometry;
225 const qreal previousRefreshRate = m_refreshRate;
226 const double previousRotation = m_rotation;
227
228 // The reference screen for the geometry is always the primary screen
229 QRectF primaryScreenGeometry = QRectF::fromCGRect(CGDisplayBounds(CGMainDisplayID()));
230 m_geometry = qt_mac_flip(QRectF::fromCGRect(nsScreen.frame), primaryScreenGeometry).toRect();
231 m_availableGeometry = qt_mac_flip(QRectF::fromCGRect(nsScreen.visibleFrame), primaryScreenGeometry).toRect();
232
233 if (QOperatingSystemVersion::current() < QOperatingSystemVersion::MacOSTahoe) {
234 // On macOS versions below 26 the visibleFrame wrongly includes the auto-hidden
235 // menu bar area while in native full screen, even though that area still
236 // intercepts clicks meant for the hidden menu bar. Carve it out ourselves
237 // so we don't report it as available, e.g. for popup placement.
238 if (NSApp.presentationOptions & NSApplicationPresentationFullScreen
239 && m_availableGeometry.height() == m_geometry.height()) {
240 if (auto menuBarHeight = NSApp.mainMenu.menuBarHeight; menuBarHeight > 0)
241 m_availableGeometry.setTop(m_availableGeometry.top() + qRound(menuBarHeight));
242 }
243 }
244
245 m_devicePixelRatio = nsScreen.backingScaleFactor;
246
247 m_format = QImage::Format_RGB32;
248 m_depth = NSBitsPerPixelFromDepth(nsScreen.depth);
249 m_colorSpace = QColorSpace::fromIccProfile(QByteArray::fromNSData(nsScreen.colorSpace.ICCProfileData));
250 if (!m_colorSpace.isValid()) {
251 qCWarning(lcQpaScreen) << "Failed to parse ICC profile for" << nsScreen.colorSpace
252 << "with ICC data" << nsScreen.colorSpace.ICCProfileData
253 << "- Falling back to sRGB";
254 m_colorSpace = QColorSpace::SRgb;
255 }
256
257 CGSize size = CGDisplayScreenSize(m_displayId);
258 m_physicalSize = QSizeF(size.width, size.height);
259
260 QCFType<CGDisplayModeRef> displayMode = CGDisplayCopyDisplayMode(m_displayId);
261 float refresh = CGDisplayModeGetRefreshRate(displayMode);
262 m_refreshRate = refresh > 0 ? refresh : 60.0;
263 m_rotation = CGDisplayRotation(displayId);
264 m_name = QString::fromNSString(nsScreen.localizedName);
265
266 const bool didChangeGeometry = m_geometry != previousGeometry || m_availableGeometry != previousAvailableGeometry;
267
268 if (m_rotation != previousRotation)
269 QWindowSystemInterface::handleScreenOrientationChange(screen(), orientation());
270
271 if (didChangeGeometry)
272 QWindowSystemInterface::handleScreenGeometryChange(screen(), geometry(), availableGeometry());
273 if (m_refreshRate != previousRefreshRate)
274 QWindowSystemInterface::handleScreenRefreshRateChange(screen(), m_refreshRate);
275}
276
277// ----------------------- Display link -----------------------
278
279Q_LOGGING_CATEGORY(lcQpaScreenUpdates, "qt.qpa.screen.updates", QtCriticalMsg);
280
282{
283 Q_ASSERT(m_displayId);
284
285 if (!isOnline()) {
286 qCDebug(lcQpaScreenUpdates) << this << "is not online. Ignoring update request";
287 return false;
288 }
289
290 // Track how many update requests we have queued, so that we
291 // know whether the display-link thread should try to deliver
292 // update requests, or if it can bail out early.
293 ++m_pendingUpdateRequests;
294
295 if (!m_displayLink) {
296 qCDebug(lcQpaScreenUpdates) << "Creating display link for" << this;
297 if (CVDisplayLinkCreateWithCGDisplay(m_displayId, &m_displayLink) != kCVReturnSuccess) {
298 qCWarning(lcQpaScreenUpdates) << "Failed to create display link for" << this;
299 return false;
300 }
301 if (auto displayId = CVDisplayLinkGetCurrentCGDisplay(m_displayLink); displayId != m_displayId) {
302 qCWarning(lcQpaScreenUpdates) << "Unexpected display" << displayId << "for display link";
303 CVDisplayLinkRelease(m_displayLink);
304 m_displayLink = nullptr;
305 return false;
306 }
307 CVDisplayLinkSetOutputCallback(m_displayLink, [](CVDisplayLinkRef, const CVTimeStamp*,
308 const CVTimeStamp*, CVOptionFlags, CVOptionFlags*, void* displayLinkContext) -> int {
309 // FIXME: It would be nice if update requests would include timing info
310 static_cast<QCocoaScreen*>(displayLinkContext)->deliverUpdateRequests();
311 return kCVReturnSuccess;
312 }, this);
313
314 // During live window resizing -[NSWindow _resizeWithEvent:] will spin a local event loop
315 // in event-tracking mode, dequeuing only the mouse drag events needed to update the window's
316 // frame. It will repeatedly spin this loop until no longer receiving any mouse drag events,
317 // and will then update the frame (effectively coalescing/compressing the events). Unfortunately
318 // the events are pulled out using -[NSApplication nextEventMatchingEventMask:untilDate:inMode:dequeue:]
319 // which internally uses CFRunLoopRunSpecific, so the event loop will also process GCD queues and other
320 // runloop sources that have been added to the tracking mode. This includes the GCD display-link
321 // source that we use to marshal the display-link callback over to the main thread. If the
322 // subsequent delivery of the update-request on the main thread stalls due to inefficient
323 // user code, the NSEventThread will have had time to deliver additional mouse drag events,
324 // and the logic in -[NSWindow _resizeWithEvent:] will keep on compressing events and never
325 // get to the point of actually updating the window frame, making it seem like the window
326 // is stuck in its original size. Only when the user stops moving their mouse, and the event
327 // queue is completely drained of drag events, will the window frame be updated.
328
329 // By keeping an event tap listening for drag events, registered as a version 1 runloop source,
330 // we prevent the GCD source from being prioritized, giving the resize logic enough time
331 // to finish coalescing the events. This is incidental, but conveniently gives us the behavior
332 // we are looking for, interleaving display-link updates and resize events.
333 static CFMachPortRef eventTap = []() {
334 CFMachPortRef eventTap = CGEventTapCreateForPid(getpid(), kCGTailAppendEventTap,
335 kCGEventTapOptionListenOnly, NSEventMaskLeftMouseDragged,
336 [](CGEventTapProxy, CGEventType type, CGEventRef event, void *) -> CGEventRef {
337 if (type == kCGEventTapDisabledByTimeout)
338 qCWarning(lcQpaScreenUpdates) << "Event tap disabled due to timeout!";
339 return event; // Listen only tap, so what we return doesn't really matter
340 }, nullptr);
341 CGEventTapEnable(eventTap, false); // Event taps are normally enabled when created
342 static CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
343 CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
344
345 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
346 [center addObserverForName:NSWindowWillStartLiveResizeNotification object:nil queue:nil
347 usingBlock:^(NSNotification *notification) {
348 qCDebug(lcQpaScreenUpdates) << "Live resize of" << notification.object
349 << "started. Enabling event tap";
350 CGEventTapEnable(eventTap, true);
351 }];
352 [center addObserverForName:NSWindowDidEndLiveResizeNotification object:nil queue:nil
353 usingBlock:^(NSNotification *notification) {
354 qCDebug(lcQpaScreenUpdates) << "Live resize of" << notification.object
355 << "ended. Disabling event tap";
356 CGEventTapEnable(eventTap, false);
357 }];
358 return eventTap;
359 }();
360 Q_UNUSED(eventTap);
361 }
362
363 if (!CVDisplayLinkIsRunning(m_displayLink)) {
364 qCDebug(lcQpaScreenUpdates) << "Starting display link for" << this;
365 CVDisplayLinkStart(m_displayLink);
366 }
367
368 return true;
369}
370
371// Helper to allow building up debug output in multiple steps
373{
374 DeferredDebugHelper(const QLoggingCategory &cat) {
375 if (cat.isDebugEnabled())
376 debug = new QDebug(QMessageLogger().debug(cat).nospace());
377 }
381 void flushOutput() {
382 if (debug) {
383 delete debug;
384 debug = nullptr;
385 }
386 }
387 QDebug *debug = nullptr;
388};
389
390#define qDeferredDebug(helper) if (Q_UNLIKELY(helper.debug)) *helper.debug
391
393{
394 if (!isOnline()) {
395 qCDebug(lcQpaScreenUpdates) << this << "is not online. Ignoring update request delivery";
396 return;
397 }
398
399 QMacAutoReleasePool pool;
400
401 // The CVDisplayLink callback is a notification that it's a good time to produce a new frame.
402 // Since the callback is delivered on a separate thread we have to marshal it over to the
403 // main thread, as Qt requires update requests to be delivered there. This needs to happen
404 // asynchronously, as otherwise we may end up deadlocking if the main thread calls back
405 // into any of the CVDisplayLink APIs.
406 if (!NSThread.isMainThread) {
407 // We're explicitly not using the data of the GCD source to track the pending updates,
408 // as the data isn't reset to 0 until after the event handler, and also doesn't update
409 // during the event handler, both of which we need to track late frames.
410 const int pendingUpdates = ++m_pendingDisplayLinkUpdates;
411
412 const int pendingUpdateRequests = m_pendingUpdateRequests;
413
414 DeferredDebugHelper screenUpdates(lcQpaScreenUpdates());
415 qDeferredDebug(screenUpdates) << "display link callback for screen " << m_displayId
416 << " with " << pendingUpdateRequests << " pending update requests";
417
418 if (const int framesAheadOfDelivery = pendingUpdates - 1) {
419 // If we have more than one update pending it means that a previous display link callback
420 // has not been fully processed on the main thread, either because GCD hasn't delivered
421 // it on the main thread yet, because the processing of the update request is taking
422 // too long, or because the update request was deferred due to window live resizing.
423 qDeferredDebug(screenUpdates) << ", " << framesAheadOfDelivery << " frame(s) ahead";
424 }
425
426 if (!pendingUpdateRequests) {
427 // There's a cost to stopping and starting the display link thread,
428 // so once started we always keep it running, to avoid missing frames.
429 // In the case where we don't have any pending update requests we don't
430 // need to signal the main thread.
431 qDeferredDebug(screenUpdates) << "; skipping signaling dispatch source";
432 m_pendingDisplayLinkUpdates = 0;
433 return;
434 }
435
436 qDeferredDebug(screenUpdates) << "; signaling dispatch source";
437
438 if (!m_displayLinkSource) {
439 m_displayLinkSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
440 dispatch_source_set_event_handler(m_displayLinkSource, ^{
442 });
443 dispatch_resume(m_displayLinkSource);
444 }
445
446 dispatch_source_merge_data(m_displayLinkSource, 1);
447
448 } else {
449 DeferredDebugHelper screenUpdates(lcQpaScreenUpdates());
450 qDeferredDebug(screenUpdates) << "gcd event handler on main thread";
451
452 const int pendingUpdates = m_pendingDisplayLinkUpdates;
453 if (pendingUpdates > 1)
454 qDeferredDebug(screenUpdates) << ", " << (pendingUpdates - 1) << " frame(s) behind display link";
455
456 screenUpdates.flushOutput();
457
458 int pendingUpdateRequests = 0;
459
460 auto windows = QGuiApplication::allWindows();
461 for (int i = 0; i < windows.size(); ++i) {
462 QWindow *window = windows.at(i);
463 if (window->screen() != screen())
464 continue;
465
466 QPointer<QCocoaWindow> platformWindow = static_cast<QCocoaWindow*>(window->handle());
467 if (!platformWindow)
468 continue;
469
470 if (!platformWindow->hasPendingUpdateRequest())
471 continue;
472
473 // Skip windows that are not doing update requests via display link
474 if (!platformWindow->updatesWithDisplayLink())
475 continue;
476
477 platformWindow->deliverUpdateRequest();
478
479 // platform window can be destroyed in deliverUpdateRequest()
480 if (!platformWindow)
481 continue;
482
483 // The update request delivery could result in another request
484 // from the window, or the platform window could decide to not
485 // deliver the request at this time.
486 if (platformWindow->hasPendingUpdateRequest())
487 ++pendingUpdateRequests;
488 }
489
490 m_pendingUpdateRequests = pendingUpdateRequests;
491
492 if (const int missedUpdates = m_pendingDisplayLinkUpdates.fetchAndStoreRelaxed(0) - pendingUpdates) {
493 qCWarning(lcQpaScreenUpdates) << "main thread missed" << missedUpdates
494 << "update(s) from display link during update request delivery";
495 }
496 }
497}
498
499void QCocoaScreen::maybeStopDisplayLink()
500{
501 if (!CVDisplayLinkIsRunning(m_displayLink))
502 return;
503
504 const auto windows = QGuiApplication::allWindows();
505 for (auto *window : windows) {
506 if (window->screen() != screen())
507 continue;
508
509 QPointer<QCocoaWindow> platformWindow = static_cast<QCocoaWindow*>(window->handle());
510 if (!platformWindow)
511 continue;
512
513 if (window->isExposed())
514 return;
515
516 if (platformWindow->hasPendingUpdateRequest())
517 return;
518 }
519
520 qCDebug(lcQpaScreenUpdates) << "Stopping display link for" << this;
521 CVDisplayLinkStop(m_displayLink);
522}
523
524
525// -----------------------------------------------------------
526
527void QCocoaScreen::updateHdrWindows()
528{
529 if (@available(macOS 14, *)) {
530 for (auto *window : QGuiApplication::allWindows()) {
531 auto *platformWindow = static_cast<QCocoaWindow*>(window->handle());
532 if (!platformWindow)
533 continue;
534
535 NSView *view = platformWindow->view();
536
537 if (!view.layer.wantsExtendedDynamicRangeContent)
538 continue;
539
540 [view setNeedsDisplay:YES];
541 }
542 }
543}
544
545// -----------------------------------------------------------
546
548{
549 QPlatformScreen::SubpixelAntialiasingType type = QPlatformScreen::subpixelAntialiasingTypeHint();
550 if (type == QPlatformScreen::Subpixel_None) {
551 // Every OSX machine has RGB pixels unless a peculiar or rotated non-Apple screen is attached
552 type = QPlatformScreen::Subpixel_RGB;
553 }
554 return type;
555}
556
558{
559 if (m_rotation == 0)
560 return Qt::LandscapeOrientation;
561 if (m_rotation == 90)
562 return Qt::PortraitOrientation;
563 if (m_rotation == 180)
564 return Qt::InvertedLandscapeOrientation;
565 if (m_rotation == 270)
566 return Qt::InvertedPortraitOrientation;
567 return QPlatformScreen::orientation();
568}
569
570QWindow *QCocoaScreen::topLevelAt(const QPoint &point) const
571{
572 __block QWindow *window = nullptr;
573 [NSApp enumerateWindowsWithOptions:NSWindowListOrderedFrontToBack
574 usingBlock:^(NSWindow *nsWindow, BOOL *stop) {
575 if (!nsWindow)
576 return;
577
578 // Continue the search if the window does not belong to Qt
579 if (![nsWindow conformsToProtocol:@protocol(QNSWindowProtocol)])
580 return;
581
582 QCocoaWindow *cocoaWindow = qnsview_cast(nsWindow.contentView).platformWindow;
583 if (!cocoaWindow)
584 return;
585
586 QWindow *w = cocoaWindow->window();
587 if (!w->isVisible())
588 return;
589
590 auto nativeGeometry = QHighDpi::toNativePixels(w->geometry(), w);
591 if (!nativeGeometry.contains(point))
592 return;
593
594 QRegion mask = QHighDpi::toNativeLocalPosition(w->mask(), w);
595 if (!mask.isEmpty() && !mask.contains(point - nativeGeometry.topLeft()))
596 return;
597
598 window = w;
599
600 // Continue the search if the window is not a top-level window
601 if (!window->isTopLevel())
602 return;
603
604 *stop = true;
605 }
606 ];
607
608 return window;
609}
610
611/*!
612 \internal
613
614 Coordinates are in screen coordinates if \a view is 0, otherwise they are in view
615 coordinates.
616*/
617QPixmap QCocoaScreen::grabWindow(WId view, int x, int y, int width, int height) const
618{
619 // ScreenCaptureKit brings down WindowServer on macOS 14 x86_64 VMs in CI
620 if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(
621 QPlatformIntegration::ScreenWindowGrabbing)) {
622 qCWarning(lcQpaScreen) << "Ignoring grabWindow to not bring down WindowServer";
623 return {};
624 }
625
626 auto grabFromDisplay = [](CGDirectDisplayID displayId, const QRect &grabRect) -> QPixmap {
627 QMacAutoReleasePool pool;
628
629 const qreal scale = QCocoaScreen::nativeScreenForDisplayId(displayId).backingScaleFactor;
630
631 dispatch_semaphore_t sem = dispatch_semaphore_create(0);
632 auto cleanup = qScopeGuard([sem]() { dispatch_release(sem); });
633
634 auto captureShareableContent = [sem](void (^capture)(SCShareableContent *)) {
635 // Try capturing all applications first, as that's the expectation of
636 // grabWindow. This will also trigger the permission system prompt on
637 // first use, matching the behavior of CGDisplayCreateImageForRect.
638 [SCShareableContent getShareableContentWithCompletionHandler:
639 ^(SCShareableContent *content, NSError *error) {
640 if (error)
641 qCDebug(lcQpaScreen) << "Failed to capture all windows" << error;
642 if (content) {
643 capture(content);
644 return;
645 }
646 // Fall back to capturing only our app, again matching the behavior
647 // of CGDisplayCreateImageForRect when we don't have permission to
648 // capture all applications. This also includes the Dock and wallpaper.
649 [SCShareableContent getCurrentProcessShareableContentWithCompletionHandler:
650 ^(SCShareableContent *content, NSError *error) {
651 if (error)
652 qCWarning(lcQpaScreen) << "Failed to capture own windows" << error;
653 if (content)
654 capture(content);
655 else
656 dispatch_semaphore_signal(sem);
657 }
658 ];
659 }
660 ];
661 };
662
663 __block QImage image;
664 captureShareableContent(^(SCShareableContent *content) {
665 Q_ASSERT(content);
666
667 QMacAutoReleasePool pool;
668
669 SCDisplay *scDisplay = nil;
670 for (SCDisplay *d in content.displays) {
671 if (d.displayID == displayId) {
672 scDisplay = d;
673 break;
674 }
675 }
676 if (!scDisplay) {
677 qCWarning(lcQpaScreen) << "No SCDisplay for display" << displayId;
678 dispatch_semaphore_signal(sem);
679 return;
680 }
681
682 SCContentFilter *filter = [[[SCContentFilter alloc]
683 initWithDisplay:scDisplay
684 includingApplications:content.applications
685 exceptingWindows:@[]] autorelease];
686 filter.includeMenuBar = YES;
687
688 SCStreamConfiguration *config = [[SCStreamConfiguration new] autorelease];
689 config.sourceRect = grabRect.toCGRect();
690 config.width = qRound(grabRect.width() * scale);
691 config.height = qRound(grabRect.height() * scale);
692 config.showsCursor = NO;
693 config.capturesAudio = NO;
694 config.ignoreShadowsDisplay = NO;
695 config.ignoreShadowsSingleWindow = NO;
696
697 [SCScreenshotManager captureImageWithFilter:filter configuration:config
698 completionHandler:^(CGImageRef cgImage, NSError *error) {
699 if (error)
700 qCWarning(lcQpaScreen) << "Failed screen capture" << error;
701 else if (cgImage)
702 image = qt_mac_toQImage(cgImage);
703 dispatch_semaphore_signal(sem);
704 }
705 ];
706 });
707
708 // Wait for screen capture to complete
709 if (dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) != 0) {
710 qCWarning(lcQpaScreen) << "Screen capture timed out for display" << displayId;
711 return QPixmap();
712 }
713
714 QPixmap pixmap = QPixmap::fromImage(image);
715 pixmap.setDevicePixelRatio(scale);
716 return pixmap;
717 };
718
719 QRect grabRect = QRect(x, y, width, height);
720 qCDebug(lcQpaScreen) << "input grab rect" << grabRect;
721
722 if (view) {
723 // Window local coordinates, so turn into global
724 NSView *nsView = reinterpret_cast<NSView*>(view);
725 NSPoint windowPoint = [nsView convertPoint:NSMakePoint(0, 0) toView:nil];
726 NSRect screenRect = [nsView.window convertRectToScreen:NSMakeRect(windowPoint.x, windowPoint.y, 1, 1)];
727 QPoint position = mapFromNative(screenRect.origin).toPoint();
728 QSize size = QRectF::fromCGRect(NSRectToCGRect(nsView.bounds)).toRect().size();
729 QRect windowRect = QRect(position, size);
730 if (!grabRect.isValid())
731 grabRect = windowRect;
732 else
733 grabRect.translate(windowRect.topLeft());
734 } else {
735 // Screen global coordinates
736 if (!grabRect.isValid())
737 grabRect = geometry();
738 }
739
740 // Find which displays to grab from
741 const int maxDisplays = 128;
742 CGDirectDisplayID displays[maxDisplays];
743 CGDisplayCount displayCount;
744 CGRect cgRect = grabRect.isValid() ? grabRect.toCGRect() : CGRectInfinite;
745 const CGDisplayErr err = CGGetDisplaysWithRect(cgRect, maxDisplays, displays, &displayCount);
746 if (err || displayCount == 0)
747 return QPixmap();
748
749 qCDebug(lcQpaScreen) << "final grab rect" << grabRect << "from" << displayCount << "displays";
750
751 // Grab images from each display, accumulating the global bounding box of the
752 // captured content. The output pixmap covers exactly that bounding box, so
753 // empty virtual-desktop space inside grabRect is not padded into the result.
754 QVector<QPixmap> pixmaps;
755 QVector<QRect> globalGrabBounds;
756 QRect outputRect;
757 for (uint i = 0; i < displayCount; ++i) {
758 auto display = displays[i];
759 const QRect displayBounds = QRectF::fromCGRect(CGDisplayBounds(display)).toRect();
760 const QRect grabBounds = displayBounds.intersected(grabRect);
761 if (grabBounds.isNull()) {
762 globalGrabBounds.append(QRect());
763 pixmaps.append(QPixmap());
764 continue;
765 }
766 const QRect displayLocalGrabBounds = QRect(QPoint(grabBounds.topLeft() - displayBounds.topLeft()), grabBounds.size());
767
768 qCDebug(lcQpaScreen) << "grab display" << i << "global" << grabBounds << "local" << displayLocalGrabBounds;
769 QPixmap displayPixmap = grabFromDisplay(display, displayLocalGrabBounds);
770 // Fast path for when grabbing from a single screen only
771 if (displayCount == 1)
772 return displayPixmap;
773
774 qCDebug(lcQpaScreen) << "grab sub-image size" << displayPixmap.size() << "devicePixelRatio" << displayPixmap.devicePixelRatio();
775 pixmaps.append(displayPixmap);
776 globalGrabBounds.append(grabBounds);
777 outputRect = outputRect.united(grabBounds);
778 }
779
780 // Determine the highest dpr, which becomes the dpr for the returned pixmap.
781 qreal dpr = 1.0;
782 for (uint i = 0; i < displayCount; ++i)
783 dpr = qMax(dpr, pixmaps.at(i).devicePixelRatio());
784
785 // Allocate target pixmap and draw each screen's content
786 qCDebug(lcQpaScreen) << "Create grap pixmap" << outputRect.size() << "at devicePixelRatio" << dpr;
787 QPixmap windowPixmap(outputRect.size() * dpr);
788 windowPixmap.setDevicePixelRatio(dpr);
789 windowPixmap.fill(Qt::transparent);
790 QPainter painter(&windowPixmap);
791 for (uint i = 0; i < displayCount; ++i) {
792 const QRect grabBounds = globalGrabBounds.at(i);
793 if (grabBounds.isNull())
794 continue;
795 const QRect dest(grabBounds.topLeft() - outputRect.topLeft(), grabBounds.size());
796 painter.drawPixmap(dest, pixmaps.at(i));
797 }
798
799 return windowPixmap;
800}
801
803{
804 // When a display is disconnected CGDisplayIsOnline and other CGDisplay
805 // functions that take a displayId will not return false, but will start
806 // returning -1 to signal that the displayId is invalid. Some functions
807 // will also assert or even crash in this case, so it's important that
808 // we double check if a display is online before calling other functions.
809 int isOnline = CGDisplayIsOnline(m_displayId);
810 static const int kCGDisplayIsDisconnected = 0xffffffff;
811 return isOnline != kCGDisplayIsDisconnected && isOnline;
812}
813
814/*
815 Returns true if a screen is mirroring another screen
816*/
817bool QCocoaScreen::isMirroring() const
818{
819 if (!isOnline())
820 return false;
821
822 return CGDisplayMirrorsDisplay(m_displayId);
823}
824
825/*!
826 The screen used as a reference for global window geometry
827*/
829{
830 // Note: The primary screen that Qt knows about may not match the current CGMainDisplayID()
831 // if macOS has not yet been able to inform us that the main display has changed, but we
832 // will update the primary screen accordingly once the reconfiguration callback comes in.
833 return static_cast<QCocoaScreen *>(QGuiApplication::primaryScreen()->handle());
834}
835
837{
838 QList<QPlatformScreen*> siblings;
839
840 // Screens on macOS are always part of the same virtual desktop
841 for (QScreen *screen : QGuiApplication::screens())
842 siblings << screen->handle();
843
844 return siblings;
845}
846
847QCocoaScreen *QCocoaScreen::get(NSScreen *nsScreen)
848{
849 auto displayId = nsScreen.qt_displayId;
850 auto *cocoaScreen = get(displayId);
851 if (!cocoaScreen) {
852 qCWarning(lcQpaScreen) << "Failed to map" << nsScreen
853 << "to QCocoaScreen. Doing last minute update.";
854 updateScreens();
855 cocoaScreen = get(displayId);
856 if (!cocoaScreen)
857 qCWarning(lcQpaScreen) << "Last minute update failed!";
858 }
859 return cocoaScreen;
860}
861
862QCocoaScreen *QCocoaScreen::get(CGDirectDisplayID displayId)
863{
864 for (QScreen *screen : QGuiApplication::screens()) {
865 QCocoaScreen *cocoaScreen = static_cast<QCocoaScreen*>(screen->handle());
866 if (cocoaScreen->m_displayId == displayId)
867 return cocoaScreen;
868 }
869
870 return nullptr;
871}
872
873QCocoaScreen *QCocoaScreen::get(CFUUIDRef uuid)
874{
875 for (QScreen *screen : QGuiApplication::screens()) {
876 auto *platformScreen = static_cast<QCocoaScreen*>(screen->handle());
877 if (!platformScreen->isOnline())
878 continue;
879
880 auto displayId = platformScreen->displayId();
881 QCFType<CFUUIDRef> candidateUuid(CGDisplayCreateUUIDFromDisplayID(displayId));
882 Q_ASSERT(candidateUuid);
883
884 if (candidateUuid == uuid)
885 return platformScreen;
886 }
887
888 return nullptr;
889}
890
891NSScreen *QCocoaScreen::nativeScreenForDisplayId(CGDirectDisplayID displayId)
892{
893 for (NSScreen *screen in NSScreen.screens) {
894 if (screen.qt_displayId == displayId)
895 return screen;
896 }
897 return nil;
898}
899
901{
902 if (!m_displayId)
903 return nil; // The display has been disconnected
904
905 return nativeScreenForDisplayId(m_displayId);
906}
907
908CGPoint QCocoaScreen::mapToNative(const QPointF &pos, QCocoaScreen *screen)
909{
910 Q_ASSERT(screen);
911 return qt_mac_flip(pos, screen->geometry()).toCGPoint();
912}
913
914CGRect QCocoaScreen::mapToNative(const QRectF &rect, QCocoaScreen *screen)
915{
916 Q_ASSERT(screen);
917 return qt_mac_flip(rect, screen->geometry()).toCGRect();
918}
919
920QPointF QCocoaScreen::mapFromNative(CGPoint pos, QCocoaScreen *screen)
921{
922 Q_ASSERT(screen);
923 return qt_mac_flip(QPointF::fromCGPoint(pos), screen->geometry());
924}
925
926QRectF QCocoaScreen::mapFromNative(CGRect rect, QCocoaScreen *screen)
927{
928 Q_ASSERT(screen);
929 return qt_mac_flip(QRectF::fromCGRect(rect), screen->geometry());
930}
931
932#ifndef QT_NO_DEBUG_STREAM
933QDebug operator<<(QDebug debug, const QCocoaScreen *screen)
934{
935 QDebugStateSaver saver(debug);
936 debug.nospace();
937 debug << "QCocoaScreen(" << (const void *)screen;
938 if (screen) {
939 debug << ", " << screen->name();
940 if (screen->isOnline()) {
941 if (CGDisplayIsAsleep(screen->displayId()))
942 debug << ", Sleeping";
943 if (auto mirroring = CGDisplayMirrorsDisplay(screen->displayId()))
944 debug << ", mirroring=" << mirroring;
945 } else {
946 debug << ", Offline";
947 }
948 debug << ", " << screen->geometry();
949 debug << ", dpr=" << screen->devicePixelRatio();
950 debug << ", displayId=" << screen->displayId();
951
952 if (auto nativeScreen = screen->nativeScreen())
953 debug << ", " << nativeScreen;
954 }
955 debug << ')';
956 return debug;
957}
958#endif // !QT_NO_DEBUG_STREAM
959
960QT_END_NAMESPACE
961
962#include "qcocoascreen.moc"
963
964@implementation NSScreen (QtExtras)
965
966- (CGDirectDisplayID)qt_displayId
967{
968 return [self.deviceDescription[@"NSScreenNumber"] unsignedIntValue];
969}
970
971@end
bool isOnline() const
QPixmap grabWindow(WId window, int x, int y, int width, int height) const override
void deliverUpdateRequests()
bool requestUpdate()
NSScreen * nativeScreen() const override
QPlatformScreen::SubpixelAntialiasingType subpixelAntialiasingTypeHint() const override
Returns a hint about this screen's subpixel layout structure.
static QCocoaScreen * primaryScreen()
The screen used as a reference for global window geometry.
Qt::ScreenOrientation orientation() const override
Reimplement this function in subclass to return the current orientation of the screen,...
QList< QPlatformScreen * > virtualSiblings() const override
Returns a list of all the platform screens that are part of the same virtual desktop.
QWindow * topLevelAt(const QPoint &point) const override
Return the given top level window for a given position.
\inmodule QtCore\reentrant
Definition qpoint.h:232
@ ReconfiguredWithFlagsMissing
#define qDeferredDebug(helper)
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
DeferredDebugHelper(const QLoggingCategory &cat)