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 <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)
103 , m_hasModalSession(false)
105 QCocoaAutoReleasePool pool;
107 m_contentView = [[QNSView alloc] initWithQWindow:tlw platformWindow:this];
108 setGeometry(tlw->geometry());
110 recreateWindow(parent());
112 m_inConstructor = false;
115 QCocoaWindow::~QCocoaWindow()
117 clearNSWindow(m_nsWindow);
118 [m_contentView release];
119 [m_nsWindow release];
122 void QCocoaWindow::setGeometry(const QRect &rect)
124 if (geometry() == rect)
126 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
127 qDebug() << "QCocoaWindow::setGeometry" << this << rect;
129 QPlatformWindow::setGeometry(rect);
130 setCocoaGeometry(rect);
133 void QCocoaWindow::setCocoaGeometry(const QRect &rect)
136 NSRect bounds = qt_mac_flipRect(rect, window());
137 [m_nsWindow setContentSize : bounds.size];
138 [m_nsWindow setFrameOrigin : bounds.origin];
140 [m_contentView setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
144 void QCocoaWindow::setVisible(bool visible)
146 QCocoaAutoReleasePool pool;
147 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
148 qDebug() << "QCocoaWindow::setVisible" << window() << visible;
151 QCocoaWindow *parentCocoaWindow = 0;
152 if (window()->transientParent()) {
153 parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
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());
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();
168 // Make sure the QWindow has a frame ready before we show the NSWindow.
169 QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
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());
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];
192 [m_nsWindow orderFront: nil];
197 // qDebug() << "close" << this;
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;
206 if ([m_nsWindow isSheet])
207 [NSApp endSheet:m_nsWindow];
209 [m_nsWindow orderOut:m_nsWindow];
211 if (!QCoreApplication::closingDown())
212 QWindowSystemInterface::handleExposeEvent(window(), QRegion());
216 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
218 m_windowFlags = flags;
219 return m_windowFlags;
222 Qt::WindowState QCocoaWindow::setWindowState(Qt::WindowState state)
224 if ([m_nsWindow isVisible])
225 syncWindowState(state); // Window state set for hidden windows take effect when show() is called.
230 void QCocoaWindow::setWindowTitle(const QString &title)
232 QCocoaAutoReleasePool pool;
236 CFStringRef windowTitle = QCFString::toCFStringRef(title);
237 [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
238 CFRelease(windowTitle);
241 void QCocoaWindow::raise()
243 //qDebug() << "raise" << this;
244 // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
247 if ([m_nsWindow isVisible])
248 [m_nsWindow orderFront: m_nsWindow];
251 void QCocoaWindow::lower()
255 if ([m_nsWindow isVisible])
256 [m_nsWindow orderBack: m_nsWindow];
259 void QCocoaWindow::propagateSizeHints()
261 QCocoaAutoReleasePool pool;
265 [m_nsWindow setMinSize : qt_mac_toNSSize(window()->minimumSize())];
266 [m_nsWindow setMaxSize : qt_mac_toNSSize(window()->maximumSize())];
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();
275 if (!window()->sizeIncrement().isNull())
276 [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
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];
285 void QCocoaWindow::setOpacity(qreal level)
288 [m_nsWindow setAlphaValue:level];
291 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
296 if (grab && ![m_nsWindow isKeyWindow])
297 [m_nsWindow makeKeyWindow];
298 else if (!grab && [m_nsWindow isKeyWindow])
299 [m_nsWindow resignKeyWindow];
303 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
308 if (grab && ![m_nsWindow isKeyWindow])
309 [m_nsWindow makeKeyWindow];
310 else if (!grab && [m_nsWindow isKeyWindow])
311 [m_nsWindow resignKeyWindow];
315 WId QCocoaWindow::winId() const
317 return WId(m_contentView);
320 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
322 // recreate the window for compatibility
323 recreateWindow(parentWindow);
324 setCocoaGeometry(geometry());
327 NSView *QCocoaWindow::contentView() const
329 return m_contentView;
332 void QCocoaWindow::windowWillMove()
334 // Close any open popups on window move
335 if (m_activePopupWindow) {
336 QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
337 m_activePopupWindow = 0;
341 void QCocoaWindow::windowDidMove()
343 [m_contentView updateGeometry];
346 void QCocoaWindow::windowDidResize()
351 NSRect rect = [[m_nsWindow contentView]frame];
352 // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
353 [[m_nsWindow contentView] setFrameSize:rect.size];
356 void QCocoaWindow::windowWillClose()
358 QWindowSystemInterface::handleSynchronousCloseEvent(window());
361 bool QCocoaWindow::windowIsPopupType() const
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.
367 return ((type & Qt::Popup) == Qt::Popup);
370 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
372 m_glContext = context;
375 QCocoaGLContext *QCocoaWindow::currentContext() const
380 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
382 // Remove current window (if any)
384 clearNSWindow(m_nsWindow);
386 [m_nsWindow release];
391 // Create a new NSWindow if this is a top-level window.
392 m_nsWindow = createNSWindow();
393 setNSWindow(m_nsWindow);
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]];
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];
407 NSWindow * QCocoaWindow::createNSWindow()
409 QCocoaAutoReleasePool pool;
411 NSRect frame = qt_mac_flipRect(window()->geometry(), window());
413 Qt::WindowType type = window()->windowType();
414 Qt::WindowFlags flags = window()->windowFlags();
416 NSUInteger styleMask;
417 NSWindow *createdWindow = 0;
418 NSInteger windowLevel = -1;
420 if (type == Qt::Tool) {
421 windowLevel = NSFloatingWindowLevel;
422 } else if ((type & Qt::Popup) == Qt::Popup) {
423 // styleMask = NSBorderlessWindowMask;
424 windowLevel = NSPopUpMenuWindowLevel;
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);
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;
443 // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
444 if ((type & Qt::Popup) == Qt::Popup) {
445 if (windowIsPopupType()) {
446 styleMask = NSBorderlessWindowMask;
448 styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
449 NSMiniaturizableWindowMask | NSTitledWindowMask);
453 window = [[QNSPanel alloc] initWithContentRect:frame
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;
462 styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
464 window = [[QNSWindow alloc] initWithContentRect:frame
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;
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];
479 createdWindow = window;
482 [createdWindow setLevel:windowLevel];
484 return createdWindow;
487 void QCocoaWindow::setNSWindow(NSWindow *window)
489 QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
490 [window setDelegate:delegate];
491 [window setAcceptsMouseMovedEvents:YES];
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];
500 [[NSNotificationCenter defaultCenter] addObserver:m_contentView
501 selector:@selector(windowNotification:)
502 name:nil // Get all notifications
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];
510 [window setContentView:m_contentView];
513 void QCocoaWindow::clearNSWindow(NSWindow *window)
515 [window setDelegate:nil];
516 [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
519 // Returns the current global screen geometry for the nswindow associated with this window.
520 QRect QCocoaWindow::windowGeometry() const
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);
532 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
533 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
535 if (window() && window()->transientParent()) {
536 return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
541 // Syncs the NSWindow minimize/maximize/fullscreen state with the current QWindow state
542 void QCocoaWindow::syncWindowState(Qt::WindowState newState)
547 if ((m_synchedWindowState & Qt::WindowMaximized) != (newState & Qt::WindowMaximized)) {
548 [m_nsWindow performZoom : m_nsWindow]; // toggles
551 if ((m_synchedWindowState & Qt::WindowMinimized) != (newState & Qt::WindowMinimized)) {
552 if (newState & Qt::WindowMinimized) {
553 [m_nsWindow performMiniaturize : m_nsWindow];
555 [m_nsWindow deminiaturize : m_nsWindow];
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];
564 // TODO: "normal" fullscreen
569 // New state is now the current synched state
570 m_synchedWindowState = newState;
573 bool QCocoaWindow::setWindowModified(bool modified)
577 [m_nsWindow setDocumentEdited:(modified?YES:NO)];