Merge branch 'master' into refactor
[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 "qnsview.h"
46 #include <QtCore/private/qcore_mac_p.h>
47 #include <qwindow.h>
48 #include <QWindowSystemInterface>
49 #include <QPlatformScreen>
50
51 #include <Cocoa/Cocoa.h>
52 #include <Carbon/Carbon.h>
53
54 #include <QDebug>
55
56 @implementation QNSWindow
57
58 - (BOOL)canBecomeKeyWindow
59 {
60     return YES;
61 }
62
63 - (BOOL)canBecomeMainWindow
64 {
65     return YES;
66 }
67
68 @end
69
70 QCocoaWindow::QCocoaWindow(QWindow *tlw)
71     : QPlatformWindow(tlw)
72     , m_windowAttributes(0)
73     , m_windowClass(0)
74     , m_glContext(0)
75 {
76     QCocoaAutoReleasePool pool;
77
78     determineWindowClass();
79     m_nsWindow = createWindow();
80
81     QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
82     [m_nsWindow setDelegate:delegate];
83     [m_nsWindow setAcceptsMouseMovedEvents:YES];
84
85     // Prevent Cocoa from releasing the window on close. Qt
86     // handles the close event asynchronously and we want to
87     // make sure that m_nsWindow stays valid until the
88     // QCocoaWindow is deleted by Qt.
89     [m_nsWindow setReleasedWhenClosed : NO];
90
91     m_contentView = [[QNSView alloc] initWithQWindow:tlw];
92
93     setGeometry(tlw->geometry());
94
95     [m_nsWindow setContentView:m_contentView];
96 }
97
98 QCocoaWindow::~QCocoaWindow()
99 {
100     [m_nsWindow release];
101 }
102
103 void QCocoaWindow::setGeometry(const QRect &rect)
104 {
105     QPlatformWindow::setGeometry(rect);
106
107     NSRect bounds = globalGeometry(rect);
108     [[m_nsWindow contentView]setFrameSize:bounds.size];
109     [m_nsWindow setContentSize : bounds.size];
110     [m_nsWindow setFrameOrigin : bounds.origin];
111
112     if (m_glContext)
113         m_glContext->update();
114 }
115
116 void QCocoaWindow::setVisible(bool visible)
117 {
118     if (visible) {
119         // The parent window might have moved while this window was hidden,
120         // update the window geometry if there is a parent.
121         if (window()->transientParent())
122             setGeometry(window()->geometry());
123
124         // Make sure the QWindow has a frame ready before we show the NSWindow.
125         QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
126
127         [m_nsWindow makeKeyAndOrderFront:nil];
128     } else {
129         [m_nsWindow orderOut:nil];
130     }
131 }
132
133 void QCocoaWindow::setWindowTitle(const QString &title)
134 {
135     CFStringRef windowTitle = QCFString::toCFStringRef(title);
136     [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
137     CFRelease(windowTitle);
138 }
139
140 void QCocoaWindow::raise()
141 {
142     // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
143     [m_nsWindow orderFront: m_nsWindow];
144 }
145
146 void QCocoaWindow::lower()
147 {
148     [m_nsWindow orderFront: m_nsWindow];
149 }
150
151 WId QCocoaWindow::winId() const
152 {
153     return WId(m_nsWindow);
154 }
155
156 NSView *QCocoaWindow::contentView() const
157 {
158     return [m_nsWindow contentView];
159 }
160
161 void QCocoaWindow::windowDidMove()
162 {
163     if (m_glContext)
164         m_glContext->update();
165 }
166
167 void QCocoaWindow::windowDidResize()
168 {
169     if (m_glContext)
170         m_glContext->update();
171
172     NSRect rect = [[m_nsWindow contentView]frame];
173     QRect geo(rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
174     QWindowSystemInterface::handleSynchronousGeometryChange(window(), geo);
175 }
176
177
178 void QCocoaWindow::windowWillClose()
179 {
180     QWindowSystemInterface::handleCloseEvent(window());
181 }
182
183 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
184 {
185     m_glContext = context;
186 }
187
188 QCocoaGLContext *QCocoaWindow::currentContext() const
189 {
190     return m_glContext;
191 }
192
193 /*
194     Determine the window class based on the window type and
195     window flags, and widget attr Sets m_windowAttributes
196     and m_windowClass.
197 */
198 void QCocoaWindow::determineWindowClass()
199 {
200     Qt::WindowType type = window()->windowType();
201     Qt::WindowFlags flags = window()->windowFlags();
202
203     const bool popup = (type == Qt::Popup);
204
205     if (type == Qt::ToolTip || type == Qt::SplashScreen || popup)
206         flags |= Qt::FramelessWindowHint;
207
208     m_windowClass = kSheetWindowClass;
209
210     if (popup || type == Qt::SplashScreen)
211         m_windowClass = kModalWindowClass;
212     else if (type == Qt::ToolTip)
213         m_windowClass = kHelpWindowClass;
214     else if (type == Qt::Tool)
215         m_windowClass = kFloatingWindowClass;
216     else
217         m_windowClass = kDocumentWindowClass;
218
219     m_windowAttributes = (kWindowCompositingAttribute | kWindowStandardHandlerAttribute);
220
221 //    if(qt_mac_is_macsheet(window())) {
222 //        m_windowClass = kSheetWindowClass;
223 //    } else
224
225     {
226         // Shift things around a bit to get the correct window class based on the presence
227         // (or lack) of the border.
228
229         bool customize = flags & Qt::CustomizeWindowHint;
230         bool framelessWindow = (flags & Qt::FramelessWindowHint || (customize && !(flags & Qt::WindowTitleHint)));
231         if (framelessWindow) {
232             if (m_windowClass == kDocumentWindowClass) {
233                 m_windowAttributes |= kWindowNoTitleBarAttribute;
234             } else if (m_windowClass == kFloatingWindowClass) {
235                 m_windowAttributes |= kWindowNoTitleBarAttribute;
236             } else if (m_windowClass  == kMovableModalWindowClass) {
237                 m_windowClass = kModalWindowClass;
238             }
239         } else {
240             m_windowAttributes |= NSTitledWindowMask;
241             if (m_windowClass != kModalWindowClass)
242                 m_windowAttributes |= NSResizableWindowMask;
243         }
244
245         // Only add extra decorations (well, buttons) for widgets that can have them
246         // and have an actual border we can put them on.
247
248         if(m_windowClass != kModalWindowClass && m_windowClass != kMovableModalWindowClass
249                 && m_windowClass != kSheetWindowClass && m_windowClass != kPlainWindowClass
250                 && !framelessWindow && m_windowClass != kDrawerWindowClass
251                 && m_windowClass != kHelpWindowClass) {
252             if (flags & Qt::WindowMinimizeButtonHint)
253                 m_windowAttributes |= NSMiniaturizableWindowMask;
254             if (flags & Qt::WindowSystemMenuHint || flags & Qt::WindowCloseButtonHint)
255                 m_windowAttributes |= NSClosableWindowMask;
256         } else {
257             // Clear these hints so that we aren't call them on invalid windows
258             flags &= ~(Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint
259                        | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint);
260         }
261
262     }
263
264     if((popup || type == Qt::Tool) && !window()->isModal())
265         m_windowAttributes |= kWindowHideOnSuspendAttribute;
266     m_windowAttributes |= kWindowLiveResizeAttribute;
267 }
268
269 /*
270
271 */
272 QNSWindow * QCocoaWindow::createWindow()
273 {
274     // Determine if we need to add in our "custom window" attribute. Cocoa is rather clever
275     // in deciding if we need the maximize button or not (i.e., it's resizeable, so you
276     // must need a maximize button). So, the only buttons we have control over are the
277     // close and minimize buttons. If someone wants to customize and NOT have the maximize
278     // button, then we have to do our hack. We only do it for these cases because otherwise
279     // the window looks different when activated. This "QtMacCustomizeWindow" attribute is
280     // intruding on a public space and WILL BREAK in the future.
281     // One can hope that there is a more public API available by that time.
282 /*
283     Qt::WindowFlags flags = widget ? widget->windowFlags() : Qt::WindowFlags(0);
284     if ((flags & Qt::CustomizeWindowHint)) {
285         if ((flags & (Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint
286                       | Qt::WindowMinimizeButtonHint | Qt::WindowTitleHint))
287             && !(flags & Qt::WindowMaximizeButtonHint))
288             wattr |= QtMacCustomizeWindow;
289     }
290 */
291     NSRect frame = globalGeometry(window()->geometry());
292     QCocoaAutoReleasePool pool;
293     QNSWindow *window;
294
295     switch (m_windowClass) {
296     case kMovableModalWindowClass:
297     case kModalWindowClass:
298     case kSheetWindowClass:
299     case kFloatingWindowClass:
300     case kOverlayWindowClass:
301     case kHelpWindowClass: {
302         NSPanel *panel;
303
304         BOOL needFloating = NO;
305         BOOL worksWhenModal = (this->window()->windowType() == Qt::Popup);
306
307         // Add in the extra flags if necessary.
308         switch (m_windowClass) {
309         case kSheetWindowClass:
310             m_windowAttributes |= NSDocModalWindowMask;
311             break;
312         case kFloatingWindowClass:
313         case kHelpWindowClass:
314             needFloating = YES;
315             m_windowAttributes |= NSUtilityWindowMask;
316             break;
317         default:
318             break;
319         }
320
321         panel = [[NSPanel alloc] initWithContentRect:frame
322                                    styleMask:m_windowAttributes
323                                    backing:NSBackingStoreBuffered
324                                    defer:NO]; // see window case below
325 //  ### crashes
326 //        [panel setFloatingPanel:needFloating];
327 //        [panel setWorksWhenModal:worksWhenModal];
328         window = static_cast<NSWindow *>(panel);
329         break;
330     }
331     default:
332         window  = [[QNSWindow alloc] initWithContentRect:frame
333                                             styleMask:(NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask)
334                                             backing:NSBackingStoreBuffered
335                                             defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
336                                                        // before the window is shown and needs a proper window.).
337         break;
338     }
339
340     //qt_syncCocoaTitleBarButtons(window, widget);
341     return window;
342 }
343
344 // Calculate the global screen geometry for the given local geometry, which
345 // might be in the parent window coordinate system.
346 NSRect QCocoaWindow::globalGeometry(const QRect localGeometry) const
347 {
348     QRect finalGeometry = localGeometry;
349
350     if (QCocoaWindow *parent = parentCocoaWindow()) {
351         QRect parentGeometry = parent->windowGeometry();
352         finalGeometry.adjust(parentGeometry.x(), parentGeometry.y(), parentGeometry.x(), parentGeometry.y());
353
354         // Qt child window geometry assumes that the origin is at the
355         // top-left of the content area of the parent window. The title
356         // bar is not a part of this contet area, but is still included
357         // in the NSWindow height. Move the child window down to acccount
358         // for this if the parent window has a title bar.
359         const int titlebarHeight = 22;
360         if (!(window()->windowFlags() & Qt::FramelessWindowHint))
361             finalGeometry.adjust(0, titlebarHeight, 0, titlebarHeight);
362     }
363
364     // The final "y invert" to get OS X global geometry:
365     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
366     int flippedY = onScreen->geometry().height() - finalGeometry.y() - finalGeometry.height();
367     return NSMakeRect(finalGeometry.x(), flippedY, finalGeometry.width(), finalGeometry.height());
368 }
369
370 // Returns the current global screen geometry for the nswindow accociated with this window.
371 QRect QCocoaWindow::windowGeometry() const
372 {
373     NSRect rect = [m_nsWindow frame];
374     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
375     int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height;  // account for nswindow inverted y.
376     QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
377     return qRect;
378 }
379
380 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
381 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
382 {
383     if (window() && window()->transientParent()) {
384         return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
385     }
386     return 0;
387 }
388