1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the plugins of the Qt Toolkit.
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.
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.
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.
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.
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"
48 #include <QtCore/private/qcore_mac_p.h>
50 #include <QtGui/qwindowsysteminterface.h>
51 #include <qpa/qplatformscreen.h>
53 #include <Cocoa/Cocoa.h>
54 #include <Carbon/Carbon.h>
58 @implementation QNSWindow
60 - (BOOL)canBecomeKeyWindow
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.
68 - (BOOL)canBecomeMainWindow
70 BOOL canBecomeMain = YES; // By default, windows can become the main window
72 // Windows with a transient parent (such as combobox popup windows)
73 // cannot become the main window:
74 if (m_cocoaPlatformWindow->window()->transientParent())
83 @implementation QNSPanel
85 - (BOOL)canBecomeKeyWindow
87 // Most panels can be come the key window. Exceptions are:
88 if (m_cocoaPlatformWindow->window()->windowType() == Qt::ToolTip)
90 if (m_cocoaPlatformWindow->window()->windowType() == Qt::SplashScreen)
97 QCocoaWindow::QCocoaWindow(QWindow *tlw)
98 : QPlatformWindow(tlw)
100 , m_synchedWindowState(Qt::WindowActive)
101 , m_inConstructor(true)
104 , m_hasModalSession(false)
106 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
107 qDebug() << "QCocoaWindow::QCocoaWindow" << this;
109 QCocoaAutoReleasePool pool;
111 m_contentView = [[QNSView alloc] initWithQWindow:tlw platformWindow:this];
112 setGeometry(tlw->geometry());
114 recreateWindow(parent());
116 m_inConstructor = false;
119 QCocoaWindow::~QCocoaWindow()
121 clearNSWindow(m_nsWindow);
122 [m_contentView release];
123 [m_nsWindow release];
126 void QCocoaWindow::setGeometry(const QRect &rect)
128 if (geometry() == rect)
130 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
131 qDebug() << "QCocoaWindow::setGeometry" << this << rect;
133 QPlatformWindow::setGeometry(rect);
134 setCocoaGeometry(rect);
137 void QCocoaWindow::setCocoaGeometry(const QRect &rect)
140 NSRect bounds = qt_mac_flipRect(rect, window());
141 [m_nsWindow setContentSize : bounds.size];
142 [m_nsWindow setFrameOrigin : bounds.origin];
144 [m_contentView setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
148 void QCocoaWindow::setVisible(bool visible)
150 QCocoaAutoReleasePool pool;
151 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
152 qDebug() << "QCocoaWindow::setVisible" << window() << visible;
155 QCocoaWindow *parentCocoaWindow = 0;
156 if (window()->transientParent()) {
157 parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
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());
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();
172 // Make sure the QWindow has a frame ready before we show the NSWindow.
173 QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
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());
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];
196 [m_nsWindow orderFront: nil];
201 // qDebug() << "close" << this;
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;
210 if ([m_nsWindow isSheet])
211 [NSApp endSheet:m_nsWindow];
213 [m_nsWindow orderOut:m_nsWindow];
215 if (!QCoreApplication::closingDown())
216 QWindowSystemInterface::handleExposeEvent(window(), QRegion());
220 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
222 m_windowFlags = flags;
223 return m_windowFlags;
226 Qt::WindowState QCocoaWindow::setWindowState(Qt::WindowState state)
228 if ([m_nsWindow isVisible])
229 syncWindowState(state); // Window state set for hidden windows take effect when show() is called.
234 void QCocoaWindow::setWindowTitle(const QString &title)
236 QCocoaAutoReleasePool pool;
240 CFStringRef windowTitle = QCFString::toCFStringRef(title);
241 [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
242 CFRelease(windowTitle);
245 void QCocoaWindow::raise()
247 //qDebug() << "raise" << this;
248 // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
251 if ([m_nsWindow isVisible])
252 [m_nsWindow orderFront: m_nsWindow];
255 void QCocoaWindow::lower()
259 if ([m_nsWindow isVisible])
260 [m_nsWindow orderBack: m_nsWindow];
263 void QCocoaWindow::propagateSizeHints()
265 QCocoaAutoReleasePool pool;
269 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
270 qDebug() << "QCocoaWindow::propagateSizeHints" << this;
271 qDebug() << " min/max " << window()->minimumSize() << window()->maximumSize();
272 qDebug() << "size increment" << window()->sizeIncrement();
273 qDebug() << " basesize" << window()->baseSize();
274 qDebug() << " geometry" << geometry();
277 // Set the minimum content size.
278 const QSize minimumSize = window()->minimumSize();
279 if (!minimumSize.isValid()) // minimumSize is (-1, -1) when not set. Make that (0, 0) for Cocoa.
280 [m_nsWindow setContentMinSize : NSMakeSize(0.0, 0.0)];
281 [m_nsWindow setContentMinSize : NSMakeSize(minimumSize.width(), minimumSize.height())];
283 // Set the maximum content size.
284 const QSize maximumSize = window()->maximumSize();
285 [m_nsWindow setContentMaxSize : NSMakeSize(maximumSize.width(), maximumSize.height())];
287 // sizeIncrement is observed to take values of (-1, -1) and (0, 0) for windows that should be
288 // resizable and that have no specific size increment set. Cocoa expects (1.0, 1.0) in this case.
289 if (!window()->sizeIncrement().isEmpty())
290 [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
292 [m_nsWindow setResizeIncrements : NSMakeSize(1.0, 1.0)];
294 QRect rect = geometry();
295 QSize baseSize = window()->baseSize();
296 if (!baseSize.isNull() && baseSize.isValid()) {
297 [m_nsWindow setFrame:NSMakeRect(rect.x(), rect.y(), baseSize.width(), baseSize.height()) display:YES];
301 void QCocoaWindow::setOpacity(qreal level)
304 [m_nsWindow setAlphaValue:level];
307 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
312 if (grab && ![m_nsWindow isKeyWindow])
313 [m_nsWindow makeKeyWindow];
314 else if (!grab && [m_nsWindow isKeyWindow])
315 [m_nsWindow resignKeyWindow];
319 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
324 if (grab && ![m_nsWindow isKeyWindow])
325 [m_nsWindow makeKeyWindow];
326 else if (!grab && [m_nsWindow isKeyWindow])
327 [m_nsWindow resignKeyWindow];
331 WId QCocoaWindow::winId() const
333 return WId(m_contentView);
336 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
338 // recreate the window for compatibility
339 recreateWindow(parentWindow);
340 setCocoaGeometry(geometry());
343 NSView *QCocoaWindow::contentView() const
345 return m_contentView;
348 void QCocoaWindow::windowWillMove()
350 // Close any open popups on window move
351 if (m_activePopupWindow) {
352 QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
353 m_activePopupWindow = 0;
357 void QCocoaWindow::windowDidMove()
359 [m_contentView updateGeometry];
362 void QCocoaWindow::windowDidResize()
367 NSRect rect = [[m_nsWindow contentView]frame];
368 // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
369 [[m_nsWindow contentView] setFrameSize:rect.size];
372 void QCocoaWindow::windowWillClose()
374 QWindowSystemInterface::handleSynchronousCloseEvent(window());
377 bool QCocoaWindow::windowIsPopupType() const
379 Qt::WindowType type = window()->windowType();
380 if (type == Qt::Tool)
381 return false; // Qt::Tool has the Popup bit set but isn't, at least on Mac.
383 return ((type & Qt::Popup) == Qt::Popup);
386 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
388 m_glContext = context;
391 QCocoaGLContext *QCocoaWindow::currentContext() const
396 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
398 // Remove current window (if any)
400 clearNSWindow(m_nsWindow);
402 [m_nsWindow release];
407 // Create a new NSWindow if this is a top-level window.
408 m_nsWindow = createNSWindow();
409 setNSWindow(m_nsWindow);
411 // QPlatformWindow subclasses must sync up with QWindow on creation:
412 propagateSizeHints();
413 setWindowFlags(window()->windowFlags());
414 setWindowTitle(window()->windowTitle());
415 setWindowState(window()->windowState());
417 if (window()->transientParent()) {
418 // keep this window on the same level as its transient parent (which may be a modal dialog, for example)
419 QCocoaWindow *parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
420 [m_nsWindow setLevel:[parentCocoaWindow->m_nsWindow level]];
423 // Child windows have no NSWindow, link the NSViews instead.
424 const QCocoaWindow *parentCococaWindow = static_cast<const QCocoaWindow *>(parentWindow);
425 [parentCococaWindow->m_contentView addSubview : m_contentView];
429 NSWindow * QCocoaWindow::createNSWindow()
431 QCocoaAutoReleasePool pool;
433 NSRect frame = qt_mac_flipRect(window()->geometry(), window());
435 Qt::WindowType type = window()->windowType();
436 Qt::WindowFlags flags = window()->windowFlags();
438 NSUInteger styleMask;
439 NSWindow *createdWindow = 0;
440 NSInteger windowLevel = -1;
442 if (type == Qt::Tool) {
443 windowLevel = NSFloatingWindowLevel;
444 } else if ((type & Qt::Popup) == Qt::Popup) {
445 // styleMask = NSBorderlessWindowMask;
446 windowLevel = NSPopUpMenuWindowLevel;
448 // Popup should be in at least the same level as its parent.
449 const QWindow * const transientParent = window()->transientParent();
450 const QCocoaWindow * const transientParentWindow = transientParent ? static_cast<QCocoaWindow *>(transientParent->handle()) : 0;
451 if (transientParentWindow)
452 windowLevel = qMax([transientParentWindow->m_nsWindow level], windowLevel);
455 // StayOnTop window should appear above Tool windows.
456 if (flags & Qt::WindowStaysOnTopHint)
457 windowLevel = NSPopUpMenuWindowLevel;
458 // Tooltips should appear above StayOnTop windows.
459 if (type == Qt::ToolTip)
460 windowLevel = NSScreenSaverWindowLevel;
461 // All other types are Normal level.
462 if (windowLevel == -1)
463 windowLevel = NSNormalWindowLevel;
465 // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
466 if ((type & Qt::Popup) == Qt::Popup) {
467 if (windowIsPopupType()) {
468 styleMask = NSBorderlessWindowMask;
470 styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
471 NSMiniaturizableWindowMask | NSTitledWindowMask);
475 window = [[QNSPanel alloc] initWithContentRect:frame
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 setHasShadow:YES];
482 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
483 if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
484 // Make popup winows show on the same desktop as the parent full-screen window.
485 [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
488 window->m_cocoaPlatformWindow = this;
489 createdWindow = window;
491 styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
493 window = [[QNSWindow alloc] initWithContentRect:frame
495 backing:NSBackingStoreBuffered
496 defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
497 // before the window is shown and needs a proper window.).
498 window->m_cocoaPlatformWindow = this;
500 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
501 if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
502 // All windows with the WindowMaximizeButtonHint set also get a full-screen button.
503 if (flags & Qt::WindowMaximizeButtonHint)
504 [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
508 createdWindow = window;
511 [createdWindow setLevel:windowLevel];
513 return createdWindow;
516 void QCocoaWindow::setNSWindow(NSWindow *window)
518 QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
519 [window setDelegate:delegate];
520 [window setAcceptsMouseMovedEvents:YES];
522 // Prevent Cocoa from releasing the window on close. Qt
523 // handles the close event asynchronously and we want to
524 // make sure that m_nsWindow stays valid until the
525 // QCocoaWindow is deleted by Qt.
526 [window setReleasedWhenClosed : NO];
529 [[NSNotificationCenter defaultCenter] addObserver:m_contentView
530 selector:@selector(windowNotification:)
531 name:nil // Get all notifications
534 // ### Accept touch events by default.
535 // Beware that enabling touch events has a negative impact on the overall performance.
536 // We probably need a QWindowSystemInterface API to enable/disable touch events.
537 [m_contentView setAcceptsTouchEvents:YES];
539 [window setContentView:m_contentView];
542 void QCocoaWindow::clearNSWindow(NSWindow *window)
544 [window setDelegate:nil];
545 [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
548 // Returns the current global screen geometry for the nswindow associated with this window.
549 QRect QCocoaWindow::windowGeometry() const
554 NSRect rect = [m_nsWindow frame];
555 QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
556 int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height; // account for nswindow inverted y.
557 QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
561 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
562 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
564 if (window() && window()->transientParent()) {
565 return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
570 // Syncs the NSWindow minimize/maximize/fullscreen state with the current QWindow state
571 void QCocoaWindow::syncWindowState(Qt::WindowState newState)
576 if ((m_synchedWindowState & Qt::WindowMaximized) != (newState & Qt::WindowMaximized)) {
577 [m_nsWindow performZoom : m_nsWindow]; // toggles
580 if ((m_synchedWindowState & Qt::WindowMinimized) != (newState & Qt::WindowMinimized)) {
581 if (newState & Qt::WindowMinimized) {
582 [m_nsWindow performMiniaturize : m_nsWindow];
584 [m_nsWindow deminiaturize : m_nsWindow];
588 if ((m_synchedWindowState & Qt::WindowFullScreen) != (newState & Qt::WindowFullScreen)) {
589 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
590 if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
591 [m_nsWindow toggleFullScreen : m_nsWindow];
593 // TODO: "normal" fullscreen
598 // New state is now the current synched state
599 m_synchedWindowState = newState;
602 bool QCocoaWindow::setWindowModified(bool modified)
606 [m_nsWindow setDocumentEdited:(modified?YES:NO)];
610 void QCocoaWindow::setMenubar(QCocoaMenuBar *mb)
615 QCocoaMenuBar *QCocoaWindow::menubar() const