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 <QWindowSystemInterface>
51 #include <QPlatformScreen>
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_inConstructor(true)
102 , m_hasModalSession(false)
104 QCocoaAutoReleasePool pool;
106 m_contentView = [[QNSView alloc] initWithQWindow:tlw platformWindow:this];
107 setGeometry(tlw->geometry());
109 recreateWindow(parent());
111 m_inConstructor = false;
114 QCocoaWindow::~QCocoaWindow()
116 clearNSWindow(m_nsWindow);
117 [m_contentView release];
118 [m_nsWindow release];
121 void QCocoaWindow::setGeometry(const QRect &rect)
123 if (geometry() == rect)
125 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
126 qDebug() << "QCocoaWindow::setGeometry" << this << rect;
128 QPlatformWindow::setGeometry(rect);
129 setCocoaGeometry(rect);
132 void QCocoaWindow::setCocoaGeometry(const QRect &rect)
135 NSRect bounds = qt_mac_flipRect(rect, window());
136 [m_nsWindow setContentSize : bounds.size];
137 [m_nsWindow setFrameOrigin : bounds.origin];
139 [m_contentView setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
143 void QCocoaWindow::setVisible(bool visible)
145 QCocoaAutoReleasePool pool;
146 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
147 qDebug() << "QCocoaWindow::setVisible" << window() << visible;
150 QCocoaWindow *parentCocoaWindow = 0;
151 if (window()->transientParent()) {
152 parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
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());
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();
167 // Make sure the QWindow has a frame ready before we show the NSWindow.
168 QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
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());
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];
191 [m_nsWindow orderFront: nil];
196 // qDebug() << "close" << this;
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;
205 if ([m_nsWindow isSheet])
206 [NSApp endSheet:m_nsWindow];
208 [m_nsWindow orderOut:m_nsWindow];
210 if (!QCoreApplication::closingDown())
211 QWindowSystemInterface::handleExposeEvent(window(), QRegion());
215 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
217 m_windowFlags = flags;
218 return m_windowFlags;
221 Qt::WindowState QCocoaWindow::setWindowState(Qt::WindowState state)
223 if ([m_nsWindow isVisible])
224 syncWindowState(state); // Window state set for hidden windows take effect when show() is called.
229 void QCocoaWindow::setWindowTitle(const QString &title)
231 QCocoaAutoReleasePool pool;
235 CFStringRef windowTitle = QCFString::toCFStringRef(title);
236 [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
237 CFRelease(windowTitle);
240 void QCocoaWindow::raise()
242 //qDebug() << "raise" << this;
243 // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
246 if ([m_nsWindow isVisible])
247 [m_nsWindow orderFront: m_nsWindow];
250 void QCocoaWindow::lower()
254 if ([m_nsWindow isVisible])
255 [m_nsWindow orderBack: m_nsWindow];
258 void QCocoaWindow::propagateSizeHints()
260 QCocoaAutoReleasePool pool;
264 [m_nsWindow setMinSize : qt_mac_toNSSize(window()->minimumSize())];
265 [m_nsWindow setMaxSize : qt_mac_toNSSize(window()->maximumSize())];
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();
274 if (!window()->sizeIncrement().isNull())
275 [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
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];
284 void QCocoaWindow::setOpacity(qreal level)
287 [m_nsWindow setAlphaValue:level];
290 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
295 if (grab && ![m_nsWindow isKeyWindow])
296 [m_nsWindow makeKeyWindow];
297 else if (!grab && [m_nsWindow isKeyWindow])
298 [m_nsWindow resignKeyWindow];
302 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
307 if (grab && ![m_nsWindow isKeyWindow])
308 [m_nsWindow makeKeyWindow];
309 else if (!grab && [m_nsWindow isKeyWindow])
310 [m_nsWindow resignKeyWindow];
314 WId QCocoaWindow::winId() const
316 return WId(m_contentView);
319 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
321 // recreate the window for compatibility
322 recreateWindow(parentWindow);
323 setCocoaGeometry(geometry());
326 NSView *QCocoaWindow::contentView() const
328 return m_contentView;
331 void QCocoaWindow::windowWillMove()
333 // Close any open popups on window move
334 if (m_activePopupWindow) {
335 QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
336 m_activePopupWindow = 0;
340 void QCocoaWindow::windowDidMove()
342 [m_contentView updateGeometry];
345 void QCocoaWindow::windowDidResize()
350 NSRect rect = [[m_nsWindow contentView]frame];
351 // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
352 [[m_nsWindow contentView] setFrameSize:rect.size];
355 void QCocoaWindow::windowWillClose()
357 QWindowSystemInterface::handleSynchronousCloseEvent(window());
360 bool QCocoaWindow::windowIsPopupType() const
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.
366 return ((type & Qt::Popup) == Qt::Popup);
369 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
371 m_glContext = context;
374 QCocoaGLContext *QCocoaWindow::currentContext() const
379 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
381 // Remove current window (if any)
383 clearNSWindow(m_nsWindow);
385 [m_nsWindow release];
390 // Create a new NSWindow if this is a top-level window.
391 m_nsWindow = createNSWindow();
392 setNSWindow(m_nsWindow);
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]];
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];
406 NSWindow * QCocoaWindow::createNSWindow()
408 QCocoaAutoReleasePool pool;
410 NSRect frame = qt_mac_flipRect(window()->geometry(), window());
412 Qt::WindowType type = window()->windowType();
413 Qt::WindowFlags flags = window()->windowFlags();
415 NSUInteger styleMask;
416 NSWindow *createdWindow = 0;
417 NSInteger windowLevel = -1;
419 if (type == Qt::Tool) {
420 windowLevel = NSFloatingWindowLevel;
421 } else if ((type & Qt::Popup) == Qt::Popup) {
422 // styleMask = NSBorderlessWindowMask;
423 windowLevel = NSPopUpMenuWindowLevel;
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);
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;
442 // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
443 if ((type & Qt::Popup) == Qt::Popup) {
444 if (windowIsPopupType()) {
445 styleMask = NSBorderlessWindowMask;
447 styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
448 NSMiniaturizableWindowMask | NSTitledWindowMask);
452 window = [[QNSPanel alloc] initWithContentRect:frame
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;
461 styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
463 window = [[QNSWindow alloc] initWithContentRect:frame
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;
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];
478 createdWindow = window;
481 [createdWindow setLevel:windowLevel];
483 return createdWindow;
486 void QCocoaWindow::setNSWindow(NSWindow *window)
488 QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
489 [window setDelegate:delegate];
490 [window setAcceptsMouseMovedEvents:YES];
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];
499 [[NSNotificationCenter defaultCenter] addObserver:m_contentView
500 selector:@selector(windowNotification:)
501 name:nil // Get all notifications
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];
509 [window setContentView:m_contentView];
512 void QCocoaWindow::clearNSWindow(NSWindow *window)
514 [window setDelegate:nil];
515 [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
518 // Returns the current global screen geometry for the nswindow associated with this window.
519 QRect QCocoaWindow::windowGeometry() const
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);
531 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
532 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
534 if (window() && window()->transientParent()) {
535 return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
540 // Syncs the NSWindow minimize/maximize/fullscreen state with the current QWindow state
541 void QCocoaWindow::syncWindowState(Qt::WindowState newState)
547 case Qt::WindowMinimized:
548 [m_nsWindow performMiniaturize : m_nsWindow];
550 case Qt::WindowMaximized:
551 [m_nsWindow performZoom : m_nsWindow];
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];
558 qWarning("Not implemented: setWindowState WindowFullScreen");
564 // Undo current states
565 if ([m_nsWindow isMiniaturized])
566 [m_nsWindow deminiaturize : m_nsWindow];
568 if ([m_nsWindow isZoomed])
569 [m_nsWindow performZoom : m_nsWindow]; // toggles
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];
576 qWarning("Not implemented: setWindowState WindowFullScreen");
583 bool QCocoaWindow::setWindowModified(bool modified)
587 [m_nsWindow setDocumentEdited:(modified?YES:NO)];