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 <qpa/qwindowsysteminterface.h>
51 #include <qpa/qplatformscreen.h>
53 #include <Cocoa/Cocoa.h>
54 #include <Carbon/Carbon.h>
58 static bool isMouseEvent(NSEvent *ev)
63 case NSRightMouseDown:
66 case NSLeftMouseDragged:
67 case NSRightMouseDragged:
74 @interface NSWindow (CocoaWindowCategory)
75 - (void) clearPlatformWindow;
76 - (NSRect) legacyConvertRectFromScreen:(NSRect) rect;
79 @implementation NSWindow (CocoaWindowCategory)
80 - (void) clearPlatformWindow
84 - (NSRect) legacyConvertRectFromScreen:(NSRect) rect
86 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
87 if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
88 return [self convertRectFromScreen: rect];
92 r.origin = [self convertScreenToBase:rect.origin];
97 @implementation QNSWindow
99 - (BOOL)canBecomeKeyWindow
101 // The default implementation returns NO for title-bar less windows,
102 // override and return yes here to make sure popup windows such as
103 // the combobox popup can become the key window.
107 - (BOOL)canBecomeMainWindow
109 BOOL canBecomeMain = YES; // By default, windows can become the main window
111 // Windows with a transient parent (such as combobox popup windows)
112 // cannot become the main window:
113 if (m_cocoaPlatformWindow->window()->transientParent())
116 return canBecomeMain;
119 - (void) sendEvent: (NSEvent*) theEvent
121 [super sendEvent: theEvent];
123 if (!m_cocoaPlatformWindow)
126 if (m_cocoaPlatformWindow->frameStrutEventsEnabled() && isMouseEvent(theEvent)) {
127 NSPoint loc = [theEvent locationInWindow];
128 NSRect windowFrame = [self legacyConvertRectFromScreen:[self frame]];
129 NSRect contentFrame = [[self contentView] frame];
130 if (NSMouseInRect(loc, windowFrame, NO) &&
131 !NSMouseInRect(loc, contentFrame, NO))
133 QNSView *contentView = (QNSView *) m_cocoaPlatformWindow->contentView();
134 [contentView handleFrameStrutMouseEvent: theEvent];
139 - (void)clearPlatformWindow
141 m_cocoaPlatformWindow = 0;
146 @implementation QNSPanel
148 - (BOOL)canBecomeKeyWindow
150 // Most panels can be come the key window. Exceptions are:
151 if (m_cocoaPlatformWindow->window()->windowType() == Qt::ToolTip)
153 if (m_cocoaPlatformWindow->window()->windowType() == Qt::SplashScreen)
158 - (void) sendEvent: (NSEvent*) theEvent
160 [super sendEvent: theEvent];
162 if (!m_cocoaPlatformWindow)
165 if (m_cocoaPlatformWindow->frameStrutEventsEnabled() && isMouseEvent(theEvent)) {
166 NSPoint loc = [theEvent locationInWindow];
167 NSRect windowFrame = [self legacyConvertRectFromScreen:[self frame]];
168 NSRect contentFrame = [[self contentView] frame];
169 if (NSMouseInRect(loc, windowFrame, NO) &&
170 !NSMouseInRect(loc, contentFrame, NO))
172 QNSView *contentView = (QNSView *) m_cocoaPlatformWindow->contentView();
173 [contentView handleFrameStrutMouseEvent: theEvent];
178 - (void)clearPlatformWindow
180 m_cocoaPlatformWindow = 0;
185 QCocoaWindow::QCocoaWindow(QWindow *tlw)
186 : QPlatformWindow(tlw)
188 , m_synchedWindowState(Qt::WindowActive)
189 , m_inConstructor(true)
192 , m_hasModalSession(false)
193 , m_frameStrutEventsEnabled(false)
195 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
196 qDebug() << "QCocoaWindow::QCocoaWindow" << this;
198 QCocoaAutoReleasePool pool;
200 m_contentView = [[QNSView alloc] initWithQWindow:tlw platformWindow:this];
201 setGeometry(tlw->geometry());
203 recreateWindow(parent());
205 m_inConstructor = false;
208 QCocoaWindow::~QCocoaWindow()
210 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
211 qDebug() << "QCocoaWindow::~QCocoaWindow" << this;
214 clearNSWindow(m_nsWindow);
215 [m_contentView release];
216 [m_nsWindow release];
219 void QCocoaWindow::setGeometry(const QRect &rect)
221 if (geometry() == rect)
223 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
224 qDebug() << "QCocoaWindow::setGeometry" << this << rect;
226 QPlatformWindow::setGeometry(rect);
227 setCocoaGeometry(rect);
230 void QCocoaWindow::setCocoaGeometry(const QRect &rect)
233 NSRect bounds = qt_mac_flipRect(rect, window());
234 [m_nsWindow setContentSize : bounds.size];
235 [m_nsWindow setFrameOrigin : bounds.origin];
237 [m_contentView setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
241 void QCocoaWindow::setVisible(bool visible)
243 QCocoaAutoReleasePool pool;
244 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
245 qDebug() << "QCocoaWindow::setVisible" << window() << visible;
248 QCocoaWindow *parentCocoaWindow = 0;
249 if (window()->transientParent()) {
250 parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
252 // The parent window might have moved while this window was hidden,
253 // update the window geometry if there is a parent.
254 setGeometry(window()->geometry());
256 // Register popup windows so that the parent window can
257 // close them when needed.
258 if (window()->windowType() == Qt::Popup) {
259 // qDebug() << "transientParent and popup" << window()->windowType() << Qt::Popup << (window()->windowType() & Qt::Popup);
260 parentCocoaWindow->m_activePopupWindow = window();
265 // Make sure the QWindow has a frame ready before we show the NSWindow.
266 QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
269 // setWindowState might have been called while the window was hidden and
270 // will not change the NSWindow state in that case. Sync up here:
271 syncWindowState(window()->windowState());
273 if (window()->windowState() != Qt::WindowMinimized) {
274 if ((window()->windowModality() == Qt::WindowModal
275 || window()->windowType() == Qt::Sheet)
276 && parentCocoaWindow) {
277 // show the window as a sheet
278 [NSApp beginSheet:m_nsWindow modalForWindow:parentCocoaWindow->m_nsWindow modalDelegate:nil didEndSelector:nil contextInfo:nil];
279 } else if (window()->windowModality() != Qt::NonModal) {
280 // show the window as application modal
281 QCocoaEventDispatcher *cocoaEventDispatcher = qobject_cast<QCocoaEventDispatcher *>(QGuiApplication::instance()->eventDispatcher());
282 Q_ASSERT(cocoaEventDispatcher != 0);
283 QCocoaEventDispatcherPrivate *cocoaEventDispatcherPrivate = static_cast<QCocoaEventDispatcherPrivate *>(QObjectPrivate::get(cocoaEventDispatcher));
284 cocoaEventDispatcherPrivate->beginModalSession(window());
285 m_hasModalSession = true;
286 } else if ([m_nsWindow canBecomeKeyWindow]) {
287 [m_nsWindow makeKeyAndOrderFront:nil];
289 [m_nsWindow orderFront: nil];
294 // qDebug() << "close" << this;
296 if (m_hasModalSession) {
297 QCocoaEventDispatcher *cocoaEventDispatcher = qobject_cast<QCocoaEventDispatcher *>(QGuiApplication::instance()->eventDispatcher());
298 Q_ASSERT(cocoaEventDispatcher != 0);
299 QCocoaEventDispatcherPrivate *cocoaEventDispatcherPrivate = static_cast<QCocoaEventDispatcherPrivate *>(QObjectPrivate::get(cocoaEventDispatcher));
300 cocoaEventDispatcherPrivate->endModalSession(window());
301 m_hasModalSession = false;
303 if ([m_nsWindow isSheet])
304 [NSApp endSheet:m_nsWindow];
306 [m_nsWindow orderOut:m_nsWindow];
308 if (!QCoreApplication::closingDown())
309 QWindowSystemInterface::handleExposeEvent(window(), QRegion());
313 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
315 m_windowFlags = flags;
316 return m_windowFlags;
319 Qt::WindowState QCocoaWindow::setWindowState(Qt::WindowState state)
321 if ([m_nsWindow isVisible])
322 syncWindowState(state); // Window state set for hidden windows take effect when show() is called.
327 void QCocoaWindow::setWindowTitle(const QString &title)
329 QCocoaAutoReleasePool pool;
333 CFStringRef windowTitle = QCFString::toCFStringRef(title);
334 [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
335 CFRelease(windowTitle);
338 void QCocoaWindow::raise()
340 //qDebug() << "raise" << this;
341 // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
344 if ([m_nsWindow isVisible])
345 [m_nsWindow orderFront: m_nsWindow];
348 void QCocoaWindow::lower()
352 if ([m_nsWindow isVisible])
353 [m_nsWindow orderBack: m_nsWindow];
356 void QCocoaWindow::propagateSizeHints()
358 QCocoaAutoReleasePool pool;
362 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
363 qDebug() << "QCocoaWindow::propagateSizeHints" << this;
364 qDebug() << " min/max " << window()->minimumSize() << window()->maximumSize();
365 qDebug() << "size increment" << window()->sizeIncrement();
366 qDebug() << " basesize" << window()->baseSize();
367 qDebug() << " geometry" << geometry();
370 // Set the minimum content size.
371 const QSize minimumSize = window()->minimumSize();
372 if (!minimumSize.isValid()) // minimumSize is (-1, -1) when not set. Make that (0, 0) for Cocoa.
373 [m_nsWindow setContentMinSize : NSMakeSize(0.0, 0.0)];
374 [m_nsWindow setContentMinSize : NSMakeSize(minimumSize.width(), minimumSize.height())];
376 // Set the maximum content size.
377 const QSize maximumSize = window()->maximumSize();
378 [m_nsWindow setContentMaxSize : NSMakeSize(maximumSize.width(), maximumSize.height())];
380 // sizeIncrement is observed to take values of (-1, -1) and (0, 0) for windows that should be
381 // resizable and that have no specific size increment set. Cocoa expects (1.0, 1.0) in this case.
382 if (!window()->sizeIncrement().isEmpty())
383 [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
385 [m_nsWindow setResizeIncrements : NSMakeSize(1.0, 1.0)];
387 QRect rect = geometry();
388 QSize baseSize = window()->baseSize();
389 if (!baseSize.isNull() && baseSize.isValid()) {
390 [m_nsWindow setFrame:NSMakeRect(rect.x(), rect.y(), baseSize.width(), baseSize.height()) display:YES];
394 void QCocoaWindow::setOpacity(qreal level)
397 [m_nsWindow setAlphaValue:level];
400 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
405 if (grab && ![m_nsWindow isKeyWindow])
406 [m_nsWindow makeKeyWindow];
407 else if (!grab && [m_nsWindow isKeyWindow])
408 [m_nsWindow resignKeyWindow];
412 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
417 if (grab && ![m_nsWindow isKeyWindow])
418 [m_nsWindow makeKeyWindow];
419 else if (!grab && [m_nsWindow isKeyWindow])
420 [m_nsWindow resignKeyWindow];
424 WId QCocoaWindow::winId() const
426 return WId(m_contentView);
429 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
431 // recreate the window for compatibility
432 recreateWindow(parentWindow);
433 setCocoaGeometry(geometry());
436 NSView *QCocoaWindow::contentView() const
438 return m_contentView;
441 void QCocoaWindow::windowWillMove()
443 // Close any open popups on window move
444 if (m_activePopupWindow) {
445 QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
446 m_activePopupWindow = 0;
450 void QCocoaWindow::windowDidMove()
452 [m_contentView updateGeometry];
455 void QCocoaWindow::windowDidResize()
460 NSRect rect = [[m_nsWindow contentView]frame];
461 // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
462 [[m_nsWindow contentView] setFrameSize:rect.size];
465 void QCocoaWindow::windowWillClose()
467 QWindowSystemInterface::handleSynchronousCloseEvent(window());
470 bool QCocoaWindow::windowIsPopupType() const
472 Qt::WindowType type = window()->windowType();
473 if (type == Qt::Tool)
474 return false; // Qt::Tool has the Popup bit set but isn't, at least on Mac.
476 return ((type & Qt::Popup) == Qt::Popup);
479 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
481 m_glContext = context;
484 QCocoaGLContext *QCocoaWindow::currentContext() const
489 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
491 // Remove current window (if any)
493 clearNSWindow(m_nsWindow);
495 [m_nsWindow release];
500 // Create a new NSWindow if this is a top-level window.
501 m_nsWindow = createNSWindow();
502 setNSWindow(m_nsWindow);
504 // QPlatformWindow subclasses must sync up with QWindow on creation:
505 propagateSizeHints();
506 setWindowFlags(window()->windowFlags());
507 setWindowTitle(window()->windowTitle());
508 setWindowState(window()->windowState());
510 if (window()->transientParent()) {
511 // keep this window on the same level as its transient parent (which may be a modal dialog, for example)
512 QCocoaWindow *parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
513 [m_nsWindow setLevel:[parentCocoaWindow->m_nsWindow level]];
516 // Child windows have no NSWindow, link the NSViews instead.
517 const QCocoaWindow *parentCococaWindow = static_cast<const QCocoaWindow *>(parentWindow);
518 [parentCococaWindow->m_contentView addSubview : m_contentView];
522 NSWindow * QCocoaWindow::createNSWindow()
524 QCocoaAutoReleasePool pool;
526 NSRect frame = qt_mac_flipRect(window()->geometry(), window());
528 Qt::WindowType type = window()->windowType();
529 Qt::WindowFlags flags = window()->windowFlags();
531 NSUInteger styleMask;
532 NSWindow *createdWindow = 0;
533 NSInteger windowLevel = -1;
535 if (type == Qt::Tool) {
536 windowLevel = NSFloatingWindowLevel;
537 } else if ((type & Qt::Popup) == Qt::Popup) {
538 // styleMask = NSBorderlessWindowMask;
539 windowLevel = NSPopUpMenuWindowLevel;
541 // Popup should be in at least the same level as its parent.
542 const QWindow * const transientParent = window()->transientParent();
543 const QCocoaWindow * const transientParentWindow = transientParent ? static_cast<QCocoaWindow *>(transientParent->handle()) : 0;
544 if (transientParentWindow)
545 windowLevel = qMax([transientParentWindow->m_nsWindow level], windowLevel);
548 // StayOnTop window should appear above Tool windows.
549 if (flags & Qt::WindowStaysOnTopHint)
550 windowLevel = NSPopUpMenuWindowLevel;
551 // Tooltips should appear above StayOnTop windows.
552 if (type == Qt::ToolTip)
553 windowLevel = NSScreenSaverWindowLevel;
554 // All other types are Normal level.
555 if (windowLevel == -1)
556 windowLevel = NSNormalWindowLevel;
558 // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
559 if ((type & Qt::Popup) == Qt::Popup) {
560 if (windowIsPopupType()) {
561 styleMask = NSBorderlessWindowMask;
563 styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
564 NSMiniaturizableWindowMask | NSTitledWindowMask);
568 window = [[QNSPanel alloc] initWithContentRect:frame
570 backing:NSBackingStoreBuffered
571 defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
572 // before the window is shown and needs a proper window.).
573 [window setHasShadow:YES];
575 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
576 if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
577 // Make popup winows show on the same desktop as the parent full-screen window.
578 [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
581 window->m_cocoaPlatformWindow = this;
582 createdWindow = window;
584 styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
586 window = [[QNSWindow alloc] initWithContentRect:frame
588 backing:NSBackingStoreBuffered
589 defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
590 // before the window is shown and needs a proper window.).
591 window->m_cocoaPlatformWindow = this;
593 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
594 if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
595 // All windows with the WindowMaximizeButtonHint set also get a full-screen button.
596 if (flags & Qt::WindowMaximizeButtonHint)
597 [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
601 createdWindow = window;
604 [createdWindow setLevel:windowLevel];
606 return createdWindow;
609 void QCocoaWindow::setNSWindow(NSWindow *window)
611 QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
612 [window setDelegate:delegate];
613 [window setAcceptsMouseMovedEvents:YES];
615 // Prevent Cocoa from releasing the window on close. Qt
616 // handles the close event asynchronously and we want to
617 // make sure that m_nsWindow stays valid until the
618 // QCocoaWindow is deleted by Qt.
619 [window setReleasedWhenClosed : NO];
622 [[NSNotificationCenter defaultCenter] addObserver:m_contentView
623 selector:@selector(windowNotification:)
624 name:nil // Get all notifications
627 // ### Accept touch events by default.
628 // Beware that enabling touch events has a negative impact on the overall performance.
629 // We probably need a QWindowSystemInterface API to enable/disable touch events.
630 [m_contentView setAcceptsTouchEvents:YES];
632 [window setContentView:m_contentView];
635 void QCocoaWindow::clearNSWindow(NSWindow *window)
637 [window setDelegate:nil];
638 [window clearPlatformWindow];
639 [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
642 // Returns the current global screen geometry for the nswindow associated with this window.
643 QRect QCocoaWindow::windowGeometry() const
648 NSRect rect = [m_nsWindow frame];
649 QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
650 int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height; // account for nswindow inverted y.
651 QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
655 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
656 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
658 if (window() && window()->transientParent()) {
659 return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
664 // Syncs the NSWindow minimize/maximize/fullscreen state with the current QWindow state
665 void QCocoaWindow::syncWindowState(Qt::WindowState newState)
670 if ((m_synchedWindowState & Qt::WindowMaximized) != (newState & Qt::WindowMaximized)) {
671 [m_nsWindow performZoom : m_nsWindow]; // toggles
674 if ((m_synchedWindowState & Qt::WindowMinimized) != (newState & Qt::WindowMinimized)) {
675 if (newState & Qt::WindowMinimized) {
676 [m_nsWindow performMiniaturize : m_nsWindow];
678 [m_nsWindow deminiaturize : m_nsWindow];
682 if ((m_synchedWindowState & Qt::WindowFullScreen) != (newState & Qt::WindowFullScreen)) {
683 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
684 if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
685 [m_nsWindow toggleFullScreen : m_nsWindow];
687 // TODO: "normal" fullscreen
692 // New state is now the current synched state
693 m_synchedWindowState = newState;
696 bool QCocoaWindow::setWindowModified(bool modified)
700 [m_nsWindow setDocumentEdited:(modified?YES:NO)];
704 void QCocoaWindow::setMenubar(QCocoaMenuBar *mb)
709 QCocoaMenuBar *QCocoaWindow::menubar() const
714 QMargins QCocoaWindow::frameMargins() const
716 NSRect frameW = [m_nsWindow frame];
717 NSRect frameC = [m_nsWindow contentRectForFrameRect:frameW];
719 return QMargins(frameW.origin.x - frameC.origin.x,
720 (frameW.origin.y + frameW.size.height) - (frameC.origin.y + frameC.size.height),
721 (frameW.origin.x + frameW.size.width) - (frameC.origin.x + frameC.size.width),
722 frameC.origin.y - frameW.origin.y);
725 void QCocoaWindow::setFrameStrutEventsEnabled(bool enabled)
727 m_frameStrutEventsEnabled = enabled;