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