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