Make cocoa opengl backend threadsafe.
[profile/ivi/qtbase.git] / src / plugins / platforms / cocoa / qcocoawindow.mm
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the plugins of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41 #include "qcocoawindow.h"
42 #include "qnswindowdelegate.h"
43 #include "qcocoaautoreleasepool.h"
44 #include "qcocoaglcontext.h"
45 #include "qcocoahelpers.h"
46 #include "qnsview.h"
47 #include <QtCore/private/qcore_mac_p.h>
48 #include <qwindow.h>
49 #include <QWindowSystemInterface>
50 #include <QPlatformScreen>
51
52 #include <Cocoa/Cocoa.h>
53 #include <Carbon/Carbon.h>
54
55 #include <QDebug>
56
57 @implementation QNSWindow
58
59 - (BOOL)canBecomeKeyWindow
60 {
61
62     // The default implementation returns NO for title-bar less windows,
63     // override and return yes here to make sure popup windows such as
64     // the combobox popup can become the key window.
65     return YES;
66 }
67
68 @end
69
70 @implementation QNSPanel
71
72 - (BOOL)canBecomeKeyWindow
73 {
74     return YES;
75 }
76
77 @end
78
79 QCocoaWindow::QCocoaWindow(QWindow *tlw)
80     : QPlatformWindow(tlw)
81     , m_windowAttributes(0)
82     , m_windowClass(0)
83     , m_glContext(0)
84 {
85     QCocoaAutoReleasePool pool;
86
87     determineWindowClass();
88     m_nsWindow = createWindow();
89
90     QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
91     [m_nsWindow setDelegate:delegate];
92     [m_nsWindow setAcceptsMouseMovedEvents:YES];
93
94     // Prevent Cocoa from releasing the window on close. Qt
95     // handles the close event asynchronously and we want to
96     // make sure that m_nsWindow stays valid until the
97     // QCocoaWindow is deleted by Qt.
98     [m_nsWindow setReleasedWhenClosed : NO];
99
100     m_contentView = [[QNSView alloc] initWithQWindow:tlw];
101
102     // ### Accept touch events by default.
103     // Beware that enabling touch events has a negative impact on the overall performance.
104     // We probably need a QWindowSystemInterface API to enable/disable touch events.
105     [m_contentView setAcceptsTouchEvents:YES];
106
107     setGeometry(tlw->geometry());
108
109     [m_nsWindow setContentView:m_contentView];
110 }
111
112 QCocoaWindow::~QCocoaWindow()
113 {
114     [m_nsWindow release];
115 }
116
117 void QCocoaWindow::setGeometry(const QRect &rect)
118 {
119     if (geometry() == rect)
120         return;
121     QPlatformWindow::setGeometry(rect);
122
123     NSRect bounds = qt_mac_flipRect(rect, window());
124
125     [[m_nsWindow contentView] setFrameSize:bounds.size];
126     [m_nsWindow setContentSize : bounds.size];
127     [m_nsWindow setFrameOrigin : bounds.origin];
128 }
129
130 void QCocoaWindow::setVisible(bool visible)
131 {
132     if (visible) {
133         // The parent window might have moved while this window was hidden,
134         // update the window geometry if there is a parent.
135         if (window()->transientParent())
136             setGeometry(window()->geometry());
137
138         // Make sure the QWindow has a frame ready before we show the NSWindow.
139         QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
140
141         [m_nsWindow makeKeyAndOrderFront:nil];
142     } else {
143         [m_nsWindow orderOut:nil];
144     }
145 }
146
147 void QCocoaWindow::setWindowTitle(const QString &title)
148 {
149     CFStringRef windowTitle = QCFString::toCFStringRef(title);
150     [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
151     CFRelease(windowTitle);
152 }
153
154 void QCocoaWindow::raise()
155 {
156     // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
157     [m_nsWindow orderFront: m_nsWindow];
158 }
159
160 void QCocoaWindow::lower()
161 {
162     [m_nsWindow orderFront: m_nsWindow];
163 }
164
165 void QCocoaWindow::propagateSizeHints()
166 {
167     [m_nsWindow setMinSize : qt_mac_toNSSize(window()->minimumSize())];
168     [m_nsWindow setMaxSize : qt_mac_toNSSize(window()->maximumSize())];
169
170     if (!window()->sizeIncrement().isNull())
171         [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
172
173     // We must set the window frame after setting the minimum size to prevent the window
174     // from being resized to the minimum size. Use QWindow::baseSize if set, otherwise
175     // use the current size.
176     QSize baseSize = window()->baseSize();
177     QRect rect = geometry();
178     if (!baseSize.isNull()) {
179         [m_nsWindow setFrame : NSMakeRect(rect.x(), rect.y(), baseSize.width(), baseSize.height()) display : YES];
180     } else {
181         [m_nsWindow setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height()) display : YES];
182     }
183 }
184
185 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
186 {
187     if (grab && ![m_nsWindow isKeyWindow])
188         [m_nsWindow makeKeyWindow];
189     else if (!grab && [m_nsWindow isKeyWindow])
190         [m_nsWindow resignKeyWindow];
191     return true;
192 }
193
194 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
195 {
196     if (grab && ![m_nsWindow isKeyWindow])
197         [m_nsWindow makeKeyWindow];
198     else if (!grab && [m_nsWindow isKeyWindow])
199         [m_nsWindow resignKeyWindow];
200     return true;
201 }
202
203 WId QCocoaWindow::winId() const
204 {
205     return WId(m_nsWindow);
206 }
207
208 NSView *QCocoaWindow::contentView() const
209 {
210     return [m_nsWindow contentView];
211 }
212
213 void QCocoaWindow::windowDidMove()
214 {
215     NSRect rect = [[m_nsWindow contentView]frame];
216     NSRect windowRect = [m_nsWindow frame];
217
218     QRect geo(windowRect.origin.x, qt_mac_flipYCoordinate(windowRect.origin.y + rect.size.height), rect.size.width, rect.size.height);
219     setGeometry(geo);
220     QWindowSystemInterface::handleSynchronousGeometryChange(window(), geo);
221 }
222
223 void QCocoaWindow::windowDidResize()
224 {
225     NSRect rect = [[m_nsWindow contentView]frame];
226     NSRect windowRect = [m_nsWindow frame];
227
228     QRect geo(windowRect.origin.x, qt_mac_flipYCoordinate(windowRect.origin.y + rect.size.height), rect.size.width, rect.size.height);
229     setGeometry(geo);
230     QWindowSystemInterface::handleSynchronousGeometryChange(window(), geo);
231 }
232
233
234 void QCocoaWindow::windowWillClose()
235 {
236     QWindowSystemInterface::handleCloseEvent(window());
237 }
238
239 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
240 {
241     m_glContext = context;
242 }
243
244 QCocoaGLContext *QCocoaWindow::currentContext() const
245 {
246     return m_glContext;
247 }
248
249 /*
250     Determine the window class based on the window type and
251     window flags, and widget attr Sets m_windowAttributes
252     and m_windowClass.
253 */
254 void QCocoaWindow::determineWindowClass()
255 {
256     Qt::WindowType type = window()->windowType();
257     Qt::WindowFlags flags = window()->windowFlags();
258
259     const bool popup = (type == Qt::Popup);
260
261     if (type == Qt::ToolTip || type == Qt::SplashScreen || popup)
262         flags |= Qt::FramelessWindowHint;
263
264     m_windowClass = kSheetWindowClass;
265
266     if (popup || type == Qt::SplashScreen)
267         m_windowClass = kModalWindowClass;
268     else if (type == Qt::ToolTip)
269         m_windowClass = kHelpWindowClass;
270     else if (type == Qt::Tool)
271         m_windowClass = kFloatingWindowClass;
272     else
273         m_windowClass = kDocumentWindowClass;
274
275     m_windowAttributes = (kWindowCompositingAttribute | kWindowStandardHandlerAttribute);
276
277 //    if(qt_mac_is_macsheet(window())) {
278 //        m_windowClass = kSheetWindowClass;
279 //    } else
280
281     {
282         // Shift things around a bit to get the correct window class based on the presence
283         // (or lack) of the border.
284
285         bool customize = flags & Qt::CustomizeWindowHint;
286         bool framelessWindow = (flags & Qt::FramelessWindowHint || (customize && !(flags & Qt::WindowTitleHint)));
287         if (framelessWindow) {
288             if (m_windowClass == kDocumentWindowClass) {
289                 m_windowAttributes |= kWindowNoTitleBarAttribute;
290             } else if (m_windowClass == kFloatingWindowClass) {
291                 m_windowAttributes |= kWindowNoTitleBarAttribute;
292             } else if (m_windowClass  == kMovableModalWindowClass) {
293                 m_windowClass = kModalWindowClass;
294             }
295         } else {
296             m_windowAttributes |= NSTitledWindowMask;
297             if (m_windowClass != kModalWindowClass)
298                 m_windowAttributes |= NSResizableWindowMask;
299         }
300
301         // Only add extra decorations (well, buttons) for widgets that can have them
302         // and have an actual border we can put them on.
303
304         if(m_windowClass != kModalWindowClass && m_windowClass != kMovableModalWindowClass
305                 && m_windowClass != kSheetWindowClass && m_windowClass != kPlainWindowClass
306                 && !framelessWindow && m_windowClass != kDrawerWindowClass
307                 && m_windowClass != kHelpWindowClass) {
308             if (flags & Qt::WindowMinimizeButtonHint)
309                 m_windowAttributes |= NSMiniaturizableWindowMask;
310             if (flags & Qt::WindowSystemMenuHint || flags & Qt::WindowCloseButtonHint)
311                 m_windowAttributes |= NSClosableWindowMask;
312         } else {
313             // Clear these hints so that we aren't call them on invalid windows
314             flags &= ~(Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint
315                        | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint);
316         }
317
318     }
319
320     if((popup || type == Qt::Tool) && !window()->isModal())
321         m_windowAttributes |= kWindowHideOnSuspendAttribute;
322     m_windowAttributes |= kWindowLiveResizeAttribute;
323 }
324
325 /*
326
327 */
328 NSWindow * QCocoaWindow::createWindow()
329 {
330     // Determine if we need to add in our "custom window" attribute. Cocoa is rather clever
331     // in deciding if we need the maximize button or not (i.e., it's resizable, so you
332     // must need a maximize button). So, the only buttons we have control over are the
333     // close and minimize buttons. If someone wants to customize and NOT have the maximize
334     // button, then we have to do our hack. We only do it for these cases because otherwise
335     // the window looks different when activated. This "QtMacCustomizeWindow" attribute is
336     // intruding on a public space and WILL BREAK in the future.
337     // One can hope that there is a more public API available by that time.
338 /*
339     Qt::WindowFlags flags = widget ? widget->windowFlags() : Qt::WindowFlags(0);
340     if ((flags & Qt::CustomizeWindowHint)) {
341         if ((flags & (Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint
342                       | Qt::WindowMinimizeButtonHint | Qt::WindowTitleHint))
343             && !(flags & Qt::WindowMaximizeButtonHint))
344             wattr |= QtMacCustomizeWindow;
345     }
346 */
347     NSRect frame = qt_mac_flipRect(window()->geometry(), window());
348     QCocoaAutoReleasePool pool;
349     NSWindow *window;
350
351     switch (m_windowClass) {
352     case kMovableModalWindowClass:
353     case kModalWindowClass:
354     case kSheetWindowClass:
355     case kFloatingWindowClass:
356     case kOverlayWindowClass:
357     case kHelpWindowClass: {
358         NSPanel *panel;
359
360         BOOL needFloating = NO;
361         //BOOL worksWhenModal = (this->window()->windowType() == Qt::Popup);
362
363         // Add in the extra flags if necessary.
364         switch (m_windowClass) {
365         case kSheetWindowClass:
366             m_windowAttributes |= NSDocModalWindowMask;
367             break;
368         case kFloatingWindowClass:
369         case kHelpWindowClass:
370             needFloating = YES;
371             m_windowAttributes |= NSUtilityWindowMask;
372             break;
373         default:
374             break;
375         }
376
377         panel = [[QNSPanel alloc] initWithContentRect:frame
378                                    styleMask:m_windowAttributes
379                                    backing:NSBackingStoreBuffered
380                                    defer:NO]; // see window case below
381 //  ### crashes
382 //        [panel setFloatingPanel:needFloating];
383 //        [panel setWorksWhenModal:worksWhenModal];
384         window = static_cast<NSWindow *>(panel);
385         break;
386     }
387     default:
388         window  = [[QNSWindow alloc] initWithContentRect:frame
389                                             styleMask:(NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask)
390                                             backing:NSBackingStoreBuffered
391                                             defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
392                                                        // before the window is shown and needs a proper window.).
393         break;
394     }
395
396     //qt_syncCocoaTitleBarButtons(window, widget);
397     return window;
398 }
399 // Returns the current global screen geometry for the nswindow associated with this window.
400 QRect QCocoaWindow::windowGeometry() const
401 {
402     NSRect rect = [m_nsWindow frame];
403     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
404     int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height;  // account for nswindow inverted y.
405     QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
406     return qRect;
407 }
408
409 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
410 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
411 {
412     if (window() && window()->transientParent()) {
413         return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
414     }
415     return 0;
416 }
417