a361027b49c987821077674b662b4a1f97fbd9d2
[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     m_logicalDpi.first = 72;
101     m_logicalDpi.second = 72;
102     m_refreshRate = CGDisplayModeGetRefreshRate(CGDisplayCopyDisplayMode(dpy));
103
104     // Get m_name (brand/model of the monitor)
105     NSDictionary *deviceInfo = (NSDictionary *)IODisplayCreateInfoDictionary(CGDisplayIOServicePort(dpy), kIODisplayOnlyPreferredName);
106     NSDictionary *localizedNames = [deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]];
107     if ([localizedNames count] > 0)
108         m_name = QString::fromUtf8([[localizedNames objectForKey:[[localizedNames allKeys] objectAtIndex:0]] UTF8String]);
109     [deviceInfo release];
110
111     QWindowSystemInterface::handleScreenGeometryChange(screen(), geometry());
112     QWindowSystemInterface::handleScreenLogicalDotsPerInchChange(screen(), m_logicalDpi.first, m_logicalDpi.second);
113     QWindowSystemInterface::handleScreenRefreshRateChange(screen(), m_refreshRate);
114     QWindowSystemInterface::handleScreenAvailableGeometryChange(screen(), availableGeometry());
115 }
116
117 extern CGContextRef qt_mac_cg_context(const QPaintDevice *pdev);
118
119 QPixmap QCocoaScreen::grabWindow(WId window, int x, int y, int width, int height) const
120 {
121     // TODO window should be handled
122     Q_UNUSED(window)
123
124     const int maxDisplays = 128; // 128 displays should be enough for everyone.
125     CGDirectDisplayID displays[maxDisplays];
126     CGDisplayCount displayCount;
127     CGRect cgRect;
128
129     if (width < 0 || height < 0) {
130         // get all displays
131         cgRect = CGRectInfinite;
132     } else {
133         cgRect = CGRectMake(x, y, width, height);
134     }
135     const CGDisplayErr err = CGGetDisplaysWithRect(cgRect, maxDisplays, displays, &displayCount);
136
137     if (err && displayCount == 0)
138         return QPixmap();
139
140     // calculate pixmap size
141     QSize windowSize(width, height);
142     if (width < 0 || height < 0) {
143         QRect windowRect;
144         for (uint i = 0; i < displayCount; ++i) {
145             const CGRect cgRect = CGDisplayBounds(displays[i]);
146             QRect qRect(cgRect.origin.x, cgRect.origin.y, cgRect.size.width, cgRect.size.height);
147             windowRect = windowRect.united(qRect);
148         }
149         if (width < 0)
150             windowSize.setWidth(windowRect.width());
151         if (height < 0)
152             windowSize.setHeight(windowRect.height());
153     }
154
155     QPixmap windowPixmap(windowSize);
156     windowPixmap.fill(Qt::transparent);
157
158     for (uint i = 0; i < displayCount; ++i) {
159         const CGRect bounds = CGDisplayBounds(displays[i]);
160         int w = (width < 0 ? bounds.size.width : width);
161         int h = (height < 0 ? bounds.size.height : height);
162         QRect displayRect = QRect(x, y, w, h);
163         QCFType<CGImageRef> image = CGDisplayCreateImageForRect(displays[i],
164             CGRectMake(displayRect.x(), displayRect.y(), displayRect.width(), displayRect.height()));
165         QPixmap pix(w, h);
166         pix.fill(Qt::transparent);
167         CGRect rect = CGRectMake(0, 0, w, h);
168         CGContextRef ctx = qt_mac_cg_context(&pix);
169         qt_mac_drawCGImage(ctx, &rect, image);
170         CGContextRelease(ctx);
171
172         QPainter painter(&windowPixmap);
173         painter.drawPixmap(bounds.origin.x, bounds.origin.y, pix);
174     }
175     return windowPixmap;
176 }
177
178 QCocoaIntegration::QCocoaIntegration()
179     : mFontDb(new QCoreTextFontDatabase())
180     , mEventDispatcher(new QCocoaEventDispatcher())
181     , mInputContext(new QCocoaInputContext)
182 #ifndef QT_NO_ACCESSIBILITY
183     , mAccessibility(new QPlatformAccessibility)
184 #endif
185     , mCocoaClipboard(new QCocoaClipboard)
186     , mCocoaDrag(new QCocoaDrag)
187     , mNativeInterface(new QCocoaNativeInterface)
188     , mServices(new QCocoaServices)
189 {
190     initResources();
191     QCocoaAutoReleasePool pool;
192
193     qApp->setAttribute(Qt::AA_DontUseNativeMenuBar, false);
194
195     NSApplication *cocoaApplication = [QT_MANGLE_NAMESPACE(QNSApplication) sharedApplication];
196     qt_redirectNSApplicationSendEvent();
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     qt_resetNSApplicationSendEvent();
238
239     QCocoaAutoReleasePool pool;
240     if (!QCoreApplication::testAttribute(Qt::AA_MacPluginApplication)) {
241         // remove the apple event handlers installed by QCocoaApplicationDelegate
242         QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *delegate = [QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate];
243         [delegate removeAppleEventHandlers];
244         // reset the application delegate
245         [[NSApplication sharedApplication] setDelegate: 0];
246     }
247
248     // Delete the clipboard integration and destroy mime type converters.
249     // Deleting the clipboard integration flushes promised pastes using
250     // the mime converters - the ordering here is important.
251     delete mCocoaClipboard;
252     QMacPasteboardMime::destroyMimeTypes();
253
254     // Delete screens in reverse order to avoid crash in case of multiple screens
255     while (!mScreens.isEmpty()) {
256         delete mScreens.takeLast();
257     }
258 }
259
260 /*!
261     \brief Synchronizes the screen list, adds new screens, removes deleted ones
262 */
263 void QCocoaIntegration::updateScreens()
264 {
265     NSArray *screens = [NSScreen screens];
266     QSet<QCocoaScreen*> remainingScreens = QSet<QCocoaScreen*>::fromList(mScreens);
267     QList<QPlatformScreen *> siblings;
268     for (uint i = 0; i < [screens count]; i++) {
269         NSScreen* scr = [[NSScreen screens] objectAtIndex:i];
270         CGDirectDisplayID dpy = [[[scr deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue];
271         // If this screen is a mirror and is not the primary one of the mirror set, ignore it.
272         if (CGDisplayIsInMirrorSet(dpy)) {
273             CGDirectDisplayID primary = CGDisplayMirrorsDisplay(dpy);
274             if (primary != kCGNullDirectDisplay && primary != dpy)
275                 continue;
276         }
277         QCocoaScreen* screen = NULL;
278         foreach (QCocoaScreen* existingScr, mScreens)
279             // NSScreen documentation says do not cache the array returned from [NSScreen screens].
280             // However in practice, we can identify a screen by its pointer: if resolution changes,
281             // the NSScreen object will be the same instance, just with different values.
282             if (existingScr->osScreen() == scr) {
283                 screen = existingScr;
284                 break;
285             }
286         if (screen) {
287             remainingScreens.remove(screen);
288             screen->updateGeometry();
289         } else {
290             screen = new QCocoaScreen(i);
291             mScreens.append(screen);
292             screenAdded(screen);
293         }
294         siblings << screen;
295     }
296     // Now the leftovers in remainingScreens are no longer current, so we can delete them.
297     foreach (QCocoaScreen* screen, remainingScreens) {
298         mScreens.removeOne(screen);
299         delete screen;
300     }
301     // All screens in mScreens are siblings, because we ignored the mirrors.
302     foreach (QCocoaScreen* screen, mScreens)
303         screen->setVirtualSiblings(siblings);
304 }
305
306 bool QCocoaIntegration::hasCapability(QPlatformIntegration::Capability cap) const
307 {
308     switch (cap) {
309     case ThreadedPixmaps:
310     case OpenGL:
311     case ThreadedOpenGL:
312     case BufferQueueingOpenGL:
313     case WindowMasks:
314     case MultipleWindows:
315         return true;
316     default:
317         return QPlatformIntegration::hasCapability(cap);
318     }
319 }
320
321
322
323 QPlatformWindow *QCocoaIntegration::createPlatformWindow(QWindow *window) const
324 {
325     return new QCocoaWindow(window);
326 }
327
328 QPlatformOpenGLContext *QCocoaIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
329 {
330     return new QCocoaGLContext(context->format(), context->shareHandle());
331 }
332
333 QPlatformBackingStore *QCocoaIntegration::createPlatformBackingStore(QWindow *window) const
334 {
335     return new QCocoaBackingStore(window);
336 }
337
338 QAbstractEventDispatcher *QCocoaIntegration::guiThreadEventDispatcher() const
339 {
340     return mEventDispatcher;
341 }
342
343 QPlatformFontDatabase *QCocoaIntegration::fontDatabase() const
344 {
345     return mFontDb.data();
346 }
347
348 QPlatformNativeInterface *QCocoaIntegration::nativeInterface() const
349 {
350     return mNativeInterface.data();
351 }
352
353 QPlatformInputContext *QCocoaIntegration::inputContext() const
354 {
355     return mInputContext.data();
356 }
357
358 QPlatformAccessibility *QCocoaIntegration::accessibility() const
359 {
360 #ifndef QT_NO_ACCESSIBILITY
361     return mAccessibility.data();
362 #else
363     return 0;
364 #endif
365 }
366
367 QPlatformClipboard *QCocoaIntegration::clipboard() const
368 {
369     return mCocoaClipboard;
370 }
371
372 QPlatformDrag *QCocoaIntegration::drag() const
373 {
374     return mCocoaDrag.data();
375 }
376
377 QStringList QCocoaIntegration::themeNames() const
378 {
379     return QStringList(QLatin1String(QCocoaTheme::name));
380 }
381
382 QPlatformTheme *QCocoaIntegration::createPlatformTheme(const QString &name) const
383 {
384     if (name == QLatin1String(QCocoaTheme::name))
385         return new QCocoaTheme;
386     return QPlatformIntegration::createPlatformTheme(name);
387 }
388
389 QPlatformServices *QCocoaIntegration::services() const
390 {
391     return mServices.data();
392 }
393
394 QVariant QCocoaIntegration::styleHint(StyleHint hint) const
395 {
396     if (hint == QPlatformIntegration::FontSmoothingGamma)
397         return 2.0;
398     if (hint == QPlatformIntegration::SynthesizeMouseFromTouchEvents)
399         return false;
400
401     return QPlatformIntegration::styleHint(hint);
402 }
403
404 QT_END_NAMESPACE