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