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