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