Added MultipleWindows platform capability.
[profile/ivi/qtbase.git] / src / plugins / platforms / cocoa / qcocoaintegration.mm
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the plugins of the Qt Toolkit.
7 **
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.
16 **
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.
24 **
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.
28 **
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.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qcocoaintegration.h"
43
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"
55 #include "qmacmime.h"
56
57 #include <qpa/qplatformaccessibility.h>
58 #include <QtCore/qcoreapplication.h>
59
60 #include <QtPlatformSupport/private/qcoretextfontdatabase_p.h>
61 #include <IOKit/graphics/IOGraphicsLib.h>
62
63 static void initResources()
64 {
65     Q_INIT_RESOURCE_EXTERN(qcocoaresources)
66     Q_INIT_RESOURCE(qcocoaresources);
67 }
68
69 QT_BEGIN_NAMESPACE
70
71 QCocoaScreen::QCocoaScreen(int screenIndex) :
72     QPlatformScreen(), m_refreshRate(60.0)
73 {
74     m_screen = [[NSScreen screens] objectAtIndex:screenIndex];
75     updateGeometry();
76     m_cursor = new QCocoaCursor;
77 }
78
79 QCocoaScreen::~QCocoaScreen()
80 {
81     delete m_cursor;
82 }
83
84 void QCocoaScreen::updateGeometry()
85 {
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);
92
93     m_format = QImage::Format_RGB32;
94     m_depth = NSBitsPerPixelFromDepth([m_screen depth]);
95
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));
104
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];
111
112     QWindowSystemInterface::handleScreenGeometryChange(screen(), geometry());
113     QWindowSystemInterface::handleScreenLogicalDotsPerInchChange(screen(), resolution.width, resolution.height);
114     QWindowSystemInterface::handleScreenRefreshRateChange(screen(), m_refreshRate);
115     QWindowSystemInterface::handleScreenAvailableGeometryChange(screen(), availableGeometry());
116 }
117
118 extern CGContextRef qt_mac_cg_context(const QPaintDevice *pdev);
119
120 QPixmap QCocoaScreen::grabWindow(WId window, int x, int y, int width, int height) const
121 {
122     // TODO window should be handled
123     Q_UNUSED(window)
124
125     const int maxDisplays = 128; // 128 displays should be enough for everyone.
126     CGDirectDisplayID displays[maxDisplays];
127     CGDisplayCount displayCount;
128     CGRect cgRect;
129
130     if (width < 0 || height < 0) {
131         // get all displays
132         cgRect = CGRectInfinite;
133     } else {
134         cgRect = CGRectMake(x, y, width, height);
135     }
136     const CGDisplayErr err = CGGetDisplaysWithRect(cgRect, maxDisplays, displays, &displayCount);
137
138     if (err && displayCount == 0)
139         return QPixmap();
140
141     // calculate pixmap size
142     QSize windowSize(width, height);
143     if (width < 0 || height < 0) {
144         QRect windowRect;
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);
149         }
150         if (width < 0)
151             windowSize.setWidth(windowRect.width());
152         if (height < 0)
153             windowSize.setHeight(windowRect.height());
154     }
155
156     QPixmap windowPixmap(windowSize);
157     windowPixmap.fill(Qt::transparent);
158
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()));
166         QPixmap pix(w, h);
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);
172
173         QPainter painter(&windowPixmap);
174         painter.drawPixmap(bounds.origin.x, bounds.origin.y, pix);
175     }
176     return windowPixmap;
177 }
178
179 QCocoaIntegration::QCocoaIntegration()
180     : mFontDb(new QCoreTextFontDatabase())
181     , mEventDispatcher(new QCocoaEventDispatcher())
182     , mInputContext(new QCocoaInputContext)
183 #ifndef QT_NO_ACCESSIBILITY
184     , mAccessibility(new QPlatformAccessibility)
185 #endif
186     , mCocoaClipboard(new QCocoaClipboard)
187     , mCocoaDrag(new QCocoaDrag)
188     , mNativeInterface(new QCocoaNativeInterface)
189     , mServices(new QCocoaServices)
190 {
191     initResources();
192     QCocoaAutoReleasePool pool;
193
194     qApp->setAttribute(Qt::AA_DontUseNativeMenuBar, false);
195
196     NSApplication *cocoaApplication = [NSApplication sharedApplication];
197
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();
205
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];
211     }
212
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
215     // is matched here.
216     if (!QCoreApplication::testAttribute(Qt::AA_MacPluginApplication)) {
217
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];
222
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];
228     }
229
230     updateScreens();
231
232     QMacPasteboardMime::initializeMimeTypes();
233 }
234
235 QCocoaIntegration::~QCocoaIntegration()
236 {
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];
244     }
245
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();
251
252     // Delete screens in reverse order to avoid crash in case of multiple screens
253     while (!mScreens.isEmpty()) {
254         delete mScreens.takeLast();
255     }
256 }
257
258 /*!
259     \brief Synchronizes the screen list, adds new screens, removes deleted ones
260 */
261 void QCocoaIntegration::updateScreens()
262 {
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)
273                 continue;
274         }
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;
282                 break;
283             }
284         if (screen) {
285             remainingScreens.remove(screen);
286             screen->updateGeometry();
287         } else {
288             screen = new QCocoaScreen(i);
289             mScreens.append(screen);
290             screenAdded(screen);
291         }
292         siblings << screen;
293     }
294     // Now the leftovers in remainingScreens are no longer current, so we can delete them.
295     foreach (QCocoaScreen* screen, remainingScreens) {
296         mScreens.removeOne(screen);
297         delete screen;
298     }
299     // All screens in mScreens are siblings, because we ignored the mirrors.
300     foreach (QCocoaScreen* screen, mScreens)
301         screen->setVirtualSiblings(siblings);
302 }
303
304 bool QCocoaIntegration::hasCapability(QPlatformIntegration::Capability cap) const
305 {
306     switch (cap) {
307     case ThreadedPixmaps:
308     case OpenGL:
309     case ThreadedOpenGL:
310     case BufferQueueingOpenGL:
311     case WindowMasks:
312     case MultipleWindows:
313         return true;
314     default:
315         return QPlatformIntegration::hasCapability(cap);
316     }
317 }
318
319
320
321 QPlatformWindow *QCocoaIntegration::createPlatformWindow(QWindow *window) const
322 {
323     return new QCocoaWindow(window);
324 }
325
326 QPlatformOpenGLContext *QCocoaIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
327 {
328     return new QCocoaGLContext(context->format(), context->shareHandle());
329 }
330
331 QPlatformBackingStore *QCocoaIntegration::createPlatformBackingStore(QWindow *window) const
332 {
333     return new QCocoaBackingStore(window);
334 }
335
336 QAbstractEventDispatcher *QCocoaIntegration::guiThreadEventDispatcher() const
337 {
338     return mEventDispatcher;
339 }
340
341 QPlatformFontDatabase *QCocoaIntegration::fontDatabase() const
342 {
343     return mFontDb.data();
344 }
345
346 QPlatformNativeInterface *QCocoaIntegration::nativeInterface() const
347 {
348     return mNativeInterface.data();
349 }
350
351 QPlatformInputContext *QCocoaIntegration::inputContext() const
352 {
353     return mInputContext.data();
354 }
355
356 QPlatformAccessibility *QCocoaIntegration::accessibility() const
357 {
358 #ifndef QT_NO_ACCESSIBILITY
359     return mAccessibility.data();
360 #else
361     return 0;
362 #endif
363 }
364
365 QPlatformClipboard *QCocoaIntegration::clipboard() const
366 {
367     return mCocoaClipboard;
368 }
369
370 QPlatformDrag *QCocoaIntegration::drag() const
371 {
372     return mCocoaDrag.data();
373 }
374
375 QStringList QCocoaIntegration::themeNames() const
376 {
377     return QStringList(QLatin1String(QCocoaTheme::name));
378 }
379
380 QPlatformTheme *QCocoaIntegration::createPlatformTheme(const QString &name) const
381 {
382     if (name == QLatin1String(QCocoaTheme::name))
383         return new QCocoaTheme;
384     return QPlatformIntegration::createPlatformTheme(name);
385 }
386
387 QPlatformServices *QCocoaIntegration::services() const
388 {
389     return mServices.data();
390 }
391
392 QVariant QCocoaIntegration::styleHint(StyleHint hint) const
393 {
394     if (hint == QPlatformIntegration::FontSmoothingGamma)
395         return 2.0;
396     if (hint == QPlatformIntegration::SynthesizeMouseFromTouchEvents)
397         return false;
398
399     return QPlatformIntegration::styleHint(hint);
400 }
401
402 QT_END_NAMESPACE