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