Cocoa: reimplement QPlatformWindow::setOpacity()
[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 "qcocoaglcontext.h"
45 #include "qcocoahelpers.h"
46 #include "qnsview.h"
47 #include <QtCore/private/qcore_mac_p.h>
48 #include <qwindow.h>
49 #include <QWindowSystemInterface>
50 #include <QPlatformScreen>
51
52 #include <Cocoa/Cocoa.h>
53 #include <Carbon/Carbon.h>
54
55 #include <QDebug>
56
57 @implementation QNSWindow
58
59 - (BOOL)canBecomeKeyWindow
60 {
61     // The default implementation returns NO for title-bar less windows,
62     // override and return yes here to make sure popup windows such as
63     // the combobox popup can become the key window.
64     return YES;
65 }
66
67 - (BOOL)canBecomeMainWindow
68 {
69     BOOL canBecomeMain = YES; // By default, windows can become the main window
70
71     // Windows with a transient parent (such as combobox popup windows)
72     // cannot become the main window:
73     if (m_cocoaPlatformWindow->window()->transientParent())
74         canBecomeMain = NO;
75
76     return canBecomeMain;
77 }
78
79
80 @end
81
82 @implementation QNSPanel
83
84 - (BOOL)canBecomeKeyWindow
85 {
86     // Most panels can be come the key window. Exceptions are:
87     if (m_cocoaPlatformWindow->window()->windowType() == Qt::ToolTip)
88         return NO;
89     if (m_cocoaPlatformWindow->window()->windowType() == Qt::SplashScreen)
90         return NO;
91     return YES;
92 }
93
94 @end
95
96 QCocoaWindow::QCocoaWindow(QWindow *tlw)
97     : QPlatformWindow(tlw)
98     , m_nsWindow(0)
99     , m_glContext(0)
100     , m_inConstructor(true)
101 {
102     QCocoaAutoReleasePool pool;
103
104     m_contentView = [[QNSView alloc] initWithQWindow:tlw platformWindow:this];
105     setGeometry(tlw->geometry());
106
107     recreateWindow(parent());
108
109     m_inConstructor = false;
110 }
111
112 QCocoaWindow::~QCocoaWindow()
113 {
114     [m_contentView release];
115     clearNSWindow(m_nsWindow);
116     [m_nsWindow release];
117 }
118
119 void QCocoaWindow::setGeometry(const QRect &rect)
120 {
121     if (geometry() == rect)
122         return;
123 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
124     qDebug() << "QCocoaWindow::setGeometry" << this << rect;
125 #endif
126     QPlatformWindow::setGeometry(rect);
127     setCocoaGeometry(rect);
128 }
129
130 void QCocoaWindow::setCocoaGeometry(const QRect &rect)
131 {
132     if (m_nsWindow) {
133         NSRect bounds = qt_mac_flipRect(rect, window());
134         [m_nsWindow setContentSize : bounds.size];
135         [m_nsWindow setFrameOrigin : bounds.origin];
136     } else {
137         [m_contentView setFrame : NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height())];
138     }
139 }
140
141 void QCocoaWindow::setVisible(bool visible)
142 {
143     QCocoaAutoReleasePool pool;
144 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
145     qDebug() << "QCocoaWindow::setVisible" << window() << visible;
146 #endif
147     if (visible) {
148         if (window()->transientParent()) {
149             // The parent window might have moved while this window was hidden,
150             // update the window geometry if there is a parent.
151             setGeometry(window()->geometry());
152
153             // Register popup windows so that the parent window can
154             // close them when needed.
155             if (window()->windowType() == Qt::Popup) {
156                 // qDebug() << "transientParent and popup" << window()->windowType() << Qt::Popup << (window()->windowType() & Qt::Popup);
157
158                 QCocoaWindow *parentCocoaWindow = static_cast<QCocoaWindow *>(window()->transientParent()->handle());
159                 parentCocoaWindow->m_activePopupWindow = window();
160             }
161
162         }
163
164         // Make sure the QWindow has a frame ready before we show the NSWindow.
165         QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
166
167         if (m_nsWindow) {
168             if ([m_nsWindow canBecomeKeyWindow])
169                 [m_nsWindow makeKeyAndOrderFront:nil];
170             else
171                 [m_nsWindow orderFront: nil];
172         }
173     } else {
174         // qDebug() << "close" << this;
175         if (m_nsWindow)
176             [m_nsWindow orderOut:m_nsWindow];
177     }
178 }
179
180 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
181 {
182     m_windowFlags = flags;
183     return m_windowFlags;
184 }
185
186 void QCocoaWindow::setWindowTitle(const QString &title)
187 {
188     QCocoaAutoReleasePool pool;
189     if (!m_nsWindow)
190         return;
191
192     CFStringRef windowTitle = QCFString::toCFStringRef(title);
193     [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
194     CFRelease(windowTitle);
195 }
196
197 void QCocoaWindow::raise()
198 {
199     //qDebug() << "raise" << this;
200     // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
201     if (m_nsWindow)
202         [m_nsWindow orderFront: m_nsWindow];
203 }
204
205 void QCocoaWindow::lower()
206 {
207     if (m_nsWindow)
208         [m_nsWindow orderBack: m_nsWindow];
209 }
210
211 void QCocoaWindow::propagateSizeHints()
212 {
213     QCocoaAutoReleasePool pool;
214     if (!m_nsWindow)
215         return;
216
217     [m_nsWindow setMinSize : qt_mac_toNSSize(window()->minimumSize())];
218     [m_nsWindow setMaxSize : qt_mac_toNSSize(window()->maximumSize())];
219
220 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
221     qDebug() << "QCocoaWindow::propagateSizeHints" << this;
222     qDebug() << "     min/max " << window()->minimumSize() << window()->maximumSize();
223     qDebug() << "     basesize" << window()->baseSize();
224     qDebug() << "     geometry" << geometry();
225 #endif
226
227     if (!window()->sizeIncrement().isNull())
228         [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
229
230     QSize baseSize = window()->baseSize();
231     if (!baseSize.isNull() && baseSize.isValid()) {
232         [m_nsWindow setFrameSize : NSMakeSize(baseSize.width(), baseSize.height()) display : YES];
233     }
234 }
235
236 void QCocoaWindow::setOpacity(qreal level)
237 {
238     if (m_nsWindow)
239         [m_nsWindow setAlphaValue:level];
240 }
241
242 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
243 {
244     if (!m_nsWindow)
245         return false;
246
247     if (grab && ![m_nsWindow isKeyWindow])
248         [m_nsWindow makeKeyWindow];
249     else if (!grab && [m_nsWindow isKeyWindow])
250         [m_nsWindow resignKeyWindow];
251     return true;
252 }
253
254 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
255 {
256     if (!m_nsWindow)
257         return false;
258
259     if (grab && ![m_nsWindow isKeyWindow])
260         [m_nsWindow makeKeyWindow];
261     else if (!grab && [m_nsWindow isKeyWindow])
262         [m_nsWindow resignKeyWindow];
263     return true;
264 }
265
266 WId QCocoaWindow::winId() const
267 {
268     return WId(m_contentView);
269 }
270
271 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
272 {
273     // recreate the window for compatibility
274     recreateWindow(parentWindow);
275     setCocoaGeometry(geometry());
276 }
277
278 NSView *QCocoaWindow::contentView() const
279 {
280     return m_contentView;
281 }
282
283 void QCocoaWindow::windowWillMove()
284 {
285     // Close any open popups on window move
286     if (m_activePopupWindow) {
287         QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
288         m_activePopupWindow = 0;
289     }
290 }
291
292 void QCocoaWindow::windowDidMove()
293 {
294     [m_contentView updateGeometry];
295 }
296
297 void QCocoaWindow::windowDidResize()
298 {
299     if (!m_nsWindow)
300         return;
301
302     NSRect rect = [[m_nsWindow contentView]frame];
303     // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
304     [[m_nsWindow contentView] setFrameSize:rect.size];
305 }
306
307 void QCocoaWindow::windowWillClose()
308 {
309     QWindowSystemInterface::handleSynchronousCloseEvent(window());
310 }
311
312 bool QCocoaWindow::windowIsPopupType() const
313 {
314     Qt::WindowType type = window()->windowType();
315     if (type == Qt::Tool)
316         return false; // Qt::Tool has the Popup bit set but isn't, at least on Mac.
317
318     return ((type & Qt::Popup) == Qt::Popup);
319 }
320
321 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
322 {
323     m_glContext = context;
324 }
325
326 QCocoaGLContext *QCocoaWindow::currentContext() const
327 {
328     return m_glContext;
329 }
330
331 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
332 {
333     // Remove current window (if any)
334     if (m_nsWindow) {
335         clearNSWindow(m_nsWindow);
336         [m_nsWindow close];
337         [m_nsWindow release];
338         m_nsWindow = 0;
339     }
340
341     if (!parentWindow) {
342         // Create a new NSWindow if this is a top-level window.
343         m_nsWindow = createNSWindow();
344         setNSWindow(m_nsWindow);
345     } else {
346         // Child windows have no NSWindow, link the NSViews instead.
347         const QCocoaWindow *parentCococaWindow = static_cast<const QCocoaWindow *>(parentWindow);
348         [parentCococaWindow->m_contentView addSubview : m_contentView];
349     }
350 }
351
352 NSWindow * QCocoaWindow::createNSWindow()
353 {
354     QCocoaAutoReleasePool pool;
355
356     NSRect frame = qt_mac_flipRect(window()->geometry(), window());
357
358     Qt::WindowType type = window()->windowType();
359     Qt::WindowFlags flags = window()->windowFlags();
360
361     NSUInteger styleMask;
362     NSWindow *createdWindow = 0;
363
364     // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
365     if ((type & Qt::Popup) == Qt::Popup) {
366         if (windowIsPopupType()) {
367             styleMask = NSBorderlessWindowMask;
368         } else {
369             styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
370                          NSMiniaturizableWindowMask | NSTitledWindowMask);
371         }
372
373         QNSPanel *window;
374         window  = [[QNSPanel alloc] initWithContentRect:frame
375                                          styleMask: styleMask
376                                          backing:NSBackingStoreBuffered
377                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
378                                                     // before the window is shown and needs a proper window.).
379         [window setHasShadow:YES];
380         window->m_cocoaPlatformWindow = this;
381         createdWindow = window;
382     } else {
383         styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
384         QNSWindow *window;
385         window  = [[QNSWindow alloc] initWithContentRect:frame
386                                          styleMask: styleMask
387                                          backing:NSBackingStoreBuffered
388                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
389                                                     // before the window is shown and needs a proper window.).
390         window->m_cocoaPlatformWindow = this;
391
392 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
393     if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
394         // All windows with the WindowMaximizeButtonHint set also get a full-screen button.
395         if (flags & Qt::WindowMaximizeButtonHint)
396             [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
397     }
398 #endif
399
400         createdWindow = window;
401     }
402     return createdWindow;
403 }
404
405 void QCocoaWindow::setNSWindow(NSWindow *window)
406 {
407     QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
408     [window setDelegate:delegate];
409     [window setAcceptsMouseMovedEvents:YES];
410
411     // Prevent Cocoa from releasing the window on close. Qt
412     // handles the close event asynchronously and we want to
413     // make sure that m_nsWindow stays valid until the
414     // QCocoaWindow is deleted by Qt.
415     [window setReleasedWhenClosed : NO];
416
417     [[NSNotificationCenter defaultCenter] addObserver:m_contentView
418                                           selector:@selector(windowDidBecomeKey)
419                                           name:NSWindowDidBecomeKeyNotification
420                                           object:m_nsWindow];
421
422     [[NSNotificationCenter defaultCenter] addObserver:m_contentView
423                                           selector:@selector(windowDidResignKey)
424                                           name:NSWindowDidResignKeyNotification
425                                           object:m_nsWindow];
426
427     [[NSNotificationCenter defaultCenter] addObserver:m_contentView
428                                           selector:@selector(windowDidBecomeMain)
429                                           name:NSWindowDidBecomeMainNotification
430                                           object:m_nsWindow];
431
432     [[NSNotificationCenter defaultCenter] addObserver:m_contentView
433                                           selector:@selector(windowDidResignMain)
434                                           name:NSWindowDidResignMainNotification
435                                           object:m_nsWindow];
436
437
438     // ### Accept touch events by default.
439     // Beware that enabling touch events has a negative impact on the overall performance.
440     // We probably need a QWindowSystemInterface API to enable/disable touch events.
441     [m_contentView setAcceptsTouchEvents:YES];
442
443     [window setContentView:m_contentView];
444 }
445
446 void QCocoaWindow::clearNSWindow(NSWindow *window)
447 {
448     [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
449 }
450
451 // Returns the current global screen geometry for the nswindow associated with this window.
452 QRect QCocoaWindow::windowGeometry() const
453 {
454     if (!m_nsWindow)
455         return geometry();
456
457     NSRect rect = [m_nsWindow frame];
458     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
459     int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height;  // account for nswindow inverted y.
460     QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
461     return qRect;
462 }
463
464 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
465 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
466 {
467     if (window() && window()->transientParent()) {
468         return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
469     }
470     return 0;
471 }
472