Make popup windows show on the correct desktop.
[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 <qpa/qplatformscreen.h>
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_synchedWindowState(Qt::WindowActive)
101     , m_inConstructor(true)
102     , m_glContext(0)
103     , m_menubar(0)
104     , m_hasModalSession(false)
105 {
106 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
107     qDebug() << "QCocoaWindow::QCocoaWindow" << this;
108 #endif
109     QCocoaAutoReleasePool pool;
110
111     m_contentView = [[QNSView alloc] initWithQWindow:tlw platformWindow:this];
112     setGeometry(tlw->geometry());
113
114     recreateWindow(parent());
115
116     m_inConstructor = false;
117 }
118
119 QCocoaWindow::~QCocoaWindow()
120 {
121     clearNSWindow(m_nsWindow);
122     [m_contentView release];
123     [m_nsWindow release];
124 }
125
126 void QCocoaWindow::setGeometry(const QRect &rect)
127 {
128     if (geometry() == rect)
129         return;
130 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
131     qDebug() << "QCocoaWindow::setGeometry" << this << rect;
132 #endif
133     QPlatformWindow::setGeometry(rect);
134     setCocoaGeometry(rect);
135 }
136
137 void QCocoaWindow::setCocoaGeometry(const QRect &rect)
138 {
139     if (m_nsWindow) {
140         NSRect bounds = qt_mac_flipRect(rect, window());
141         [m_nsWindow setContentSize : bounds.size];
142         [m_nsWindow setFrameOrigin : bounds.origin];
143     } else {
144         [m_contentView setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
145     }
146 }
147
148 void QCocoaWindow::setVisible(bool visible)
149 {
150     QCocoaAutoReleasePool pool;
151 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
152     qDebug() << "QCocoaWindow::setVisible" << window() << visible;
153 #endif
154     if (visible) {
155         QCocoaWindow *parentCocoaWindow = 0;
156         if (window()->transientParent()) {
157             parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
158
159             // The parent window might have moved while this window was hidden,
160             // update the window geometry if there is a parent.
161             setGeometry(window()->geometry());
162
163             // Register popup windows so that the parent window can
164             // close them when needed.
165             if (window()->windowType() == Qt::Popup) {
166                 // qDebug() << "transientParent and popup" << window()->windowType() << Qt::Popup << (window()->windowType() & Qt::Popup);
167                 parentCocoaWindow->m_activePopupWindow = window();
168             }
169
170         }
171
172         // Make sure the QWindow has a frame ready before we show the NSWindow.
173         QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
174
175         if (m_nsWindow) {
176             // setWindowState might have been called while the window was hidden and
177             // will not change the NSWindow state in that case. Sync up here:
178             syncWindowState(window()->windowState());
179
180             if (window()->windowState() != Qt::WindowMinimized) {
181                 if ((window()->windowModality() == Qt::WindowModal
182                      || window()->windowType() == Qt::Sheet)
183                         && parentCocoaWindow) {
184                     // show the window as a sheet
185                     [NSApp beginSheet:m_nsWindow modalForWindow:parentCocoaWindow->m_nsWindow modalDelegate:nil didEndSelector:nil contextInfo:nil];
186                 } else if (window()->windowModality() != Qt::NonModal) {
187                     // show the window as application modal
188                     QCocoaEventDispatcher *cocoaEventDispatcher = qobject_cast<QCocoaEventDispatcher *>(QGuiApplication::instance()->eventDispatcher());
189                     Q_ASSERT(cocoaEventDispatcher != 0);
190                     QCocoaEventDispatcherPrivate *cocoaEventDispatcherPrivate = static_cast<QCocoaEventDispatcherPrivate *>(QObjectPrivate::get(cocoaEventDispatcher));
191                     cocoaEventDispatcherPrivate->beginModalSession(window());
192                     m_hasModalSession = true;
193                 } else if ([m_nsWindow canBecomeKeyWindow]) {
194                     [m_nsWindow makeKeyAndOrderFront:nil];
195                 } else {
196                     [m_nsWindow orderFront: nil];
197                 }
198             }
199         }
200     } else {
201         // qDebug() << "close" << this;
202         if (m_nsWindow) {
203             if (m_hasModalSession) {
204                 QCocoaEventDispatcher *cocoaEventDispatcher = qobject_cast<QCocoaEventDispatcher *>(QGuiApplication::instance()->eventDispatcher());
205                 Q_ASSERT(cocoaEventDispatcher != 0);
206                 QCocoaEventDispatcherPrivate *cocoaEventDispatcherPrivate = static_cast<QCocoaEventDispatcherPrivate *>(QObjectPrivate::get(cocoaEventDispatcher));
207                 cocoaEventDispatcherPrivate->endModalSession(window());
208                 m_hasModalSession = false;
209             } else {
210                 if ([m_nsWindow isSheet])
211                     [NSApp endSheet:m_nsWindow];
212             }
213             [m_nsWindow orderOut:m_nsWindow];
214         }
215         if (!QCoreApplication::closingDown())
216             QWindowSystemInterface::handleExposeEvent(window(), QRegion());
217     }
218 }
219
220 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
221 {
222     m_windowFlags = flags;
223     return m_windowFlags;
224 }
225
226 Qt::WindowState QCocoaWindow::setWindowState(Qt::WindowState state)
227 {
228     if ([m_nsWindow isVisible])
229         syncWindowState(state);  // Window state set for hidden windows take effect when show() is called.
230
231     return state;
232 }
233
234 void QCocoaWindow::setWindowTitle(const QString &title)
235 {
236     QCocoaAutoReleasePool pool;
237     if (!m_nsWindow)
238         return;
239
240     CFStringRef windowTitle = QCFString::toCFStringRef(title);
241     [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
242     CFRelease(windowTitle);
243 }
244
245 void QCocoaWindow::raise()
246 {
247     //qDebug() << "raise" << this;
248     // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
249     if (!m_nsWindow)
250         return;
251     if ([m_nsWindow isVisible])
252         [m_nsWindow orderFront: m_nsWindow];
253 }
254
255 void QCocoaWindow::lower()
256 {
257     if (!m_nsWindow)
258         return;
259     if ([m_nsWindow isVisible])
260         [m_nsWindow orderBack: m_nsWindow];
261 }
262
263 void QCocoaWindow::propagateSizeHints()
264 {
265     QCocoaAutoReleasePool pool;
266     if (!m_nsWindow)
267         return;
268
269     [m_nsWindow setMinSize : qt_mac_toNSSize(window()->minimumSize())];
270     [m_nsWindow setMaxSize : qt_mac_toNSSize(window()->maximumSize())];
271
272 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
273     qDebug() << "QCocoaWindow::propagateSizeHints" << this;
274     qDebug() << "     min/max " << window()->minimumSize() << window()->maximumSize();
275     qDebug() << "     basesize" << window()->baseSize();
276     qDebug() << "     geometry" << geometry();
277 #endif
278
279     if (!window()->sizeIncrement().isNull())
280         [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
281
282     QRect rect = geometry();
283     QSize baseSize = window()->baseSize();
284     if (!baseSize.isNull() && baseSize.isValid()) {
285         [m_nsWindow setFrame:NSMakeRect(rect.x(), rect.y(), baseSize.width(), baseSize.height()) display:YES];
286     }
287 }
288
289 void QCocoaWindow::setOpacity(qreal level)
290 {
291     if (m_nsWindow)
292         [m_nsWindow setAlphaValue:level];
293 }
294
295 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
296 {
297     if (!m_nsWindow)
298         return false;
299
300     if (grab && ![m_nsWindow isKeyWindow])
301         [m_nsWindow makeKeyWindow];
302     else if (!grab && [m_nsWindow isKeyWindow])
303         [m_nsWindow resignKeyWindow];
304     return true;
305 }
306
307 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
308 {
309     if (!m_nsWindow)
310         return false;
311
312     if (grab && ![m_nsWindow isKeyWindow])
313         [m_nsWindow makeKeyWindow];
314     else if (!grab && [m_nsWindow isKeyWindow])
315         [m_nsWindow resignKeyWindow];
316     return true;
317 }
318
319 WId QCocoaWindow::winId() const
320 {
321     return WId(m_contentView);
322 }
323
324 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
325 {
326     // recreate the window for compatibility
327     recreateWindow(parentWindow);
328     setCocoaGeometry(geometry());
329 }
330
331 NSView *QCocoaWindow::contentView() const
332 {
333     return m_contentView;
334 }
335
336 void QCocoaWindow::windowWillMove()
337 {
338     // Close any open popups on window move
339     if (m_activePopupWindow) {
340         QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
341         m_activePopupWindow = 0;
342     }
343 }
344
345 void QCocoaWindow::windowDidMove()
346 {
347     [m_contentView updateGeometry];
348 }
349
350 void QCocoaWindow::windowDidResize()
351 {
352     if (!m_nsWindow)
353         return;
354
355     NSRect rect = [[m_nsWindow contentView]frame];
356     // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
357     [[m_nsWindow contentView] setFrameSize:rect.size];
358 }
359
360 void QCocoaWindow::windowWillClose()
361 {
362     QWindowSystemInterface::handleSynchronousCloseEvent(window());
363 }
364
365 bool QCocoaWindow::windowIsPopupType() const
366 {
367     Qt::WindowType type = window()->windowType();
368     if (type == Qt::Tool)
369         return false; // Qt::Tool has the Popup bit set but isn't, at least on Mac.
370
371     return ((type & Qt::Popup) == Qt::Popup);
372 }
373
374 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
375 {
376     m_glContext = context;
377 }
378
379 QCocoaGLContext *QCocoaWindow::currentContext() const
380 {
381     return m_glContext;
382 }
383
384 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
385 {
386     // Remove current window (if any)
387     if (m_nsWindow) {
388         clearNSWindow(m_nsWindow);
389         [m_nsWindow close];
390         [m_nsWindow release];
391         m_nsWindow = 0;
392     }
393
394     if (!parentWindow) {
395         // Create a new NSWindow if this is a top-level window.
396         m_nsWindow = createNSWindow();
397         setNSWindow(m_nsWindow);
398
399         if (window()->transientParent()) {
400             // keep this window on the same level as its transient parent (which may be a modal dialog, for example)
401             QCocoaWindow *parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
402             [m_nsWindow setLevel:[parentCocoaWindow->m_nsWindow level]];
403         }
404     } else {
405         // Child windows have no NSWindow, link the NSViews instead.
406         const QCocoaWindow *parentCococaWindow = static_cast<const QCocoaWindow *>(parentWindow);
407         [parentCococaWindow->m_contentView addSubview : m_contentView];
408     }
409 }
410
411 NSWindow * QCocoaWindow::createNSWindow()
412 {
413     QCocoaAutoReleasePool pool;
414
415     NSRect frame = qt_mac_flipRect(window()->geometry(), window());
416
417     Qt::WindowType type = window()->windowType();
418     Qt::WindowFlags flags = window()->windowFlags();
419
420     NSUInteger styleMask;
421     NSWindow *createdWindow = 0;
422     NSInteger windowLevel = -1;
423
424     if (type == Qt::Tool) {
425         windowLevel = NSFloatingWindowLevel;
426     } else if ((type & Qt::Popup) == Qt::Popup) {
427         // styleMask = NSBorderlessWindowMask;
428         windowLevel = NSPopUpMenuWindowLevel;
429
430         // Popup should be in at least the same level as its parent.
431         const QWindow * const transientParent = window()->transientParent();
432         const QCocoaWindow * const transientParentWindow = transientParent ? static_cast<QCocoaWindow *>(transientParent->handle()) : 0;
433         if (transientParentWindow)
434             windowLevel = qMax([transientParentWindow->m_nsWindow level], windowLevel);
435     }
436
437     // StayOnTop window should appear above Tool windows.
438     if (flags & Qt::WindowStaysOnTopHint)
439         windowLevel = NSPopUpMenuWindowLevel;
440     // Tooltips should appear above StayOnTop windows.
441     if (type == Qt::ToolTip)
442         windowLevel = NSScreenSaverWindowLevel;
443     // All other types are Normal level.
444     if (windowLevel == -1)
445         windowLevel = NSNormalWindowLevel;
446
447     // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
448     if ((type & Qt::Popup) == Qt::Popup) {
449         if (windowIsPopupType()) {
450             styleMask = NSBorderlessWindowMask;
451         } else {
452             styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
453                          NSMiniaturizableWindowMask | NSTitledWindowMask);
454         }
455
456         QNSPanel *window;
457         window  = [[QNSPanel alloc] initWithContentRect:frame
458                                          styleMask: styleMask
459                                          backing:NSBackingStoreBuffered
460                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
461                                                     // before the window is shown and needs a proper window.).
462         [window setHasShadow:YES];
463
464 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
465         if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
466             // Make popup winows show on the same desktop as the parent full-screen window.
467             [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
468         }
469 #endif
470         window->m_cocoaPlatformWindow = this;
471         createdWindow = window;
472     } else {
473         styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
474         QNSWindow *window;
475         window  = [[QNSWindow alloc] initWithContentRect:frame
476                                          styleMask: styleMask
477                                          backing:NSBackingStoreBuffered
478                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
479                                                     // before the window is shown and needs a proper window.).
480         window->m_cocoaPlatformWindow = this;
481
482 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
483     if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
484         // All windows with the WindowMaximizeButtonHint set also get a full-screen button.
485         if (flags & Qt::WindowMaximizeButtonHint)
486             [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
487     }
488 #endif
489
490         createdWindow = window;
491     }
492
493     [createdWindow setLevel:windowLevel];
494
495     return createdWindow;
496 }
497
498 void QCocoaWindow::setNSWindow(NSWindow *window)
499 {
500     QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
501     [window setDelegate:delegate];
502     [window setAcceptsMouseMovedEvents:YES];
503
504     // Prevent Cocoa from releasing the window on close. Qt
505     // handles the close event asynchronously and we want to
506     // make sure that m_nsWindow stays valid until the
507     // QCocoaWindow is deleted by Qt.
508     [window setReleasedWhenClosed : NO];
509
510
511     [[NSNotificationCenter defaultCenter] addObserver:m_contentView
512                                           selector:@selector(windowNotification:)
513                                           name:nil // Get all notifications
514                                           object:m_nsWindow];
515
516     // ### Accept touch events by default.
517     // Beware that enabling touch events has a negative impact on the overall performance.
518     // We probably need a QWindowSystemInterface API to enable/disable touch events.
519     [m_contentView setAcceptsTouchEvents:YES];
520
521     [window setContentView:m_contentView];
522 }
523
524 void QCocoaWindow::clearNSWindow(NSWindow *window)
525 {
526     [window setDelegate:nil];
527     [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
528 }
529
530 // Returns the current global screen geometry for the nswindow associated with this window.
531 QRect QCocoaWindow::windowGeometry() const
532 {
533     if (!m_nsWindow)
534         return geometry();
535
536     NSRect rect = [m_nsWindow frame];
537     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
538     int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height;  // account for nswindow inverted y.
539     QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
540     return qRect;
541 }
542
543 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
544 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
545 {
546     if (window() && window()->transientParent()) {
547         return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
548     }
549     return 0;
550 }
551
552 // Syncs the NSWindow minimize/maximize/fullscreen state with the current QWindow state
553 void QCocoaWindow::syncWindowState(Qt::WindowState newState)
554 {
555     if (!m_nsWindow)
556         return;
557
558     if ((m_synchedWindowState & Qt::WindowMaximized) != (newState & Qt::WindowMaximized)) {
559         [m_nsWindow performZoom : m_nsWindow]; // toggles
560     }
561
562     if ((m_synchedWindowState & Qt::WindowMinimized) != (newState & Qt::WindowMinimized)) {
563         if (newState & Qt::WindowMinimized) {
564             [m_nsWindow performMiniaturize : m_nsWindow];
565         } else {
566             [m_nsWindow deminiaturize : m_nsWindow];
567         }
568     }
569
570     if ((m_synchedWindowState & Qt::WindowFullScreen) != (newState & Qt::WindowFullScreen)) {
571 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
572         if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
573             [m_nsWindow toggleFullScreen : m_nsWindow];
574         } else {
575             // TODO: "normal" fullscreen
576         }
577 #endif
578     }
579
580     // New state is now the current synched state
581     m_synchedWindowState = newState;
582 }
583
584 bool QCocoaWindow::setWindowModified(bool modified)
585 {
586     if (!m_nsWindow)
587         return false;
588     [m_nsWindow setDocumentEdited:(modified?YES:NO)];
589     return true;
590 }
591
592 void QCocoaWindow::setMenubar(QCocoaMenuBar *mb)
593 {
594     m_menubar = mb;
595 }
596
597 QCocoaMenuBar *QCocoaWindow::menubar() const
598 {
599     return m_menubar;
600 }