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