Cocoa: bugfix staysOnTopFlag in combination with transient parent
[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         }
296     } else {
297         // qDebug() << "close" << this;
298         if (m_nsWindow) {
299             if (m_hasModalSession) {
300                 QCocoaEventDispatcher *cocoaEventDispatcher = qobject_cast<QCocoaEventDispatcher *>(QGuiApplication::instance()->eventDispatcher());
301                 Q_ASSERT(cocoaEventDispatcher != 0);
302                 QCocoaEventDispatcherPrivate *cocoaEventDispatcherPrivate = static_cast<QCocoaEventDispatcherPrivate *>(QObjectPrivate::get(cocoaEventDispatcher));
303                 cocoaEventDispatcherPrivate->endModalSession(window());
304                 m_hasModalSession = false;
305             } else {
306                 if ([m_nsWindow isSheet])
307                     [NSApp endSheet:m_nsWindow];
308             }
309             [m_nsWindow orderOut:m_nsWindow];
310         }
311         if (!QCoreApplication::closingDown())
312             QWindowSystemInterface::handleExposeEvent(window(), QRegion());
313     }
314 }
315
316 NSInteger QCocoaWindow::windowLevel(Qt::WindowFlags flags)
317 {
318     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
319
320     NSInteger windowLevel = NSNormalWindowLevel;
321
322     if (type == Qt::Tool)
323         windowLevel = NSFloatingWindowLevel;
324     else if ((type & Qt::Popup) == Qt::Popup)
325         windowLevel = NSPopUpMenuWindowLevel;
326
327     // StayOnTop window should appear above Tool windows.
328     if (flags & Qt::WindowStaysOnTopHint)
329         windowLevel = NSPopUpMenuWindowLevel;
330     // Tooltips should appear above StayOnTop windows.
331     if (type == Qt::ToolTip)
332         windowLevel = NSScreenSaverWindowLevel;
333
334     // A window should be in at least the same level as its parent.
335     const QWindow * const transientParent = window()->transientParent();
336     const QCocoaWindow * const transientParentWindow = transientParent ? static_cast<QCocoaWindow *>(transientParent->handle()) : 0;
337     if (transientParentWindow)
338         windowLevel = qMax([transientParentWindow->m_nsWindow level], windowLevel);
339
340     return windowLevel;
341 }
342
343 NSUInteger QCocoaWindow::windowStyleMask(Qt::WindowFlags flags)
344 {
345     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
346     NSInteger styleMask = NSBorderlessWindowMask;
347
348     if ((type & Qt::Popup) == Qt::Popup) {
349         if (!windowIsPopupType(type))
350             styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
351                          NSMiniaturizableWindowMask | NSTitledWindowMask);
352     } else {
353         // Filter flags for supported properties
354         flags &= Qt::WindowType_Mask | Qt::FramelessWindowHint | Qt::WindowTitleHint |
355                  Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint;
356         if (flags == Qt::Window) {
357             styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
358         } else if (!(flags & Qt::FramelessWindowHint)) {
359             if (flags & Qt::WindowMaximizeButtonHint)
360                 styleMask |= NSResizableWindowMask;
361             if (flags & Qt::WindowTitleHint)
362                 styleMask |= NSTitledWindowMask;
363             if (flags & Qt::WindowCloseButtonHint)
364                 styleMask |= NSClosableWindowMask;
365             if (flags & Qt::WindowMinimizeButtonHint)
366                 styleMask |= NSMiniaturizableWindowMask;
367         }
368     }
369
370     return styleMask;
371 }
372
373 void QCocoaWindow::setWindowShadow(Qt::WindowFlags flags)
374 {
375     bool keepShadow = !(flags & Qt::NoDropShadowWindowHint);
376     [m_nsWindow setHasShadow:(keepShadow ? YES : NO)];
377 }
378
379 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
380 {
381     if (m_nsWindow) {
382         NSUInteger styleMask = windowStyleMask(flags);
383         NSInteger level = this->windowLevel(flags);
384         [m_nsWindow setStyleMask:styleMask];
385         [m_nsWindow setLevel:level];
386         setWindowShadow(flags);
387     }
388
389     m_windowFlags = flags;
390     return m_windowFlags;
391 }
392
393 Qt::WindowState QCocoaWindow::setWindowState(Qt::WindowState state)
394 {
395     if ([m_nsWindow isVisible])
396         syncWindowState(state);  // Window state set for hidden windows take effect when show() is called.
397
398     return state;
399 }
400
401 void QCocoaWindow::setWindowTitle(const QString &title)
402 {
403     QCocoaAutoReleasePool pool;
404     if (!m_nsWindow)
405         return;
406
407     CFStringRef windowTitle = QCFString::toCFStringRef(title);
408     [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
409     CFRelease(windowTitle);
410 }
411
412 void QCocoaWindow::setWindowFilePath(const QString &filePath)
413 {
414     QCocoaAutoReleasePool pool;
415     if (!m_nsWindow)
416         return;
417
418     QFileInfo fi(filePath);
419     [m_nsWindow setRepresentedFilename: fi.exists() ? QCFString::toNSString(filePath) : @""];
420 }
421
422 void QCocoaWindow::raise()
423 {
424     //qDebug() << "raise" << this;
425     // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
426     if (!m_nsWindow)
427         return;
428     if ([m_nsWindow isVisible])
429         [m_nsWindow orderFront: m_nsWindow];
430 }
431
432 void QCocoaWindow::lower()
433 {
434     if (!m_nsWindow)
435         return;
436     if ([m_nsWindow isVisible])
437         [m_nsWindow orderBack: m_nsWindow];
438 }
439
440 void QCocoaWindow::propagateSizeHints()
441 {
442     QCocoaAutoReleasePool pool;
443     if (!m_nsWindow)
444         return;
445
446 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
447     qDebug() << "QCocoaWindow::propagateSizeHints" << this;
448     qDebug() << "     min/max " << window()->minimumSize() << window()->maximumSize();
449     qDebug() << "size increment" << window()->sizeIncrement();
450     qDebug() << "     basesize" << window()->baseSize();
451     qDebug() << "     geometry" << geometry();
452 #endif
453
454     // Set the minimum content size.
455     const QSize minimumSize = window()->minimumSize();
456     if (!minimumSize.isValid()) // minimumSize is (-1, -1) when not set. Make that (0, 0) for Cocoa.
457         [m_nsWindow setContentMinSize : NSMakeSize(0.0, 0.0)];
458     [m_nsWindow setContentMinSize : NSMakeSize(minimumSize.width(), minimumSize.height())];
459
460     // Set the maximum content size.
461     const QSize maximumSize = window()->maximumSize();
462     [m_nsWindow setContentMaxSize : NSMakeSize(maximumSize.width(), maximumSize.height())];
463
464     // sizeIncrement is observed to take values of (-1, -1) and (0, 0) for windows that should be
465     // resizable and that have no specific size increment set. Cocoa expects (1.0, 1.0) in this case.
466     if (!window()->sizeIncrement().isEmpty())
467         [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
468     else
469         [m_nsWindow setResizeIncrements : NSMakeSize(1.0, 1.0)];
470
471     QRect rect = geometry();
472     QSize baseSize = window()->baseSize();
473     if (!baseSize.isNull() && baseSize.isValid()) {
474         [m_nsWindow setFrame:NSMakeRect(rect.x(), rect.y(), baseSize.width(), baseSize.height()) display:YES];
475     }
476 }
477
478 void QCocoaWindow::setOpacity(qreal level)
479 {
480     if (m_nsWindow)
481         [m_nsWindow setAlphaValue:level];
482 }
483
484 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
485 {
486     if (!m_nsWindow)
487         return false;
488
489     if (grab && ![m_nsWindow isKeyWindow])
490         [m_nsWindow makeKeyWindow];
491     else if (!grab && [m_nsWindow isKeyWindow])
492         [m_nsWindow resignKeyWindow];
493     return true;
494 }
495
496 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
497 {
498     if (!m_nsWindow)
499         return false;
500
501     if (grab && ![m_nsWindow isKeyWindow])
502         [m_nsWindow makeKeyWindow];
503     else if (!grab && [m_nsWindow isKeyWindow])
504         [m_nsWindow resignKeyWindow];
505     return true;
506 }
507
508 WId QCocoaWindow::winId() const
509 {
510     return WId(m_contentView);
511 }
512
513 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
514 {
515     // recreate the window for compatibility
516     recreateWindow(parentWindow);
517     setCocoaGeometry(geometry());
518 }
519
520 NSView *QCocoaWindow::contentView() const
521 {
522     return m_contentView;
523 }
524
525 void QCocoaWindow::windowWillMove()
526 {
527     // Close any open popups on window move
528     if (m_activePopupWindow) {
529         QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
530         m_activePopupWindow = 0;
531     }
532 }
533
534 void QCocoaWindow::windowDidMove()
535 {
536     [m_contentView updateGeometry];
537 }
538
539 void QCocoaWindow::windowDidResize()
540 {
541     if (!m_nsWindow)
542         return;
543
544     NSRect rect = [[m_nsWindow contentView]frame];
545     // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
546     [[m_nsWindow contentView] setFrameSize:rect.size];
547 }
548
549 void QCocoaWindow::windowWillClose()
550 {
551     QWindowSystemInterface::handleSynchronousCloseEvent(window());
552 }
553
554 bool QCocoaWindow::windowIsPopupType(Qt::WindowType type) const
555 {
556     if (type == Qt::Widget)
557         type = window()->windowType();
558     if (type == Qt::Tool)
559         return false; // Qt::Tool has the Popup bit set but isn't, at least on Mac.
560
561     return ((type & Qt::Popup) == Qt::Popup);
562 }
563
564 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
565 {
566     m_glContext = context;
567 }
568
569 QCocoaGLContext *QCocoaWindow::currentContext() const
570 {
571     return m_glContext;
572 }
573
574 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
575 {
576     // Remove current window (if any)
577     if (m_nsWindow) {
578         clearNSWindow(m_nsWindow);
579         [m_nsWindow close];
580         [m_nsWindow release];
581         m_nsWindow = 0;
582     }
583
584     if (!parentWindow) {
585         // Create a new NSWindow if this is a top-level window.
586         m_nsWindow = createNSWindow();
587         setNSWindow(m_nsWindow);
588
589         // QPlatformWindow subclasses must sync up with QWindow on creation:
590         propagateSizeHints();
591         setWindowFlags(window()->windowFlags());
592         setWindowTitle(window()->windowTitle());
593         setWindowState(window()->windowState());
594     } else {
595         // Child windows have no NSWindow, link the NSViews instead.
596         const QCocoaWindow *parentCococaWindow = static_cast<const QCocoaWindow *>(parentWindow);
597         [parentCococaWindow->m_contentView addSubview : m_contentView];
598     }
599 }
600
601 NSWindow * QCocoaWindow::createNSWindow()
602 {
603     QCocoaAutoReleasePool pool;
604
605     NSRect frame = qt_mac_flipRect(window()->geometry(), window());
606
607     Qt::WindowType type = window()->windowType();
608     Qt::WindowFlags flags = window()->windowFlags();
609
610     NSUInteger styleMask = windowStyleMask(flags);
611     NSWindow *createdWindow = 0;
612
613     // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
614     if ((type & Qt::Popup) == Qt::Popup) {
615         QNSPanel *window;
616         window  = [[QNSPanel alloc] initWithContentRect:frame
617                                          styleMask: styleMask
618                                          backing:NSBackingStoreBuffered
619                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
620                                                     // before the window is shown and needs a proper window.).
621         [window setHasShadow:YES];
622
623 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
624         if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
625             // Make popup winows show on the same desktop as the parent full-screen window.
626             [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
627         }
628 #endif
629         window->m_cocoaPlatformWindow = this;
630         createdWindow = window;
631     } else {
632         QNSWindow *window;
633         window  = [[QNSWindow alloc] initWithContentRect:frame
634                                          styleMask: styleMask
635                                          backing:NSBackingStoreBuffered
636                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
637                                                     // before the window is shown and needs a proper window.).
638         window->m_cocoaPlatformWindow = this;
639         setWindowShadow(flags);
640
641 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
642     if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
643         // All windows with the WindowMaximizeButtonHint set also get a full-screen button.
644         if (flags & Qt::WindowMaximizeButtonHint)
645             [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
646     }
647 #endif
648
649         createdWindow = window;
650     }
651
652     NSInteger level = windowLevel(flags);
653     [createdWindow setLevel:level];
654
655     return createdWindow;
656 }
657
658 void QCocoaWindow::setNSWindow(NSWindow *window)
659 {
660     QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
661     [window setDelegate:delegate];
662     [window setAcceptsMouseMovedEvents:YES];
663
664     // Prevent Cocoa from releasing the window on close. Qt
665     // handles the close event asynchronously and we want to
666     // make sure that m_nsWindow stays valid until the
667     // QCocoaWindow is deleted by Qt.
668     [window setReleasedWhenClosed : NO];
669
670
671     [[NSNotificationCenter defaultCenter] addObserver:m_contentView
672                                           selector:@selector(windowNotification:)
673                                           name:nil // Get all notifications
674                                           object:m_nsWindow];
675
676     // ### Accept touch events by default.
677     // Beware that enabling touch events has a negative impact on the overall performance.
678     // We probably need a QWindowSystemInterface API to enable/disable touch events.
679     [m_contentView setAcceptsTouchEvents:YES];
680
681     [window setContentView:m_contentView];
682 }
683
684 void QCocoaWindow::clearNSWindow(NSWindow *window)
685 {
686     [window setDelegate:nil];
687     [window clearPlatformWindow];
688     [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
689 }
690
691 // Returns the current global screen geometry for the nswindow associated with this window.
692 QRect QCocoaWindow::windowGeometry() const
693 {
694     if (!m_nsWindow)
695         return geometry();
696
697     NSRect rect = [m_nsWindow frame];
698     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
699     int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height;  // account for nswindow inverted y.
700     QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
701     return qRect;
702 }
703
704 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
705 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
706 {
707     if (window() && window()->transientParent()) {
708         return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
709     }
710     return 0;
711 }
712
713 // Syncs the NSWindow minimize/maximize/fullscreen state with the current QWindow state
714 void QCocoaWindow::syncWindowState(Qt::WindowState newState)
715 {
716     if (!m_nsWindow)
717         return;
718
719     if ((m_synchedWindowState & Qt::WindowMaximized) != (newState & Qt::WindowMaximized)) {
720         [m_nsWindow performZoom : m_nsWindow]; // toggles
721     }
722
723     if ((m_synchedWindowState & Qt::WindowMinimized) != (newState & Qt::WindowMinimized)) {
724         if (newState & Qt::WindowMinimized) {
725             [m_nsWindow performMiniaturize : m_nsWindow];
726         } else {
727             [m_nsWindow deminiaturize : m_nsWindow];
728         }
729     }
730
731     if ((m_synchedWindowState & Qt::WindowFullScreen) != (newState & Qt::WindowFullScreen)) {
732 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
733         if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
734             [m_nsWindow toggleFullScreen : m_nsWindow];
735         } else {
736             // TODO: "normal" fullscreen
737         }
738 #endif
739     }
740
741     // New state is now the current synched state
742     m_synchedWindowState = newState;
743 }
744
745 bool QCocoaWindow::setWindowModified(bool modified)
746 {
747     if (!m_nsWindow)
748         return false;
749     [m_nsWindow setDocumentEdited:(modified?YES:NO)];
750     return true;
751 }
752
753 void QCocoaWindow::setMenubar(QCocoaMenuBar *mb)
754 {
755     m_menubar = mb;
756 }
757
758 QCocoaMenuBar *QCocoaWindow::menubar() const
759 {
760     return m_menubar;
761 }
762
763 QMargins QCocoaWindow::frameMargins() const
764 {
765     NSRect frameW = [m_nsWindow frame];
766     NSRect frameC = [m_nsWindow contentRectForFrameRect:frameW];
767
768     return QMargins(frameW.origin.x - frameC.origin.x,
769         (frameW.origin.y + frameW.size.height) - (frameC.origin.y + frameC.size.height),
770         (frameW.origin.x + frameW.size.width) - (frameC.origin.x + frameC.size.width),
771         frameC.origin.y - frameW.origin.y);
772 }
773
774 void QCocoaWindow::setFrameStrutEventsEnabled(bool enabled)
775 {
776     m_frameStrutEventsEnabled = enabled;
777 }