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