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