Implement QCocoaWindow::setWindowState.
[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_inConstructor(true)
100     , m_glContext(0)
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     clearNSWindow(m_nsWindow);
115     [m_contentView release];
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             // setWindowState might have been called while the window was hidden and
169             // will not change the NSWindow state in that case. Sync up here:
170             syncWindowState(window()->windowState());
171
172             if (window()->windowState() != Qt::WindowMinimized) {
173                 if ([m_nsWindow canBecomeKeyWindow])
174                     [m_nsWindow makeKeyAndOrderFront:nil];
175                 else
176                     [m_nsWindow orderFront: nil];
177             }
178         }
179     } else {
180         // qDebug() << "close" << this;
181         if (m_nsWindow)
182             [m_nsWindow orderOut:m_nsWindow];
183         if (!QCoreApplication::closingDown())
184             QWindowSystemInterface::handleExposeEvent(window(), QRegion());
185     }
186 }
187
188 Qt::WindowFlags QCocoaWindow::setWindowFlags(Qt::WindowFlags flags)
189 {
190     m_windowFlags = flags;
191     return m_windowFlags;
192 }
193
194 Qt::WindowState QCocoaWindow::setWindowState(Qt::WindowState state)
195 {
196     if ([m_nsWindow isVisible])
197         syncWindowState(state);  // Window state set for hidden windows take effect when show() is called.
198
199     return state;
200 }
201
202 void QCocoaWindow::setWindowTitle(const QString &title)
203 {
204     QCocoaAutoReleasePool pool;
205     if (!m_nsWindow)
206         return;
207
208     CFStringRef windowTitle = QCFString::toCFStringRef(title);
209     [m_nsWindow setTitle: const_cast<NSString *>(reinterpret_cast<const NSString *>(windowTitle))];
210     CFRelease(windowTitle);
211 }
212
213 void QCocoaWindow::raise()
214 {
215     //qDebug() << "raise" << this;
216     // ### handle spaces (see Qt 4 raise_sys in qwidget_mac.mm)
217     if (!m_nsWindow)
218         return;
219     if ([m_nsWindow isVisible])
220         [m_nsWindow orderFront: m_nsWindow];
221 }
222
223 void QCocoaWindow::lower()
224 {
225     if (!m_nsWindow)
226         return;
227     if ([m_nsWindow isVisible])
228         [m_nsWindow orderBack: m_nsWindow];
229 }
230
231 void QCocoaWindow::propagateSizeHints()
232 {
233     QCocoaAutoReleasePool pool;
234     if (!m_nsWindow)
235         return;
236
237     [m_nsWindow setMinSize : qt_mac_toNSSize(window()->minimumSize())];
238     [m_nsWindow setMaxSize : qt_mac_toNSSize(window()->maximumSize())];
239
240 #ifdef QT_COCOA_ENABLE_WINDOW_DEBUG
241     qDebug() << "QCocoaWindow::propagateSizeHints" << this;
242     qDebug() << "     min/max " << window()->minimumSize() << window()->maximumSize();
243     qDebug() << "     basesize" << window()->baseSize();
244     qDebug() << "     geometry" << geometry();
245 #endif
246
247     if (!window()->sizeIncrement().isNull())
248         [m_nsWindow setResizeIncrements : qt_mac_toNSSize(window()->sizeIncrement())];
249
250     QRect rect = geometry();
251     QSize baseSize = window()->baseSize();
252     if (!baseSize.isNull() && baseSize.isValid()) {
253         [m_nsWindow setFrame:NSMakeRect(rect.x(), rect.y(), baseSize.width(), baseSize.height()) display:YES];
254     }
255 }
256
257 void QCocoaWindow::setOpacity(qreal level)
258 {
259     if (m_nsWindow)
260         [m_nsWindow setAlphaValue:level];
261 }
262
263 bool QCocoaWindow::setKeyboardGrabEnabled(bool grab)
264 {
265     if (!m_nsWindow)
266         return false;
267
268     if (grab && ![m_nsWindow isKeyWindow])
269         [m_nsWindow makeKeyWindow];
270     else if (!grab && [m_nsWindow isKeyWindow])
271         [m_nsWindow resignKeyWindow];
272     return true;
273 }
274
275 bool QCocoaWindow::setMouseGrabEnabled(bool grab)
276 {
277     if (!m_nsWindow)
278         return false;
279
280     if (grab && ![m_nsWindow isKeyWindow])
281         [m_nsWindow makeKeyWindow];
282     else if (!grab && [m_nsWindow isKeyWindow])
283         [m_nsWindow resignKeyWindow];
284     return true;
285 }
286
287 WId QCocoaWindow::winId() const
288 {
289     return WId(m_contentView);
290 }
291
292 void QCocoaWindow::setParent(const QPlatformWindow *parentWindow)
293 {
294     // recreate the window for compatibility
295     recreateWindow(parentWindow);
296     setCocoaGeometry(geometry());
297 }
298
299 NSView *QCocoaWindow::contentView() const
300 {
301     return m_contentView;
302 }
303
304 void QCocoaWindow::windowWillMove()
305 {
306     // Close any open popups on window move
307     if (m_activePopupWindow) {
308         QWindowSystemInterface::handleSynchronousCloseEvent(m_activePopupWindow);
309         m_activePopupWindow = 0;
310     }
311 }
312
313 void QCocoaWindow::windowDidMove()
314 {
315     [m_contentView updateGeometry];
316 }
317
318 void QCocoaWindow::windowDidResize()
319 {
320     if (!m_nsWindow)
321         return;
322
323     NSRect rect = [[m_nsWindow contentView]frame];
324     // Call setFrameSize which will trigger a frameDidChangeNotification on QNSView.
325     [[m_nsWindow contentView] setFrameSize:rect.size];
326 }
327
328 void QCocoaWindow::windowWillClose()
329 {
330     QWindowSystemInterface::handleSynchronousCloseEvent(window());
331 }
332
333 bool QCocoaWindow::windowIsPopupType() const
334 {
335     Qt::WindowType type = window()->windowType();
336     if (type == Qt::Tool)
337         return false; // Qt::Tool has the Popup bit set but isn't, at least on Mac.
338
339     return ((type & Qt::Popup) == Qt::Popup);
340 }
341
342 void QCocoaWindow::setCurrentContext(QCocoaGLContext *context)
343 {
344     m_glContext = context;
345 }
346
347 QCocoaGLContext *QCocoaWindow::currentContext() const
348 {
349     return m_glContext;
350 }
351
352 void QCocoaWindow::recreateWindow(const QPlatformWindow *parentWindow)
353 {
354     // Remove current window (if any)
355     if (m_nsWindow) {
356         clearNSWindow(m_nsWindow);
357         [m_nsWindow close];
358         [m_nsWindow release];
359         m_nsWindow = 0;
360     }
361
362     if (!parentWindow) {
363         // Create a new NSWindow if this is a top-level window.
364         m_nsWindow = createNSWindow();
365         setNSWindow(m_nsWindow);
366     } else {
367         // Child windows have no NSWindow, link the NSViews instead.
368         const QCocoaWindow *parentCococaWindow = static_cast<const QCocoaWindow *>(parentWindow);
369         [parentCococaWindow->m_contentView addSubview : m_contentView];
370     }
371 }
372
373 NSWindow * QCocoaWindow::createNSWindow()
374 {
375     QCocoaAutoReleasePool pool;
376
377     NSRect frame = qt_mac_flipRect(window()->geometry(), window());
378
379     Qt::WindowType type = window()->windowType();
380     Qt::WindowFlags flags = window()->windowFlags();
381
382     NSUInteger styleMask;
383     NSWindow *createdWindow = 0;
384     NSInteger windowLevel = -1;
385
386     if (type == Qt::Tool) {
387         windowLevel = NSFloatingWindowLevel;
388     } else if ((type & Qt::Popup) == Qt::Popup) {
389         // styleMask = NSBorderlessWindowMask;
390         windowLevel = NSPopUpMenuWindowLevel;
391
392         // Popup should be in at least the same level as its parent.
393         const QWindow * const transientParent = window()->transientParent();
394         const QCocoaWindow * const transientParentWindow = transientParent ? static_cast<QCocoaWindow *>(transientParent->handle()) : 0;
395         if (transientParentWindow)
396             windowLevel = qMax([transientParentWindow->m_nsWindow level], windowLevel);
397     }
398
399     // StayOnTop window should appear above Tool windows.
400     if (flags & Qt::WindowStaysOnTopHint)
401         windowLevel = NSPopUpMenuWindowLevel;
402     // Tooltips should appear above StayOnTop windows.
403     if (type == Qt::ToolTip)
404         windowLevel = NSScreenSaverWindowLevel;
405     // All other types are Normal level.
406     if (windowLevel == -1)
407         windowLevel = NSNormalWindowLevel;
408
409     // Use NSPanel for popup-type windows. (Popup, Tool, ToolTip, SplashScreen)
410     if ((type & Qt::Popup) == Qt::Popup) {
411         if (windowIsPopupType()) {
412             styleMask = NSBorderlessWindowMask;
413         } else {
414             styleMask = (NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask |
415                          NSMiniaturizableWindowMask | NSTitledWindowMask);
416         }
417
418         QNSPanel *window;
419         window  = [[QNSPanel alloc] initWithContentRect:frame
420                                          styleMask: styleMask
421                                          backing:NSBackingStoreBuffered
422                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
423                                                     // before the window is shown and needs a proper window.).
424         [window setHasShadow:YES];
425         window->m_cocoaPlatformWindow = this;
426         createdWindow = window;
427     } else {
428         styleMask = (NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask);
429         QNSWindow *window;
430         window  = [[QNSWindow alloc] initWithContentRect:frame
431                                          styleMask: styleMask
432                                          backing:NSBackingStoreBuffered
433                                          defer:NO]; // Deferring window creation breaks OpenGL (the GL context is set up
434                                                     // before the window is shown and needs a proper window.).
435         window->m_cocoaPlatformWindow = this;
436
437 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
438     if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
439         // All windows with the WindowMaximizeButtonHint set also get a full-screen button.
440         if (flags & Qt::WindowMaximizeButtonHint)
441             [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
442     }
443 #endif
444
445         createdWindow = window;
446     }
447
448     [createdWindow setLevel:windowLevel];
449
450     return createdWindow;
451 }
452
453 void QCocoaWindow::setNSWindow(NSWindow *window)
454 {
455     QNSWindowDelegate *delegate = [[QNSWindowDelegate alloc] initWithQCocoaWindow:this];
456     [window setDelegate:delegate];
457     [window setAcceptsMouseMovedEvents:YES];
458
459     // Prevent Cocoa from releasing the window on close. Qt
460     // handles the close event asynchronously and we want to
461     // make sure that m_nsWindow stays valid until the
462     // QCocoaWindow is deleted by Qt.
463     [window setReleasedWhenClosed : NO];
464
465
466     [[NSNotificationCenter defaultCenter] addObserver:m_contentView
467                                           selector:@selector(windowNotification:)
468                                           name:nil // Get all notifications
469                                           object:m_nsWindow];
470
471     // ### Accept touch events by default.
472     // Beware that enabling touch events has a negative impact on the overall performance.
473     // We probably need a QWindowSystemInterface API to enable/disable touch events.
474     [m_contentView setAcceptsTouchEvents:YES];
475
476     [window setContentView:m_contentView];
477 }
478
479 void QCocoaWindow::clearNSWindow(NSWindow *window)
480 {
481     [window setDelegate:nil];
482     [[NSNotificationCenter defaultCenter] removeObserver:m_contentView];
483 }
484
485 // Returns the current global screen geometry for the nswindow associated with this window.
486 QRect QCocoaWindow::windowGeometry() const
487 {
488     if (!m_nsWindow)
489         return geometry();
490
491     NSRect rect = [m_nsWindow frame];
492     QPlatformScreen *onScreen = QPlatformScreen::platformScreenForWindow(window());
493     int flippedY = onScreen->geometry().height() - rect.origin.y - rect.size.height;  // account for nswindow inverted y.
494     QRect qRect = QRect(rect.origin.x, flippedY, rect.size.width, rect.size.height);
495     return qRect;
496 }
497
498 // Returns a pointer to the parent QCocoaWindow for this window, or 0 if there is none.
499 QCocoaWindow *QCocoaWindow::parentCocoaWindow() const
500 {
501     if (window() && window()->transientParent()) {
502         return static_cast<QCocoaWindow*>(window()->transientParent()->handle());
503     }
504     return 0;
505 }
506
507 // Syncs the NSWindow minimize/maximize/fullscreen state with the current QWindow state
508 void QCocoaWindow::syncWindowState(Qt::WindowState newState)
509 {
510     if (!m_nsWindow)
511         return;
512
513     switch (newState) {
514         case Qt::WindowMinimized:
515             [m_nsWindow performMiniaturize : m_nsWindow];
516         break;
517         case Qt::WindowMaximized:
518             [m_nsWindow performZoom : m_nsWindow];
519         break;
520         case Qt::WindowFullScreen:
521 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
522             if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
523                 [m_nsWindow toggleFullScreen : m_nsWindow];
524             } else {
525                 qWarning("Not implemented: setWindowState WindowFullScreen");
526             }
527 #endif
528         break;
529
530         default:
531             // Undo current states
532             if ([m_nsWindow isMiniaturized])
533                 [m_nsWindow deminiaturize : m_nsWindow];
534
535             if ([m_nsWindow isZoomed])
536                 [m_nsWindow performZoom : m_nsWindow]; // toggles
537
538 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
539             if (QSysInfo::QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) {
540                 if (window()->windowState() & Qt::WindowFullScreen)
541                     [m_nsWindow toggleFullScreen : m_nsWindow];
542             } else {
543                 qWarning("Not implemented: setWindowState WindowFullScreen");
544             }
545 #endif
546         break;
547     }
548 }
549
550 bool QCocoaWindow::setWindowModified(bool modified)
551 {
552     if (!m_nsWindow)
553         return false;
554     [m_nsWindow setDocumentEdited:(modified?YES:NO)];
555     return true;
556 }