1 /****************************************************************************
3 ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtGui module of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
42 /****************************************************************************
44 ** Copyright (c) 2007-2008, Apple, Inc.
46 ** All rights reserved.
48 ** Redistribution and use in source and binary forms, with or without
49 ** modification, are permitted provided that the following conditions are met:
51 ** * Redistributions of source code must retain the above copyright notice,
52 ** this list of conditions and the following disclaimer.
54 ** * Redistributions in binary form must reproduce the above copyright notice,
55 ** this list of conditions and the following disclaimer in the documentation
56 ** and/or other materials provided with the distribution.
58 ** * Neither the name of Apple, Inc. nor the names of its contributors
59 ** may be used to endorse or promote products derived from this software
60 ** without specific prior written permission.
62 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
63 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
64 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
65 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
66 ** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
67 ** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
68 ** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
69 ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
70 ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
71 ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
72 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
74 ****************************************************************************/
76 #define QT_MAC_SYSTEMTRAY_USE_GROWL
78 #include <private/qt_cocoa_helpers_mac_p.h>
79 #include <private/qsystemtrayicon_p.h>
80 #include <qtemporaryfile.h>
81 #include <qimagewriter.h>
82 #include <qapplication.h>
86 #include <private/qt_mac_p.h>
87 #import <AppKit/AppKit.h>
90 extern bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret); //qapplication_mac.cpp
91 extern void qtsystray_sendActivated(QSystemTrayIcon *i, int r); //qsystemtrayicon.cpp
92 extern NSString *keySequenceToKeyEqivalent(const QKeySequence &accel); // qmenu_mac.mm
93 extern NSUInteger keySequenceModifierMask(const QKeySequence &accel); // qmenu_mac.mm
94 extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum);
99 @class QT_MANGLE_NAMESPACE(QNSMenu);
100 @class QT_MANGLE_NAMESPACE(QNSImageView);
102 @interface QT_MANGLE_NAMESPACE(QNSStatusItem) : NSObject {
104 QSystemTrayIcon *icon;
105 QSystemTrayIconPrivate *iconPrivate;
106 QT_MANGLE_NAMESPACE(QNSImageView) *imageCell;
108 -(id)initWithIcon:(QSystemTrayIcon*)icon iconPrivate:(QSystemTrayIconPrivate *)iprivate;
110 -(QSystemTrayIcon*)icon;
111 -(NSStatusItem*)item;
113 - (void)triggerSelector:(id)sender button:(Qt::MouseButton)mouseButton;
114 - (void)doubleClickSelector:(id)sender;
117 @interface QT_MANGLE_NAMESPACE(QNSImageView) : NSImageView {
119 QT_MANGLE_NAMESPACE(QNSStatusItem) *parent;
121 -(id)initWithParent:(QT_MANGLE_NAMESPACE(QNSStatusItem)*)myParent;
122 -(QSystemTrayIcon*)icon;
123 -(void)menuTrackingDone:(NSNotification*)notification;
124 -(void)mousePressed:(NSEvent *)mouseEvent button:(Qt::MouseButton)mouseButton;
128 #if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
130 @protocol NSMenuDelegate <NSObject>
131 -(void)menuNeedsUpdate:(NSMenu*)menu;
136 @interface QT_MANGLE_NAMESPACE(QNSMenu) : NSMenu <NSMenuDelegate> {
140 -(id)initWithQMenu:(QMenu*)qmenu;
141 -(void)selectedAction:(id)item;
145 class QSystemTrayIconSys
148 QSystemTrayIconSys(QSystemTrayIcon *icon, QSystemTrayIconPrivate *d) {
149 QMacCocoaAutoReleasePool pool;
150 item = [[QT_MANGLE_NAMESPACE(QNSStatusItem) alloc] initWithIcon:icon iconPrivate:d];
152 ~QSystemTrayIconSys() {
153 QMacCocoaAutoReleasePool pool;
154 [[[item item] view] setHidden: YES];
157 QT_MANGLE_NAMESPACE(QNSStatusItem) *item;
160 void QSystemTrayIconPrivate::install_sys()
162 Q_Q(QSystemTrayIcon);
164 sys = new QSystemTrayIconSys(q, this);
171 QRect QSystemTrayIconPrivate::geometry_sys() const
174 const QRectF geom = [sys->item geometry];
176 return geom.toRect();
181 void QSystemTrayIconPrivate::remove_sys()
187 void QSystemTrayIconPrivate::updateIcon_sys()
189 if(sys && !icon.isNull()) {
190 QMacCocoaAutoReleasePool pool;
191 #ifndef QT_MAC_USE_COCOA
192 const short scale = GetMBarHeight()-4;
194 CGFloat hgt = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
195 const short scale = hgt - 4;
197 NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(icon.pixmap(QSize(scale, scale))));
198 [(NSImageView*)[[sys->item item] view] setImage: nsimage];
203 void QSystemTrayIconPrivate::updateMenu_sys()
206 QMacCocoaAutoReleasePool pool;
207 if(menu && !menu->isEmpty()) {
208 [[sys->item item] setHighlightMode:YES];
210 [[sys->item item] setHighlightMode:NO];
215 void QSystemTrayIconPrivate::updateToolTip_sys()
218 QMacCocoaAutoReleasePool pool;
219 QCFString string(toolTip);
220 [[[sys->item item] view] setToolTip:(NSString*)static_cast<CFStringRef>(string)];
224 bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
229 bool QSystemTrayIconPrivate::supportsMessages_sys()
234 void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon icon, int)
238 #ifdef QT_MAC_SYSTEMTRAY_USE_GROWL
239 // Make sure that we have Growl installed on the machine we are running on.
240 QCFType<CFURLRef> cfurl;
241 OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator,
242 CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
243 if (status == kLSApplicationNotFoundErr)
245 QCFType<CFBundleRef> bundle = CFBundleCreate(0, cfurl);
247 if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"),
248 kCFCompareCaseInsensitive | kCFCompareBackwards) != kCFCompareEqualTo)
250 QPixmap notificationIconPixmap;
251 if(icon == QSystemTrayIcon::Information)
252 notificationIconPixmap = QApplication::style()->standardPixmap(QStyle::SP_MessageBoxInformation);
253 else if(icon == QSystemTrayIcon::Warning)
254 notificationIconPixmap = QApplication::style()->standardPixmap(QStyle::SP_MessageBoxWarning);
255 else if(icon == QSystemTrayIcon::Critical)
256 notificationIconPixmap = QApplication::style()->standardPixmap(QStyle::SP_MessageBoxCritical);
257 QTemporaryFile notificationIconFile;
258 QString notificationType(QLatin1String("Notification")), notificationIcon, notificationApp(QApplication::applicationName());
259 if(notificationApp.isEmpty())
260 notificationApp = QLatin1String("Application");
261 if(!notificationIconPixmap.isNull() && notificationIconFile.open()) {
262 QImageWriter writer(¬ificationIconFile, "PNG");
263 if(writer.write(notificationIconPixmap.toImage()))
264 notificationIcon = QLatin1String("image from location \"file://") + notificationIconFile.fileName() + QLatin1String("\"");
266 const QString script(QLatin1String(
267 "tell application \"GrowlHelperApp\"\n"
268 "-- Make a list of all the notification types (all)\n"
269 "set the allNotificationsList to {\"") + notificationType + QLatin1String("\"}\n"
271 "-- Make a list of the notifications (enabled)\n"
272 "set the enabledNotificationsList to {\"") + notificationType + QLatin1String("\"}\n"
274 "-- Register our script with growl.\n"
275 "register as application \"") + notificationApp + QLatin1String("\" all notifications allNotificationsList default notifications enabledNotificationsList\n"
277 "-- Send a Notification...\n") +
278 QLatin1String("notify with name \"") + notificationType +
279 QLatin1String("\" title \"") + title +
280 QLatin1String("\" description \"") + message +
281 QLatin1String("\" application name \"") + notificationApp +
282 QLatin1String("\" ") + notificationIcon +
283 QLatin1String("\nend tell"));
284 qt_mac_execute_apple_script(script, 0);
286 Q_Q(QSystemTrayIcon);
287 NSView *v = [[sys->item item] view];
288 NSWindow *w = [v window];
289 w = [[sys->item item] window];
291 QPoint p(qRound([w frame].origin.x), qRound([w frame].origin.y));
293 QBalloonTip::showBalloon(icon, message, title, q, QPoint(0, 0), msecs);
303 @implementation NSStatusItem (Qt)
306 @implementation QT_MANGLE_NAMESPACE(QNSImageView)
307 -(id)initWithParent:(QT_MANGLE_NAMESPACE(QNSStatusItem)*)myParent {
314 -(QSystemTrayIcon*)icon {
315 return [parent icon];
318 -(void)menuTrackingDone:(NSNotification*)notification
320 Q_UNUSED(notification);
323 if( ![self icon]->icon().isNull() ) {
324 #ifndef QT_MAC_USE_COCOA
325 const short scale = GetMBarHeight()-4;
327 CGFloat hgt = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
328 const short scale = hgt - 4;
330 NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage([self icon]->icon().pixmap(QSize(scale, scale))));
331 [self setImage: nsimage];
335 if([self icon]->contextMenu())
336 [self icon]->contextMenu()->hide();
338 [self setNeedsDisplay:YES];
341 -(void)mousePressed:(NSEvent *)mouseEvent button:(Qt::MouseButton)mouseButton
344 int clickCount = [mouseEvent clickCount];
345 [self setNeedsDisplay:YES];
347 #ifndef QT_MAC_USE_COCOA
348 const short scale = GetMBarHeight()-4;
350 CGFloat hgt = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
351 const short scale = hgt - 4;
354 if (![self icon]->icon().isNull() ) {
355 NSImage *nsaltimage = static_cast<NSImage *>(qt_mac_create_nsimage([self icon]->icon().pixmap(QSize(scale, scale), QIcon::Selected)));
356 [self setImage: nsaltimage];
357 [nsaltimage release];
360 if ((clickCount == 2)) {
361 [self menuTrackingDone:nil];
362 [parent doubleClickSelector:self];
364 [parent triggerSelector:self button:mouseButton];
368 -(void)mouseDown:(NSEvent *)mouseEvent
370 [self mousePressed:mouseEvent button:Qt::LeftButton];
373 -(void)mouseUp:(NSEvent *)mouseEvent
375 Q_UNUSED(mouseEvent);
376 [self menuTrackingDone:nil];
379 - (void)rightMouseDown:(NSEvent *)mouseEvent
381 [self mousePressed:mouseEvent button:Qt::RightButton];
384 -(void)rightMouseUp:(NSEvent *)mouseEvent
386 Q_UNUSED(mouseEvent);
387 [self menuTrackingDone:nil];
390 - (void)otherMouseDown:(NSEvent *)mouseEvent
392 [self mousePressed:mouseEvent button:cocoaButton2QtButton([mouseEvent buttonNumber])];
395 -(void)otherMouseUp:(NSEvent *)mouseEvent
397 Q_UNUSED(mouseEvent);
398 [self menuTrackingDone:nil];
401 -(void)drawRect:(NSRect)rect {
402 [[parent item] drawStatusBarBackgroundInRect:rect withHighlight:down];
403 [super drawRect:rect];
407 @implementation QT_MANGLE_NAMESPACE(QNSStatusItem)
409 -(id)initWithIcon:(QSystemTrayIcon*)i iconPrivate:(QSystemTrayIconPrivate *)iPrivate
414 iconPrivate = iPrivate;
415 item = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
416 imageCell = [[QT_MANGLE_NAMESPACE(QNSImageView) alloc] initWithParent:self];
417 [item setView: imageCell];
422 [[NSStatusBar systemStatusBar] removeStatusItem:item];
429 -(QSystemTrayIcon*)icon {
433 -(NSStatusItem*)item {
437 if(NSWindow *window = [[item view] window]) {
438 NSRect screenRect = [[window screen] frame];
439 NSRect windowRect = [window frame];
440 return QRectF(windowRect.origin.x, screenRect.size.height-windowRect.origin.y-windowRect.size.height, windowRect.size.width, windowRect.size.height);
445 - (void)triggerSelector:(id)sender button:(Qt::MouseButton)mouseButton {
450 if (mouseButton == Qt::MidButton)
451 qtsystray_sendActivated(icon, QSystemTrayIcon::MiddleClick);
453 qtsystray_sendActivated(icon, QSystemTrayIcon::Trigger);
455 if (icon->contextMenu()) {
456 #ifndef QT_MAC_USE_COCOA
457 [[[self item] view] removeAllToolTips];
458 iconPrivate->updateToolTip_sys();
460 NSMenu *m = [[QT_MANGLE_NAMESPACE(QNSMenu) alloc] initWithQMenu:icon->contextMenu()];
461 [m setAutoenablesItems: NO];
462 [[NSNotificationCenter defaultCenter] addObserver:imageCell
463 selector:@selector(menuTrackingDone:)
464 name:NSMenuDidEndTrackingNotification
466 [item popUpStatusItemMenu: m];
471 - (void)doubleClickSelector:(id)sender {
475 qtsystray_sendActivated(icon, QSystemTrayIcon::DoubleClick);
480 class QSystemTrayIconQMenu : public QMenu
483 void doAboutToShow() { emit aboutToShow(); }
485 QSystemTrayIconQMenu();
488 @implementation QT_MANGLE_NAMESPACE(QNSMenu)
489 -(id)initWithQMenu:(QMenu*)qm {
493 [self setDelegate:self];
500 -(void)menuNeedsUpdate:(NSMenu*)nsmenu {
501 QT_MANGLE_NAMESPACE(QNSMenu) *menu = static_cast<QT_MANGLE_NAMESPACE(QNSMenu) *>(nsmenu);
502 emit static_cast<QSystemTrayIconQMenu*>(menu->qmenu)->doAboutToShow();
503 for(int i = [menu numberOfItems]-1; i >= 0; --i)
504 [menu removeItemAtIndex:i];
505 QList<QAction*> actions = menu->qmenu->actions();;
506 for(int i = 0; i < actions.size(); ++i) {
507 const QAction *action = actions[i];
508 if(!action->isVisible())
511 NSMenuItem *item = 0;
512 bool needRelease = false;
513 if(action->isSeparator()) {
514 item = [NSMenuItem separatorItem];
516 item = [[NSMenuItem alloc] init];
518 QString text = action->text();
519 QKeySequence accel = action->shortcut();
521 int st = text.lastIndexOf(QLatin1Char('\t'));
523 accel = QKeySequence(text.right(text.length()-(st+1)));
524 text.remove(st, text.length()-st);
527 if(accel.count() > 1)
528 text += QLatin1String(" (****)"); //just to denote a multi stroke shortcut
530 [item setTitle:(NSString*)QCFString::toCFStringRef(qt_mac_removeMnemonics(text))];
531 [item setEnabled:menu->qmenu->isEnabled() && action->isEnabled()];
532 [item setState:action->isChecked() ? NSOnState : NSOffState];
533 [item setToolTip:(NSString*)QCFString::toCFStringRef(action->toolTip())];
534 const QIcon icon = action->icon();
535 if (!icon.isNull() && action->isIconVisibleInMenu()) {
536 #ifndef QT_MAC_USE_COCOA
537 const short scale = GetMBarHeight();
539 const short scale = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
541 NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(icon.pixmap(QSize(scale, scale))));
542 [item setImage: nsimage];
546 QT_MANGLE_NAMESPACE(QNSMenu) *sub = [[QT_MANGLE_NAMESPACE(QNSMenu) alloc] initWithQMenu:action->menu()];
547 [item setSubmenu:sub];
549 [item setAction:@selector(selectedAction:)];
550 [item setTarget:self];
552 if(!accel.isEmpty()) {
553 [item setKeyEquivalent:keySequenceToKeyEqivalent(accel)];
554 [item setKeyEquivalentModifierMask:keySequenceModifierMask(accel)];
563 -(void)selectedAction:(id)a {
564 const int activated = [self indexOfItem:a];
566 QList<QAction*> actions = qmenu->actions();
567 for(int i = 0, cnt = 0; i < actions.size(); ++i) {
568 if(actions.at(i)->isVisible() && (cnt++) == activated) {
569 action = actions.at(i);
574 action->activate(QAction::Trigger);