Cocoa: Update QPlatformWindow geometry on move
[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     setGeometry(geo);
177     QWindowSystemInterface::handleSynchronousGeometryChange(window(), geo);
178 }
179
180 void QCocoaWindow::windowDidResize()
181 {
182     if (m_glContext)
183         m_glContext->update();
184
185     NSRect rect = [[m_nsWindow contentView]frame];
186     NSRect windowRect = [m_nsWindow frame];
187
188     QRect geo(windowRect.origin.x, qt_mac_flipYCoordinate(windowRect.origin.y + rect.size.height), rect.size.width, rect.size.height);
189     setGeometry(geo);
190     QWindowSystemInterface::handleSynchronousGeometryChange(window(), geo);
191 }
192
193
194 void QCocoaWindow::windowWillClose()
195 {
196     QWindowSystemInterface::handleCloseEvent(window());
197 }
198
199 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
200 {
201     m_glContext = context;
202 }
203
204 QCocoaGLContext *QCocoaWindow::currentContext() const
205 {
206     return m_glContext;
207 }
208
209 /*
210     Determine the window class based on the window type and
211     window flags, and widget attr Sets m_windowAttributes
212     and m_windowClass.
213 */
214 void QCocoaWindow::determineWindowClass()
215 {
216     Qt::WindowType type = window()->windowType();
217     Qt::WindowFlags flags = window()->windowFlags();
218
219     const bool popup = (type == Qt::Popup);
220
221     if (type == Qt::ToolTip || type == Qt::SplashScreen || popup)
222         flags |= Qt::FramelessWindowHint;
223
224     m_windowClass = kSheetWindowClass;
225
226     if (popup || type == Qt::SplashScreen)
227         m_windowClass = kModalWindowClass;
228     else if (type == Qt::ToolTip)
229         m_windowClass = kHelpWindowClass;
230     else if (type == Qt::Tool)
231         m_windowClass = kFloatingWindowClass;
232     else
233         m_windowClass = kDocumentWindowClass;
234
235     m_windowAttributes = (kWindowCompositingAttribute | kWindowStandardHandlerAttribute);
236
237 //    if(qt_mac_is_macsheet(window())) {
238 //        m_windowClass = kSheetWindowClass;
239 //    } else
240
241     {
242         // Shift things around a bit to get the correct window class based on the presence
243         // (or lack) of the border.
244
245         bool customize = flags & Qt::CustomizeWindowHint;
246         bool framelessWindow = (flags & Qt::FramelessWindowHint || (customize && !(flags & Qt::WindowTitleHint)));
247         if (framelessWindow) {
248             if (m_windowClass == kDocumentWindowClass) {
249                 m_windowAttributes |= kWindowNoTitleBarAttribute;
250             } else if (m_windowClass == kFloatingWindowClass) {
251                 m_windowAttributes |= kWindowNoTitleBarAttribute;
252             } else if (m_windowClass  == kMovableModalWindowClass) {
253                 m_windowClass = kModalWindowClass;
254             }
255         } else {
256             m_windowAttributes |= NSTitledWindowMask;
257             if (m_windowClass != kModalWindowClass)
258                 m_windowAttributes |= NSResizableWindowMask;
259         }
260
261         // Only add extra decorations (well, buttons) for widgets that can have them
262         // and have an actual border we can put them on.
263
264         if(m_windowClass != kModalWindowClass && m_windowClass != kMovableModalWindowClass
265                 && m_windowClass != kSheetWindowClass && m_windowClass != kPlainWindowClass
266                 && !framelessWindow && m_windowClass != kDrawerWindowClass
267                 && m_windowClass != kHelpWindowClass) {
268             if (flags & Qt::WindowMinimizeButtonHint)
269                 m_windowAttributes |= NSMiniaturizableWindowMask;
270             if (flags & Qt::WindowSystemMenuHint || flags & Qt::WindowCloseButtonHint)
271                 m_windowAttributes |= NSClosableWindowMask;
272         } else {
273             // Clear these hints so that we aren't call them on invalid windows
274             flags &= ~(Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint
275                        | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint);
276         }
277
278     }
279
280     if((popup || type == Qt::Tool) && !window()->isModal())
281         m_windowAttributes |= kWindowHideOnSuspendAttribute;
282     m_windowAttributes |= kWindowLiveResizeAttribute;
283 }
284
285 /*
286
287 */
288 QNSWindow * QCocoaWindow::createWindow()
289 {
290     // Determine if we need to add in our "custom window" attribute. Cocoa is rather clever
291     // in deciding if we need the maximize button or not (i.e., it's resizable, so you
292     // must need a maximize button). So, the only buttons we have control over are the
293     // close and minimize buttons. If someone wants to customize and NOT have the maximize
294     // button, then we have to do our hack. We only do it for these cases because otherwise
295     // the window looks different when activated. This "QtMacCustomizeWindow" attribute is
296     // intruding on a public space and WILL BREAK in the future.
297     // One can hope that there is a more public API available by that time.
298 /*
299     Qt::WindowFlags flags = widget ? widget->windowFlags() : Qt::WindowFlags(0);
300     if ((flags & Qt::CustomizeWindowHint)) {
301         if ((flags & (Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint
302                       | Qt::WindowMinimizeButtonHint | Qt::WindowTitleHint))
303             && !(flags & Qt::WindowMaximizeButtonHint))
304             wattr |= QtMacCustomizeWindow;
305     }
306 */
307     NSRect frame = globalGeometry(window()->geometry());
308     QCocoaAutoReleasePool pool;
309     QNSWindow *window;
310
311     switch (m_windowClass) {
312     case kMovableModalWindowClass:
313     case kModalWindowClass:
314     case kSheetWindowClass:
315     case kFloatingWindowClass:
316     case kOverlayWindowClass:
317     case kHelpWindowClass: {
318         NSPanel *panel;
319
320         BOOL needFloating = NO;
321         BOOL worksWhenModal = (this->window()->windowType() == Qt::Popup);
322
323         // Add in the extra flags if necessary.
324         switch (m_windowClass) {
325         case kSheetWindowClass:
326             m_windowAttributes |= NSDocModalWindowMask;
327             break;
328         case kFloatingWindowClass:
329         case kHelpWindowClass:
330             needFloating = YES;
331             m_windowAttributes |= NSUtilityWindowMask;
332             break;
333         default:
334             break;
335         }
336
337         panel = [[NSPanel alloc] initWithContentRect:frame
338                                    styleMask:m_windowAttributes
339                                    backing:NSBackingStoreBuffered
340                                    defer:NO]; // see window case below
341 //  ### crashes
342 //        [panel setFloatingPanel:needFloating];
343 //        [panel setWorksWhenModal:worksWhenModal];
344         window = static_cast<NSWindow *>(panel);
345         break;
346     }
347     default:
348         window  = [[QNSWindow alloc] initWithContentRect:frame
349                                             styleMask:(NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask)
350                                             backing:NSBackingStoreBuffered
351                                             defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
352                                                        // before the window is shown and needs a proper window.).
353         break;
354     }
355
356     //qt_syncCocoaTitleBarButtons(window, widget);
357     return window;
358 }
359
360 // Calculate the global screen geometry for the given local geometry, which
361 // might be in the parent window coordinate system.
362 NSRect QCocoaWindow::globalGeometry(const QRect localGeometry) const
363 {
364     QRect finalGeometry = localGeometry;
365
366     if (QCocoaWindow *parent = parentCocoaWindow()) {
367         QRect parentGeometry = parent->windowGeometry();
368         finalGeometry.adjust(parentGeometry.x(), parentGeometry.y(), parentGeometry.x(), parentGeometry.y());
369
370         // Qt child window geometry assumes that the origin is at the
371         // top-left of the content area of the parent window. The title
372         // bar is not a part of this content area, but is still included
373         // in the NSWindow height. Move the child window down to account
374         // for this if the parent window has a title bar.
375         const int titlebarHeight = 22;
376         if (!(window()->windowFlags() & Qt::FramelessWindowHint))
377             finalGeometry.adjust(0, titlebarHeight, 0, titlebarHeight);
378     }
379
380     // The final "y invert" to get OS X global geometry:
381     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
382     int flippedY = onScreen->geometry().height() - finalGeometry.y() - finalGeometry.height();
383     return NSMakeRect(finalGeometry.x(), flippedY, finalGeometry.width(), finalGeometry.height());
384 }
385
386 // Returns the current global screen geometry for the nswindow associated with this window.
387 QRect QCocoaWindow::windowGeometry() const
388 {
389     NSRect rect = [m_nsWindow frame];
390     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
391     int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height;  // account for nswindow inverted y.
392     QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
393     return qRect;
394 }
395
396 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
397 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
398 {
399     if (window() && window()->transientParent()) {
400         return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
401     }
402     return 0;
403 }
404