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