Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qcocoasystemtrayicon.mm
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2012 Klaralvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Christoph Schleifenbaum <christoph.schleifenbaum@kdab.com>
3// Copyright (c) 2007-2008, Apple, Inc.
4// SPDX-License-Identifier: BSD-3-Clause
5// Qt-Security score:significant reason:default
6
7#include <AppKit/AppKit.h>
8
10
11#ifndef QT_NO_SYSTEMTRAYICON
12
13#include <qtemporaryfile.h>
14#include <qimagewriter.h>
15#include <qdebug.h>
16
17#include <QtCore/private/qcore_mac_p.h>
18
19#include "qcocoamenu.h"
20#include "qcocoansmenu.h"
21
22#include "qcocoahelpers.h"
24#include "qcocoascreen.h"
25#include <QtGui/private/qcoregraphics_p.h>
26
27// NSUserNotification was deprecated in macOS 11.
28// We should be using UserNotifications.framework instead.
29// See QTBUG-110998 for more information.
30#define NSUserNotificationCenter QT_IGNORE_DEPRECATIONS(NSUserNotificationCenter)
31#define NSUserNotification QT_IGNORE_DEPRECATIONS(NSUserNotification)
32
34
35void QCocoaSystemTrayIcon::init()
36{
37 m_statusItem = [[NSStatusBar.systemStatusBar statusItemWithLength:NSSquareStatusItemLength] retain];
38
39 m_delegate = [[QStatusItemDelegate alloc] initWithSysTray:this];
40
41 // In case the status item does not have a menu assigned to it
42 // we fall back to the item's button to detect activation.
43 m_statusItem.button.target = m_delegate;
44 m_statusItem.button.action = @selector(statusItemClicked);
45 [m_statusItem.button sendActionOn:NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown | NSEventMaskOtherMouseDown];
46}
47
48void QCocoaSystemTrayIcon::cleanup()
49{
50 NSUserNotificationCenter *center = NSUserNotificationCenter.defaultUserNotificationCenter;
51 if (center.delegate == m_delegate)
52 center.delegate = nil;
53
54 [NSStatusBar.systemStatusBar removeStatusItem:m_statusItem];
55 [m_statusItem release];
56 m_statusItem = nil;
57
58 [m_delegate release];
59 m_delegate = nil;
60}
61
62QRect QCocoaSystemTrayIcon::geometry() const
63{
64 if (!m_statusItem)
65 return QRect();
66
67 if (NSWindow *window = m_statusItem.button.window) {
68 if (QCocoaScreen *screen = QCocoaScreen::get(window.screen))
69 return screen->mapFromNative(window.frame).toRect();
70 }
71
72 return QRect();
73}
74
75static bool heightCompareFunction (QSize a, QSize b) { return (a.height() < b.height()); }
76static QList<QSize> sortByHeight(const QList<QSize> &sizes)
77{
78 QList<QSize> sorted = sizes;
79 std::sort(sorted.begin(), sorted.end(), heightCompareFunction);
80 return sorted;
81}
82
83void QCocoaSystemTrayIcon::updateIcon(const QIcon &icon)
84{
85 if (!m_statusItem)
86 return;
87
88 // The recommended maximum title bar icon height is 18 points
89 // (device independent pixels). The menu height on past and
90 // current OS X versions is 22 points. Provide some future-proofing
91 // by deriving the icon height from the menu height.
92 const int padding = 4;
93 const int menuHeight = NSStatusBar.systemStatusBar.thickness;
94 const int maxImageHeight = menuHeight - padding;
95
96 // Select pixmap based on the device pixel height. Ideally we would use
97 // the devicePixelRatio of the target screen, but that value is not
98 // known until draw time. Use qApp->devicePixelRatio, which returns the
99 // devicePixelRatio for the "best" screen on the system.
100 qreal devicePixelRatio = qApp->devicePixelRatio();
101 const int maxPixmapHeight = maxImageHeight * devicePixelRatio;
102 QSize selectedSize;
103 for (const QSize& size : sortByHeight(icon.availableSizes())) {
104 // Select a pixmap based on the height. We want the largest pixmap
105 // with a height smaller or equal to maxPixmapHeight. The pixmap
106 // may rectangular; assume it has a reasonable size. If there is
107 // not suitable pixmap use the smallest one the icon can provide.
108 if (size.height() <= maxPixmapHeight) {
109 selectedSize = size;
110 } else {
111 if (!selectedSize.isValid())
112 selectedSize = size;
113 break;
114 }
115 }
116
117 // Handle SVG icons, which do not return anything for availableSizes().
118 if (!selectedSize.isValid())
119 selectedSize = icon.actualSize(QSize(maxPixmapHeight, maxPixmapHeight));
120
121 QPixmap pixmap = icon.pixmap(selectedSize);
122
123 // Draw a low-resolution icon if there is not enough pixels for a retina
124 // icon. This prevents showing a small icon on retina displays.
125 if (devicePixelRatio > 1.0 && selectedSize.height() < maxPixmapHeight / 2)
126 devicePixelRatio = 1.0;
127
128 // Scale large pixmaps to fit the available menu bar area.
129 if (pixmap.height() > maxPixmapHeight)
130 pixmap = pixmap.scaledToHeight(maxPixmapHeight, Qt::SmoothTransformation);
131
132 // The icon will be stretched over the full height of the menu bar
133 // therefore we create a second pixmap which has the full height
134 QSize fullHeightSize(!pixmap.isNull() ? pixmap.width():
135 menuHeight * devicePixelRatio,
136 menuHeight * devicePixelRatio);
137 QPixmap fullHeightPixmap(fullHeightSize);
138 fullHeightPixmap.fill(Qt::transparent);
139 if (!pixmap.isNull()) {
140 QPainter p(&fullHeightPixmap);
141 QRect r = pixmap.rect();
142 r.moveCenter(fullHeightPixmap.rect().center());
143 p.drawPixmap(r, pixmap);
144 }
145 fullHeightPixmap.setDevicePixelRatio(devicePixelRatio);
146
147 auto *nsimage = [NSImage imageFromQImage:fullHeightPixmap.toImage()];
148 [nsimage setTemplate:icon.isMask()];
149 m_statusItem.button.image = nsimage;
150 m_statusItem.button.imageScaling = NSImageScaleProportionallyDown;
151}
152
153void QCocoaSystemTrayIcon::updateMenu(QPlatformMenu *menu)
154{
155 auto *nsMenu = menu ? static_cast<QCocoaMenu *>(menu)->nsMenu() : nil;
156 if (m_statusItem.menu == nsMenu)
157 return;
158
159 if (m_statusItem.menu) {
160 [NSNotificationCenter.defaultCenter removeObserver:m_delegate
161 name:NSMenuDidBeginTrackingNotification
162 object:m_statusItem.menu
163 ];
164 }
165
166 m_statusItem.menu = nsMenu;
167
168 if (m_statusItem.menu) {
169 // When a menu is assigned, NSStatusBarButtonCell will intercept the mouse
170 // down to pop up the menu, and we never see the NSStatusBarButton action.
171 // To ensure we emit the 'activated' signal in both cases we detect when
172 // menu starts tracking, which happens before the menu delegate is sent
173 // the menuWillOpen callback we use to emit aboutToShow for the menu.
174 [NSNotificationCenter.defaultCenter addObserver:m_delegate
175 selector:@selector(statusItemMenuBeganTracking:)
176 name:NSMenuDidBeginTrackingNotification
177 object:m_statusItem.menu
178 ];
179 }
180}
181
182void QCocoaSystemTrayIcon::updateToolTip(const QString &toolTip)
183{
184 if (!m_statusItem)
185 return;
186
187 m_statusItem.button.toolTip = toolTip.toNSString();
188}
189
190bool QCocoaSystemTrayIcon::isSystemTrayAvailable() const
191{
192 return true;
193}
194
195bool QCocoaSystemTrayIcon::supportsMessages() const
196{
197 return true;
198}
199
200void QCocoaSystemTrayIcon::showMessage(const QString &title, const QString &message,
201 const QIcon& icon, MessageIcon, int msecs)
202{
203 if (!m_statusItem)
204 return;
205
206 auto *notification = [[NSUserNotification alloc] init];
207 notification.title = title.toNSString();
208 notification.informativeText = message.toNSString();
209 notification.contentImage = [NSImage imageFromQIcon:icon];
210
211 NSUserNotificationCenter *center = NSUserNotificationCenter.defaultUserNotificationCenter;
212 center.delegate = m_delegate;
213
214 [center deliverNotification:[notification autorelease]];
215
216 if (msecs) {
217 NSTimeInterval timeout = msecs / 1000.0;
218 [center performSelector:@selector(removeDeliveredNotification:) withObject:notification afterDelay:timeout];
219 }
220}
221
222void QCocoaSystemTrayIcon::emitActivated()
223{
224 auto *mouseEvent = NSApp.currentEvent;
225
226 auto activationReason = QPlatformSystemTrayIcon::Unknown;
227
228 if (mouseEvent.clickCount == 2) {
229 activationReason = QPlatformSystemTrayIcon::DoubleClick;
230 } else {
231 auto mouseButton = cocoaButton2QtButton(mouseEvent);
232 if (mouseButton == Qt::MiddleButton)
233 activationReason = QPlatformSystemTrayIcon::MiddleClick;
234 else if (mouseButton == Qt::RightButton)
235 activationReason = QPlatformSystemTrayIcon::Context;
236 else
237 activationReason = QPlatformSystemTrayIcon::Trigger;
238 }
239
240 emit activated(activationReason);
241}
242
243QT_END_NAMESPACE
244
245@implementation QStatusItemDelegate
246
247- (instancetype)initWithSysTray:(QCocoaSystemTrayIcon *)platformSystemTray
248{
249 if ((self = [super init]))
250 self.platformSystemTray = platformSystemTray;
251
252 return self;
253}
254
255- (void)dealloc
256{
257 self.platformSystemTray = nullptr;
258 [super dealloc];
259}
260
261- (void)statusItemClicked
262{
263 self.platformSystemTray->emitActivated();
264}
265
266- (void)statusItemMenuBeganTracking:(NSNotification*)notification
267{
268 self.platformSystemTray->emitActivated();
269}
270
271- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification
272{
273 Q_UNUSED(center);
274 Q_UNUSED(notification);
275 return YES;
276}
277
278- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
279{
280 [center removeDeliveredNotification:notification];
281 emit self.platformSystemTray->messageClicked();
282}
283
284@end
285
286#endif // QT_NO_SYSTEMTRAYICON
static bool heightCompareFunction(QSize a, QSize b)
#define NSUserNotificationCenter
static QList< QSize > sortByHeight(const QList< QSize > &sizes)
#define NSUserNotification