1 /****************************************************************************
2 **
3 ** Copyright (C) 2017 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the plugins of the Qt Toolkit.
7 **
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 The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
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 3 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 3 requirements
23 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24 **
25 ** GNU General Public License Usage
26 ** Alternatively, this file may be used under the terms of the GNU
27 ** General Public License version 2.0 or (at your option) the GNU General
28 ** Public license version 3 or any later version approved by the KDE Free
29 ** Qt Foundation. The licenses are as published by the Free Software
30 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31 ** included in the packaging of this file. Please review the following
32 ** information to ensure the GNU General Public License requirements will
33 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34 ** https://www.gnu.org/licenses/gpl-3.0.html.
35 **
36 ** $QT_END_LICENSE$
37 **
38 ****************************************************************************/
39 
40 #if defined(WINVER) && WINVER < 0x0601
41 #  undef WINVER
42 #endif
43 #if !defined(WINVER)
44 #  define WINVER 0x0601 // required for NOTIFYICONDATA_V2_SIZE, ChangeWindowMessageFilterEx() (MinGW 5.3)
45 #endif
46 
47 #if defined(NTDDI_VERSION) && NTDDI_VERSION < 0x06010000
48 #  undef NTDDI_VERSION
49 #endif
50 #if !defined(NTDDI_VERSION)
51 #  define NTDDI_VERSION 0x06010000 // required for Shell_NotifyIconGetRect (MinGW 5.3)
52 #endif
53 
54 #include "qwindowssystemtrayicon.h"
55 #include "qwindowscontext.h"
56 #include "qwindowstheme.h"
57 #include "qwindowsmenu.h"
58 #include "qwindowsscreen.h"
59 
60 #include <QtGui/qguiapplication.h>
61 #include <QtGui/qpixmap.h>
62 #include <QtCore/qdebug.h>
63 #include <QtCore/qrect.h>
64 #include <QtCore/qvector.h>
65 #include <QtCore/qsettings.h>
66 #include <qpa/qwindowsysteminterface.h>
67 
68 #include <qt_windows.h>
69 #include <commctrl.h>
70 #include <shellapi.h>
71 #include <shlobj.h>
72 #include <windowsx.h>
73 
74 QT_BEGIN_NAMESPACE
75 
76 static const UINT q_uNOTIFYICONID = 0;
77 
78 static uint MYWM_TASKBARCREATED = 0;
79 #define MYWM_NOTIFYICON (WM_APP+101)
80 
81 Q_GUI_EXPORT HICON qt_pixmapToWinHICON(const QPixmap &);
82 
83 // Copy QString data to a limited wchar_t array including \0.
qStringToLimitedWCharArray(QString in,wchar_t * target,int maxLength)84 static inline void qStringToLimitedWCharArray(QString in, wchar_t *target, int maxLength)
85 {
86     const int length = qMin(maxLength - 1, in.size());
87     if (length < in.size())
88         in.truncate(length);
89     in.toWCharArray(target);
90     target[length] = wchar_t(0);
91 }
92 
initNotifyIconData(NOTIFYICONDATA & tnd)93 static inline void initNotifyIconData(NOTIFYICONDATA &tnd)
94 {
95     memset(&tnd, 0, sizeof(NOTIFYICONDATA));
96     tnd.cbSize = sizeof(NOTIFYICONDATA);
97     tnd.uVersion = NOTIFYICON_VERSION_4;
98 }
99 
setIconContents(NOTIFYICONDATA & tnd,const QString & tip,HICON hIcon)100 static void setIconContents(NOTIFYICONDATA &tnd, const QString &tip, HICON hIcon)
101 {
102     tnd.uFlags |= NIF_MESSAGE | NIF_ICON | NIF_TIP;
103     tnd.uCallbackMessage = MYWM_NOTIFYICON;
104     tnd.hIcon = hIcon;
105     qStringToLimitedWCharArray(tip, tnd.szTip, sizeof(tnd.szTip) / sizeof(wchar_t));
106 }
107 
setIconVisibility(NOTIFYICONDATA & tnd,bool v)108 static void setIconVisibility(NOTIFYICONDATA &tnd, bool v)
109 {
110     tnd.uFlags |= NIF_STATE;
111     tnd.dwStateMask = NIS_HIDDEN;
112     tnd.dwState = v ? 0 : NIS_HIDDEN;
113 }
114 
115 // Match the HWND of the dummy window to the instances
116 struct QWindowsHwndSystemTrayIconEntry
117 {
118     HWND hwnd;
119     QWindowsSystemTrayIcon *trayIcon;
120 };
121 
122 using HwndTrayIconEntries = QVector<QWindowsHwndSystemTrayIconEntry>;
123 
Q_GLOBAL_STATIC(HwndTrayIconEntries,hwndTrayIconEntries)124 Q_GLOBAL_STATIC(HwndTrayIconEntries, hwndTrayIconEntries)
125 
126 static int indexOfHwnd(HWND hwnd)
127 {
128     const HwndTrayIconEntries *entries = hwndTrayIconEntries();
129     for (int i = 0, size = entries->size(); i < size; ++i) {
130         if (entries->at(i).hwnd == hwnd)
131             return i;
132     }
133     return -1;
134 }
135 
qWindowsTrayIconWndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)136 extern "C" LRESULT QT_WIN_CALLBACK qWindowsTrayIconWndProc(HWND hwnd, UINT message,
137                                                            WPARAM wParam, LPARAM lParam)
138 {
139     // QTBUG-79248: Trigger screen update if there are no other windows.
140     if (message == WM_DPICHANGED && QGuiApplication::topLevelWindows().isEmpty())
141         QWindowsContext::instance()->screenManager().handleScreenChanges();
142     if (message == MYWM_TASKBARCREATED || message == MYWM_NOTIFYICON
143         || message == WM_INITMENU || message == WM_INITMENUPOPUP
144         || message == WM_CLOSE || message == WM_COMMAND) {
145         const int index = indexOfHwnd(hwnd);
146         if (index >= 0) {
147             MSG msg;
148             msg.hwnd = hwnd;         // re-create MSG structure
149             msg.message = message;   // time and pt fields ignored
150             msg.wParam = wParam;
151             msg.lParam = lParam;
152             msg.pt.x = GET_X_LPARAM(lParam);
153             msg.pt.y = GET_Y_LPARAM(lParam);
154             long result = 0;
155             if (hwndTrayIconEntries()->at(index).trayIcon->winEvent(msg, &result))
156                 return result;
157         }
158     }
159     return DefWindowProc(hwnd, message, wParam, lParam);
160 }
161 
162 // Note: Message windows (HWND_MESSAGE) are not sufficient, they
163 // will not receive the "TaskbarCreated" message.
createTrayIconMessageWindow()164 static inline HWND createTrayIconMessageWindow()
165 {
166     QWindowsContext *ctx = QWindowsContext::instance();
167     if (!ctx)
168         return nullptr;
169     // Register window class in the platform plugin.
170     const QString className =
171         ctx->registerWindowClass(QWindowsContext::classNamePrefix() + QStringLiteral("TrayIconMessageWindowClass"),
172                                  qWindowsTrayIconWndProc);
173     const wchar_t windowName[] = L"QTrayIconMessageWindow";
174     return CreateWindowEx(0, reinterpret_cast<const wchar_t *>(className.utf16()),
175                           windowName, WS_OVERLAPPED,
176                           CW_USEDEFAULT, CW_USEDEFAULT,
177                           CW_USEDEFAULT, CW_USEDEFAULT,
178                           nullptr, nullptr,
179                           static_cast<HINSTANCE>(GetModuleHandle(nullptr)), nullptr);
180 }
181 
182 /*!
183     \class QWindowsSystemTrayIcon
184     \brief Windows native system tray icon
185 
186     \internal
187 */
188 
QWindowsSystemTrayIcon()189 QWindowsSystemTrayIcon::QWindowsSystemTrayIcon()
190 {
191 }
192 
~QWindowsSystemTrayIcon()193 QWindowsSystemTrayIcon::~QWindowsSystemTrayIcon()
194 {
195     qCDebug(lcQpaTrayIcon) << __FUNCTION__ << this;
196     ensureCleanup();
197 }
198 
init()199 void QWindowsSystemTrayIcon::init()
200 {
201     qCDebug(lcQpaTrayIcon) << __FUNCTION__ << this;
202     m_visible = true;
203     if (!setIconVisible(m_visible))
204         ensureInstalled();
205 }
206 
cleanup()207 void QWindowsSystemTrayIcon::cleanup()
208 {
209     qCDebug(lcQpaTrayIcon) << __FUNCTION__ << this;
210     m_visible = false;
211     ensureCleanup();
212 }
213 
updateIcon(const QIcon & icon)214 void QWindowsSystemTrayIcon::updateIcon(const QIcon &icon)
215 {
216     qCDebug(lcQpaTrayIcon) << __FUNCTION__ << '(' << icon << ')' << this;
217     if (icon.cacheKey() == m_icon.cacheKey())
218         return;
219     const HICON hIconToDestroy = createIcon(icon);
220     if (ensureInstalled())
221         sendTrayMessage(NIM_MODIFY);
222     if (hIconToDestroy)
223         DestroyIcon(hIconToDestroy);
224 }
225 
updateToolTip(const QString & tooltip)226 void QWindowsSystemTrayIcon::updateToolTip(const QString &tooltip)
227 {
228     qCDebug(lcQpaTrayIcon) << __FUNCTION__ << '(' << tooltip << ')' << this;
229     if (m_toolTip == tooltip)
230         return;
231     m_toolTip = tooltip;
232     if (isInstalled())
233         sendTrayMessage(NIM_MODIFY);
234 }
235 
geometry() const236 QRect QWindowsSystemTrayIcon::geometry() const
237 {
238     NOTIFYICONIDENTIFIER nid;
239     memset(&nid, 0, sizeof(nid));
240     nid.cbSize = sizeof(nid);
241     nid.hWnd = m_hwnd;
242     nid.uID = q_uNOTIFYICONID;
243     RECT rect;
244     const QRect result = SUCCEEDED(Shell_NotifyIconGetRect(&nid, &rect))
245         ? QRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top)
246         : QRect();
247     qCDebug(lcQpaTrayIcon) << __FUNCTION__ << this << "returns" << result;
248     return result;
249 }
250 
showMessage(const QString & title,const QString & messageIn,const QIcon & icon,QPlatformSystemTrayIcon::MessageIcon iconType,int msecsIn)251 void QWindowsSystemTrayIcon::showMessage(const QString &title, const QString &messageIn,
252                                          const QIcon &icon,
253                                          QPlatformSystemTrayIcon::MessageIcon iconType,
254                                          int msecsIn)
255 {
256     qCDebug(lcQpaTrayIcon) << __FUNCTION__ << '(' << title << messageIn << icon
257         << iconType << msecsIn  << ')' << this;
258     if (!supportsMessages())
259         return;
260     // For empty messages, ensures that they show when only title is set
261     QString message = messageIn;
262     if (message.isEmpty() && !title.isEmpty())
263         message.append(u' ');
264 
265     NOTIFYICONDATA tnd;
266     initNotifyIconData(tnd);
267     qStringToLimitedWCharArray(message, tnd.szInfo, 256);
268     qStringToLimitedWCharArray(title, tnd.szInfoTitle, 64);
269 
270     tnd.uID = q_uNOTIFYICONID;
271     tnd.dwInfoFlags = NIIF_USER;
272 
273     QSize size(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
274     const QSize largeIcon(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
275     const QSize more = icon.actualSize(largeIcon);
276     if (more.height() > (largeIcon.height() * 3/4) || more.width() > (largeIcon.width() * 3/4)) {
277         tnd.dwInfoFlags |= NIIF_LARGE_ICON;
278         size = largeIcon;
279     }
280     QPixmap pm = icon.pixmap(size);
281     if (pm.isNull()) {
282         tnd.dwInfoFlags = NIIF_INFO;
283     } else {
284         if (pm.size() != size) {
285             qWarning("QSystemTrayIcon::showMessage: Wrong icon size (%dx%d), please add standard one: %dx%d",
286                       pm.size().width(), pm.size().height(), size.width(), size.height());
287             pm = pm.scaled(size, Qt::IgnoreAspectRatio);
288         }
289         tnd.hBalloonIcon = qt_pixmapToWinHICON(pm);
290     }
291     tnd.hWnd = m_hwnd;
292     tnd.uTimeout = msecsIn <= 0 ?  UINT(10000) : UINT(msecsIn); // 10s default
293     tnd.uFlags = NIF_INFO | NIF_SHOWTIP;
294 
295     Shell_NotifyIcon(NIM_MODIFY, &tnd);
296 }
297 
supportsMessages() const298 bool QWindowsSystemTrayIcon::supportsMessages() const
299 {
300     // The key does typically not exist on Windows 10, default to true.
301     return QWindowsContext::readAdvancedExplorerSettings(L"EnableBalloonTips", 1) != 0;
302 }
303 
createMenu() const304 QPlatformMenu *QWindowsSystemTrayIcon::createMenu() const
305 {
306     if (QWindowsTheme::useNativeMenus() && m_menu.isNull())
307         m_menu = new QWindowsPopupMenu;
308     qCDebug(lcQpaTrayIcon) << __FUNCTION__ << this << "returns" << m_menu.data();
309     return m_menu.data();
310 }
311 
312 // Delay-install until an Icon exists
ensureInstalled()313 bool QWindowsSystemTrayIcon::ensureInstalled()
314 {
315     if (isInstalled())
316         return true;
317     if (m_hIcon == nullptr)
318         return false;
319     m_hwnd = createTrayIconMessageWindow();
320     if (Q_UNLIKELY(m_hwnd == nullptr))
321         return false;
322     // For restoring the tray icon after explorer crashes
323     if (!MYWM_TASKBARCREATED)
324         MYWM_TASKBARCREATED = RegisterWindowMessage(L"TaskbarCreated");
325     // Allow the WM_TASKBARCREATED message through the UIPI filter
326     ChangeWindowMessageFilterEx(m_hwnd, MYWM_TASKBARCREATED, MSGFLT_ALLOW, nullptr);
327     qCDebug(lcQpaTrayIcon) << __FUNCTION__ << this << "MYWM_TASKBARCREATED=" << MYWM_TASKBARCREATED;
328 
329     QWindowsHwndSystemTrayIconEntry entry{m_hwnd, this};
330     hwndTrayIconEntries()->append(entry);
331     sendTrayMessage(NIM_ADD);
332     return true;
333 }
334 
ensureCleanup()335 void QWindowsSystemTrayIcon::ensureCleanup()
336 {
337     if (isInstalled()) {
338         const int index = indexOfHwnd(m_hwnd);
339         if (index >= 0)
340             hwndTrayIconEntries()->removeAt(index);
341         sendTrayMessage(NIM_DELETE);
342         DestroyWindow(m_hwnd);
343         m_hwnd = nullptr;
344     }
345     if (m_hIcon != nullptr)
346         DestroyIcon(m_hIcon);
347     m_hIcon = nullptr;
348     m_menu = nullptr; // externally owned
349     m_toolTip.clear();
350 }
351 
setIconVisible(bool visible)352 bool QWindowsSystemTrayIcon::setIconVisible(bool visible)
353 {
354     if (!isInstalled())
355         return false;
356     NOTIFYICONDATA tnd;
357     initNotifyIconData(tnd);
358     tnd.uID = q_uNOTIFYICONID;
359     tnd.hWnd = m_hwnd;
360     setIconVisibility(tnd, visible);
361     return Shell_NotifyIcon(NIM_MODIFY, &tnd) == TRUE;
362 }
363 
sendTrayMessage(DWORD msg)364 bool QWindowsSystemTrayIcon::sendTrayMessage(DWORD msg)
365 {
366     NOTIFYICONDATA tnd;
367     initNotifyIconData(tnd);
368     tnd.uID = q_uNOTIFYICONID;
369     tnd.hWnd = m_hwnd;
370     tnd.uFlags = NIF_SHOWTIP;
371     if (msg != NIM_DELETE && !m_visible)
372         setIconVisibility(tnd, m_visible);
373     if (msg == NIM_ADD || msg == NIM_MODIFY)
374         setIconContents(tnd, m_toolTip, m_hIcon);
375     if (!Shell_NotifyIcon(msg, &tnd))
376         return false;
377     return msg != NIM_ADD || Shell_NotifyIcon(NIM_SETVERSION, &tnd);
378 }
379 
380 // Return the old icon to be freed after modifying the tray icon.
createIcon(const QIcon & icon)381 HICON QWindowsSystemTrayIcon::createIcon(const QIcon &icon)
382 {
383     const HICON oldIcon = m_hIcon;
384     m_hIcon = nullptr;
385     if (icon.isNull())
386         return oldIcon;
387     const QSize requestedSize = QSize(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
388     const QSize size = icon.actualSize(requestedSize);
389     const QPixmap pm = icon.pixmap(size);
390     if (!pm.isNull())
391         m_hIcon = qt_pixmapToWinHICON(pm);
392     return oldIcon;
393 }
394 
winEvent(const MSG & message,long * result)395 bool QWindowsSystemTrayIcon::winEvent(const MSG &message, long *result)
396 {
397     *result = 0;
398     switch (message.message) {
399     case MYWM_NOTIFYICON: {
400         Q_ASSERT(q_uNOTIFYICONID == HIWORD(message.lParam));
401         const int trayMessage = LOWORD(message.lParam);
402         switch (trayMessage) {
403         case NIN_SELECT:
404         case NIN_KEYSELECT:
405             if (m_ignoreNextMouseRelease)
406                 m_ignoreNextMouseRelease = false;
407             else
408                 emit activated(Trigger);
409             break;
410         case WM_LBUTTONDBLCLK:
411             m_ignoreNextMouseRelease = true; // Since DBLCLICK Generates a second mouse
412             emit activated(DoubleClick);     // release we must ignore it
413             break;
414         case WM_CONTEXTMENU: {
415             // QTBUG-67966: Coordinates may be out of any screen in PROCESS_DPI_UNAWARE mode
416             // since hi-res coordinates are delivered in this case (Windows issue).
417             // Default to primary screen with check to prevent a crash.
418             const QPoint globalPos = QPoint(GET_X_LPARAM(message.wParam), GET_Y_LPARAM(message.wParam));
419             const auto &screenManager = QWindowsContext::instance()->screenManager();
420             const QPlatformScreen *screen = screenManager.screenAtDp(globalPos);
421             if (!screen)
422                 screen = screenManager.screens().value(0);
423             if (screen) {
424                 emit contextMenuRequested(globalPos, screen);
425                 emit activated(Context);
426                 if (m_menu) {
427                     // Set the foreground window to the controlling window so that clicking outside
428                     // of the menu or window will cause the menu to close
429                     SetForegroundWindow(m_hwnd);
430                     m_menu->trackPopupMenu(message.hwnd, globalPos.x(), globalPos.y());
431                 }
432             }
433         }
434             break;
435         case NIN_BALLOONUSERCLICK:
436             emit messageClicked();
437             break;
438         case WM_MBUTTONUP:
439             emit activated(MiddleClick);
440             break;
441         default:
442             break;
443         }
444     }
445         break;
446     case WM_INITMENU:
447     case WM_INITMENUPOPUP:
448         QWindowsPopupMenu::notifyAboutToShow(reinterpret_cast<HMENU>(message.wParam));
449         break;
450     case WM_CLOSE:
451         QWindowSystemInterface::handleApplicationTermination<QWindowSystemInterface::SynchronousDelivery>();
452         break;
453     case WM_COMMAND:
454         QWindowsPopupMenu::notifyTriggered(LOWORD(message.wParam));
455         break;
456     default:
457         if (message.message == MYWM_TASKBARCREATED) // self-registered message id (tray crashed)
458             sendTrayMessage(NIM_ADD);
459         break;
460     }
461     return false;
462 }
463 
464 #ifndef QT_NO_DEBUG_STREAM
465 
formatDebug(QDebug & d) const466 void QWindowsSystemTrayIcon::formatDebug(QDebug &d) const
467 {
468     d << static_cast<const void *>(this) << ", \"" << m_toolTip
469         << "\", hwnd=" << m_hwnd << ", m_hIcon=" << m_hIcon << ", menu="
470         << m_menu.data();
471 }
472 
operator <<(QDebug d,const QWindowsSystemTrayIcon * t)473 QDebug operator<<(QDebug d, const QWindowsSystemTrayIcon *t)
474 {
475     QDebugStateSaver saver(d);
476     d.nospace();
477     d.noquote();
478     d << "QWindowsSystemTrayIcon(";
479     if (t)
480         t->formatDebug(d);
481     else
482         d << '0';
483     d << ')';
484     return d;
485 }
486 #endif // !QT_NO_DEBUG_STREAM
487 
488 QT_END_NAMESPACE
489