Cocoa: support modal windows
[profile/ivi/qtbase.git] / src / plugins / platforms / cocoa / qcocoawindow.mm
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the plugins of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
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 "qcocoaeventdispatcher.h"
45 #include "qcocoaglcontext.h"
46 #include "qcocoahelpers.h"
47 #include "qnsview.h"
48 #include <QtCore/private/qcore_mac_p.h>
49 #include <qwindow.h>
50 #include <QWindowSystemInterface>
51 #include <QPlatformScreen>
52
53 #include <Cocoa/Cocoa.h>
54 #include <Carbon/Carbon.h>
55
56 #include <QDebug>
57
58 @implementation QNSWindow
59
60 - (BOOL)canBecomeKeyWindow
61 {
62     // The default implementation returns NO for title-bar less windows,
63     // override and return yes here to make sure popup windows such as
64     // the combobox popup can become the key window.
65     return YES;
66 }
67
68 - (BOOL)canBecomeMainWindow
69 {
70     BOOL canBecomeMain = YES; // By default, windows can become the main window
71
72     // Windows with a transient parent (such as combobox popup windows)
73     // cannot become the main window:
74     if (m_cocoaPlatformWindow->window()->transientParent())
75         canBecomeMain = NO;
76
77     return canBecomeMain;
78 }
79
80
81 @end
82
83 @implementation QNSPanel
84
85 - (BOOL)canBecomeKeyWindow
86 {
87     // Most panels can be come the key window. Exceptions are:
88     if (m_cocoaPlatformWindow->window()->windowType() == Qt::ToolTip)
89         return NO;
90     if (m_cocoaPlatformWindow->window()->windowType() == Qt::SplashScreen)
91         return NO;
92     return YES;
93 }
94
95 @end
96
97 QCocoaWindow::QCocoaWindow(QWindow *tlw)
98     : QPlatformWindow(tlw)
99     , m_nsWindow(0)
100     , m_inConstructor(true)
101     , m_glContext(0)
102     , m_hasModalSession(false)
103 {
104     QCocoaAutoReleasePool pool;
105
106     m_contentView = [[QNSView alloc] initWithQWindow:tlw platformWindow:this];
107     setGeometry(tlw->geometry());
108
109     recreateWindow(parent());
110
111     m_inConstructor = false;
112 }
113
114 QCocoaWindow::~QCocoaWindow()
115 {
116     clearNSWindow(m_nsWindow);
117     [m_contentView release];
118     [m_nsWindow release];
119 }
120
121 void QCocoaWindow::setGeometry(const QRect &rect)
122 {
123     if (geometry() == rect)
124         return;
125 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
126     qDebug() << "QCocoaWindow::setGeometry" << this << rect;
127 #endif
128     QPlatformWindow::setGeometry(rect);
129     setCocoaGeometry(rect);
130 }
131
132 void QCocoaWindow::setCocoaGeometry(const QRect &rect)
133 {
134     if (m_nsWindow) {
135         NSRect bounds = qt_mac_flipRect(rect, window());
136         [m_nsWindow setContentSize : bounds.size];
137         [m_nsWindow setFrameOrigin : bounds.origin];
138     } else {
139         [m_contentView setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
140     }
141 }
142
143 void QCocoaWindow::setVisible(bool visible)
144 {
145     QCocoaAutoReleasePool pool;
146 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
147     qDebug() << "QCocoaWindow::setVisible" << window() << visible;
148 #endif
149     if (visible) {
150         QCocoaWindow *parentCocoaWindow = 0;
151         if (window()->transientParent()) {
152             parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
153
154             // The parent window might have moved while this window was hidden,
155             // update the window geometry if there is a parent.
156             setGeometry(window()->geometry());
157
158             // Register popup windows so that the parent window can
159             // close them when needed.
160             if (window()->windowType() == Qt::Popup) {
161                 // qDebug() << "transientParent and popup" << window()->windowType() << Qt::Popup << (window()->windowType() & Qt::Popup);
162                 parentCocoaWindow->m_activePopupWindow = window();
163             }
164
165         }
166
167         // Make sure the QWindow has a frame ready before we show the NSWindow.
168         QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
169
170         if (m_nsWindow) {
171             // setWindowState might have been called while the window was hidden and
172             // will not change the NSWindow state in that case. Sync up here:
173             syncWindowState(window()->windowState());
174
175             if (window()->windowState() != Qt::WindowMinimized) {
176                 if ((window()->windowModality() == Qt::WindowModal
177                      || window()->windowType() == Qt::Sheet)
178                         && parentCocoaWindow) {
179                     // show the window as a sheet
180                     [NSApp beginSheet:m_nsWindow modalForWindow:parentCocoaWindow->m_nsWindow modalDelegate:nil didEndSelector:nil contextInfo:nil];
181                 } else if (window()->windowModality() != Qt::NonModal) {
182                     // show the window as application modal
183                     QCocoaEventDispatcher *cocoaEventDispatcher = qobject_cast<QCocoaEventDispatcher *>(QGuiApplication::instance()->eventDispatcher());
184                     Q_ASSERT(cocoaEventDispatcher != 0);
185                     QCocoaEventDispatcherPrivate *cocoaEventDispatcherPrivate = static_cast<QCocoaEventDispatcherPrivate *>(QObjectPrivate::get(cocoaEventDispatcher));
186                     cocoaEventDispatcherPrivate->beginModalSession(window());
187                     m_hasModalSession = true;
188                 } else if ([m_nsWindow canBecomeKeyWindow]) {
189                     [m_nsWindow makeKeyAndOrderFront:nil];
190                 } else {
191                     [m_nsWindow orderFront: nil];
192                 }
193             }
194         }
195     } else {
196         // qDebug() << "close" << this;
197         if (m_nsWindow) {
198             if (m_hasModalSession) {
199                 QCocoaEventDispatcher *cocoaEventDispatcher = qobject_cast<QCocoaEventDispatcher *>(QGuiApplication::instance()->eventDispatcher());
200                 Q_ASSERT(cocoaEventDispatcher != 0);
201                 QCocoaEventDispatcherPrivate *cocoaEventDispatcherPrivate = static_cast<QCocoaEventDispatcherPrivate *>(QObjectPrivate::get(cocoaEventDispatcher));
202                 cocoaEventDispatcherPrivate->endModalSession(window());
203                 m_hasModalSession = false;
204             } else {
205                 if ([m_nsWindow isSheet])
206                     [NSApp endSheet:m_nsWindow];
207             }
208             [m_nsWindow orderOut:m_nsWindow];
209         }
210         if (!QCoreApplication::closingDown())
211             QWindowSystemInterface::handleExposeEvent(window(), QRegion());
212     }
213 }
214
215 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
216 {
217     m_windowFlags = flags;
218     return m_windowFlags;
219 }
220
221 Qt::WindowState QCocoaWindow::setWindowState(Qt::WindowState state)
222 {
223     if ([m_nsWindow isVisible])
224         syncWindowState(state);  // Window state set for hidden windows take effect when show() is called.
225
226     return state;
227 }
228
229 void QCocoaWindow::setWindowTitle(const QString &title)
230 {
231     QCocoaAutoReleasePool pool;
232     if (!m_nsWindow)
233         return;
234
235     CFStringRef windowTitle = QCFString::toCFStringRef(title);
236     [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
237     CFRelease(windowTitle);
238 }
239
240 void QCocoaWindow::raise()
241 {
242     //qDebug() << "raise" << this;
243     // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
244     if (!m_nsWindow)
245         return;
246     if ([m_nsWindow isVisible])
247         [m_nsWindow orderFront: m_nsWindow];
248 }
249
250 void QCocoaWindow::lower()
251 {
252     if (!m_nsWindow)
253         return;
254     if ([m_nsWindow isVisible])
255         [m_nsWindow orderBack: m_nsWindow];
256 }
257
258 void QCocoaWindow::propagateSizeHints()
259 {
260     QCocoaAutoReleasePool pool;
261     if (!m_nsWindow)
262         return;
263
264     [m_nsWindow setMinSize : qt_mac_toNSSize(window()->minimumSize())];
265     [m_nsWindow setMaxSize : qt_mac_toNSSize(window()->maximumSize())];
266
267 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
268     qDebug() << "QCocoaWindow::propagateSizeHints" << this;
269     qDebug() << "     min/max " << window()->minimumSize() << window()->maximumSize();
270     qDebug() << "     basesize" << window()->baseSize();
271     qDebug() << "     geometry" << geometry();
272 #endif
273
274     if (!window()->sizeIncrement().isNull())
275         [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
276
277     QRect rect = geometry();
278     QSize baseSize = window()->baseSize();
279     if (!baseSize.isNull() && baseSize.isValid()) {
280         [m_nsWindow setFrame:NSMakeRect(rect.x(), rect.y(), baseSize.width(), baseSize.height()) display:YES];
281     }
282 }
283
284 void QCocoaWindow::setOpacity(qreal level)
285 {
286     if (m_nsWindow)
287         [m_nsWindow setAlphaValue:level];
288 }
289
290 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
291 {
292     if (!m_nsWindow)
293         return false;
294
295     if (grab && ![m_nsWindow isKeyWindow])
296         [m_nsWindow makeKeyWindow];
297     else if (!grab && [m_nsWindow isKeyWindow])
298         [m_nsWindow resignKeyWindow];
299     return true;
300 }
301
302 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
303 {
304     if (!m_nsWindow)
305         return false;
306
307     if (grab && ![m_nsWindow isKeyWindow])
308         [m_nsWindow makeKeyWindow];
309     else if (!grab && [m_nsWindow isKeyWindow])
310         [m_nsWindow resignKeyWindow];
311     return true;
312 }
313
314 WId QCocoaWindow::winId() const
315 {
316     return WId(m_contentView);
317 }
318
319 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
320 {
321     // recreate the window for compatibility
322     recreateWindow(parentWindow);
323     setCocoaGeometry(geometry());
324 }
325
326 NSView *QCocoaWindow::contentView() const
327 {
328     return m_contentView;
329 }
330
331 void QCocoaWindow::windowWillMove()
332 {
333     // Close any open popups on window move
334     if (m_activePopupWindow) {
335         QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
336         m_activePopupWindow = 0;
337     }
338 }
339
340 void QCocoaWindow::windowDidMove()
341 {
342     [m_contentView updateGeometry];
343 }
344
345 void QCocoaWindow::windowDidResize()
346 {
347     if (!m_nsWindow)
348         return;
349
350     NSRect rect = [[m_nsWindow contentView]frame];
351     // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
352     [[m_nsWindow contentView] setFrameSize:rect.size];
353 }
354
355 void QCocoaWindow::windowWillClose()
356 {
357     QWindowSystemInterface::handleSynchronousCloseEvent(window());
358 }
359
360 bool QCocoaWindow::windowIsPopupType() const
361 {
362     Qt::WindowType type = window()->windowType();
363     if (type == Qt::Tool)
364         return false; // Qt::Tool has the Popup bit set but isn't, at least on Mac.
365
366     return ((type & Qt::Popup) == Qt::Popup);
367 }
368
369 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
370 {
371     m_glContext = context;
372 }
373
374 QCocoaGLContext *QCocoaWindow::currentContext() const
375 {
376     return m_glContext;
377 }
378
379 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
380 {
381     // Remove current window (if any)
382     if (m_nsWindow) {
383         clearNSWindow(m_nsWindow);
384         [m_nsWindow close];
385         [m_nsWindow release];
386         m_nsWindow = 0;
387     }
388
389     if (!parentWindow) {
390         // Create a new NSWindow if this is a top-level window.
391         m_nsWindow = createNSWindow();
392         setNSWindow(m_nsWindow);
393
394         if (window()->transientParent()) {
395             // keep this window on the same level as its transient parent (which may be a modal dialog, for example)
396             QCocoaWindow *parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
397             [m_nsWindow setLevel:[parentCocoaWindow->m_nsWindow level]];
398         }
399     } else {
400         // Child windows have no NSWindow, link the NSViews instead.
401         const QCocoaWindow *parentCococaWindow = static_cast<const QCocoaWindow *>(parentWindow);
402         [parentCococaWindow->m_contentView addSubview : m_contentView];
403     }
404 }
405
406 NSWindow * QCocoaWindow::createNSWindow()
407 {
408     QCocoaAutoReleasePool pool;
409
410     NSRect frame = qt_mac_flipRect(window()->geometry(), window());
411
412     Qt::WindowType type = window()->windowType();
413     Qt::WindowFlags flags = window()->windowFlags();
414
415     NSUInteger styleMask;
416     NSWindow *createdWindow = 0;
417     NSInteger windowLevel = -1;
418
419     if (type == Qt::Tool) {
420         windowLevel = NSFloatingWindowLevel;
421     } else if ((type & Qt::Popup) == Qt::Popup) {
422         // styleMask = NSBorderlessWindowMask;
423         windowLevel = NSPopUpMenuWindowLevel;
424
425         // Popup should be in at least the same level as its parent.
426         const QWindow * const transientParent = window()->transientParent();
427         const QCocoaWindow * const transientParentWindow = transientParent ? static_cast<QCocoaWindow *>(transientParent->handle()) : 0;
428         if (transientParentWindow)
429             windowLevel = qMax([transientParentWindow->m_nsWindow level], windowLevel);
430     }
431
432     // StayOnTop window should appear above Tool windows.
433     if (flags & Qt::WindowStaysOnTopHint)
434         windowLevel = NSPopUpMenuWindowLevel;
435     // Tooltips should appear above StayOnTop windows.
436     if (type == Qt::ToolTip)
437         windowLevel = NSScreenSaverWindowLevel;
438     // All other types are Normal level.
439     if (windowLevel == -1)
440         windowLevel = NSNormalWindowLevel;
441
442     // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
443     if ((type & Qt::Popup) == Qt::Popup) {
444         if (windowIsPopupType()) {
445             styleMask = NSBorderlessWindowMask;
446         } else {
447             styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
448                          NSMiniaturizableWindowMask | NSTitledWindowMask);
449         }
450
451         QNSPanel *window;
452         window  = [[QNSPanel alloc] initWithContentRect:frame
453                                          styleMask: styleMask
454                                          backing:NSBackingStoreBuffered
455                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
456                                                     // before the window is shown and needs a proper window.).
457         [window setHasShadow:YES];
458         window->m_cocoaPlatformWindow = this;
459         createdWindow = window;
460     } else {
461         styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
462         QNSWindow *window;
463         window  = [[QNSWindow alloc] initWithContentRect:frame
464                                          styleMask: styleMask
465                                          backing:NSBackingStoreBuffered
466                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
467                                                     // before the window is shown and needs a proper window.).
468         window->m_cocoaPlatformWindow = this;
469
470 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
471     if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
472         // All windows with the WindowMaximizeButtonHint set also get a full-screen button.
473         if (flags & Qt::WindowMaximizeButtonHint)
474             [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
475     }
476 #endif
477
478         createdWindow = window;
479     }
480
481     [createdWindow setLevel:windowLevel];
482
483     return createdWindow;
484 }
485
486 void QCocoaWindow::setNSWindow(NSWindow *window)
487 {
488     QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
489     [window setDelegate:delegate];
490     [window setAcceptsMouseMovedEvents:YES];
491
492     // Prevent Cocoa from releasing the window on close. Qt
493     // handles the close event asynchronously and we want to
494     // make sure that m_nsWindow stays valid until the
495     // QCocoaWindow is deleted by Qt.
496     [window setReleasedWhenClosed : NO];
497
498
499     [[NSNotificationCenter defaultCenter] addObserver:m_contentView
500                                           selector:@selector(windowNotification:)
501                                           name:nil // Get all notifications
502                                           object:m_nsWindow];
503
504     // ### Accept touch events by default.
505     // Beware that enabling touch events has a negative impact on the overall performance.
506     // We probably need a QWindowSystemInterface API to enable/disable touch events.
507     [m_contentView setAcceptsTouchEvents:YES];
508
509     [window setContentView:m_contentView];
510 }
511
512 void QCocoaWindow::clearNSWindow(NSWindow *window)
513 {
514     [window setDelegate:nil];
515     [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
516 }
517
518 // Returns the current global screen geometry for the nswindow associated with this window.
519 QRect QCocoaWindow::windowGeometry() const
520 {
521     if (!m_nsWindow)
522         return geometry();
523
524     NSRect rect = [m_nsWindow frame];
525     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
526     int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height;  // account for nswindow inverted y.
527     QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
528     return qRect;
529 }
530
531 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
532 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
533 {
534     if (window() && window()->transientParent()) {
535         return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
536     }
537     return 0;
538 }
539
540 // Syncs the NSWindow minimize/maximize/fullscreen state with the current QWindow state
541 void QCocoaWindow::syncWindowState(Qt::WindowState newState)
542 {
543     if (!m_nsWindow)
544         return;
545
546     switch (newState) {
547         case Qt::WindowMinimized:
548             [m_nsWindow performMiniaturize : m_nsWindow];
549         break;
550         case Qt::WindowMaximized:
551             [m_nsWindow performZoom : m_nsWindow];
552         break;
553         case Qt::WindowFullScreen:
554 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
555             if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
556                 [m_nsWindow toggleFullScreen : m_nsWindow];
557             } else {
558                 qWarning("Not implemented: setWindowState WindowFullScreen");
559             }
560 #endif
561         break;
562
563         default:
564             // Undo current states
565             if ([m_nsWindow isMiniaturized])
566                 [m_nsWindow deminiaturize : m_nsWindow];
567
568             if ([m_nsWindow isZoomed])
569                 [m_nsWindow performZoom : m_nsWindow]; // toggles
570
571 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
572             if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
573                 if (window()->windowState() & Qt::WindowFullScreen)
574                     [m_nsWindow toggleFullScreen : m_nsWindow];
575             } else {
576                 qWarning("Not implemented: setWindowState WindowFullScreen");
577             }
578 #endif
579         break;
580     }
581 }
582
583 bool QCocoaWindow::setWindowModified(bool modified)
584 {
585     if (!m_nsWindow)
586         return false;
587     [m_nsWindow setDocumentEdited:(modified?YES:NO)];
588     return true;
589 }