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/qpainter.h>
26#include <QtGui/private/qcoregraphics_p.h>
27
28// NSUserNotification was deprecated in macOS 11.
29// We should be using UserNotifications.framework instead.
30// See QTBUG-110998 for more information.
31#define NSUserNotificationCenter QT_IGNORE_DEPRECATIONS(NSUserNotificationCenter)
32#define NSUserNotification QT_IGNORE_DEPRECATIONS(NSUserNotification)
33
35
36void QCocoaSystemTrayIcon::init()
37{
38 m_statusItem = [[NSStatusBar.systemStatusBar statusItemWithLength:NSSquareStatusItemLength] retain];
39
40 m_delegate = [[QStatusItemDelegate alloc] initWithSysTray:this];
41
42 // In case the status item does not have a menu assigned to it
43 // we fall back to the item's button to detect activation.
44 m_statusItem.button.target = m_delegate;
45 m_statusItem.button.action = @selector(statusItemClicked);
46 [m_statusItem.button sendActionOn:NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown | NSEventMaskOtherMouseDown];
47}
48
49void QCocoaSystemTrayIcon::cleanup()
50{
51 NSUserNotificationCenter *center = NSUserNotificationCenter.defaultUserNotificationCenter;
52 if (center.delegate == m_delegate)
53 center.delegate = nil;
54
55 [NSStatusBar.systemStatusBar removeStatusItem:m_statusItem];
56 [m_statusItem release];
57 m_statusItem = nil;
58
59 [m_delegate release];
60 m_delegate = nil;
61}
62
63QRect QCocoaSystemTrayIcon::geometry() const
64{
65 if (!m_statusItem)
66 return QRect();
67
68 if (NSWindow *window = m_statusItem.button.window) {
69 if (QCocoaScreen *screen = QCocoaScreen::get(window.screen))
70 return screen->mapFromNative(window.frame).toRect();
71 }
72
73 return QRect();
74}
75
76static bool heightCompareFunction (QSize a, QSize b) { return (a.height() < b.height()); }
77static QList<QSize> sortByHeight(const QList<QSize> &sizes)
78{
79 QList<QSize> sorted = sizes;
80 std::sort(sorted.begin(), sorted.end(), heightCompareFunction);
81 return sorted;
82}
83
84void QCocoaSystemTrayIcon::updateIcon(const QIcon &icon)
85{
86 if (!m_statusItem)
87 return;
88
89 if (auto *image = [NSImage internalImageFromQIcon:icon]) {
90 // The icon is backed by QAppleIconEngine, in which case we
91 // want to pass on the underlying NSImage instead of flattening
92 // to a QImage. This preserves the isTemplate property of the
93 // image, and allows AppKit to size and configure the icon for
94 // the status bar. We also enable NSVariableStatusItemLength,
95 // to match the behavior of SwiftUI's MenuBarExtra.
96 m_statusItem.button.image = [[image copy] autorelease];
97 m_statusItem.button.imageScaling = NSImageScaleProportionallyDown;
98 m_statusItem.length = NSVariableStatusItemLength;
99 return;
100 }
101
102 // The recommended maximum title bar icon height is 18 points
103 // (device independent pixels). The menu height on past and
104 // current OS X versions is 22 points. Provide some future-proofing
105 // by deriving the icon height from the menu height.
106 const int padding = 4;
107 const int menuHeight = NSStatusBar.systemStatusBar.thickness;
108 const int maxImageHeight = menuHeight - padding;
109
110 // Select pixmap based on the device pixel height. Ideally we would use
111 // the devicePixelRatio of the target screen, but that value is not
112 // known until draw time. Use qApp->devicePixelRatio, which returns the
113 // devicePixelRatio for the "best" screen on the system.
114 qreal devicePixelRatio = qApp->devicePixelRatio();
115 const int maxPixmapHeight = maxImageHeight * devicePixelRatio;
116 QSize selectedSize;
117 for (const QSize& size : sortByHeight(icon.availableSizes())) {
118 // Select a pixmap based on the height. We want the largest pixmap
119 // with a height smaller or equal to maxPixmapHeight. The pixmap
120 // may rectangular; assume it has a reasonable size. If there is
121 // not suitable pixmap use the smallest one the icon can provide.
122 if (size.height() <= maxPixmapHeight) {
123 selectedSize = size;
124 } else {
125 if (!selectedSize.isValid())
126 selectedSize = size;
127 break;
128 }
129 }
130
131 // Handle SVG icons, which do not return anything for availableSizes().
132 if (!selectedSize.isValid())
133 selectedSize = icon.actualSize(QSize(maxPixmapHeight, maxPixmapHeight));
134
135 QPixmap pixmap = icon.pixmap(selectedSize);
136
137 // Draw a low-resolution icon if there is not enough pixels for a retina
138 // icon. This prevents showing a small icon on retina displays.
139 if (devicePixelRatio > 1.0 && selectedSize.height() < maxPixmapHeight / 2)
140 devicePixelRatio = 1.0;
141
142 // Scale large pixmaps to fit the available menu bar area.
143 if (pixmap.height() > maxPixmapHeight)
144 pixmap = pixmap.scaledToHeight(maxPixmapHeight, Qt::SmoothTransformation);
145
146 // The icon will be stretched over the full height of the menu bar
147 // therefore we create a second pixmap which has the full height
148 QSize fullHeightSize(!pixmap.isNull() ? pixmap.width():
149 menuHeight * devicePixelRatio,
150 menuHeight * devicePixelRatio);
151 QPixmap fullHeightPixmap(fullHeightSize);
152 fullHeightPixmap.fill(Qt::transparent);
153 if (!pixmap.isNull()) {
154 QPainter p(&fullHeightPixmap);
155 QRect r = pixmap.rect();
156 r.moveCenter(fullHeightPixmap.rect().center());
157 p.drawPixmap(r, pixmap);
158 }
159 fullHeightPixmap.setDevicePixelRatio(devicePixelRatio);
160
161 auto *nsimage = [NSImage imageFromQImage:fullHeightPixmap.toImage()];
162 [nsimage setTemplate:icon.isMask()];
163 m_statusItem.button.image = nsimage;
164 m_statusItem.button.imageScaling = NSImageScaleProportionallyDown;
165}
166
167void QCocoaSystemTrayIcon::updateMenu(QPlatformMenu *menu)
168{
169 auto *nsMenu = menu ? static_cast<QCocoaMenu *>(menu)->nsMenu() : nil;
170 if (m_statusItem.menu == nsMenu)
171 return;
172
173 if (m_statusItem.menu) {
174 [NSNotificationCenter.defaultCenter removeObserver:m_delegate
175 name:NSMenuDidBeginTrackingNotification
176 object:m_statusItem.menu
177 ];
178 }
179
180 m_statusItem.menu = nsMenu;
181
182 if (m_statusItem.menu) {
183 // When a menu is assigned, NSStatusBarButtonCell will intercept the mouse
184 // down to pop up the menu, and we never see the NSStatusBarButton action.
185 // To ensure we emit the 'activated' signal in both cases we detect when
186 // menu starts tracking, which happens before the menu delegate is sent
187 // the menuWillOpen callback we use to emit aboutToShow for the menu.
188 [NSNotificationCenter.defaultCenter addObserver:m_delegate
189 selector:@selector(statusItemMenuBeganTracking:)
190 name:NSMenuDidBeginTrackingNotification
191 object:m_statusItem.menu
192 ];
193 }
194}
195
196void QCocoaSystemTrayIcon::updateToolTip(const QString &toolTip)
197{
198 if (!m_statusItem)
199 return;
200
201 m_statusItem.button.toolTip = toolTip.toNSString();
202}
203
204bool QCocoaSystemTrayIcon::isSystemTrayAvailable() const
205{
206 return true;
207}
208
209bool QCocoaSystemTrayIcon::supportsMessages() const
210{
211 return true;
212}
213
214void QCocoaSystemTrayIcon::showMessage(const QString &title, const QString &message,
215 const QIcon& icon, MessageIcon, int msecs)
216{
217 if (!m_statusItem)
218 return;
219
220 auto *notification = [[NSUserNotification alloc] init];
221 notification.title = title.toNSString();
222 notification.informativeText = message.toNSString();
223
224 // Request a size that looks good on the highest resolution screen available
225 // for icon engines that don't have an intrinsic size (like SVG).
226 auto image = icon.pixmap(QSize(64, 64), qGuiApp->devicePixelRatio()).toImage();
227
228 // The assigned image is scaled by the system to fit into the tile,
229 // but without taking aspect ratio into account, so let's pad the
230 // image up front if it's not already square.
231 image = qt_mac_padToSquareImage(image);
232
233 notification.contentImage = [NSImage imageFromQImage:image];
234
235 NSUserNotificationCenter *center = NSUserNotificationCenter.defaultUserNotificationCenter;
236 center.delegate = m_delegate;
237
238 [center deliverNotification:[notification autorelease]];
239
240 if (msecs) {
241 NSTimeInterval timeout = msecs / 1000.0;
242 [center performSelector:@selector(removeDeliveredNotification:) withObject:notification afterDelay:timeout];
243 }
244}
245
246void QCocoaSystemTrayIcon::emitActivated()
247{
248 // NSControls are driven by gesture recognizers in macOS 27,
249 // which means NSApp.currentEvent may not be a mouse event
250 // at the point when we receive the status bar button's
251 // action callback. This is a quick fix to avoid crashing.
252 if (!qt_mac_isMouseEvent(NSApp.currentEvent)) {
253 emit activated(QPlatformSystemTrayIcon::Unknown);
254 return;
255 }
256
257 auto *mouseEvent = NSApp.currentEvent;
258
259 auto activationReason = QPlatformSystemTrayIcon::Unknown;
260
261 if (mouseEvent.clickCount == 2) {
262 activationReason = QPlatformSystemTrayIcon::DoubleClick;
263 } else {
264 auto mouseButton = cocoaButton2QtButton(mouseEvent);
265 if (mouseButton == Qt::MiddleButton)
266 activationReason = QPlatformSystemTrayIcon::MiddleClick;
267 else if (mouseButton == Qt::RightButton)
268 activationReason = QPlatformSystemTrayIcon::Context;
269 else
270 activationReason = QPlatformSystemTrayIcon::Trigger;
271 }
272
273 emit activated(activationReason);
274}
275
276QT_END_NAMESPACE
277
278@implementation QStatusItemDelegate
279
280- (instancetype)initWithSysTray:(QCocoaSystemTrayIcon *)platformSystemTray
281{
282 if ((self = [super init]))
283 self.platformSystemTray = platformSystemTray;
284
285 return self;
286}
287
288- (void)dealloc
289{
290 self.platformSystemTray = nullptr;
291 [super dealloc];
292}
293
294- (void)statusItemClicked
295{
296 self.platformSystemTray->emitActivated();
297}
298
299- (void)statusItemMenuBeganTracking:(NSNotification*)notification
300{
301 self.platformSystemTray->emitActivated();
302}
303
304- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification
305{
306 Q_UNUSED(center);
307 Q_UNUSED(notification);
308 return YES;
309}
310
311- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
312{
313 [center removeDeliveredNotification:notification];
314 emit self.platformSystemTray->messageClicked();
315}
316
317@end
318
319#endif // QT_NO_SYSTEMTRAYICON
Combined button and popup list for selecting options.
static bool heightCompareFunction(QSize a, QSize b)
#define NSUserNotificationCenter
static QList< QSize > sortByHeight(const QList< QSize > &sizes)
#define NSUserNotification