Mac: QComboBox wouldn't receive mouse events when shown within a modal dialog
[profile/ivi/qtbase.git] / src / plugins / platforms / cocoa / qcocoawindow.mm
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the plugins of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights.  These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file.  Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
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/qfileinfo.h>
49 #include <QtCore/private/qcore_mac_p.h>
50 #include <qwindow.h>
51 #include <qpa/qwindowsysteminterface.h>
52 #include <qpa/qplatformscreen.h>
53
54 #include <Cocoa/Cocoa.h>
55 #include <Carbon/Carbon.h>
56
57 #include <QDebug>
58
59 static bool isMouseEvent(NSEvent *ev)
60 {
61     switch ([ev type]) {
62     case NSLeftMouseDown:
63     case NSLeftMouseUp:
64     case NSRightMouseDown:
65     case NSRightMouseUp:
66     case NSMouseMoved:
67     case NSLeftMouseDragged:
68     case NSRightMouseDragged:
69         return true;
70     default:
71         return false;
72     }
73 }
74
75 @interface NSWindow (CocoaWindowCategory)
76 - (void) clearPlatformWindow;
77 - (NSRect) legacyConvertRectFromScreen:(NSRect) rect;
78 @end
79
80 @implementation NSWindow (CocoaWindowCategory)
81 - (void) clearPlatformWindow
82 {
83 }
84
85 - (NSRect) legacyConvertRectFromScreen:(NSRect) rect
86 {
87 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
88     if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
89         return [self convertRectFromScreen: rect];
90     }
91 #endif
92     NSRect r = rect;
93     r.origin = [self convertScreenToBase:rect.origin];
94     return r;
95 }
96 @end
97
98 @implementation QNSWindow
99
100 - (BOOL)canBecomeKeyWindow
101 {
102     // The default implementation returns NO for title-bar less windows,
103     // override and return yes here to make sure popup windows such as
104     // the combobox popup can become the key window.
105     return YES;
106 }
107
108 - (BOOL)canBecomeMainWindow
109 {
110     BOOL canBecomeMain = YES; // By default, windows can become the main window
111
112     // Windows with a transient parent (such as combobox popup windows)
113     // cannot become the main window:
114     if (m_cocoaPlatformWindow->window()->transientParent())
115         canBecomeMain = NO;
116
117     return canBecomeMain;
118 }
119
120 - (void) sendEvent: (NSEvent*) theEvent
121 {
122     [super sendEvent: theEvent];
123
124     if (!m_cocoaPlatformWindow)
125         return;
126
127     if (m_cocoaPlatformWindow->frameStrutEventsEnabled() && isMouseEvent(theEvent)) {
128         NSPoint loc = [theEvent locationInWindow];
129         NSRect windowFrame = [self legacyConvertRectFromScreen:[self frame]];
130         NSRect contentFrame = [[self contentView] frame];
131         if (NSMouseInRect(loc, windowFrame, NO) &&
132             !NSMouseInRect(loc, contentFrame, NO))
133         {
134             QNSView *contentView = (QNSView *) m_cocoaPlatformWindow->contentView();
135             [contentView handleFrameStrutMouseEvent: theEvent];
136         }
137     }
138 }
139
140 - (void)clearPlatformWindow
141 {
142     m_cocoaPlatformWindow = 0;
143 }
144
145 @end
146
147 @implementation QNSPanel
148
149 - (BOOL)canBecomeKeyWindow
150 {
151     // Most panels can be come the key window. Exceptions are:
152     if (m_cocoaPlatformWindow->window()->windowType() == Qt::ToolTip)
153         return NO;
154     if (m_cocoaPlatformWindow->window()->windowType() == Qt::SplashScreen)
155         return NO;
156     return YES;
157 }
158
159 - (void) sendEvent: (NSEvent*) theEvent
160 {
161     [super sendEvent: theEvent];
162
163     if (!m_cocoaPlatformWindow)
164         return;
165
166     if (m_cocoaPlatformWindow->frameStrutEventsEnabled() && isMouseEvent(theEvent)) {
167         NSPoint loc = [theEvent locationInWindow];
168         NSRect windowFrame = [self legacyConvertRectFromScreen:[self frame]];
169         NSRect contentFrame = [[self contentView] frame];
170         if (NSMouseInRect(loc, windowFrame, NO) &&
171             !NSMouseInRect(loc, contentFrame, NO))
172         {
173             QNSView *contentView = (QNSView *) m_cocoaPlatformWindow->contentView();
174             [contentView handleFrameStrutMouseEvent: theEvent];
175         }
176     }
177 }
178
179 - (void)clearPlatformWindow
180 {
181     m_cocoaPlatformWindow = 0;
182 }
183
184 @end
185
186 QCocoaWindow::QCocoaWindow(QWindow *tlw)
187     : QPlatformWindow(tlw)
188     , m_nsWindow(0)
189     , m_synchedWindowState(Qt::WindowActive)
190     , m_inConstructor(true)
191     , m_glContext(0)
192     , m_menubar(0)
193     , m_hasModalSession(false)
194     , m_frameStrutEventsEnabled(false)
195 {
196 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
197     qDebug() << "QCocoaWindow::QCocoaWindow" << this;
198 #endif
199     QCocoaAutoReleasePool pool;
200
201     m_contentView = [[QNSView alloc] initWithQWindow:tlw platformWindow:this];
202     setGeometry(tlw->geometry());
203
204     recreateWindow(parent());
205
206     m_inConstructor = false;
207 }
208
209 QCocoaWindow::~QCocoaWindow()
210 {
211 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
212     qDebug() << "QCocoaWindow::~QCocoaWindow" << this;
213 #endif
214
215     QCocoaAutoReleasePool pool;
216     clearNSWindow(m_nsWindow);
217     [m_contentView release];
218     [m_nsWindow release];
219 }
220
221 void QCocoaWindow::setGeometry(const QRect &rect)
222 {
223     if (geometry() == rect)
224         return;
225 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
226     qDebug() << "QCocoaWindow::setGeometry" << this << rect;
227 #endif
228     QPlatformWindow::setGeometry(rect);
229     setCocoaGeometry(rect);
230 }
231
232 void QCocoaWindow::setCocoaGeometry(const QRect &rect)
233 {
234     QCocoaAutoReleasePool pool;
235     if (m_nsWindow) {
236         NSRect bounds = qt_mac_flipRect(rect, window());
237         [m_nsWindow setContentSize : bounds.size];
238         [m_nsWindow setFrameOrigin : bounds.origin];
239     } else {
240         [m_contentView setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
241     }
242 }
243
244 void QCocoaWindow::setVisible(bool visible)
245 {
246     QCocoaAutoReleasePool pool;
247 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
248     qDebug() << "QCocoaWindow::setVisible" << window() << visible;
249 #endif
250     if (visible) {
251         QCocoaWindow *parentCocoaWindow = 0;
252         if (window()->transientParent()) {
253             parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
254
255             // The parent window might have moved while this window was hidden,
256             // update the window geometry if there is a parent.
257             setGeometry(window()->geometry());
258
259             // Register popup windows so that the parent window can
260             // close them when needed.
261             if (window()->windowType() == Qt::Popup) {
262                 // qDebug() << "transientParent and popup" << window()->windowType() << Qt::Popup << (window()->windowType() & Qt::Popup);
263                 parentCocoaWindow->m_activePopupWindow = window();
264             }
265
266         }
267
268         // Make sure the QWindow has a frame ready before we show the NSWindow.
269         QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
270
271         if (m_nsWindow) {
272             // setWindowState might have been called while the window was hidden and
273             // will not change the NSWindow state in that case. Sync up here:
274             syncWindowState(window()->windowState());
275
276             if (window()->windowState() != Qt::WindowMinimized) {
277                 if ((window()->windowModality() == Qt::WindowModal
278                      || window()->windowType() == Qt::Sheet)
279                         && parentCocoaWindow) {
280                     // show the window as a sheet
281                     [NSApp beginSheet:m_nsWindow modalForWindow:parentCocoaWindow->m_nsWindow modalDelegate:nil didEndSelector:nil contextInfo:nil];
282                 } else if (window()->windowModality() != Qt::NonModal) {
283                     // show the window as application modal
284                     QCocoaEventDispatcher *cocoaEventDispatcher = qobject_cast<QCocoaEventDispatcher *>(QGuiApplication::instance()->eventDispatcher());
285                     Q_ASSERT(cocoaEventDispatcher != 0);
286                     QCocoaEventDispatcherPrivate *cocoaEventDispatcherPrivate = static_cast<QCocoaEventDispatcherPrivate *>(QObjectPrivate::get(cocoaEventDispatcher));
287                     cocoaEventDispatcherPrivate->beginModalSession(window());
288                     m_hasModalSession = true;
289                 } else if ([m_nsWindow canBecomeKeyWindow]) {
290                     [m_nsWindow makeKeyAndOrderFront:nil];
291                 } else {
292                     [m_nsWindow orderFront: nil];
293                 }
294
295                 // We want the events to properly reach the popup
296                 if (window()->windowType() == Qt::Popup)
297                     [(NSPanel *)m_nsWindow setWorksWhenModal:YES];
298             }
299         }
300     } else {
301         // qDebug() << "close" << this;
302         if (m_nsWindow) {
303             if (m_hasModalSession) {
304                 QCocoaEventDispatcher *cocoaEventDispatcher = qobject_cast<QCocoaEventDispatcher *>(QGuiApplication::instance()->eventDispatcher());
305                 Q_ASSERT(cocoaEventDispatcher != 0);
306                 QCocoaEventDispatcherPrivate *cocoaEventDispatcherPrivate = static_cast<QCocoaEventDispatcherPrivate *>(QObjectPrivate::get(cocoaEventDispatcher));
307                 cocoaEventDispatcherPrivate->endModalSession(window());
308                 m_hasModalSession = false;
309             } else {
310                 if ([m_nsWindow isSheet])
311                     [NSApp endSheet:m_nsWindow];
312             }
313             [m_nsWindow orderOut:m_nsWindow];
314         }
315         if (!QCoreApplication::closingDown())
316             QWindowSystemInterface::handleExposeEvent(window(), QRegion());
317     }
318 }
319
320 NSInteger QCocoaWindow::windowLevel(Qt::WindowFlags flags)
321 {
322     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
323
324     NSInteger windowLevel = NSNormalWindowLevel;
325
326     if (type == Qt::Tool)
327         windowLevel = NSFloatingWindowLevel;
328     else if ((type & Qt::Popup) == Qt::Popup)
329         windowLevel = NSPopUpMenuWindowLevel;
330
331     // StayOnTop window should appear above Tool windows.
332     if (flags & Qt::WindowStaysOnTopHint)
333         windowLevel = NSPopUpMenuWindowLevel;
334     // Tooltips should appear above StayOnTop windows.
335     if (type == Qt::ToolTip)
336         windowLevel = NSScreenSaverWindowLevel;
337
338     // A window should be in at least the same level as its parent.
339     const QWindow * const transientParent = window()->transientParent();
340     const QCocoaWindow * const transientParentWindow = transientParent ? static_cast<QCocoaWindow *>(transientParent->handle()) : 0;
341     if (transientParentWindow)
342         windowLevel = qMax([transientParentWindow->m_nsWindow level], windowLevel);
343
344     return windowLevel;
345 }
346
347 NSUInteger QCocoaWindow::windowStyleMask(Qt::WindowFlags flags)
348 {
349     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
350     NSInteger styleMask = NSBorderlessWindowMask;
351
352     if ((type & Qt::Popup) == Qt::Popup) {
353         if (!windowIsPopupType(type))
354             styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
355                          NSMiniaturizableWindowMask | NSTitledWindowMask);
356     } else {
357         // Filter flags for supported properties
358         flags &= Qt::WindowType_Mask | Qt::FramelessWindowHint | Qt::WindowTitleHint |
359                  Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint;
360         if (flags == Qt::Window) {
361             styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
362         } else if (!(flags & Qt::FramelessWindowHint)) {
363             if (flags & Qt::WindowMaximizeButtonHint)
364                 styleMask |= NSResizableWindowMask;
365             if (flags & Qt::WindowTitleHint)
366                 styleMask |= NSTitledWindowMask;
367             if (flags & Qt::WindowCloseButtonHint)
368                 styleMask |= NSClosableWindowMask;
369             if (flags & Qt::WindowMinimizeButtonHint)
370                 styleMask |= NSMiniaturizableWindowMask;
371         }
372     }
373
374     return styleMask;
375 }
376
377 void QCocoaWindow::setWindowShadow(Qt::WindowFlags flags)
378 {
379     bool keepShadow = !(flags & Qt::NoDropShadowWindowHint);
380     [m_nsWindow setHasShadow:(keepShadow ? YES : NO)];
381 }
382
383 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
384 {
385     if (m_nsWindow) {
386         NSUInteger styleMask = windowStyleMask(flags);
387         NSInteger level = this->windowLevel(flags);
388         [m_nsWindow setStyleMask:styleMask];
389         [m_nsWindow setLevel:level];
390         setWindowShadow(flags);
391     }
392
393     m_windowFlags = flags;
394     return m_windowFlags;
395 }
396
397 Qt::WindowState QCocoaWindow::setWindowState(Qt::WindowState state)
398 {
399     if ([m_nsWindow isVisible])
400         syncWindowState(state);  // Window state set for hidden windows take effect when show() is called.
401
402     return state;
403 }
404
405 void QCocoaWindow::setWindowTitle(const QString &title)
406 {
407     QCocoaAutoReleasePool pool;
408     if (!m_nsWindow)
409         return;
410
411     CFStringRef windowTitle = QCFString::toCFStringRef(title);
412     [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
413     CFRelease(windowTitle);
414 }
415
416 void QCocoaWindow::setWindowFilePath(const QString &filePath)
417 {
418     QCocoaAutoReleasePool pool;
419     if (!m_nsWindow)
420         return;
421
422     QFileInfo fi(filePath);
423     [m_nsWindow setRepresentedFilename: fi.exists() ? QCFString::toNSString(filePath) : @""];
424 }
425
426 void QCocoaWindow::raise()
427 {
428     //qDebug() << "raise" << this;
429     // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
430     if (!m_nsWindow)
431         return;
432     if ([m_nsWindow isVisible])
433         [m_nsWindow orderFront: m_nsWindow];
434 }
435
436 void QCocoaWindow::lower()
437 {
438     if (!m_nsWindow)
439         return;
440     if ([m_nsWindow isVisible])
441         [m_nsWindow orderBack: m_nsWindow];
442 }
443
444 void QCocoaWindow::propagateSizeHints()
445 {
446     QCocoaAutoReleasePool pool;
447     if (!m_nsWindow)
448         return;
449
450 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
451     qDebug() << "QCocoaWindow::propagateSizeHints" << this;
452     qDebug() << "     min/max " << window()->minimumSize() << window()->maximumSize();
453     qDebug() << "size increment" << window()->sizeIncrement();
454     qDebug() << "     basesize" << window()->baseSize();
455     qDebug() << "     geometry" << geometry();
456 #endif
457
458     // Set the minimum content size.
459     const QSize minimumSize = window()->minimumSize();
460     if (!minimumSize.isValid()) // minimumSize is (-1, -1) when not set. Make that (0, 0) for Cocoa.
461         [m_nsWindow setContentMinSize : NSMakeSize(0.0, 0.0)];
462     [m_nsWindow setContentMinSize : NSMakeSize(minimumSize.width(), minimumSize.height())];
463
464     // Set the maximum content size.
465     const QSize maximumSize = window()->maximumSize();
466     [m_nsWindow setContentMaxSize : NSMakeSize(maximumSize.width(), maximumSize.height())];
467
468     // sizeIncrement is observed to take values of (-1, -1) and (0, 0) for windows that should be
469     // resizable and that have no specific size increment set. Cocoa expects (1.0, 1.0) in this case.
470     if (!window()->sizeIncrement().isEmpty())
471         [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
472     else
473         [m_nsWindow setResizeIncrements : NSMakeSize(1.0, 1.0)];
474
475     QRect rect = geometry();
476     QSize baseSize = window()->baseSize();
477     if (!baseSize.isNull() && baseSize.isValid()) {
478         [m_nsWindow setFrame:NSMakeRect(rect.x(), rect.y(), baseSize.width(), baseSize.height()) display:YES];
479     }
480 }
481
482 void QCocoaWindow::setOpacity(qreal level)
483 {
484     if (m_nsWindow)
485         [m_nsWindow setAlphaValue:level];
486 }
487
488 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
489 {
490     if (!m_nsWindow)
491         return false;
492
493     if (grab && ![m_nsWindow isKeyWindow])
494         [m_nsWindow makeKeyWindow];
495     else if (!grab && [m_nsWindow isKeyWindow])
496         [m_nsWindow resignKeyWindow];
497     return true;
498 }
499
500 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
501 {
502     if (!m_nsWindow)
503         return false;
504
505     if (grab && ![m_nsWindow isKeyWindow])
506         [m_nsWindow makeKeyWindow];
507     else if (!grab && [m_nsWindow isKeyWindow])
508         [m_nsWindow resignKeyWindow];
509     return true;
510 }
511
512 WId QCocoaWindow::winId() const
513 {
514     return WId(m_contentView);
515 }
516
517 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
518 {
519     // recreate the window for compatibility
520     recreateWindow(parentWindow);
521     setCocoaGeometry(geometry());
522 }
523
524 NSView *QCocoaWindow::contentView() const
525 {
526     return m_contentView;
527 }
528
529 void QCocoaWindow::windowWillMove()
530 {
531     // Close any open popups on window move
532     if (m_activePopupWindow) {
533         QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
534         m_activePopupWindow = 0;
535     }
536 }
537
538 void QCocoaWindow::windowDidMove()
539 {
540     [m_contentView updateGeometry];
541 }
542
543 void QCocoaWindow::windowDidResize()
544 {
545     if (!m_nsWindow)
546         return;
547
548     NSRect rect = [[m_nsWindow contentView]frame];
549     // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
550     [[m_nsWindow contentView] setFrameSize:rect.size];
551 }
552
553 void QCocoaWindow::windowWillClose()
554 {
555     QWindowSystemInterface::handleSynchronousCloseEvent(window());
556 }
557
558 bool QCocoaWindow::windowIsPopupType(Qt::WindowType type) const
559 {
560     if (type == Qt::Widget)
561         type = window()->windowType();
562     if (type == Qt::Tool)
563         return false; // Qt::Tool has the Popup bit set but isn't, at least on Mac.
564
565     return ((type & Qt::Popup) == Qt::Popup);
566 }
567
568 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
569 {
570     m_glContext = context;
571 }
572
573 QCocoaGLContext *QCocoaWindow::currentContext() const
574 {
575     return m_glContext;
576 }
577
578 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
579 {
580     // Remove current window (if any)
581     if (m_nsWindow) {
582         clearNSWindow(m_nsWindow);
583         [m_nsWindow close];
584         [m_nsWindow release];
585         m_nsWindow = 0;
586     }
587
588     if (!parentWindow) {
589         // Create a new NSWindow if this is a top-level window.
590         m_nsWindow = createNSWindow();
591         setNSWindow(m_nsWindow);
592
593         // QPlatformWindow subclasses must sync up with QWindow on creation:
594         propagateSizeHints();
595         setWindowFlags(window()->windowFlags());
596         setWindowTitle(window()->windowTitle());
597         setWindowState(window()->windowState());
598     } else {
599         // Child windows have no NSWindow, link the NSViews instead.
600         const QCocoaWindow *parentCococaWindow = static_cast<const QCocoaWindow *>(parentWindow);
601         [parentCococaWindow->m_contentView addSubview : m_contentView];
602     }
603 }
604
605 NSWindow * QCocoaWindow::createNSWindow()
606 {
607     QCocoaAutoReleasePool pool;
608
609     NSRect frame = qt_mac_flipRect(window()->geometry(), window());
610
611     Qt::WindowType type = window()->windowType();
612     Qt::WindowFlags flags = window()->windowFlags();
613
614     NSUInteger styleMask = windowStyleMask(flags);
615     NSWindow *createdWindow = 0;
616
617     // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
618     if ((type & Qt::Popup) == Qt::Popup) {
619         QNSPanel *window;
620         window  = [[QNSPanel alloc] initWithContentRect:frame
621                                          styleMask: styleMask
622                                          backing:NSBackingStoreBuffered
623                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
624                                                     // before the window is shown and needs a proper window.).
625         [window setHasShadow:YES];
626
627 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
628         if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
629             // Make popup winows show on the same desktop as the parent full-screen window.
630             [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
631         }
632 #endif
633         window->m_cocoaPlatformWindow = this;
634         createdWindow = window;
635     } else {
636         QNSWindow *window;
637         window  = [[QNSWindow alloc] initWithContentRect:frame
638                                          styleMask: styleMask
639                                          backing:NSBackingStoreBuffered
640                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
641                                                     // before the window is shown and needs a proper window.).
642         window->m_cocoaPlatformWindow = this;
643         setWindowShadow(flags);
644
645 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
646     if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
647         // All windows with the WindowMaximizeButtonHint set also get a full-screen button.
648         if (flags & Qt::WindowMaximizeButtonHint)
649             [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
650     }
651 #endif
652
653         createdWindow = window;
654     }
655
656     NSInteger level = windowLevel(flags);
657     [createdWindow setLevel:level];
658
659     return createdWindow;
660 }
661
662 void QCocoaWindow::setNSWindow(NSWindow *window)
663 {
664     QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
665     [window setDelegate:delegate];
666     [window setAcceptsMouseMovedEvents:YES];
667
668     // Prevent Cocoa from releasing the window on close. Qt
669     // handles the close event asynchronously and we want to
670     // make sure that m_nsWindow stays valid until the
671     // QCocoaWindow is deleted by Qt.
672     [window setReleasedWhenClosed : NO];
673
674
675     [[NSNotificationCenter defaultCenter] addObserver:m_contentView
676                                           selector:@selector(windowNotification:)
677                                           name:nil // Get all notifications
678                                           object:m_nsWindow];
679
680     // ### Accept touch events by default.
681     // Beware that enabling touch events has a negative impact on the overall performance.
682     // We probably need a QWindowSystemInterface API to enable/disable touch events.
683     [m_contentView setAcceptsTouchEvents:YES];
684
685     [window setContentView:m_contentView];
686 }
687
688 void QCocoaWindow::clearNSWindow(NSWindow *window)
689 {
690     [window setDelegate:nil];
691     [window clearPlatformWindow];
692     [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
693 }
694
695 // Returns the current global screen geometry for the nswindow associated with this window.
696 QRect QCocoaWindow::windowGeometry() const
697 {
698     if (!m_nsWindow)
699         return geometry();
700
701     NSRect rect = [m_nsWindow frame];
702     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
703     int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height;  // account for nswindow inverted y.
704     QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
705     return qRect;
706 }
707
708 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
709 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
710 {
711     if (window() && window()->transientParent()) {
712         return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
713     }
714     return 0;
715 }
716
717 // Syncs the NSWindow minimize/maximize/fullscreen state with the current QWindow state
718 void QCocoaWindow::syncWindowState(Qt::WindowState newState)
719 {
720     if (!m_nsWindow)
721         return;
722
723     if ((m_synchedWindowState & Qt::WindowMaximized) != (newState & Qt::WindowMaximized)) {
724         [m_nsWindow performZoom : m_nsWindow]; // toggles
725     }
726
727     if ((m_synchedWindowState & Qt::WindowMinimized) != (newState & Qt::WindowMinimized)) {
728         if (newState & Qt::WindowMinimized) {
729             [m_nsWindow performMiniaturize : m_nsWindow];
730         } else {
731             [m_nsWindow deminiaturize : m_nsWindow];
732         }
733     }
734
735     if ((m_synchedWindowState & Qt::WindowFullScreen) != (newState & Qt::WindowFullScreen)) {
736 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
737         if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
738             [m_nsWindow toggleFullScreen : m_nsWindow];
739         } else {
740             // TODO: "normal" fullscreen
741         }
742 #endif
743     }
744
745     // New state is now the current synched state
746     m_synchedWindowState = newState;
747 }
748
749 bool QCocoaWindow::setWindowModified(bool modified)
750 {
751     if (!m_nsWindow)
752         return false;
753     [m_nsWindow setDocumentEdited:(modified?YES:NO)];
754     return true;
755 }
756
757 void QCocoaWindow::setMenubar(QCocoaMenuBar *mb)
758 {
759     m_menubar = mb;
760 }
761
762 QCocoaMenuBar *QCocoaWindow::menubar() const
763 {
764     return m_menubar;
765 }
766
767 QMargins QCocoaWindow::frameMargins() const
768 {
769     NSRect frameW = [m_nsWindow frame];
770     NSRect frameC = [m_nsWindow contentRectForFrameRect:frameW];
771
772     return QMargins(frameW.origin.x - frameC.origin.x,
773         (frameW.origin.y + frameW.size.height) - (frameC.origin.y + frameC.size.height),
774         (frameW.origin.x + frameW.size.width) - (frameC.origin.x + frameC.size.width),
775         frameC.origin.y - frameW.origin.y);
776 }
777
778 void QCocoaWindow::setFrameStrutEventsEnabled(bool enabled)
779 {
780     m_frameStrutEventsEnabled = enabled;
781 }