1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the plugins of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #include "qcocoaintegration.h"
44 #include "qcocoawindow.h"
45 #include "qcocoabackingstore.h"
46 #include "qcocoanativeinterface.h"
47 #include "qcocoamenuloader.h"
48 #include "qcocoaeventdispatcher.h"
49 #include "qcocoahelpers.h"
50 #include "qcocoaapplication.h"
51 #include "qcocoaapplicationdelegate.h"
52 #include "qcocoafiledialoghelper.h"
53 #include "qcocoatheme.h"
54 #include "qcocoainputcontext.h"
57 #include <qpa/qplatformaccessibility.h>
58 #include <QtCore/qcoreapplication.h>
60 #include <QtPlatformSupport/private/qcoretextfontdatabase_p.h>
61 #include <IOKit/graphics/IOGraphicsLib.h>
63 static void initResources()
65 Q_INIT_RESOURCE_EXTERN(qcocoaresources)
66 Q_INIT_RESOURCE(qcocoaresources);
71 QCocoaScreen::QCocoaScreen(int screenIndex) :
72 QPlatformScreen(), m_refreshRate(60.0)
74 m_screen = [[NSScreen screens] objectAtIndex:screenIndex];
76 m_cursor = new QCocoaCursor;
79 QCocoaScreen::~QCocoaScreen()
84 void QCocoaScreen::updateGeometry()
86 NSRect frameRect = [m_screen frame];
87 m_geometry = QRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width, frameRect.size.height);
88 NSRect visibleRect = [m_screen visibleFrame];
89 m_availableGeometry = QRect(visibleRect.origin.x,
90 frameRect.size.height - (visibleRect.origin.y + visibleRect.size.height), // invert y
91 visibleRect.size.width, visibleRect.size.height);
93 m_format = QImage::Format_RGB32;
94 m_depth = NSBitsPerPixelFromDepth([m_screen depth]);
96 NSDictionary *devDesc = [m_screen deviceDescription];
97 CGDirectDisplayID dpy = [[devDesc objectForKey:@"NSScreenNumber"] unsignedIntValue];
98 CGSize size = CGDisplayScreenSize(dpy);
99 m_physicalSize = QSizeF(size.width, size.height);
100 NSSize resolution = [[devDesc valueForKey:NSDeviceResolution] sizeValue];
101 m_logicalDpi.first = resolution.width;
102 m_logicalDpi.second = resolution.height;
103 m_refreshRate = CGDisplayModeGetRefreshRate(CGDisplayCopyDisplayMode(dpy));
105 // Get m_name (brand/model of the monitor)
106 NSDictionary *deviceInfo = (NSDictionary *)IODisplayCreateInfoDictionary(CGDisplayIOServicePort(dpy), kIODisplayOnlyPreferredName);
107 NSDictionary *localizedNames = [deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]];
108 if ([localizedNames count] > 0)
109 m_name = QString::fromUtf8([[localizedNames objectForKey:[[localizedNames allKeys] objectAtIndex:0]] UTF8String]);
110 [deviceInfo release];
112 QWindowSystemInterface::handleScreenGeometryChange(screen(), geometry());
113 QWindowSystemInterface::handleScreenLogicalDotsPerInchChange(screen(), resolution.width, resolution.height);
114 QWindowSystemInterface::handleScreenRefreshRateChange(screen(), m_refreshRate);
115 QWindowSystemInterface::handleScreenAvailableGeometryChange(screen(), availableGeometry());
118 extern CGContextRef qt_mac_cg_context(const QPaintDevice *pdev);
120 QPixmap QCocoaScreen::grabWindow(WId window, int x, int y, int width, int height) const
122 // TODO window should be handled
125 const int maxDisplays = 128; // 128 displays should be enough for everyone.
126 CGDirectDisplayID displays[maxDisplays];
127 CGDisplayCount displayCount;
130 if (width < 0 || height < 0) {
132 cgRect = CGRectInfinite;
134 cgRect = CGRectMake(x, y, width, height);
136 const CGDisplayErr err = CGGetDisplaysWithRect(cgRect, maxDisplays, displays, &displayCount);
138 if (err && displayCount == 0)
141 // calculate pixmap size
142 QSize windowSize(width, height);
143 if (width < 0 || height < 0) {
145 for (uint i = 0; i < displayCount; ++i) {
146 const CGRect cgRect = CGDisplayBounds(displays[i]);
147 QRect qRect(cgRect.origin.x, cgRect.origin.y, cgRect.size.width, cgRect.size.height);
148 windowRect = windowRect.united(qRect);
151 windowSize.setWidth(windowRect.width());
153 windowSize.setHeight(windowRect.height());
156 QPixmap windowPixmap(windowSize);
157 windowPixmap.fill(Qt::transparent);
159 for (uint i = 0; i < displayCount; ++i) {
160 const CGRect bounds = CGDisplayBounds(displays[i]);
161 int w = (width < 0 ? bounds.size.width : width);
162 int h = (height < 0 ? bounds.size.height : height);
163 QRect displayRect = QRect(x, y, w, h);
164 QCFType<CGImageRef> image = CGDisplayCreateImageForRect(displays[i],
165 CGRectMake(displayRect.x(), displayRect.y(), displayRect.width(), displayRect.height()));
167 pix.fill(Qt::transparent);
168 CGRect rect = CGRectMake(0, 0, w, h);
169 CGContextRef ctx = qt_mac_cg_context(&pix);
170 qt_mac_drawCGImage(ctx, &rect, image);
171 CGContextRelease(ctx);
173 QPainter painter(&windowPixmap);
174 painter.drawPixmap(bounds.origin.x, bounds.origin.y, pix);
179 QCocoaIntegration::QCocoaIntegration()
180 : mFontDb(new QCoreTextFontDatabase())
181 , mEventDispatcher(new QCocoaEventDispatcher())
182 , mInputContext(new QCocoaInputContext)
183 #ifndef QT_NO_ACCESSIBILITY
184 , mAccessibility(new QPlatformAccessibility)
186 , mCocoaClipboard(new QCocoaClipboard)
187 , mCocoaDrag(new QCocoaDrag)
188 , mNativeInterface(new QCocoaNativeInterface)
189 , mServices(new QCocoaServices)
192 QCocoaAutoReleasePool pool;
194 qApp->setAttribute(Qt::AA_DontUseNativeMenuBar, false);
196 NSApplication *cocoaApplication = [NSApplication sharedApplication];
198 if (qEnvironmentVariableIsEmpty("QT_MAC_DISABLE_FOREGROUND_APPLICATION_TRANSFORM")) {
199 // Applications launched from plain executables (without an app
200 // bundle) are "background" applications that does not take keybaord
201 // focus or have a dock icon or task switcher entry. Qt Gui apps generally
202 // wants to be foreground applications so change the process type. (But
203 // see the function implementation for exceptions.)
204 qt_mac_transformProccessToForegroundApplication();
206 // Move the application window to front to avoid launching behind the terminal.
207 // Ignoring other apps is neccessary (we must ignore the terminal), but makes
208 // Qt apps play slightly less nice with other apps when lanching from Finder
209 // (See the activateIgnoringOtherApps docs.)
210 [cocoaApplication activateIgnoringOtherApps : YES];
213 // ### For AA_MacPluginApplication we don't want to load the menu nib.
214 // Qt 4 also does not set the application delegate, so that behavior
216 if (!QCoreApplication::testAttribute(Qt::AA_MacPluginApplication)) {
218 // Set app delegate, link to the current delegate (if any)
219 QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *newDelegate = [QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate];
220 [newDelegate setReflectionDelegate:[cocoaApplication delegate]];
221 [cocoaApplication setDelegate:newDelegate];
223 // Load the application menu. This menu contains Preferences, Hide, Quit.
224 QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *qtMenuLoader = [[QT_MANGLE_NAMESPACE(QCocoaMenuLoader) alloc] init];
225 qt_mac_loadMenuNib(qtMenuLoader);
226 [cocoaApplication setMenu:[qtMenuLoader menu]];
227 [newDelegate setMenuLoader:qtMenuLoader];
232 QMacPasteboardMime::initializeMimeTypes();
235 QCocoaIntegration::~QCocoaIntegration()
237 QCocoaAutoReleasePool pool;
238 if (!QCoreApplication::testAttribute(Qt::AA_MacPluginApplication)) {
239 // remove the apple event handlers installed by QCocoaApplicationDelegate
240 QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *delegate = [QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate];
241 [delegate removeAppleEventHandlers];
242 // reset the application delegate
243 [[NSApplication sharedApplication] setDelegate: 0];
246 // Delete the clipboard integration and destroy mime type converters.
247 // Deleting the clipboard integration flushes promised pastes using
248 // the mime converters - the ordering here is important.
249 delete mCocoaClipboard;
250 QMacPasteboardMime::destroyMimeTypes();
252 // Delete screens in reverse order to avoid crash in case of multiple screens
253 while (!mScreens.isEmpty()) {
254 delete mScreens.takeLast();
259 \brief Synchronizes the screen list, adds new screens, removes deleted ones
261 void QCocoaIntegration::updateScreens()
263 NSArray *screens = [NSScreen screens];
264 QSet<QCocoaScreen*> remainingScreens = QSet<QCocoaScreen*>::fromList(mScreens);
265 QList<QPlatformScreen *> siblings;
266 for (uint i = 0; i < [screens count]; i++) {
267 NSScreen* scr = [[NSScreen screens] objectAtIndex:i];
268 CGDirectDisplayID dpy = [[[scr deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue];
269 // If this screen is a mirror and is not the primary one of the mirror set, ignore it.
270 if (CGDisplayIsInMirrorSet(dpy)) {
271 CGDirectDisplayID primary = CGDisplayMirrorsDisplay(dpy);
272 if (primary != kCGNullDirectDisplay && primary != dpy)
275 QCocoaScreen* screen = NULL;
276 foreach (QCocoaScreen* existingScr, mScreens)
277 // NSScreen documentation says do not cache the array returned from [NSScreen screens].
278 // However in practice, we can identify a screen by its pointer: if resolution changes,
279 // the NSScreen object will be the same instance, just with different values.
280 if (existingScr->osScreen() == scr) {
281 screen = existingScr;
285 remainingScreens.remove(screen);
286 screen->updateGeometry();
288 screen = new QCocoaScreen(i);
289 mScreens.append(screen);
294 // Now the leftovers in remainingScreens are no longer current, so we can delete them.
295 foreach (QCocoaScreen* screen, remainingScreens) {
296 mScreens.removeOne(screen);
299 // All screens in mScreens are siblings, because we ignored the mirrors.
300 foreach (QCocoaScreen* screen, mScreens)
301 screen->setVirtualSiblings(siblings);
304 bool QCocoaIntegration::hasCapability(QPlatformIntegration::Capability cap) const
307 case ThreadedPixmaps:
310 case BufferQueueingOpenGL:
314 return QPlatformIntegration::hasCapability(cap);
320 QPlatformWindow *QCocoaIntegration::createPlatformWindow(QWindow *window) const
322 return new QCocoaWindow(window);
325 QPlatformOpenGLContext *QCocoaIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
327 return new QCocoaGLContext(context->format(), context->shareHandle());
330 QPlatformBackingStore *QCocoaIntegration::createPlatformBackingStore(QWindow *window) const
332 return new QCocoaBackingStore(window);
335 QAbstractEventDispatcher *QCocoaIntegration::guiThreadEventDispatcher() const
337 return mEventDispatcher;
340 QPlatformFontDatabase *QCocoaIntegration::fontDatabase() const
342 return mFontDb.data();
345 QPlatformNativeInterface *QCocoaIntegration::nativeInterface() const
347 return mNativeInterface.data();
350 QPlatformInputContext *QCocoaIntegration::inputContext() const
352 return mInputContext.data();
355 QPlatformAccessibility *QCocoaIntegration::accessibility() const
357 #ifndef QT_NO_ACCESSIBILITY
358 return mAccessibility.data();
364 QPlatformClipboard *QCocoaIntegration::clipboard() const
366 return mCocoaClipboard;
369 QPlatformDrag *QCocoaIntegration::drag() const
371 return mCocoaDrag.data();
374 QStringList QCocoaIntegration::themeNames() const
376 return QStringList(QLatin1String(QCocoaTheme::name));
379 QPlatformTheme *QCocoaIntegration::createPlatformTheme(const QString &name) const
381 if (name == QLatin1String(QCocoaTheme::name))
382 return new QCocoaTheme;
383 return QPlatformIntegration::createPlatformTheme(name);
386 QPlatformServices *QCocoaIntegration::services() const
388 return mServices.data();
391 QVariant QCocoaIntegration::styleHint(StyleHint hint) const
393 if (hint == QPlatformIntegration::FontSmoothingGamma)
395 if (hint == QPlatformIntegration::SynthesizeMouseFromTouchEvents)
398 return QPlatformIntegration::styleHint(hint);