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