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