source: trunk/src/gui/util/qsystemtrayicon_win.cpp@ 694

Last change on this file since 694 was 651, checked in by Dmitry A. Kuminov, 16 years ago

trunk: Merged in qt 4.6.2 sources.

File size: 17.3 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtGui module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "qsystemtrayicon_p.h"
43#ifndef QT_NO_SYSTEMTRAYICON
44#define _WIN32_IE 0x0600 //required for NOTIFYICONDATA_V2_SIZE
45
46//missing defines for MINGW :
47#ifndef NIN_BALLOONTIMEOUT
48#define NIN_BALLOONTIMEOUT (WM_USER + 4)
49#endif
50#ifndef NIN_BALLOONUSERCLICK
51#define NIN_BALLOONUSERCLICK (WM_USER + 5)
52#endif
53
54#include <qt_windows.h>
55#include <commctrl.h>
56#include <shlwapi.h>
57#include <QBitmap>
58#include <QLibrary>
59#include <QApplication>
60#include <QToolTip>
61#include <QDesktopWidget>
62#include <QSettings>
63
64#if defined(Q_WS_WINCE) && !defined(STANDARDSHELL_UI_MODEL)
65# include <streams.h>
66#endif
67
68QT_BEGIN_NAMESPACE
69
70#if defined(Q_WS_WINCE)
71static const UINT q_uNOTIFYICONID = 13; // IDs from 0 to 12 are reserved on WinCE.
72#else
73static const UINT q_uNOTIFYICONID = 0;
74#endif
75
76static uint MYWM_TASKBARCREATED = 0;
77#define MYWM_NOTIFYICON (WM_APP+101)
78
79struct Q_NOTIFYICONIDENTIFIER {
80 DWORD cbSize;
81 HWND hWnd;
82 UINT uID;
83 GUID guidItem;
84};
85
86#define Q_MSGFLT_ALLOW 1
87
88typedef HRESULT (WINAPI *PtrShell_NotifyIconGetRect)(const Q_NOTIFYICONIDENTIFIER* identifier, RECT* iconLocation);
89typedef BOOL (WINAPI *PtrChangeWindowMessageFilter)(UINT message, DWORD dwFlag);
90typedef BOOL (WINAPI *PtrChangeWindowMessageFilterEx)(HWND hWnd, UINT message, DWORD action, void* pChangeFilterStruct);
91
92class QSystemTrayIconSys : QWidget
93{
94public:
95 QSystemTrayIconSys(QSystemTrayIcon *object);
96 ~QSystemTrayIconSys();
97 bool winEvent( MSG *m, long *result );
98 bool trayMessage(DWORD msg);
99 bool iconDrawItem(LPDRAWITEMSTRUCT lpdi);
100 void setIconContents(NOTIFYICONDATA &data);
101 bool showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs);
102 bool allowsMessages();
103 bool supportsMessages();
104 QRect findIconGeometry(const int a_iButtonID);
105 void createIcon();
106 HICON hIcon;
107 QPoint globalPos;
108 QSystemTrayIcon *q;
109private:
110 uint notifyIconSize;
111 int maxTipLength;
112 bool ignoreNextMouseRelease;
113};
114
115bool QSystemTrayIconSys::allowsMessages()
116{
117#ifndef QT_NO_SETTINGS
118 QSettings settings(QLatin1String("HKEY_CURRENT_USER\\Software\\Microsoft"
119 "\\Windows\\CurrentVersion\\Explorer\\Advanced"), QSettings::NativeFormat);
120 return settings.value(QLatin1String("EnableBalloonTips"), true).toBool();
121#else
122 return false;
123#endif
124}
125
126bool QSystemTrayIconSys::supportsMessages()
127{
128#ifndef Q_OS_WINCE
129 return allowsMessages();
130#endif
131 return false;
132}
133
134QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *object)
135 : hIcon(0), q(object), ignoreNextMouseRelease(false)
136
137{
138#ifndef Q_OS_WINCE
139 notifyIconSize = FIELD_OFFSET(NOTIFYICONDATA, guidItem); // NOTIFYICONDATAW_V2_SIZE;
140 maxTipLength = 128;
141#else
142 notifyIconSize = FIELD_OFFSET(NOTIFYICONDATA, szTip[64]); // NOTIFYICONDATAW_V1_SIZE;
143 maxTipLength = 64;
144#endif
145
146 // For restoring the tray icon after explorer crashes
147 if (!MYWM_TASKBARCREATED) {
148 MYWM_TASKBARCREATED = RegisterWindowMessage(L"TaskbarCreated");
149 }
150
151 // Allow the WM_TASKBARCREATED message through the UIPI filter on Windows Vista and higher
152 static PtrChangeWindowMessageFilterEx pChangeWindowMessageFilterEx =
153 (PtrChangeWindowMessageFilterEx)QLibrary::resolve(QLatin1String("user32"), "ChangeWindowMessageFilterEx");
154
155 if (pChangeWindowMessageFilterEx) {
156 // Call the safer ChangeWindowMessageFilterEx API if available
157 pChangeWindowMessageFilterEx(winId(), MYWM_TASKBARCREATED, Q_MSGFLT_ALLOW, 0);
158 } else {
159 static PtrChangeWindowMessageFilter pChangeWindowMessageFilter =
160 (PtrChangeWindowMessageFilter)QLibrary::resolve(QLatin1String("user32"), "ChangeWindowMessageFilter");
161
162 if (pChangeWindowMessageFilter) {
163 // Call the deprecated ChangeWindowMessageFilter API otherwise
164 pChangeWindowMessageFilter(MYWM_TASKBARCREATED, Q_MSGFLT_ALLOW);
165 }
166 }
167}
168
169QSystemTrayIconSys::~QSystemTrayIconSys()
170{
171 if (hIcon)
172 DestroyIcon(hIcon);
173}
174
175void QSystemTrayIconSys::setIconContents(NOTIFYICONDATA &tnd)
176{
177 tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
178 tnd.uCallbackMessage = MYWM_NOTIFYICON;
179 tnd.hIcon = hIcon;
180 QString tip = q->toolTip();
181
182 if (!tip.isNull()) {
183 tip = tip.left(maxTipLength - 1) + QChar();
184 memcpy(tnd.szTip, tip.utf16(), qMin(tip.length() + 1, maxTipLength) * sizeof(wchar_t));
185 }
186}
187
188static int iconFlag( QSystemTrayIcon::MessageIcon icon )
189{
190#if NOTIFYICON_VERSION >= 3
191 switch (icon) {
192 case QSystemTrayIcon::Information:
193 return NIIF_INFO;
194 case QSystemTrayIcon::Warning:
195 return NIIF_WARNING;
196 case QSystemTrayIcon::Critical:
197 return NIIF_ERROR;
198 case QSystemTrayIcon::NoIcon:
199 return NIIF_NONE;
200 default:
201 Q_ASSERT_X(false, "QSystemTrayIconSys::showMessage", "Invalid QSystemTrayIcon::MessageIcon value");
202 return NIIF_NONE;
203 }
204#else
205 Q_UNUSED(icon);
206 return 0;
207#endif
208}
209
210bool QSystemTrayIconSys::showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs)
211{
212#if NOTIFYICON_VERSION >= 3
213 NOTIFYICONDATA tnd;
214 memset(&tnd, 0, notifyIconSize);
215 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
216
217 setIconContents(tnd);
218 memcpy(tnd.szInfo, message.utf16(), qMin(message.length() + 1, 256) * sizeof(wchar_t));
219 memcpy(tnd.szInfoTitle, title.utf16(), qMin(title.length() + 1, 64) * sizeof(wchar_t));
220
221 tnd.uID = q_uNOTIFYICONID;
222 tnd.dwInfoFlags = iconFlag(type);
223 tnd.cbSize = notifyIconSize;
224 tnd.hWnd = winId();
225 tnd.uTimeout = uSecs;
226 tnd.uFlags = NIF_INFO;
227
228 return Shell_NotifyIcon(NIM_MODIFY, &tnd);
229#else
230 Q_UNUSED(title);
231 Q_UNUSED(message);
232 Q_UNUSED(type);
233 Q_UNUSED(uSecs);
234 return false;
235#endif
236}
237
238bool QSystemTrayIconSys::trayMessage(DWORD msg)
239{
240 NOTIFYICONDATA tnd;
241 memset(&tnd, 0, notifyIconSize);
242 tnd.uID = q_uNOTIFYICONID;
243 tnd.cbSize = notifyIconSize;
244 tnd.hWnd = winId();
245
246 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
247
248 if (msg != NIM_DELETE) {
249 setIconContents(tnd);
250 }
251
252 return Shell_NotifyIcon(msg, &tnd);
253}
254
255bool QSystemTrayIconSys::iconDrawItem(LPDRAWITEMSTRUCT lpdi)
256{
257 if (!hIcon)
258 return false;
259
260 DrawIconEx(lpdi->hDC, lpdi->rcItem.left, lpdi->rcItem.top, hIcon, 0, 0, 0, 0, DI_NORMAL);
261 return true;
262}
263
264void QSystemTrayIconSys::createIcon()
265{
266 hIcon = 0;
267 QIcon icon = q->icon();
268 if (icon.isNull())
269 return;
270
271 const int iconSizeX = GetSystemMetrics(SM_CXSMICON);
272 const int iconSizeY = GetSystemMetrics(SM_CYSMICON);
273 QSize size = icon.actualSize(QSize(iconSizeX, iconSizeY));
274 QPixmap pm = icon.pixmap(size);
275 if (pm.isNull())
276 return;
277
278 hIcon = pm.toWinHICON();
279}
280
281bool QSystemTrayIconSys::winEvent( MSG *m, long *result )
282{
283 switch(m->message) {
284 case WM_CREATE:
285#ifdef GWLP_USERDATA
286 SetWindowLongPtr(winId(), GWLP_USERDATA, (LONG_PTR)((CREATESTRUCTW*)m->lParam)->lpCreateParams);
287#else
288 SetWindowLong(winId(), GWL_USERDATA, (LONG)((CREATESTRUCTW*)m->lParam)->lpCreateParams);
289#endif
290 break;
291
292 case WM_DRAWITEM:
293 return iconDrawItem((LPDRAWITEMSTRUCT)m->lParam);
294
295 case MYWM_NOTIFYICON:
296 {
297 RECT r;
298 GetWindowRect(winId(), &r);
299 QEvent *e = 0;
300 Qt::KeyboardModifiers keys = QApplication::keyboardModifiers();
301 QPoint gpos = QCursor::pos();
302
303 switch (m->lParam) {
304 case WM_LBUTTONUP:
305 if (ignoreNextMouseRelease)
306 ignoreNextMouseRelease = false;
307 else
308 emit q->activated(QSystemTrayIcon::Trigger);
309 break;
310
311 case WM_LBUTTONDBLCLK:
312 ignoreNextMouseRelease = true; // Since DBLCLICK Generates a second mouse
313 // release we must ignore it
314 emit q->activated(QSystemTrayIcon::DoubleClick);
315 break;
316
317 case WM_RBUTTONUP:
318 if (q->contextMenu()) {
319 q->contextMenu()->popup(gpos);
320#if defined(Q_WS_WINCE)
321 // We must ensure that the popup menu doesn't show up behind the task bar.
322 QRect desktopRect = qApp->desktop()->availableGeometry();
323 int maxY = desktopRect.y() + desktopRect.height() - q->contextMenu()->height();
324 if (gpos.y() > maxY) {
325 gpos.ry() = maxY;
326 q->contextMenu()->move(gpos);
327 }
328#endif
329 q->contextMenu()->activateWindow();
330 //Must be activated for proper keyboardfocus and menu closing on windows:
331 }
332 emit q->activated(QSystemTrayIcon::Context);
333 break;
334
335#if !defined(Q_WS_WINCE)
336 case NIN_BALLOONUSERCLICK:
337 emit q->messageClicked();
338 break;
339#endif
340
341 case WM_MBUTTONUP:
342 emit q->activated(QSystemTrayIcon::MiddleClick);
343 break;
344 default:
345 break;
346 }
347 if (e) {
348 bool res = QApplication::sendEvent(q, e);
349 delete e;
350 return res;
351 }
352 break;
353 }
354 default:
355 if (m->message == MYWM_TASKBARCREATED)
356 trayMessage(NIM_ADD);
357 else
358 return QWidget::winEvent(m, result);
359 break;
360 }
361 return 0;
362}
363
364void QSystemTrayIconPrivate::install_sys()
365{
366 Q_Q(QSystemTrayIcon);
367 if (!sys) {
368 sys = new QSystemTrayIconSys(q);
369 sys->createIcon();
370 sys->trayMessage(NIM_ADD);
371 }
372}
373
374/*
375* This function tries to determine the icon geometry from the tray
376*
377* If it fails an invalid rect is returned.
378*/
379QRect QSystemTrayIconSys::findIconGeometry(const int iconId)
380{
381 static PtrShell_NotifyIconGetRect Shell_NotifyIconGetRect =
382 (PtrShell_NotifyIconGetRect)QLibrary::resolve(QLatin1String("shell32"), "Shell_NotifyIconGetRect");
383
384 if (Shell_NotifyIconGetRect) {
385 Q_NOTIFYICONIDENTIFIER nid;
386 memset(&nid, 0, sizeof(nid));
387 nid.cbSize = sizeof(nid);
388 nid.hWnd = winId();
389 nid.uID = iconId;
390
391 RECT rect;
392 HRESULT hr = Shell_NotifyIconGetRect(&nid, &rect);
393 if (SUCCEEDED(hr)) {
394 return QRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
395 }
396 }
397
398 QRect ret;
399
400 TBBUTTON buttonData;
401 DWORD processID = 0;
402 HWND trayHandle = FindWindow(L"Shell_TrayWnd", NULL);
403
404 //find the toolbar used in the notification area
405 if (trayHandle) {
406#if defined(Q_OS_WINCE)
407 trayHandle = FindWindow(L"TrayNotifyWnd", NULL);
408#else
409 trayHandle = FindWindowEx(trayHandle, NULL, L"TrayNotifyWnd", NULL);
410#endif
411 if (trayHandle) {
412#if defined(Q_OS_WINCE)
413 HWND hwnd = FindWindow(L"SysPager", NULL);
414#else
415 HWND hwnd = FindWindowEx(trayHandle, NULL, L"SysPager", NULL);
416#endif
417 if (hwnd) {
418#if defined(Q_OS_WINCE)
419 hwnd = FindWindow(L"ToolbarWindow32", NULL);
420#else
421 hwnd = FindWindowEx(hwnd, NULL, L"ToolbarWindow32", NULL);
422#endif
423 if (hwnd)
424 trayHandle = hwnd;
425 }
426 }
427 }
428
429 if (!trayHandle)
430 return ret;
431
432 GetWindowThreadProcessId(trayHandle, &processID);
433 if (processID <= 0)
434 return ret;
435
436 HANDLE trayProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ, 0, processID);
437 if (!trayProcess)
438 return ret;
439
440 int buttonCount = SendMessage(trayHandle, TB_BUTTONCOUNT, 0, 0);
441#if defined(Q_OS_WINCE)
442 LPVOID data = VirtualAlloc(NULL, sizeof(TBBUTTON), MEM_COMMIT, PAGE_READWRITE);
443#else
444 LPVOID data = VirtualAllocEx(trayProcess, NULL, sizeof(TBBUTTON), MEM_COMMIT, PAGE_READWRITE);
445#endif
446
447 if ( buttonCount < 1 || !data ) {
448 CloseHandle(trayProcess);
449 return ret;
450 }
451
452 //search for our icon among all toolbar buttons
453 for (int toolbarButton = 0; toolbarButton < buttonCount; ++toolbarButton ) {
454 SIZE_T numBytes = 0;
455 DWORD appData[2] = { 0, 0 };
456 SendMessage(trayHandle, TB_GETBUTTON, toolbarButton , (LPARAM)data);
457
458 if (!ReadProcessMemory(trayProcess, data, &buttonData, sizeof(TBBUTTON), &numBytes))
459 continue;
460
461 if (!ReadProcessMemory(trayProcess, (LPVOID) buttonData.dwData, appData, sizeof(appData), &numBytes))
462 continue;
463
464 int currentIconId = appData[1];
465 HWND currentIconHandle = (HWND) appData[0];
466 bool isHidden = buttonData.fsState & TBSTATE_HIDDEN;
467
468 if (currentIconHandle == winId() &&
469 currentIconId == iconId && !isHidden) {
470 SendMessage(trayHandle, TB_GETITEMRECT, toolbarButton , (LPARAM)data);
471 RECT iconRect = {0, 0};
472 if(ReadProcessMemory(trayProcess, data, &iconRect, sizeof(RECT), &numBytes)) {
473 MapWindowPoints(trayHandle, NULL, (LPPOINT)&iconRect, 2);
474 QRect geometry(iconRect.left + 1, iconRect.top + 1,
475 iconRect.right - iconRect.left - 2,
476 iconRect.bottom - iconRect.top - 2);
477 if (geometry.isValid())
478 ret = geometry;
479 break;
480 }
481 }
482 }
483#if defined(Q_OS_WINCE)
484 VirtualFree(data, 0, MEM_RELEASE);
485#else
486 VirtualFreeEx(trayProcess, data, 0, MEM_RELEASE);
487#endif
488 CloseHandle(trayProcess);
489 return ret;
490}
491
492void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, int timeOut)
493{
494 if (!sys || !sys->allowsMessages())
495 return;
496
497 uint uSecs = 0;
498 if ( timeOut < 0)
499 uSecs = 10000; //10 sec default
500 else uSecs = (int)timeOut;
501
502 //message is limited to 255 chars + NULL
503 QString messageString;
504 if (message.isEmpty() && !title.isEmpty())
505 messageString = QLatin1Char(' '); //ensures that the message shows when only title is set
506 else
507 messageString = message.left(255) + QChar();
508
509 //title is limited to 63 chars + NULL
510 QString titleString = title.left(63) + QChar();
511
512 if (sys->supportsMessages()) {
513 sys->showMessage(titleString, messageString, type, (unsigned int)uSecs);
514 } else {
515 //use fallback
516 QRect iconPos = sys->findIconGeometry(q_uNOTIFYICONID);
517 if (iconPos.isValid()) {
518 QBalloonTip::showBalloon(type, title, message, sys->q, iconPos.center(), uSecs, true);
519 }
520 }
521}
522
523QRect QSystemTrayIconPrivate::geometry_sys() const
524{
525 if (!sys)
526 return QRect();
527 return sys->findIconGeometry(q_uNOTIFYICONID);
528}
529
530void QSystemTrayIconPrivate::remove_sys()
531{
532 if (!sys)
533 return;
534
535 sys->trayMessage(NIM_DELETE);
536 delete sys;
537 sys = 0;
538}
539
540void QSystemTrayIconPrivate::updateIcon_sys()
541{
542 if (!sys)
543 return;
544
545 HICON hIconToDestroy = sys->hIcon;
546
547 sys->createIcon();
548 sys->trayMessage(NIM_MODIFY);
549
550 if (hIconToDestroy)
551 DestroyIcon(hIconToDestroy);
552}
553
554void QSystemTrayIconPrivate::updateMenu_sys()
555{
556
557}
558
559void QSystemTrayIconPrivate::updateToolTip_sys()
560{
561#ifdef Q_WS_WINCE
562 // Calling sys->trayMessage(NIM_MODIFY) on an existing icon is broken on Windows CE.
563 // So we need to call updateIcon_sys() which creates a new icon handle.
564 updateIcon_sys();
565#else
566 if (!sys)
567 return;
568
569 sys->trayMessage(NIM_MODIFY);
570#endif
571}
572
573bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
574{
575 return true;
576}
577
578QT_END_NAMESPACE
579
580#endif
Note: See TracBrowser for help on using the repository browser.