cmd: Remove spaces before '\n' in resource strings.
[wine] / programs / explorer / systray.c
1 /*
2  * Copyright (C) 2004 Mike Hearn, for CodeWeavers
3  * Copyright (C) 2005 Robert Shearman
4  * Copyright (C) 2008 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <assert.h>
22
23 #define UNICODE
24 #define _WIN32_IE 0x500
25 #include <windows.h>
26 #include <commctrl.h>
27
28 #include <wine/debug.h>
29 #include <wine/list.h>
30
31 #include "explorer_private.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(systray);
34
35 #define IS_OPTION_FALSE(ch) \
36     ((ch) == 'n' || (ch) == 'N' || (ch) == 'f' || (ch) == 'F' || (ch) == '0')
37
38 static int (*wine_notify_icon)(DWORD,NOTIFYICONDATAW *);
39
40 /* an individual systray icon, unpacked from the NOTIFYICONDATA and always in unicode */
41 struct icon
42 {
43     struct list    entry;
44     HICON          image;    /* the image to render */
45     HWND           owner;    /* the HWND passed in to the Shell_NotifyIcon call */
46     HWND           tooltip;  /* Icon tooltip */
47     UINT           id;       /* the unique id given by the app */
48     UINT           callback_message;
49     int            display;  /* index in display list, or -1 if hidden */
50     WCHAR          tiptext[128]; /* Tooltip text. If empty => tooltip disabled */
51 };
52
53 static struct list icon_list = LIST_INIT( icon_list );
54 static HWND tray_window;
55
56 static unsigned int alloc_displayed;
57 static unsigned int nb_displayed;
58 static struct icon **displayed;  /* array of currently displayed icons */
59
60 static BOOL hide_systray;
61 static int icon_cx, icon_cy;
62
63 #define MIN_DISPLAYED 8
64 #define ICON_BORDER  2
65
66 /* Retrieves icon record by owner window and ID */
67 static struct icon *get_icon(HWND owner, UINT id)
68 {
69     struct icon *this;
70
71     /* search for the icon */
72     LIST_FOR_EACH_ENTRY( this, &icon_list, struct icon, entry )
73         if ((this->id == id) && (this->owner == owner)) return this;
74
75     return NULL;
76 }
77
78 /* compute the size of the tray window */
79 static SIZE get_window_size(void)
80 {
81     SIZE size;
82     RECT rect;
83
84     rect.left = 0;
85     rect.top = 0;
86     rect.right = icon_cx * max( nb_displayed, MIN_DISPLAYED );
87     rect.bottom = icon_cy;
88     AdjustWindowRect( &rect, WS_CAPTION, FALSE );
89     size.cx = rect.right - rect.left;
90     size.cy = rect.bottom - rect.top;
91     return size;
92 }
93
94 /* Creates tooltip window for icon. */
95 static void create_tooltip(struct icon *icon)
96 {
97     TTTOOLINFOW ti;
98     static BOOL tooltips_initialized = FALSE;
99
100     /* Register tooltip classes if this is the first icon */
101     if (!tooltips_initialized)
102     {
103         INITCOMMONCONTROLSEX init_tooltip;
104
105         init_tooltip.dwSize = sizeof(INITCOMMONCONTROLSEX);
106         init_tooltip.dwICC = ICC_TAB_CLASSES;
107
108         InitCommonControlsEx(&init_tooltip);
109         tooltips_initialized = TRUE;
110     }
111
112     icon->tooltip = CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, NULL,
113                                    WS_POPUP | TTS_ALWAYSTIP,
114                                    CW_USEDEFAULT, CW_USEDEFAULT,
115                                    CW_USEDEFAULT, CW_USEDEFAULT,
116                                    tray_window, NULL, NULL, NULL);
117
118     ZeroMemory(&ti, sizeof(ti));
119     ti.cbSize = sizeof(TTTOOLINFOW);
120     ti.hwnd = tray_window;
121     ti.lpszText = icon->tiptext;
122     if (icon->display != -1)
123     {
124         ti.rect.left = icon_cx * icon->display;
125         ti.rect.right = icon_cx * (icon->display + 1);
126         ti.rect.top = 0;
127         ti.rect.bottom = icon_cy;
128     }
129     SendMessageW(icon->tooltip, TTM_ADDTOOLW, 0, (LPARAM)&ti);
130 }
131
132 /* Synchronize tooltip text with tooltip window */
133 static void update_tooltip_text(struct icon *icon)
134 {
135     TTTOOLINFOW ti;
136
137     ZeroMemory(&ti, sizeof(ti));
138     ti.cbSize = sizeof(TTTOOLINFOW);
139     ti.hwnd = tray_window;
140     ti.lpszText = icon->tiptext;
141
142     SendMessageW(icon->tooltip, TTM_UPDATETIPTEXTW, 0, (LPARAM)&ti);
143 }
144
145 /* synchronize tooltip position with tooltip window */
146 static void update_tooltip_position( struct icon *icon )
147 {
148     TTTOOLINFOW ti;
149
150     ZeroMemory(&ti, sizeof(ti));
151     ti.cbSize = sizeof(TTTOOLINFOW);
152     ti.hwnd = tray_window;
153     if (icon->display != -1)
154     {
155         ti.rect.left = icon_cx * icon->display;
156         ti.rect.right = icon_cx * (icon->display + 1);
157         ti.rect.top = 0;
158         ti.rect.bottom = icon_cy;
159     }
160     SendMessageW( icon->tooltip, TTM_NEWTOOLRECTW, 0, (LPARAM)&ti );
161 }
162
163 /* find the icon located at a certain point in the tray window */
164 static struct icon *icon_from_point( int x, int y )
165 {
166     if (y < 0 || y >= icon_cy) return NULL;
167     if (x < 0 || x >= icon_cx * nb_displayed) return NULL;
168     return displayed[x / icon_cx];
169 }
170
171 /* invalidate the portion of the tray window that contains the specified icons */
172 static void invalidate_icons( unsigned int start, unsigned int end )
173 {
174     RECT rect;
175
176     rect.left = start * icon_cx;
177     rect.top  = 0;
178     rect.right = (end + 1) * icon_cx;
179     rect.bottom = icon_cy;
180     InvalidateRect( tray_window, &rect, TRUE );
181 }
182
183 /* make an icon visible */
184 static BOOL show_icon(struct icon *icon)
185 {
186     WINE_TRACE("id=0x%x, hwnd=%p\n", icon->id, icon->owner);
187
188     if (icon->display != -1) return TRUE;  /* already displayed */
189
190     if (nb_displayed >= alloc_displayed)
191     {
192         unsigned int new_count = max( alloc_displayed * 2, 32 );
193         struct icon **ptr;
194         if (displayed) ptr = HeapReAlloc( GetProcessHeap(), 0, displayed, new_count * sizeof(*ptr) );
195         else ptr = HeapAlloc( GetProcessHeap(), 0, new_count * sizeof(*ptr) );
196         if (!ptr) return FALSE;
197         displayed = ptr;
198         alloc_displayed = new_count;
199     }
200
201     icon->display = nb_displayed;
202     displayed[nb_displayed++] = icon;
203     update_tooltip_position( icon );
204     invalidate_icons( nb_displayed-1, nb_displayed-1 );
205
206     if (nb_displayed > MIN_DISPLAYED)
207     {
208         SIZE size = get_window_size();
209         SetWindowPos( tray_window, 0, 0, 0, size.cx, size.cy, SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE );
210     }
211     else if (nb_displayed == 1)
212     {
213         if (!hide_systray) ShowWindow( tray_window, SW_SHOWNA );
214     }
215
216     create_tooltip(icon);
217     return TRUE;
218 }
219
220 /* make an icon invisible */
221 static BOOL hide_icon(struct icon *icon)
222 {
223     unsigned int i;
224
225     WINE_TRACE("id=0x%x, hwnd=%p\n", icon->id, icon->owner);
226
227     if (icon->display == -1) return TRUE;  /* already hidden */
228
229     assert( nb_displayed );
230     for (i = icon->display; i < nb_displayed - 1; i++)
231     {
232         displayed[i] = displayed[i + 1];
233         displayed[i]->display = i;
234         update_tooltip_position( displayed[i] );
235     }
236     nb_displayed--;
237     invalidate_icons( icon->display, nb_displayed );
238     icon->display = -1;
239
240     if (nb_displayed >= MIN_DISPLAYED)
241     {
242         SIZE size = get_window_size();
243         SetWindowPos( tray_window, 0, 0, 0, size.cx, size.cy, SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE );
244     }
245     else if (!nb_displayed)
246     {
247         ShowWindow( tray_window, SW_HIDE );
248     }
249
250     update_tooltip_position( icon );
251     return TRUE;
252 }
253
254 /* Modifies an existing icon record */
255 static BOOL modify_icon( struct icon *icon, NOTIFYICONDATAW *nid )
256 {
257     WINE_TRACE("id=0x%x, hwnd=%p\n", nid->uID, nid->hWnd);
258
259     /* demarshal the request from the NID */
260     if (!icon)
261     {
262         WINE_WARN("Invalid icon ID (0x%x) for HWND %p\n", nid->uID, nid->hWnd);
263         return FALSE;
264     }
265
266     if ((nid->uFlags & NIF_STATE) && (nid->dwStateMask & NIS_HIDDEN))
267     {
268         if (nid->dwState & NIS_HIDDEN) hide_icon( icon );
269         else show_icon( icon );
270     }
271
272     if (nid->uFlags & NIF_ICON)
273     {
274         if (icon->image) DestroyIcon(icon->image);
275         icon->image = CopyIcon(nid->hIcon);
276         if (icon->display != -1) invalidate_icons( icon->display, icon->display );
277     }
278
279     if (nid->uFlags & NIF_MESSAGE)
280     {
281         icon->callback_message = nid->uCallbackMessage;
282     }
283     if (nid->uFlags & NIF_TIP)
284     {
285         lstrcpynW(icon->tiptext, nid->szTip, sizeof(icon->tiptext)/sizeof(WCHAR));
286         if (icon->display != -1) update_tooltip_text(icon);
287     }
288     if (nid->uFlags & NIF_INFO && nid->cbSize >= NOTIFYICONDATAA_V2_SIZE)
289     {
290         WINE_FIXME("balloon tip title %s, message %s\n", wine_dbgstr_w(nid->szInfoTitle), wine_dbgstr_w(nid->szInfo));
291     }
292     return TRUE;
293 }
294
295 /* Adds a new icon record to the list */
296 static BOOL add_icon(NOTIFYICONDATAW *nid)
297 {
298     struct icon  *icon;
299
300     WINE_TRACE("id=0x%x, hwnd=%p\n", nid->uID, nid->hWnd);
301
302     if ((icon = get_icon(nid->hWnd, nid->uID)))
303     {
304         WINE_WARN("duplicate tray icon add, buggy app?\n");
305         return FALSE;
306     }
307
308     if (!(icon = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*icon))))
309     {
310         WINE_ERR("out of memory\n");
311         return FALSE;
312     }
313
314     ZeroMemory(icon, sizeof(struct icon));
315     icon->id     = nid->uID;
316     icon->owner  = nid->hWnd;
317     icon->display = -1;
318
319     list_add_tail(&icon_list, &icon->entry);
320
321     modify_icon( icon, nid );
322     /* show icon, unless hidden state was explicitly specified */
323     if (!((nid->uFlags & NIF_STATE) && (nid->dwStateMask & NIS_HIDDEN))) show_icon( icon );
324     return TRUE;
325 }
326
327 /* Deletes tray icon window and icon record */
328 static BOOL delete_icon(struct icon *icon)
329 {
330     hide_icon(icon);
331     list_remove(&icon->entry);
332     DestroyIcon(icon->image);
333     HeapFree(GetProcessHeap(), 0, icon);
334     return TRUE;
335 }
336
337 /* cleanup icons belonging to windows that have been destroyed */
338 static void cleanup_destroyed_windows(void)
339 {
340     struct icon *icon, *next;
341
342     LIST_FOR_EACH_ENTRY_SAFE( icon, next, &icon_list, struct icon, entry )
343         if (!IsWindow( icon->owner )) delete_icon( icon );
344 }
345
346 static BOOL handle_incoming(HWND hwndSource, COPYDATASTRUCT *cds)
347 {
348     struct icon *icon = NULL;
349     NOTIFYICONDATAW nid;
350     DWORD cbSize;
351     int ret = FALSE;
352
353     if (cds->cbData < NOTIFYICONDATAW_V1_SIZE) return FALSE;
354     cbSize = ((PNOTIFYICONDATA)cds->lpData)->cbSize;
355     if (cbSize < NOTIFYICONDATAW_V1_SIZE) return FALSE;
356
357     ZeroMemory(&nid, sizeof(nid));
358     memcpy(&nid, cds->lpData, min(sizeof(nid), cbSize));
359
360     /* FIXME: if statement only needed because we don't support interprocess
361      * icon handles */
362     if ((nid.uFlags & NIF_ICON) && (cds->cbData >= nid.cbSize + 2 * sizeof(BITMAP)))
363     {
364         LONG cbMaskBits;
365         LONG cbColourBits;
366         BITMAP bmMask;
367         BITMAP bmColour;
368         const char *buffer = cds->lpData;
369
370         buffer += nid.cbSize;
371
372         memcpy(&bmMask, buffer, sizeof(bmMask));
373         buffer += sizeof(bmMask);
374         memcpy(&bmColour, buffer, sizeof(bmColour));
375         buffer += sizeof(bmColour);
376
377         cbMaskBits = (bmMask.bmPlanes * bmMask.bmWidth * bmMask.bmHeight * bmMask.bmBitsPixel) / 8;
378         cbColourBits = (bmColour.bmPlanes * bmColour.bmWidth * bmColour.bmHeight * bmColour.bmBitsPixel) / 8;
379
380         if (cds->cbData < nid.cbSize + 2 * sizeof(BITMAP) + cbMaskBits + cbColourBits)
381         {
382             WINE_ERR("buffer underflow\n");
383             return FALSE;
384         }
385
386         /* sanity check */
387         if ((bmColour.bmWidth != bmMask.bmWidth) || (bmColour.bmHeight != bmMask.bmHeight))
388         {
389             WINE_ERR("colour and mask bitmaps aren't consistent\n");
390             return FALSE;
391         }
392
393         nid.hIcon = CreateIcon(NULL, bmColour.bmWidth, bmColour.bmHeight,
394                                bmColour.bmPlanes, bmColour.bmBitsPixel,
395                                buffer, buffer + cbMaskBits);
396     }
397
398     /* try forward to x11drv first */
399     if (cds->dwData == NIM_ADD || !(icon = get_icon( nid.hWnd, nid.uID )))
400     {
401         if (wine_notify_icon && ((ret = wine_notify_icon( cds->dwData, &nid )) != -1))
402         {
403             if (nid.uFlags & NIF_ICON) DestroyIcon( nid.hIcon );
404             return ret;
405         }
406         ret = FALSE;
407     }
408
409     switch (cds->dwData)
410     {
411     case NIM_ADD:
412         ret = add_icon(&nid);
413         break;
414     case NIM_DELETE:
415         if (icon) ret = delete_icon( icon );
416         break;
417     case NIM_MODIFY:
418         if (icon) ret = modify_icon( icon, &nid );
419         break;
420     default:
421         WINE_FIXME("unhandled tray message: %ld\n", cds->dwData);
422         break;
423     }
424
425     /* FIXME: if statement only needed because we don't support interprocess
426      * icon handles */
427     if (nid.uFlags & NIF_ICON)
428         DestroyIcon(nid.hIcon);
429
430     return ret;
431 }
432
433 static LRESULT WINAPI tray_wndproc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
434 {
435     switch (msg)
436     {
437     case WM_COPYDATA:
438         return handle_incoming((HWND)wparam, (COPYDATASTRUCT *)lparam);
439
440     case WM_TIMER:
441         cleanup_destroyed_windows();
442         break;
443
444     case WM_PAINT:
445         {
446             unsigned int i;
447             PAINTSTRUCT ps;
448             HDC hdc;
449
450             hdc = BeginPaint( hwnd, &ps );
451             for (i = ps.rcPaint.left / icon_cx;
452                  (i < (ps.rcPaint.right + icon_cx - 1) / icon_cx) && (i < nb_displayed);
453                  i++)
454             {
455                 DrawIconEx( hdc, i * icon_cx + ICON_BORDER, ICON_BORDER, displayed[i]->image,
456                             icon_cx - 2*ICON_BORDER, icon_cy - 2*ICON_BORDER,
457                             0, 0, DI_DEFAULTSIZE|DI_NORMAL);
458             }
459             EndPaint( hwnd, &ps );
460             break;
461         }
462
463     case WM_MOUSEMOVE:
464     case WM_LBUTTONDOWN:
465     case WM_LBUTTONUP:
466     case WM_RBUTTONDOWN:
467     case WM_RBUTTONUP:
468     case WM_MBUTTONDOWN:
469     case WM_MBUTTONUP:
470     case WM_LBUTTONDBLCLK:
471     case WM_RBUTTONDBLCLK:
472     case WM_MBUTTONDBLCLK:
473         {
474             MSG message;
475             struct icon *icon = icon_from_point( (short)LOWORD(lparam), (short)HIWORD(lparam) );
476             if (!icon) break;
477
478             /* notify the owner hwnd of the message */
479             WINE_TRACE("relaying 0x%x\n", msg);
480
481             message.hwnd = hwnd;
482             message.message = msg;
483             message.wParam = wparam;
484             message.lParam = lparam;
485             SendMessageW( icon->tooltip, TTM_RELAYEVENT, 0, (LPARAM)&message );
486
487             if (!PostMessageW( icon->owner, icon->callback_message, (WPARAM) icon->id, (LPARAM) msg ) &&
488                 GetLastError() == ERROR_INVALID_WINDOW_HANDLE)
489             {
490                 WINE_WARN("application window was destroyed without removing "
491                           "notification icon, removing automatically\n");
492                 delete_icon( icon );
493             }
494             break;
495         }
496
497     case WM_CLOSE:
498         /* don't destroy the tray window, just hide it */
499         ShowWindow( hwnd, SW_HIDE );
500         return 0;
501
502     default:
503         return DefWindowProcW( hwnd, msg, wparam, lparam );
504     }
505     return 0;
506 }
507
508 static BOOL is_systray_hidden(void)
509 {
510     const WCHAR show_systray_keyname[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\',
511                                           'X','1','1',' ','D','r','i','v','e','r',0};
512     const WCHAR show_systray_valuename[] = {'S','h','o','w','S','y','s','t','r','a','y',0};
513     HKEY hkey;
514     BOOL ret = FALSE;
515
516     /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver */
517     if (RegOpenKeyW(HKEY_CURRENT_USER, show_systray_keyname, &hkey) == ERROR_SUCCESS)
518     {
519         WCHAR value[10];
520         DWORD type, size = sizeof(value);
521         if (RegQueryValueExW(hkey, show_systray_valuename, 0, &type, (LPBYTE)&value, &size) == ERROR_SUCCESS)
522         {
523             ret = IS_OPTION_FALSE(value[0]);
524         }
525         RegCloseKey(hkey);
526     }
527     return ret;
528 }
529
530 /* this function creates the listener window */
531 void initialize_systray(void)
532 {
533     HMODULE x11drv;
534     SIZE size;
535     WNDCLASSEX class;
536     static const WCHAR classname[] = {'S','h','e','l','l','_','T','r','a','y','W','n','d',0};
537     static const WCHAR winname[] = {'W','i','n','e',' ','S','y','s','t','e','m',' ','T','r','a','y',0};
538
539     if ((x11drv = GetModuleHandleA( "winex11.drv" )))
540         wine_notify_icon = (void *)GetProcAddress( x11drv, "wine_notify_icon" );
541
542     icon_cx = GetSystemMetrics( SM_CXSMICON ) + 2*ICON_BORDER;
543     icon_cy = GetSystemMetrics( SM_CYSMICON ) + 2*ICON_BORDER;
544     hide_systray = is_systray_hidden();
545
546     /* register the systray listener window class */
547     ZeroMemory(&class, sizeof(class));
548     class.cbSize        = sizeof(class);
549     class.style         = CS_DBLCLKS;
550     class.lpfnWndProc   = tray_wndproc;
551     class.hInstance     = NULL;
552     class.hIcon         = LoadIcon(0, IDI_WINLOGO);
553     class.hCursor       = LoadCursor(0, IDC_ARROW);
554     class.hbrBackground = (HBRUSH) COLOR_WINDOW;
555     class.lpszClassName = (WCHAR *) &classname;
556
557     if (!RegisterClassEx(&class))
558     {
559         WINE_ERR("Could not register SysTray window class\n");
560         return;
561     }
562
563     size = get_window_size();
564     tray_window = CreateWindowW( classname, winname, WS_OVERLAPPED | WS_CAPTION,
565                                  CW_USEDEFAULT, CW_USEDEFAULT, size.cx, size.cy, 0, 0, 0, 0 );
566     if (!tray_window)
567     {
568         WINE_ERR("Could not create tray window\n");
569         return;
570     }
571     SetTimer( tray_window, 1, 2000, NULL );
572 }