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