crypt32: Fixed day/month mismatch in time encoding routines.
[wine] / dlls / user / message.c
1 /*
2  * Window messaging support
3  *
4  * Copyright 2001 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <stdarg.h>
26
27 #include "ntstatus.h"
28 #define WIN32_NO_STATUS
29 #include "windef.h"
30 #include "winbase.h"
31 #include "wingdi.h"
32 #include "winuser.h"
33 #include "winerror.h"
34 #include "winnls.h"
35 #include "dbt.h"
36 #include "dde.h"
37 #include "wine/unicode.h"
38 #include "wine/server.h"
39 #include "user_private.h"
40 #include "win.h"
41 #include "winpos.h"
42 #include "controls.h"
43 #include "winproc.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(msg);
47 WINE_DECLARE_DEBUG_CHANNEL(relay);
48 WINE_DECLARE_DEBUG_CHANNEL(key);
49
50 #define WM_NCMOUSEFIRST WM_NCMOUSEMOVE
51 #define WM_NCMOUSELAST  (WM_NCMOUSEFIRST+(WM_MOUSELAST-WM_MOUSEFIRST))
52
53 #define MAX_PACK_COUNT 4
54 #define MAX_SENDMSG_RECURSION  64
55
56 #define SYS_TIMER_RATE  55   /* min. timer rate in ms (actually 54.925)*/
57
58 /* description of the data fields that need to be packed along with a sent message */
59 struct packed_message
60 {
61     int         count;
62     const void *data[MAX_PACK_COUNT];
63     size_t      size[MAX_PACK_COUNT];
64 };
65
66 /* info about the message currently being received by the current thread */
67 struct received_message_info
68 {
69     enum message_type type;
70     MSG               msg;
71     UINT              flags;  /* InSendMessageEx return flags */
72     HWINEVENTHOOK     hook;   /* winevent hook handle */
73     WINEVENTPROC      hook_proc; /* winevent hook proc address */
74 };
75
76 /* structure to group all parameters for sent messages of the various kinds */
77 struct send_message_info
78 {
79     enum message_type type;
80     HWND              hwnd;
81     UINT              msg;
82     WPARAM            wparam;
83     LPARAM            lparam;
84     UINT              flags;      /* flags for SendMessageTimeout */
85     UINT              timeout;    /* timeout for SendMessageTimeout */
86     SENDASYNCPROC     callback;   /* callback function for SendMessageCallback */
87     ULONG_PTR         data;       /* callback data */
88 };
89
90
91 /* flag for messages that contain pointers */
92 /* 32 messages per entry, messages 0..31 map to bits 0..31 */
93
94 #define SET(msg) (1 << ((msg) & 31))
95
96 static const unsigned int message_pointer_flags[] =
97 {
98     /* 0x00 - 0x1f */
99     SET(WM_CREATE) | SET(WM_SETTEXT) | SET(WM_GETTEXT) |
100     SET(WM_WININICHANGE) | SET(WM_DEVMODECHANGE),
101     /* 0x20 - 0x3f */
102     SET(WM_GETMINMAXINFO) | SET(WM_DRAWITEM) | SET(WM_MEASUREITEM) | SET(WM_DELETEITEM) |
103     SET(WM_COMPAREITEM),
104     /* 0x40 - 0x5f */
105     SET(WM_WINDOWPOSCHANGING) | SET(WM_WINDOWPOSCHANGED) | SET(WM_COPYDATA) |
106     SET(WM_NOTIFY) | SET(WM_HELP),
107     /* 0x60 - 0x7f */
108     SET(WM_STYLECHANGING) | SET(WM_STYLECHANGED),
109     /* 0x80 - 0x9f */
110     SET(WM_NCCREATE) | SET(WM_NCCALCSIZE) | SET(WM_GETDLGCODE),
111     /* 0xa0 - 0xbf */
112     SET(EM_GETSEL) | SET(EM_GETRECT) | SET(EM_SETRECT) | SET(EM_SETRECTNP),
113     /* 0xc0 - 0xdf */
114     SET(EM_REPLACESEL) | SET(EM_GETLINE) | SET(EM_SETTABSTOPS),
115     /* 0xe0 - 0xff */
116     SET(SBM_GETRANGE) | SET(SBM_SETSCROLLINFO) | SET(SBM_GETSCROLLINFO) | SET(SBM_GETSCROLLBARINFO),
117     /* 0x100 - 0x11f */
118     0,
119     /* 0x120 - 0x13f */
120     0,
121     /* 0x140 - 0x15f */
122     SET(CB_GETEDITSEL) | SET(CB_ADDSTRING) | SET(CB_DIR) | SET(CB_GETLBTEXT) |
123     SET(CB_INSERTSTRING) | SET(CB_FINDSTRING) | SET(CB_SELECTSTRING) |
124     SET(CB_GETDROPPEDCONTROLRECT) | SET(CB_FINDSTRINGEXACT),
125     /* 0x160 - 0x17f */
126     0,
127     /* 0x180 - 0x19f */
128     SET(LB_ADDSTRING) | SET(LB_INSERTSTRING) | SET(LB_GETTEXT) | SET(LB_SELECTSTRING) |
129     SET(LB_DIR) | SET(LB_FINDSTRING) |
130     SET(LB_GETSELITEMS) | SET(LB_SETTABSTOPS) | SET(LB_ADDFILE) | SET(LB_GETITEMRECT),
131     /* 0x1a0 - 0x1bf */
132     SET(LB_FINDSTRINGEXACT),
133     /* 0x1c0 - 0x1df */
134     0,
135     /* 0x1e0 - 0x1ff */
136     0,
137     /* 0x200 - 0x21f */
138     SET(WM_NEXTMENU) | SET(WM_SIZING) | SET(WM_MOVING) | SET(WM_DEVICECHANGE),
139     /* 0x220 - 0x23f */
140     SET(WM_MDICREATE) | SET(WM_MDIGETACTIVE) | SET(WM_DROPOBJECT) |
141     SET(WM_QUERYDROPOBJECT) | SET(WM_DRAGLOOP) | SET(WM_DRAGSELECT) | SET(WM_DRAGMOVE),
142     /* 0x240 - 0x25f */
143     0,
144     /* 0x260 - 0x27f */
145     0,
146     /* 0x280 - 0x29f */
147     0,
148     /* 0x2a0 - 0x2bf */
149     0,
150     /* 0x2c0 - 0x2df */
151     0,
152     /* 0x2e0 - 0x2ff */
153     0,
154     /* 0x300 - 0x31f */
155     SET(WM_ASKCBFORMATNAME)
156 };
157
158 /* flags for messages that contain Unicode strings */
159 static const unsigned int message_unicode_flags[] =
160 {
161     /* 0x00 - 0x1f */
162     SET(WM_CREATE) | SET(WM_SETTEXT) | SET(WM_GETTEXT) | SET(WM_GETTEXTLENGTH) |
163     SET(WM_WININICHANGE) | SET(WM_DEVMODECHANGE),
164     /* 0x20 - 0x3f */
165     SET(WM_CHARTOITEM),
166     /* 0x40 - 0x5f */
167     0,
168     /* 0x60 - 0x7f */
169     0,
170     /* 0x80 - 0x9f */
171     SET(WM_NCCREATE),
172     /* 0xa0 - 0xbf */
173     0,
174     /* 0xc0 - 0xdf */
175     SET(EM_REPLACESEL) | SET(EM_GETLINE) | SET(EM_SETPASSWORDCHAR),
176     /* 0xe0 - 0xff */
177     0,
178     /* 0x100 - 0x11f */
179     SET(WM_CHAR) | SET(WM_DEADCHAR) | SET(WM_SYSCHAR) | SET(WM_SYSDEADCHAR),
180     /* 0x120 - 0x13f */
181     SET(WM_MENUCHAR),
182     /* 0x140 - 0x15f */
183     SET(CB_ADDSTRING) | SET(CB_DIR) | SET(CB_GETLBTEXT) | SET(CB_GETLBTEXTLEN) |
184     SET(CB_INSERTSTRING) | SET(CB_FINDSTRING) | SET(CB_SELECTSTRING) | SET(CB_FINDSTRINGEXACT),
185     /* 0x160 - 0x17f */
186     0,
187     /* 0x180 - 0x19f */
188     SET(LB_ADDSTRING) | SET(LB_INSERTSTRING) | SET(LB_GETTEXT) | SET(LB_GETTEXTLEN) |
189     SET(LB_SELECTSTRING) | SET(LB_DIR) | SET(LB_FINDSTRING) | SET(LB_ADDFILE),
190     /* 0x1a0 - 0x1bf */
191     SET(LB_FINDSTRINGEXACT),
192     /* 0x1c0 - 0x1df */
193     0,
194     /* 0x1e0 - 0x1ff */
195     0,
196     /* 0x200 - 0x21f */
197     0,
198     /* 0x220 - 0x23f */
199     SET(WM_MDICREATE),
200     /* 0x240 - 0x25f */
201     0,
202     /* 0x260 - 0x27f */
203     0,
204     /* 0x280 - 0x29f */
205     SET(WM_IME_CHAR),
206     /* 0x2a0 - 0x2bf */
207     0,
208     /* 0x2c0 - 0x2df */
209     0,
210     /* 0x2e0 - 0x2ff */
211     0,
212     /* 0x300 - 0x31f */
213     SET(WM_PAINTCLIPBOARD) | SET(WM_SIZECLIPBOARD) | SET(WM_ASKCBFORMATNAME)
214 };
215
216 /* check whether a given message type includes pointers */
217 inline static int is_pointer_message( UINT message )
218 {
219     if (message >= 8*sizeof(message_pointer_flags)) return FALSE;
220     return (message_pointer_flags[message / 32] & SET(message)) != 0;
221 }
222
223 /* check whether a given message type contains Unicode (or ASCII) chars */
224 inline static int is_unicode_message( UINT message )
225 {
226     if (message >= 8*sizeof(message_unicode_flags)) return FALSE;
227     return (message_unicode_flags[message / 32] & SET(message)) != 0;
228 }
229
230 #undef SET
231
232 /* add a data field to a packed message */
233 inline static void push_data( struct packed_message *data, const void *ptr, size_t size )
234 {
235     data->data[data->count] = ptr;
236     data->size[data->count] = size;
237     data->count++;
238 }
239
240 /* add a string to a packed message */
241 inline static void push_string( struct packed_message *data, LPCWSTR str )
242 {
243     push_data( data, str, (strlenW(str) + 1) * sizeof(WCHAR) );
244 }
245
246 /* retrieve a pointer to data from a packed message and increment the buffer pointer */
247 inline static void *get_data( void **buffer, size_t size )
248 {
249     void *ret = *buffer;
250     *buffer = (char *)*buffer + size;
251     return ret;
252 }
253
254 /* make sure that the buffer contains a valid null-terminated Unicode string */
255 inline static BOOL check_string( LPCWSTR str, size_t size )
256 {
257     for (size /= sizeof(WCHAR); size; size--, str++)
258         if (!*str) return TRUE;
259     return FALSE;
260 }
261
262 /* make sure that there is space for 'size' bytes in buffer, growing it if needed */
263 inline static void *get_buffer_space( void **buffer, size_t size )
264 {
265     void *ret;
266
267     if (*buffer)
268     {
269         if (!(ret = HeapReAlloc( GetProcessHeap(), 0, *buffer, size )))
270             HeapFree( GetProcessHeap(), 0, *buffer );
271     }
272     else ret = HeapAlloc( GetProcessHeap(), 0, size );
273
274     *buffer = ret;
275     return ret;
276 }
277
278 /* retrieve a string pointer from packed data */
279 inline static LPWSTR get_string( void **buffer )
280 {
281     return get_data( buffer, (strlenW( (LPWSTR)*buffer ) + 1) * sizeof(WCHAR) );
282 }
283
284 /* check whether a combobox expects strings or ids in CB_ADDSTRING/CB_INSERTSTRING */
285 inline static BOOL combobox_has_strings( HWND hwnd )
286 {
287     DWORD style = GetWindowLongA( hwnd, GWL_STYLE );
288     return (!(style & (CBS_OWNERDRAWFIXED | CBS_OWNERDRAWVARIABLE)) || (style & CBS_HASSTRINGS));
289 }
290
291 /* check whether a listbox expects strings or ids in LB_ADDSTRING/LB_INSERTSTRING */
292 inline static BOOL listbox_has_strings( HWND hwnd )
293 {
294     DWORD style = GetWindowLongA( hwnd, GWL_STYLE );
295     return (!(style & (LBS_OWNERDRAWFIXED | LBS_OWNERDRAWVARIABLE)) || (style & LBS_HASSTRINGS));
296 }
297
298 /* check whether message is in the range of keyboard messages */
299 inline static BOOL is_keyboard_message( UINT message )
300 {
301     return (message >= WM_KEYFIRST && message <= WM_KEYLAST);
302 }
303
304 /* check whether message is in the range of mouse messages */
305 inline static BOOL is_mouse_message( UINT message )
306 {
307     return ((message >= WM_NCMOUSEFIRST && message <= WM_NCMOUSELAST) ||
308             (message >= WM_MOUSEFIRST && message <= WM_MOUSELAST));
309 }
310
311 /* check whether message matches the specified hwnd filter */
312 inline static BOOL check_hwnd_filter( const MSG *msg, HWND hwnd_filter )
313 {
314     if (!hwnd_filter) return TRUE;
315     return (msg->hwnd == hwnd_filter || IsChild( hwnd_filter, msg->hwnd ));
316 }
317
318
319 /***********************************************************************
320  *              broadcast_message_callback
321  *
322  * Helper callback for broadcasting messages.
323  */
324 static BOOL CALLBACK broadcast_message_callback( HWND hwnd, LPARAM lparam )
325 {
326     struct send_message_info *info = (struct send_message_info *)lparam;
327     if (!(GetWindowLongW( hwnd, GWL_STYLE ) & (WS_POPUP|WS_CAPTION))) return TRUE;
328     switch(info->type)
329     {
330     case MSG_UNICODE:
331         SendMessageTimeoutW( hwnd, info->msg, info->wparam, info->lparam,
332                              info->flags, info->timeout, NULL );
333         break;
334     case MSG_ASCII:
335         SendMessageTimeoutA( hwnd, info->msg, info->wparam, info->lparam,
336                              info->flags, info->timeout, NULL );
337         break;
338     case MSG_NOTIFY:
339         SendNotifyMessageW( hwnd, info->msg, info->wparam, info->lparam );
340         break;
341     case MSG_CALLBACK:
342         SendMessageCallbackW( hwnd, info->msg, info->wparam, info->lparam,
343                               info->callback, info->data );
344         break;
345     case MSG_POSTED:
346         PostMessageW( hwnd, info->msg, info->wparam, info->lparam );
347         break;
348     default:
349         ERR( "bad type %d\n", info->type );
350         break;
351     }
352     return TRUE;
353 }
354
355
356 /***********************************************************************
357  *              map_wparam_AtoW
358  *
359  * Convert the wparam of an ASCII message to Unicode.
360  */
361 static WPARAM map_wparam_AtoW( UINT message, WPARAM wparam )
362 {
363     switch(message)
364     {
365     case WM_CHARTOITEM:
366     case EM_SETPASSWORDCHAR:
367     case WM_CHAR:
368     case WM_DEADCHAR:
369     case WM_SYSCHAR:
370     case WM_SYSDEADCHAR:
371     case WM_MENUCHAR:
372         {
373             char ch[2];
374             WCHAR wch[2];
375             ch[0] = (wparam & 0xff);
376             ch[1] = (wparam >> 8);
377             MultiByteToWideChar(CP_ACP, 0, ch, 2, wch, 2);
378             wparam = MAKEWPARAM(wch[0], wch[1]);
379         }
380         break;
381     case WM_IME_CHAR:
382         {
383             char ch[2];
384             WCHAR wch;
385             ch[0] = (wparam >> 8);
386             ch[1] = (wparam & 0xff);
387             if (ch[0]) MultiByteToWideChar(CP_ACP, 0, ch, 2, &wch, 1);
388             else MultiByteToWideChar(CP_ACP, 0, &ch[1], 1, &wch, 1);
389             wparam = MAKEWPARAM( wch, HIWORD(wparam) );
390         }
391         break;
392     }
393     return wparam;
394 }
395
396
397 /***********************************************************************
398  *              map_wparam_WtoA
399  *
400  * Convert the wparam of a Unicode message to ASCII.
401  */
402 static WPARAM map_wparam_WtoA( UINT message, WPARAM wparam )
403 {
404     switch(message)
405     {
406     case WM_CHARTOITEM:
407     case EM_SETPASSWORDCHAR:
408     case WM_CHAR:
409     case WM_DEADCHAR:
410     case WM_SYSCHAR:
411     case WM_SYSDEADCHAR:
412     case WM_MENUCHAR:
413         {
414             WCHAR wch[2];
415             BYTE ch[2];
416             wch[0] = LOWORD(wparam);
417             wch[1] = HIWORD(wparam);
418             WideCharToMultiByte( CP_ACP, 0, wch, 2, (LPSTR)ch, 2, NULL, NULL );
419             wparam = MAKEWPARAM( ch[0] | (ch[1] << 8), 0 );
420         }
421         break;
422     case WM_IME_CHAR:
423         {
424             WCHAR wch = LOWORD(wparam);
425             BYTE ch[2];
426
427             if (WideCharToMultiByte( CP_ACP, 0, &wch, 1, (LPSTR)ch, 2, NULL, NULL ) == 2)
428                 wparam = MAKEWPARAM( (ch[0] << 8) | ch[1], HIWORD(wparam) );
429             else
430                 wparam = MAKEWPARAM( ch[0], HIWORD(wparam) );
431         }
432         break;
433     }
434     return wparam;
435 }
436
437
438 /***********************************************************************
439  *              pack_message
440  *
441  * Pack a message for sending to another process.
442  * Return the size of the data we expect in the message reply.
443  * Set data->count to -1 if there is an error.
444  */
445 static size_t pack_message( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam,
446                             struct packed_message *data )
447 {
448     data->count = 0;
449     switch(message)
450     {
451     case WM_NCCREATE:
452     case WM_CREATE:
453     {
454         CREATESTRUCTW *cs = (CREATESTRUCTW *)lparam;
455         push_data( data, cs, sizeof(*cs) );
456         if (HIWORD(cs->lpszName)) push_string( data, cs->lpszName );
457         if (HIWORD(cs->lpszClass)) push_string( data, cs->lpszClass );
458         return sizeof(*cs);
459     }
460     case WM_GETTEXT:
461     case WM_ASKCBFORMATNAME:
462         return wparam * sizeof(WCHAR);
463     case WM_WININICHANGE:
464         if (lparam) push_string(data, (LPWSTR)lparam );
465         return 0;
466     case WM_SETTEXT:
467     case WM_DEVMODECHANGE:
468     case CB_DIR:
469     case LB_DIR:
470     case LB_ADDFILE:
471     case EM_REPLACESEL:
472         push_string( data, (LPWSTR)lparam );
473         return 0;
474     case WM_GETMINMAXINFO:
475         push_data( data, (MINMAXINFO *)lparam, sizeof(MINMAXINFO) );
476         return sizeof(MINMAXINFO);
477     case WM_DRAWITEM:
478         push_data( data, (DRAWITEMSTRUCT *)lparam, sizeof(DRAWITEMSTRUCT) );
479         return 0;
480     case WM_MEASUREITEM:
481         push_data( data, (MEASUREITEMSTRUCT *)lparam, sizeof(MEASUREITEMSTRUCT) );
482         return sizeof(MEASUREITEMSTRUCT);
483     case WM_DELETEITEM:
484         push_data( data, (DELETEITEMSTRUCT *)lparam, sizeof(DELETEITEMSTRUCT) );
485         return 0;
486     case WM_COMPAREITEM:
487         push_data( data, (COMPAREITEMSTRUCT *)lparam, sizeof(COMPAREITEMSTRUCT) );
488         return 0;
489     case WM_WINDOWPOSCHANGING:
490     case WM_WINDOWPOSCHANGED:
491         push_data( data, (WINDOWPOS *)lparam, sizeof(WINDOWPOS) );
492         return sizeof(WINDOWPOS);
493     case WM_COPYDATA:
494     {
495         COPYDATASTRUCT *cp = (COPYDATASTRUCT *)lparam;
496         push_data( data, cp, sizeof(*cp) );
497         if (cp->lpData) push_data( data, cp->lpData, cp->cbData );
498         return 0;
499     }
500     case WM_NOTIFY:
501         /* WM_NOTIFY cannot be sent across processes (MSDN) */
502         data->count = -1;
503         return 0;
504     case WM_HELP:
505         push_data( data, (HELPINFO *)lparam, sizeof(HELPINFO) );
506         return 0;
507     case WM_STYLECHANGING:
508     case WM_STYLECHANGED:
509         push_data( data, (STYLESTRUCT *)lparam, sizeof(STYLESTRUCT) );
510         return 0;
511     case WM_NCCALCSIZE:
512         if (!wparam)
513         {
514             push_data( data, (RECT *)lparam, sizeof(RECT) );
515             return sizeof(RECT);
516         }
517         else
518         {
519             NCCALCSIZE_PARAMS *nc = (NCCALCSIZE_PARAMS *)lparam;
520             push_data( data, nc, sizeof(*nc) );
521             push_data( data, nc->lppos, sizeof(*nc->lppos) );
522             return sizeof(*nc) + sizeof(*nc->lppos);
523         }
524     case WM_GETDLGCODE:
525         if (lparam) push_data( data, (MSG *)lparam, sizeof(MSG) );
526         return sizeof(MSG);
527     case SBM_SETSCROLLINFO:
528         push_data( data, (SCROLLINFO *)lparam, sizeof(SCROLLINFO) );
529         return 0;
530     case SBM_GETSCROLLINFO:
531         push_data( data, (SCROLLINFO *)lparam, sizeof(SCROLLINFO) );
532         return sizeof(SCROLLINFO);
533     case SBM_GETSCROLLBARINFO:
534     {
535         const SCROLLBARINFO *info = (const SCROLLBARINFO *)lparam;
536         size_t size = min( info->cbSize, sizeof(SCROLLBARINFO) );
537         push_data( data, info, size );
538         return size;
539     }
540     case EM_GETSEL:
541     case SBM_GETRANGE:
542     case CB_GETEDITSEL:
543     {
544         size_t size = 0;
545         if (wparam) size += sizeof(DWORD);
546         if (lparam) size += sizeof(DWORD);
547         return size;
548     }
549     case EM_GETRECT:
550     case LB_GETITEMRECT:
551     case CB_GETDROPPEDCONTROLRECT:
552         return sizeof(RECT);
553     case EM_SETRECT:
554     case EM_SETRECTNP:
555         push_data( data, (RECT *)lparam, sizeof(RECT) );
556         return 0;
557     case EM_GETLINE:
558     {
559         WORD *pw = (WORD *)lparam;
560         push_data( data, pw, sizeof(*pw) );
561         return *pw * sizeof(WCHAR);
562     }
563     case EM_SETTABSTOPS:
564     case LB_SETTABSTOPS:
565         if (wparam) push_data( data, (UINT *)lparam, sizeof(UINT) * wparam );
566         return 0;
567     case CB_ADDSTRING:
568     case CB_INSERTSTRING:
569     case CB_FINDSTRING:
570     case CB_FINDSTRINGEXACT:
571     case CB_SELECTSTRING:
572         if (combobox_has_strings( hwnd )) push_string( data, (LPWSTR)lparam );
573         return 0;
574     case CB_GETLBTEXT:
575         if (!combobox_has_strings( hwnd )) return sizeof(ULONG_PTR);
576         return (SendMessageW( hwnd, CB_GETLBTEXTLEN, wparam, 0 ) + 1) * sizeof(WCHAR);
577     case LB_ADDSTRING:
578     case LB_INSERTSTRING:
579     case LB_FINDSTRING:
580     case LB_FINDSTRINGEXACT:
581     case LB_SELECTSTRING:
582         if (listbox_has_strings( hwnd )) push_string( data, (LPWSTR)lparam );
583         return 0;
584     case LB_GETTEXT:
585         if (!listbox_has_strings( hwnd )) return sizeof(ULONG_PTR);
586         return (SendMessageW( hwnd, LB_GETTEXTLEN, wparam, 0 ) + 1) * sizeof(WCHAR);
587     case LB_GETSELITEMS:
588         return wparam * sizeof(UINT);
589     case WM_NEXTMENU:
590         push_data( data, (MDINEXTMENU *)lparam, sizeof(MDINEXTMENU) );
591         return sizeof(MDINEXTMENU);
592     case WM_SIZING:
593     case WM_MOVING:
594         push_data( data, (RECT *)lparam, sizeof(RECT) );
595         return sizeof(RECT);
596     case WM_MDICREATE:
597     {
598         MDICREATESTRUCTW *cs = (MDICREATESTRUCTW *)lparam;
599         push_data( data, cs, sizeof(*cs) );
600         if (HIWORD(cs->szTitle)) push_string( data, cs->szTitle );
601         if (HIWORD(cs->szClass)) push_string( data, cs->szClass );
602         return sizeof(*cs);
603     }
604     case WM_MDIGETACTIVE:
605         if (lparam) return sizeof(BOOL);
606         return 0;
607     case WM_DEVICECHANGE:
608     {
609         DEV_BROADCAST_HDR *header = (DEV_BROADCAST_HDR *)lparam;
610         push_data( data, header, header->dbch_size );
611         return 0;
612     }
613     case WM_WINE_SETWINDOWPOS:
614         push_data( data, (WINDOWPOS *)lparam, sizeof(WINDOWPOS) );
615         return 0;
616     case WM_WINE_KEYBOARD_LL_HOOK:
617         push_data( data, (KBDLLHOOKSTRUCT *)lparam, sizeof(KBDLLHOOKSTRUCT) );
618         return 0;
619     case WM_WINE_MOUSE_LL_HOOK:
620         push_data( data, (MSLLHOOKSTRUCT *)lparam, sizeof(MSLLHOOKSTRUCT) );
621         return 0;
622     case WM_PAINT:
623         if (!wparam) return 0;
624         /* fall through */
625
626     /* these contain an HFONT */
627     case WM_SETFONT:
628     case WM_GETFONT:
629     /* these contain an HDC */
630     case WM_ERASEBKGND:
631     case WM_ICONERASEBKGND:
632     case WM_NCPAINT:
633     case WM_CTLCOLORMSGBOX:
634     case WM_CTLCOLOREDIT:
635     case WM_CTLCOLORLISTBOX:
636     case WM_CTLCOLORBTN:
637     case WM_CTLCOLORDLG:
638     case WM_CTLCOLORSCROLLBAR:
639     case WM_CTLCOLORSTATIC:
640     case WM_PRINT:
641     case WM_PRINTCLIENT:
642     /* these contain an HGLOBAL */
643     case WM_PAINTCLIPBOARD:
644     case WM_SIZECLIPBOARD:
645     /* these contain HICON */
646     case WM_GETICON:
647     case WM_SETICON:
648     case WM_QUERYDRAGICON:
649     case WM_QUERYPARKICON:
650     /* these contain pointers */
651     case WM_DROPOBJECT:
652     case WM_QUERYDROPOBJECT:
653     case WM_DRAGLOOP:
654     case WM_DRAGSELECT:
655     case WM_DRAGMOVE:
656         FIXME( "msg %x (%s) not supported yet\n", message, SPY_GetMsgName(message, hwnd) );
657         data->count = -1;
658         return 0;
659     }
660     return 0;
661 }
662
663
664 /***********************************************************************
665  *              unpack_message
666  *
667  * Unpack a message received from another process.
668  */
669 static BOOL unpack_message( HWND hwnd, UINT message, WPARAM *wparam, LPARAM *lparam,
670                             void **buffer, size_t size )
671 {
672     size_t minsize = 0;
673
674     switch(message)
675     {
676     case WM_NCCREATE:
677     case WM_CREATE:
678     {
679         CREATESTRUCTW *cs = *buffer;
680         WCHAR *str = (WCHAR *)(cs + 1);
681         if (size < sizeof(*cs)) return FALSE;
682         size -= sizeof(*cs);
683         if (HIWORD(cs->lpszName))
684         {
685             if (!check_string( str, size )) return FALSE;
686             cs->lpszName = str;
687             size -= (strlenW(str) + 1) * sizeof(WCHAR);
688             str += strlenW(str) + 1;
689         }
690         if (HIWORD(cs->lpszClass))
691         {
692             if (!check_string( str, size )) return FALSE;
693             cs->lpszClass = str;
694         }
695         break;
696     }
697     case WM_GETTEXT:
698     case WM_ASKCBFORMATNAME:
699         if (!get_buffer_space( buffer, (*wparam * sizeof(WCHAR)) )) return FALSE;
700         break;
701     case WM_WININICHANGE:
702         if (!*lparam) return TRUE;
703         /* fall through */
704     case WM_SETTEXT:
705     case WM_DEVMODECHANGE:
706     case CB_DIR:
707     case LB_DIR:
708     case LB_ADDFILE:
709     case EM_REPLACESEL:
710         if (!check_string( *buffer, size )) return FALSE;
711         break;
712     case WM_GETMINMAXINFO:
713         minsize = sizeof(MINMAXINFO);
714         break;
715     case WM_DRAWITEM:
716         minsize = sizeof(DRAWITEMSTRUCT);
717         break;
718     case WM_MEASUREITEM:
719         minsize = sizeof(MEASUREITEMSTRUCT);
720         break;
721     case WM_DELETEITEM:
722         minsize = sizeof(DELETEITEMSTRUCT);
723         break;
724     case WM_COMPAREITEM:
725         minsize = sizeof(COMPAREITEMSTRUCT);
726         break;
727     case WM_WINDOWPOSCHANGING:
728     case WM_WINDOWPOSCHANGED:
729     case WM_WINE_SETWINDOWPOS:
730         minsize = sizeof(WINDOWPOS);
731         break;
732     case WM_COPYDATA:
733     {
734         COPYDATASTRUCT *cp = *buffer;
735         if (size < sizeof(*cp)) return FALSE;
736         if (cp->lpData)
737         {
738             minsize = sizeof(*cp) + cp->cbData;
739             cp->lpData = cp + 1;
740         }
741         break;
742     }
743     case WM_NOTIFY:
744         /* WM_NOTIFY cannot be sent across processes (MSDN) */
745         return FALSE;
746     case WM_HELP:
747         minsize = sizeof(HELPINFO);
748         break;
749     case WM_STYLECHANGING:
750     case WM_STYLECHANGED:
751         minsize = sizeof(STYLESTRUCT);
752         break;
753     case WM_NCCALCSIZE:
754         if (!*wparam) minsize = sizeof(RECT);
755         else
756         {
757             NCCALCSIZE_PARAMS *nc = *buffer;
758             if (size < sizeof(*nc) + sizeof(*nc->lppos)) return FALSE;
759             nc->lppos = (WINDOWPOS *)(nc + 1);
760         }
761         break;
762     case WM_GETDLGCODE:
763         if (!*lparam) return TRUE;
764         minsize = sizeof(MSG);
765         break;
766     case SBM_SETSCROLLINFO:
767         minsize = sizeof(SCROLLINFO);
768         break;
769     case SBM_GETSCROLLINFO:
770         if (!get_buffer_space( buffer, sizeof(SCROLLINFO ))) return FALSE;
771         break;
772     case SBM_GETSCROLLBARINFO:
773         if (!get_buffer_space( buffer, sizeof(SCROLLBARINFO ))) return FALSE;
774         break;
775     case EM_GETSEL:
776     case SBM_GETRANGE:
777     case CB_GETEDITSEL:
778         if (*wparam || *lparam)
779         {
780             if (!get_buffer_space( buffer, 2*sizeof(DWORD) )) return FALSE;
781             if (*wparam) *wparam = (WPARAM)*buffer;
782             if (*lparam) *lparam = (LPARAM)((DWORD *)*buffer + 1);
783         }
784         return TRUE;
785     case EM_GETRECT:
786     case LB_GETITEMRECT:
787     case CB_GETDROPPEDCONTROLRECT:
788         if (!get_buffer_space( buffer, sizeof(RECT) )) return FALSE;
789         break;
790     case EM_SETRECT:
791     case EM_SETRECTNP:
792         minsize = sizeof(RECT);
793         break;
794     case EM_GETLINE:
795     {
796         WORD len;
797         if (size < sizeof(WORD)) return FALSE;
798         len = *(WORD *)*buffer;
799         if (!get_buffer_space( buffer, (len + 1) * sizeof(WCHAR) )) return FALSE;
800         *lparam = (LPARAM)*buffer + sizeof(WORD);  /* don't erase WORD at start of buffer */
801         return TRUE;
802     }
803     case EM_SETTABSTOPS:
804     case LB_SETTABSTOPS:
805         if (!*wparam) return TRUE;
806         minsize = *wparam * sizeof(UINT);
807         break;
808     case CB_ADDSTRING:
809     case CB_INSERTSTRING:
810     case CB_FINDSTRING:
811     case CB_FINDSTRINGEXACT:
812     case CB_SELECTSTRING:
813     case LB_ADDSTRING:
814     case LB_INSERTSTRING:
815     case LB_FINDSTRING:
816     case LB_FINDSTRINGEXACT:
817     case LB_SELECTSTRING:
818         if (!*buffer) return TRUE;
819         if (!check_string( *buffer, size )) return FALSE;
820         break;
821     case CB_GETLBTEXT:
822     {
823         size = sizeof(ULONG_PTR);
824         if (combobox_has_strings( hwnd ))
825             size = (SendMessageW( hwnd, CB_GETLBTEXTLEN, *wparam, 0 ) + 1) * sizeof(WCHAR);
826         if (!get_buffer_space( buffer, size )) return FALSE;
827         break;
828     }
829     case LB_GETTEXT:
830     {
831         size = sizeof(ULONG_PTR);
832         if (listbox_has_strings( hwnd ))
833             size = (SendMessageW( hwnd, LB_GETTEXTLEN, *wparam, 0 ) + 1) * sizeof(WCHAR);
834         if (!get_buffer_space( buffer, size )) return FALSE;
835         break;
836     }
837     case LB_GETSELITEMS:
838         if (!get_buffer_space( buffer, *wparam * sizeof(UINT) )) return FALSE;
839         break;
840     case WM_NEXTMENU:
841         minsize = sizeof(MDINEXTMENU);
842         if (!get_buffer_space( buffer, sizeof(MDINEXTMENU) )) return FALSE;
843         break;
844     case WM_SIZING:
845     case WM_MOVING:
846         minsize = sizeof(RECT);
847         if (!get_buffer_space( buffer, sizeof(RECT) )) return FALSE;
848         break;
849     case WM_MDICREATE:
850     {
851         MDICREATESTRUCTW *cs = *buffer;
852         WCHAR *str = (WCHAR *)(cs + 1);
853         if (size < sizeof(*cs)) return FALSE;
854         size -= sizeof(*cs);
855         if (HIWORD(cs->szTitle))
856         {
857             if (!check_string( str, size )) return FALSE;
858             cs->szTitle = str;
859             size -= (strlenW(str) + 1) * sizeof(WCHAR);
860             str += strlenW(str) + 1;
861         }
862         if (HIWORD(cs->szClass))
863         {
864             if (!check_string( str, size )) return FALSE;
865             cs->szClass = str;
866         }
867         break;
868     }
869     case WM_MDIGETACTIVE:
870         if (!*lparam) return TRUE;
871         if (!get_buffer_space( buffer, sizeof(BOOL) )) return FALSE;
872         break;
873     case WM_DEVICECHANGE:
874         minsize = sizeof(DEV_BROADCAST_HDR);
875         break;
876     case WM_WINE_KEYBOARD_LL_HOOK:
877         minsize = sizeof(KBDLLHOOKSTRUCT);
878         break;
879     case WM_WINE_MOUSE_LL_HOOK:
880         minsize = sizeof(MSLLHOOKSTRUCT);
881         break;
882     case WM_PAINT:
883         if (!*wparam) return TRUE;
884         /* fall through */
885
886     /* these contain an HFONT */
887     case WM_SETFONT:
888     case WM_GETFONT:
889     /* these contain an HDC */
890     case WM_ERASEBKGND:
891     case WM_ICONERASEBKGND:
892     case WM_NCPAINT:
893     case WM_CTLCOLORMSGBOX:
894     case WM_CTLCOLOREDIT:
895     case WM_CTLCOLORLISTBOX:
896     case WM_CTLCOLORBTN:
897     case WM_CTLCOLORDLG:
898     case WM_CTLCOLORSCROLLBAR:
899     case WM_CTLCOLORSTATIC:
900     case WM_PRINT:
901     case WM_PRINTCLIENT:
902     /* these contain an HGLOBAL */
903     case WM_PAINTCLIPBOARD:
904     case WM_SIZECLIPBOARD:
905     /* these contain HICON */
906     case WM_GETICON:
907     case WM_SETICON:
908     case WM_QUERYDRAGICON:
909     case WM_QUERYPARKICON:
910     /* these contain pointers */
911     case WM_DROPOBJECT:
912     case WM_QUERYDROPOBJECT:
913     case WM_DRAGLOOP:
914     case WM_DRAGSELECT:
915     case WM_DRAGMOVE:
916         FIXME( "msg %x (%s) not supported yet\n", message, SPY_GetMsgName(message, hwnd) );
917         return FALSE;
918
919     default:
920         return TRUE; /* message doesn't need any unpacking */
921     }
922
923     /* default exit for most messages: check minsize and store buffer in lparam */
924     if (size < minsize) return FALSE;
925     *lparam = (LPARAM)*buffer;
926     return TRUE;
927 }
928
929
930 /***********************************************************************
931  *              pack_reply
932  *
933  * Pack a reply to a message for sending to another process.
934  */
935 static void pack_reply( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam,
936                         LRESULT res, struct packed_message *data )
937 {
938     data->count = 0;
939     switch(message)
940     {
941     case WM_NCCREATE:
942     case WM_CREATE:
943         push_data( data, (CREATESTRUCTW *)lparam, sizeof(CREATESTRUCTW) );
944         break;
945     case WM_GETTEXT:
946     case CB_GETLBTEXT:
947     case LB_GETTEXT:
948         push_data( data, (WCHAR *)lparam, (res + 1) * sizeof(WCHAR) );
949         break;
950     case WM_GETMINMAXINFO:
951         push_data( data, (MINMAXINFO *)lparam, sizeof(MINMAXINFO) );
952         break;
953     case WM_MEASUREITEM:
954         push_data( data, (MEASUREITEMSTRUCT *)lparam, sizeof(MEASUREITEMSTRUCT) );
955         break;
956     case WM_WINDOWPOSCHANGING:
957     case WM_WINDOWPOSCHANGED:
958         push_data( data, (WINDOWPOS *)lparam, sizeof(WINDOWPOS) );
959         break;
960     case WM_GETDLGCODE:
961         if (lparam) push_data( data, (MSG *)lparam, sizeof(MSG) );
962         break;
963     case SBM_GETSCROLLINFO:
964         push_data( data, (SCROLLINFO *)lparam, sizeof(SCROLLINFO) );
965         break;
966     case EM_GETRECT:
967     case LB_GETITEMRECT:
968     case CB_GETDROPPEDCONTROLRECT:
969     case WM_SIZING:
970     case WM_MOVING:
971         push_data( data, (RECT *)lparam, sizeof(RECT) );
972         break;
973     case EM_GETLINE:
974     {
975         WORD *ptr = (WORD *)lparam;
976         push_data( data, ptr, ptr[-1] * sizeof(WCHAR) );
977         break;
978     }
979     case LB_GETSELITEMS:
980         push_data( data, (UINT *)lparam, wparam * sizeof(UINT) );
981         break;
982     case WM_MDIGETACTIVE:
983         if (lparam) push_data( data, (BOOL *)lparam, sizeof(BOOL) );
984         break;
985     case WM_NCCALCSIZE:
986         if (!wparam)
987             push_data( data, (RECT *)lparam, sizeof(RECT) );
988         else
989         {
990             NCCALCSIZE_PARAMS *nc = (NCCALCSIZE_PARAMS *)lparam;
991             push_data( data, nc, sizeof(*nc) );
992             push_data( data, nc->lppos, sizeof(*nc->lppos) );
993         }
994         break;
995     case EM_GETSEL:
996     case SBM_GETRANGE:
997     case CB_GETEDITSEL:
998         if (wparam) push_data( data, (DWORD *)wparam, sizeof(DWORD) );
999         if (lparam) push_data( data, (DWORD *)lparam, sizeof(DWORD) );
1000         break;
1001     case WM_NEXTMENU:
1002         push_data( data, (MDINEXTMENU *)lparam, sizeof(MDINEXTMENU) );
1003         break;
1004     case WM_MDICREATE:
1005         push_data( data, (MDICREATESTRUCTW *)lparam, sizeof(MDICREATESTRUCTW) );
1006         break;
1007     case WM_ASKCBFORMATNAME:
1008         push_data( data, (WCHAR *)lparam, (strlenW((WCHAR *)lparam) + 1) * sizeof(WCHAR) );
1009         break;
1010     }
1011 }
1012
1013
1014 /***********************************************************************
1015  *              unpack_reply
1016  *
1017  * Unpack a message reply received from another process.
1018  */
1019 static void unpack_reply( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam,
1020                           void *buffer, size_t size )
1021 {
1022     switch(message)
1023     {
1024     case WM_NCCREATE:
1025     case WM_CREATE:
1026     {
1027         CREATESTRUCTW *cs = (CREATESTRUCTW *)lparam;
1028         LPCWSTR name = cs->lpszName, class = cs->lpszClass;
1029         memcpy( cs, buffer, min( sizeof(*cs), size ));
1030         cs->lpszName = name;  /* restore the original pointers */
1031         cs->lpszClass = class;
1032         break;
1033     }
1034     case WM_GETTEXT:
1035     case WM_ASKCBFORMATNAME:
1036         memcpy( (WCHAR *)lparam, buffer, min( wparam*sizeof(WCHAR), size ));
1037         break;
1038     case WM_GETMINMAXINFO:
1039         memcpy( (MINMAXINFO *)lparam, buffer, min( sizeof(MINMAXINFO), size ));
1040         break;
1041     case WM_MEASUREITEM:
1042         memcpy( (MEASUREITEMSTRUCT *)lparam, buffer, min( sizeof(MEASUREITEMSTRUCT), size ));
1043         break;
1044     case WM_WINDOWPOSCHANGING:
1045     case WM_WINDOWPOSCHANGED:
1046         memcpy( (WINDOWPOS *)lparam, buffer, min( sizeof(WINDOWPOS), size ));
1047         break;
1048     case WM_GETDLGCODE:
1049         if (lparam) memcpy( (MSG *)lparam, buffer, min( sizeof(MSG), size ));
1050         break;
1051     case SBM_GETSCROLLINFO:
1052         memcpy( (SCROLLINFO *)lparam, buffer, min( sizeof(SCROLLINFO), size ));
1053         break;
1054     case SBM_GETSCROLLBARINFO:
1055         memcpy( (SCROLLBARINFO *)lparam, buffer, min( sizeof(SCROLLBARINFO), size ));
1056         break;
1057     case EM_GETRECT:
1058     case CB_GETDROPPEDCONTROLRECT:
1059     case LB_GETITEMRECT:
1060     case WM_SIZING:
1061     case WM_MOVING:
1062         memcpy( (RECT *)lparam, buffer, min( sizeof(RECT), size ));
1063         break;
1064     case EM_GETLINE:
1065         size = min( size, (size_t)*(WORD *)lparam );
1066         memcpy( (WCHAR *)lparam, buffer, size );
1067         break;
1068     case LB_GETSELITEMS:
1069         memcpy( (UINT *)lparam, buffer, min( wparam*sizeof(UINT), size ));
1070         break;
1071     case LB_GETTEXT:
1072     case CB_GETLBTEXT:
1073         memcpy( (WCHAR *)lparam, buffer, size );
1074         break;
1075     case WM_NEXTMENU:
1076         memcpy( (MDINEXTMENU *)lparam, buffer, min( sizeof(MDINEXTMENU), size ));
1077         break;
1078     case WM_MDIGETACTIVE:
1079         if (lparam) memcpy( (BOOL *)lparam, buffer, min( sizeof(BOOL), size ));
1080         break;
1081     case WM_NCCALCSIZE:
1082         if (!wparam)
1083             memcpy( (RECT *)lparam, buffer, min( sizeof(RECT), size ));
1084         else
1085         {
1086             NCCALCSIZE_PARAMS *nc = (NCCALCSIZE_PARAMS *)lparam;
1087             WINDOWPOS *wp = nc->lppos;
1088             memcpy( nc, buffer, min( sizeof(*nc), size ));
1089             if (size > sizeof(*nc))
1090             {
1091                 size -= sizeof(*nc);
1092                 memcpy( wp, (NCCALCSIZE_PARAMS*)buffer + 1, min( sizeof(*wp), size ));
1093             }
1094             nc->lppos = wp;  /* restore the original pointer */
1095         }
1096         break;
1097     case EM_GETSEL:
1098     case SBM_GETRANGE:
1099     case CB_GETEDITSEL:
1100         if (wparam)
1101         {
1102             memcpy( (DWORD *)wparam, buffer, min( sizeof(DWORD), size ));
1103             if (size <= sizeof(DWORD)) break;
1104             size -= sizeof(DWORD);
1105             buffer = (DWORD *)buffer + 1;
1106         }
1107         if (lparam) memcpy( (DWORD *)lparam, buffer, min( sizeof(DWORD), size ));
1108         break;
1109     case WM_MDICREATE:
1110     {
1111         MDICREATESTRUCTW *cs = (MDICREATESTRUCTW *)lparam;
1112         LPCWSTR title = cs->szTitle, class = cs->szClass;
1113         memcpy( cs, buffer, min( sizeof(*cs), size ));
1114         cs->szTitle = title;  /* restore the original pointers */
1115         cs->szClass = class;
1116         break;
1117     }
1118     default:
1119         ERR( "should not happen: unexpected message %x\n", message );
1120         break;
1121     }
1122 }
1123
1124
1125 /***********************************************************************
1126  *           reply_message
1127  *
1128  * Send a reply to a sent message.
1129  */
1130 static void reply_message( struct received_message_info *info, LRESULT result, BOOL remove )
1131 {
1132     struct packed_message data;
1133     int i, replied = info->flags & ISMEX_REPLIED;
1134
1135     if (info->flags & ISMEX_NOTIFY) return;  /* notify messages don't get replies */
1136     if (!remove && replied) return;  /* replied already */
1137
1138     data.count = 0;
1139     info->flags |= ISMEX_REPLIED;
1140
1141     if (info->type == MSG_OTHER_PROCESS && !replied)
1142     {
1143         pack_reply( info->msg.hwnd, info->msg.message, info->msg.wParam,
1144                     info->msg.lParam, result, &data );
1145     }
1146
1147     SERVER_START_REQ( reply_message )
1148     {
1149         req->result = result;
1150         req->remove = remove;
1151         for (i = 0; i < data.count; i++) wine_server_add_data( req, data.data[i], data.size[i] );
1152         wine_server_call( req );
1153     }
1154     SERVER_END_REQ;
1155 }
1156
1157
1158 /***********************************************************************
1159  *           handle_internal_message
1160  *
1161  * Handle an internal Wine message instead of calling the window proc.
1162  */
1163 static LRESULT handle_internal_message( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
1164 {
1165     switch(msg)
1166     {
1167     case WM_WINE_DESTROYWINDOW:
1168         return WIN_DestroyWindow( hwnd );
1169     case WM_WINE_SETWINDOWPOS:
1170         if (hwnd == GetDesktopWindow()) return 0;
1171         return USER_Driver->pSetWindowPos( (WINDOWPOS *)lparam );
1172     case WM_WINE_SHOWWINDOW:
1173         if (hwnd == GetDesktopWindow()) return 0;
1174         return ShowWindow( hwnd, wparam );
1175     case WM_WINE_SETPARENT:
1176         if (hwnd == GetDesktopWindow()) return 0;
1177         return (LRESULT)SetParent( hwnd, (HWND)wparam );
1178     case WM_WINE_SETWINDOWLONG:
1179         return (LRESULT)SetWindowLongW( hwnd, wparam, lparam );
1180     case WM_WINE_ENABLEWINDOW:
1181         if (hwnd == GetDesktopWindow()) return 0;
1182         return EnableWindow( hwnd, wparam );
1183     case WM_WINE_SETACTIVEWINDOW:
1184         if (hwnd == GetDesktopWindow()) return 0;
1185         return (LRESULT)SetActiveWindow( (HWND)wparam );
1186     case WM_WINE_KEYBOARD_LL_HOOK:
1187         return HOOK_CallHooks( WH_KEYBOARD_LL, HC_ACTION, wparam, lparam, TRUE );
1188     case WM_WINE_MOUSE_LL_HOOK:
1189         return HOOK_CallHooks( WH_MOUSE_LL, HC_ACTION, wparam, lparam, TRUE );
1190     default:
1191         if (msg >= WM_WINE_FIRST_DRIVER_MSG && msg <= WM_WINE_LAST_DRIVER_MSG)
1192             return USER_Driver->pWindowMessage( hwnd, msg, wparam, lparam );
1193         FIXME( "unknown internal message %x\n", msg );
1194         return 0;
1195     }
1196 }
1197
1198 /* since the WM_DDE_ACK response to a WM_DDE_EXECUTE message should contain the handle
1199  * to the memory handle, we keep track (in the server side) of all pairs of handle
1200  * used (the client passes its value and the content of the memory handle), and
1201  * the server stored both values (the client, and the local one, created after the
1202  * content). When a ACK message is generated, the list of pair is searched for a
1203  * matching pair, so that the client memory handle can be returned.
1204  */
1205 struct DDE_pair {
1206     HGLOBAL     client_hMem;
1207     HGLOBAL     server_hMem;
1208 };
1209
1210 static      struct DDE_pair*    dde_pairs;
1211 static      int                 dde_num_alloc;
1212 static      int                 dde_num_used;
1213
1214 static CRITICAL_SECTION dde_crst;
1215 static CRITICAL_SECTION_DEBUG critsect_debug =
1216 {
1217     0, 0, &dde_crst,
1218     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1219       0, 0, { (DWORD_PTR)(__FILE__ ": dde_crst") }
1220 };
1221 static CRITICAL_SECTION dde_crst = { &critsect_debug, -1, 0, 0, 0, 0 };
1222
1223 static BOOL dde_add_pair(HGLOBAL chm, HGLOBAL shm)
1224 {
1225     int  i;
1226 #define GROWBY  4
1227
1228     EnterCriticalSection(&dde_crst);
1229
1230     /* now remember the pair of hMem on both sides */
1231     if (dde_num_used == dde_num_alloc)
1232     {
1233         struct DDE_pair* tmp;
1234         if (dde_pairs)
1235             tmp  = HeapReAlloc( GetProcessHeap(), 0, dde_pairs,
1236                                             (dde_num_alloc + GROWBY) * sizeof(struct DDE_pair));
1237         else
1238             tmp  = HeapAlloc( GetProcessHeap(), 0, 
1239                                             (dde_num_alloc + GROWBY) * sizeof(struct DDE_pair));
1240
1241         if (!tmp)
1242         {
1243             LeaveCriticalSection(&dde_crst);
1244             return FALSE;
1245         }
1246         dde_pairs = tmp;
1247         /* zero out newly allocated part */
1248         memset(&dde_pairs[dde_num_alloc], 0, GROWBY * sizeof(struct DDE_pair));
1249         dde_num_alloc += GROWBY;
1250     }
1251 #undef GROWBY
1252     for (i = 0; i < dde_num_alloc; i++)
1253     {
1254         if (dde_pairs[i].server_hMem == 0)
1255         {
1256             dde_pairs[i].client_hMem = chm;
1257             dde_pairs[i].server_hMem = shm;
1258             dde_num_used++;
1259             break;
1260         }
1261     }
1262     LeaveCriticalSection(&dde_crst);
1263     return TRUE;
1264 }
1265
1266 static HGLOBAL dde_get_pair(HGLOBAL shm)
1267 {
1268     int  i;
1269     HGLOBAL     ret = 0;
1270
1271     EnterCriticalSection(&dde_crst);
1272     for (i = 0; i < dde_num_alloc; i++)
1273     {
1274         if (dde_pairs[i].server_hMem == shm)
1275         {
1276             /* free this pair */
1277             dde_pairs[i].server_hMem = 0;
1278             dde_num_used--;
1279             ret = dde_pairs[i].client_hMem;
1280             break;
1281         }
1282     }
1283     LeaveCriticalSection(&dde_crst);
1284     return ret;
1285 }
1286
1287 /***********************************************************************
1288  *              post_dde_message
1289  *
1290  * Post a DDE message
1291  */
1292 static BOOL post_dde_message( DWORD dest_tid, struct packed_message *data, const struct send_message_info *info )
1293 {
1294     void*       ptr = NULL;
1295     int         size = 0;
1296     UINT_PTR    uiLo, uiHi;
1297     LPARAM      lp = 0;
1298     HGLOBAL     hunlock = 0;
1299     int         i;
1300     DWORD       res;
1301
1302     if (!UnpackDDElParam( info->msg, info->lparam, &uiLo, &uiHi ))
1303         return FALSE;
1304
1305     lp = info->lparam;
1306     switch (info->msg)
1307     {
1308         /* DDE messages which don't require packing are:
1309          * WM_DDE_INITIATE
1310          * WM_DDE_TERMINATE
1311          * WM_DDE_REQUEST
1312          * WM_DDE_UNADVISE
1313          */
1314     case WM_DDE_ACK:
1315         if (HIWORD(uiHi))
1316         {
1317             /* uiHi should contain a hMem from WM_DDE_EXECUTE */
1318             HGLOBAL h = dde_get_pair( (HANDLE)uiHi );
1319             if (h)
1320             {
1321                 /* send back the value of h on the other side */
1322                 push_data( data, &h, sizeof(HGLOBAL) );
1323                 lp = uiLo;
1324                 TRACE( "send dde-ack %x %08x => %p\n", uiLo, uiHi, h );
1325             }
1326         }
1327         else
1328         {
1329             /* uiHi should contain either an atom or 0 */
1330             TRACE( "send dde-ack %x atom=%x\n", uiLo, uiHi );
1331             lp = MAKELONG( uiLo, uiHi );
1332         }
1333         break;
1334     case WM_DDE_ADVISE:
1335     case WM_DDE_DATA:
1336     case WM_DDE_POKE:
1337         size = 0;
1338         if (uiLo)
1339         {
1340             size = GlobalSize( (HGLOBAL)uiLo ) ;
1341             if ((info->msg == WM_DDE_ADVISE && size < sizeof(DDEADVISE)) ||
1342                 (info->msg == WM_DDE_DATA   && size < sizeof(DDEDATA))   ||
1343                 (info->msg == WM_DDE_POKE   && size < sizeof(DDEPOKE))
1344                 )
1345             return FALSE;
1346         }
1347         else if (info->msg != WM_DDE_DATA) return FALSE;
1348
1349         lp = uiHi;
1350         if (uiLo)
1351         {
1352             if ((ptr = GlobalLock( (HGLOBAL)uiLo) ))
1353             {
1354                 DDEDATA *dde_data = (DDEDATA *)ptr;
1355                 TRACE("unused %d, fResponse %d, fRelease %d, fDeferUpd %d, fAckReq %d, cfFormat %d\n",
1356                        dde_data->unused, dde_data->fResponse, dde_data->fRelease,
1357                        dde_data->reserved, dde_data->fAckReq, dde_data->cfFormat);
1358                 push_data( data, ptr, size );
1359                 hunlock = (HGLOBAL)uiLo;
1360             }
1361         }
1362         TRACE( "send ddepack %u %x\n", size, uiHi );
1363         break;
1364     case WM_DDE_EXECUTE:
1365         if (info->lparam)
1366         {
1367             if ((ptr = GlobalLock( (HGLOBAL)info->lparam) ))
1368             {
1369                 push_data(data, ptr, GlobalSize( (HGLOBAL)info->lparam ));
1370                 /* so that the other side can send it back on ACK */
1371                 lp = info->lparam;
1372                 hunlock = (HGLOBAL)info->lparam;
1373             }
1374         }
1375         break;
1376     }
1377     SERVER_START_REQ( send_message )
1378     {
1379         req->id      = dest_tid;
1380         req->type    = info->type;
1381         req->flags   = 0;
1382         req->win     = info->hwnd;
1383         req->msg     = info->msg;
1384         req->wparam  = info->wparam;
1385         req->lparam  = lp;
1386         req->time    = GetCurrentTime();
1387         req->timeout = 0;
1388         for (i = 0; i < data->count; i++)
1389             wine_server_add_data( req, data->data[i], data->size[i] );
1390         if ((res = wine_server_call( req )))
1391         {
1392             if (res == STATUS_INVALID_PARAMETER)
1393                 /* FIXME: find a STATUS_ value for this one */
1394                 SetLastError( ERROR_INVALID_THREAD_ID );
1395             else
1396                 SetLastError( RtlNtStatusToDosError(res) );
1397         }
1398         else
1399             FreeDDElParam(info->msg, info->lparam);
1400     }
1401     SERVER_END_REQ;
1402     if (hunlock) GlobalUnlock(hunlock);
1403
1404     return !res;
1405 }
1406
1407 /***********************************************************************
1408  *              unpack_dde_message
1409  *
1410  * Unpack a posted DDE message received from another process.
1411  */
1412 static BOOL unpack_dde_message( HWND hwnd, UINT message, WPARAM *wparam, LPARAM *lparam,
1413                                 void **buffer, size_t size )
1414 {
1415     UINT_PTR    uiLo, uiHi;
1416     HGLOBAL     hMem = 0;
1417     void*       ptr;
1418
1419     switch (message)
1420     {
1421     case WM_DDE_ACK:
1422         if (size)
1423         {
1424             /* hMem is being passed */
1425             if (size != sizeof(HGLOBAL)) return FALSE;
1426             if (!buffer || !*buffer) return FALSE;
1427             uiLo = *lparam;
1428             memcpy( &hMem, *buffer, size );
1429             uiHi = (UINT_PTR)hMem;
1430             TRACE("recv dde-ack %x mem=%x[%lx]\n", uiLo, uiHi, GlobalSize( hMem ));
1431         }
1432         else
1433         {
1434             uiLo = LOWORD( *lparam );
1435             uiHi = HIWORD( *lparam );
1436             TRACE("recv dde-ack %x atom=%x\n", uiLo, uiHi);
1437         }
1438         *lparam = PackDDElParam( WM_DDE_ACK, uiLo, uiHi );
1439         break;
1440     case WM_DDE_ADVISE:
1441     case WM_DDE_DATA:
1442     case WM_DDE_POKE:
1443         if ((!buffer || !*buffer) && message != WM_DDE_DATA) return FALSE;
1444         uiHi = *lparam;
1445         TRACE( "recv ddepack %u %x\n", size, uiHi );
1446         if (size)
1447         {
1448             if (!(hMem = GlobalAlloc( GMEM_MOVEABLE|GMEM_DDESHARE, size )))
1449                 return FALSE;
1450             if ((ptr = GlobalLock( hMem )))
1451             {
1452                 memcpy( ptr, *buffer, size );
1453                 GlobalUnlock( hMem );
1454             }
1455             else
1456             {
1457                 GlobalFree( hMem );
1458                 return FALSE;
1459             }
1460         }
1461         uiLo = (UINT_PTR)hMem;
1462
1463         *lparam = PackDDElParam( message, uiLo, uiHi );
1464         break;
1465     case WM_DDE_EXECUTE:
1466         if (size)
1467         {
1468             if (!buffer || !*buffer) return FALSE;
1469             if (!(hMem = GlobalAlloc( GMEM_MOVEABLE|GMEM_DDESHARE, size ))) return FALSE;
1470             if ((ptr = GlobalLock( hMem )))
1471             {
1472                 memcpy( ptr, *buffer, size );
1473                 GlobalUnlock( hMem );
1474                 TRACE( "exec: pairing c=%08lx s=%08lx\n", *lparam, (DWORD)hMem );
1475                 if (!dde_add_pair( (HGLOBAL)*lparam, hMem ))
1476                 {
1477                     GlobalFree( hMem );
1478                     return FALSE;
1479                 }
1480             }
1481             else
1482             {
1483                 GlobalFree( hMem );
1484                 return FALSE;
1485             }
1486         } else return FALSE;
1487         *lparam = (LPARAM)hMem;
1488         break;
1489     }
1490     return TRUE;
1491 }
1492
1493 /***********************************************************************
1494  *           call_window_proc
1495  *
1496  * Call a window procedure and the corresponding hooks.
1497  */
1498 static LRESULT call_window_proc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam,
1499                                  BOOL unicode, BOOL same_thread )
1500 {
1501     struct user_thread_info *thread_info = get_user_thread_info();
1502     LRESULT result = 0;
1503     WNDPROC winproc;
1504     CWPSTRUCT cwp;
1505     CWPRETSTRUCT cwpret;
1506
1507     if (thread_info->recursion_count > MAX_SENDMSG_RECURSION) return 0;
1508     thread_info->recursion_count++;
1509
1510     if (msg & 0x80000000)
1511     {
1512         result = handle_internal_message( hwnd, msg, wparam, lparam );
1513         goto done;
1514     }
1515
1516     /* first the WH_CALLWNDPROC hook */
1517     hwnd = WIN_GetFullHandle( hwnd );
1518     cwp.lParam  = lparam;
1519     cwp.wParam  = wparam;
1520     cwp.message = msg;
1521     cwp.hwnd    = hwnd;
1522     HOOK_CallHooks( WH_CALLWNDPROC, HC_ACTION, same_thread, (LPARAM)&cwp, unicode );
1523
1524     /* now call the window procedure */
1525     if (unicode)
1526     {
1527         if (!(winproc = (WNDPROC)GetWindowLongPtrW( hwnd, GWLP_WNDPROC ))) goto done;
1528         result = CallWindowProcW( winproc, hwnd, msg, wparam, lparam );
1529     }
1530     else
1531     {
1532         if (!(winproc = (WNDPROC)GetWindowLongPtrA( hwnd, GWLP_WNDPROC ))) goto done;
1533         result = CallWindowProcA( winproc, hwnd, msg, wparam, lparam );
1534     }
1535
1536     /* and finally the WH_CALLWNDPROCRET hook */
1537     cwpret.lResult = result;
1538     cwpret.lParam  = lparam;
1539     cwpret.wParam  = wparam;
1540     cwpret.message = msg;
1541     cwpret.hwnd    = hwnd;
1542     HOOK_CallHooks( WH_CALLWNDPROCRET, HC_ACTION, same_thread, (LPARAM)&cwpret, unicode );
1543  done:
1544     thread_info->recursion_count--;
1545     return result;
1546 }
1547
1548
1549 /***********************************************************************
1550  *           send_parent_notify
1551  *
1552  * Send a WM_PARENTNOTIFY to all ancestors of the given window, unless
1553  * the window has the WS_EX_NOPARENTNOTIFY style.
1554  */
1555 static void send_parent_notify( HWND hwnd, WORD event, WORD idChild, POINT pt )
1556 {
1557     /* pt has to be in the client coordinates of the parent window */
1558     MapWindowPoints( 0, hwnd, &pt, 1 );
1559     for (;;)
1560     {
1561         HWND parent;
1562
1563         if (!(GetWindowLongW( hwnd, GWL_STYLE ) & WS_CHILD)) break;
1564         if (GetWindowLongW( hwnd, GWL_EXSTYLE ) & WS_EX_NOPARENTNOTIFY) break;
1565         if (!(parent = GetParent(hwnd))) break;
1566         if (parent == GetDesktopWindow()) break;
1567         MapWindowPoints( hwnd, parent, &pt, 1 );
1568         hwnd = parent;
1569         SendMessageW( hwnd, WM_PARENTNOTIFY,
1570                       MAKEWPARAM( event, idChild ), MAKELPARAM( pt.x, pt.y ) );
1571     }
1572 }
1573
1574
1575 /***********************************************************************
1576  *          accept_hardware_message
1577  *
1578  * Tell the server we have passed the message to the app
1579  * (even though we may end up dropping it later on)
1580  */
1581 static void accept_hardware_message( UINT hw_id, BOOL remove, HWND new_hwnd )
1582 {
1583     SERVER_START_REQ( accept_hardware_message )
1584     {
1585         req->hw_id   = hw_id;
1586         req->remove  = remove;
1587         req->new_win = new_hwnd;
1588         if (wine_server_call( req ))
1589             FIXME("Failed to reply to MSG_HARDWARE message. Message may not be removed from queue.\n");
1590     }
1591     SERVER_END_REQ;
1592 }
1593
1594
1595 /***********************************************************************
1596  *          process_keyboard_message
1597  *
1598  * returns TRUE if the contents of 'msg' should be passed to the application
1599  */
1600 static BOOL process_keyboard_message( MSG *msg, UINT hw_id, HWND hwnd_filter,
1601                                       UINT first, UINT last, BOOL remove )
1602 {
1603     EVENTMSG event;
1604
1605     /* FIXME: is this really the right place for this hook? */
1606     event.message = msg->message;
1607     event.hwnd    = msg->hwnd;
1608     event.time    = msg->time;
1609     event.paramL  = (msg->wParam & 0xFF) | (HIWORD(msg->lParam) << 8);
1610     event.paramH  = msg->lParam & 0x7FFF;
1611     if (HIWORD(msg->lParam) & 0x0100) event.paramH |= 0x8000; /* special_key - bit */
1612     HOOK_CallHooks( WH_JOURNALRECORD, HC_ACTION, 0, (LPARAM)&event, TRUE );
1613
1614     /* check message filters */
1615     if (msg->message < first || msg->message > last) return FALSE;
1616     if (!check_hwnd_filter( msg, hwnd_filter )) return FALSE;
1617
1618     if (remove)
1619     {
1620         /* Handle F1 key by sending out WM_HELP message */
1621         if ((msg->message == WM_KEYUP) &&
1622             (msg->wParam == VK_F1) &&
1623             (msg->hwnd != GetDesktopWindow()) &&
1624             !MENU_IsMenuActive())
1625         {
1626             HELPINFO hi;
1627             hi.cbSize = sizeof(HELPINFO);
1628             hi.iContextType = HELPINFO_WINDOW;
1629             hi.iCtrlId = GetWindowLongPtrA( msg->hwnd, GWLP_ID );
1630             hi.hItemHandle = msg->hwnd;
1631             hi.dwContextId = GetWindowContextHelpId( msg->hwnd );
1632             hi.MousePos = msg->pt;
1633             SendMessageW( msg->hwnd, WM_HELP, 0, (LPARAM)&hi );
1634         }
1635     }
1636
1637     if (HOOK_CallHooks( WH_KEYBOARD, remove ? HC_ACTION : HC_NOREMOVE,
1638                         LOWORD(msg->wParam), msg->lParam, TRUE ))
1639     {
1640         /* skip this message */
1641         HOOK_CallHooks( WH_CBT, HCBT_KEYSKIPPED, LOWORD(msg->wParam), msg->lParam, TRUE );
1642         accept_hardware_message( hw_id, TRUE, 0 );
1643         return FALSE;
1644     }
1645     accept_hardware_message( hw_id, remove, 0 );
1646     return TRUE;
1647 }
1648
1649
1650 /***********************************************************************
1651  *          process_mouse_message
1652  *
1653  * returns TRUE if the contents of 'msg' should be passed to the application
1654  */
1655 static BOOL process_mouse_message( MSG *msg, UINT hw_id, ULONG_PTR extra_info, HWND hwnd_filter,
1656                                    UINT first, UINT last, BOOL remove )
1657 {
1658     static MSG clk_msg;
1659
1660     POINT pt;
1661     UINT message;
1662     INT hittest;
1663     EVENTMSG event;
1664     GUITHREADINFO info;
1665     MOUSEHOOKSTRUCT hook;
1666     BOOL eatMsg;
1667
1668     /* find the window to dispatch this mouse message to */
1669
1670     GetGUIThreadInfo( GetCurrentThreadId(), &info );
1671     if (info.hwndCapture)
1672     {
1673         hittest = HTCLIENT;
1674         msg->hwnd = info.hwndCapture;
1675     }
1676     else
1677     {
1678         msg->hwnd = WINPOS_WindowFromPoint( msg->hwnd, msg->pt, &hittest );
1679     }
1680
1681     if (!msg->hwnd || !WIN_IsCurrentThread( msg->hwnd ))
1682     {
1683         accept_hardware_message( hw_id, TRUE, msg->hwnd );
1684         return FALSE;
1685     }
1686
1687     /* FIXME: is this really the right place for this hook? */
1688     event.message = msg->message;
1689     event.time    = msg->time;
1690     event.hwnd    = msg->hwnd;
1691     event.paramL  = msg->pt.x;
1692     event.paramH  = msg->pt.y;
1693     HOOK_CallHooks( WH_JOURNALRECORD, HC_ACTION, 0, (LPARAM)&event, TRUE );
1694
1695     if (!check_hwnd_filter( msg, hwnd_filter )) return FALSE;
1696
1697     pt = msg->pt;
1698     message = msg->message;
1699     /* Note: windows has no concept of a non-client wheel message */
1700     if (message != WM_MOUSEWHEEL)
1701     {
1702         if (hittest != HTCLIENT)
1703         {
1704             message += WM_NCMOUSEMOVE - WM_MOUSEMOVE;
1705             msg->wParam = hittest;
1706         }
1707         else
1708         {
1709             /* coordinates don't get translated while tracking a menu */
1710             /* FIXME: should differentiate popups and top-level menus */
1711             if (!(info.flags & GUI_INMENUMODE))
1712                 ScreenToClient( msg->hwnd, &pt );
1713         }
1714     }
1715     msg->lParam = MAKELONG( pt.x, pt.y );
1716
1717     /* translate double clicks */
1718
1719     if ((msg->message == WM_LBUTTONDOWN) ||
1720         (msg->message == WM_RBUTTONDOWN) ||
1721         (msg->message == WM_MBUTTONDOWN) ||
1722         (msg->message == WM_XBUTTONDOWN))
1723     {
1724         BOOL update = remove;
1725
1726         /* translate double clicks -
1727          * note that ...MOUSEMOVEs can slip in between
1728          * ...BUTTONDOWN and ...BUTTONDBLCLK messages */
1729
1730         if ((info.flags & (GUI_INMENUMODE|GUI_INMOVESIZE)) ||
1731             hittest != HTCLIENT ||
1732             (GetClassLongA( msg->hwnd, GCL_STYLE ) & CS_DBLCLKS))
1733         {
1734            if ((msg->message == clk_msg.message) &&
1735                (msg->hwnd == clk_msg.hwnd) &&
1736                (msg->wParam == clk_msg.wParam) &&
1737                (msg->time - clk_msg.time < GetDoubleClickTime()) &&
1738                (abs(msg->pt.x - clk_msg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
1739                (abs(msg->pt.y - clk_msg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
1740            {
1741                message += (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
1742                if (update)
1743                {
1744                    clk_msg.message = 0;  /* clear the double click conditions */
1745                    update = FALSE;
1746                }
1747            }
1748         }
1749         if (message < first || message > last) return FALSE;
1750         /* update static double click conditions */
1751         if (update) clk_msg = *msg;
1752     }
1753     else
1754     {
1755         if (message < first || message > last) return FALSE;
1756     }
1757
1758     /* message is accepted now (but may still get dropped) */
1759
1760     hook.pt           = msg->pt;
1761     hook.hwnd         = msg->hwnd;
1762     hook.wHitTestCode = hittest;
1763     hook.dwExtraInfo  = extra_info;
1764     if (HOOK_CallHooks( WH_MOUSE, remove ? HC_ACTION : HC_NOREMOVE,
1765                         message, (LPARAM)&hook, TRUE ))
1766     {
1767         hook.pt           = msg->pt;
1768         hook.hwnd         = msg->hwnd;
1769         hook.wHitTestCode = hittest;
1770         hook.dwExtraInfo  = extra_info;
1771         HOOK_CallHooks( WH_CBT, HCBT_CLICKSKIPPED, message, (LPARAM)&hook, TRUE );
1772         accept_hardware_message( hw_id, TRUE, 0 );
1773         return FALSE;
1774     }
1775
1776     if ((hittest == HTERROR) || (hittest == HTNOWHERE))
1777     {
1778         SendMessageW( msg->hwnd, WM_SETCURSOR, (WPARAM)msg->hwnd,
1779                       MAKELONG( hittest, msg->message ));
1780         accept_hardware_message( hw_id, TRUE, 0 );
1781         return FALSE;
1782     }
1783
1784     accept_hardware_message( hw_id, remove, 0 );
1785
1786     if (!remove || info.hwndCapture)
1787     {
1788         msg->message = message;
1789         return TRUE;
1790     }
1791
1792     eatMsg = FALSE;
1793
1794     if ((msg->message == WM_LBUTTONDOWN) ||
1795         (msg->message == WM_RBUTTONDOWN) ||
1796         (msg->message == WM_MBUTTONDOWN) ||
1797         (msg->message == WM_XBUTTONDOWN))
1798     {
1799         /* Send the WM_PARENTNOTIFY,
1800          * note that even for double/nonclient clicks
1801          * notification message is still WM_L/M/RBUTTONDOWN.
1802          */
1803         send_parent_notify( msg->hwnd, msg->message, 0, msg->pt );
1804
1805         /* Activate the window if needed */
1806
1807         if (msg->hwnd != info.hwndActive)
1808         {
1809             HWND hwndTop = msg->hwnd;
1810             while (hwndTop)
1811             {
1812                 if ((GetWindowLongW( hwndTop, GWL_STYLE ) & (WS_POPUP|WS_CHILD)) != WS_CHILD) break;
1813                 hwndTop = GetParent( hwndTop );
1814             }
1815
1816             if (hwndTop && hwndTop != GetDesktopWindow())
1817             {
1818                 LONG ret = SendMessageW( msg->hwnd, WM_MOUSEACTIVATE, (WPARAM)hwndTop,
1819                                          MAKELONG( hittest, msg->message ) );
1820                 switch(ret)
1821                 {
1822                 case MA_NOACTIVATEANDEAT:
1823                     eatMsg = TRUE;
1824                     /* fall through */
1825                 case MA_NOACTIVATE:
1826                     break;
1827                 case MA_ACTIVATEANDEAT:
1828                     eatMsg = TRUE;
1829                     /* fall through */
1830                 case MA_ACTIVATE:
1831                 case 0:
1832                     if (!FOCUS_MouseActivate( hwndTop )) eatMsg = TRUE;
1833                     break;
1834                 default:
1835                     WARN( "unknown WM_MOUSEACTIVATE code %ld\n", ret );
1836                     break;
1837                 }
1838             }
1839         }
1840     }
1841
1842     /* send the WM_SETCURSOR message */
1843
1844     /* Windows sends the normal mouse message as the message parameter
1845        in the WM_SETCURSOR message even if it's non-client mouse message */
1846     SendMessageW( msg->hwnd, WM_SETCURSOR, (WPARAM)msg->hwnd, MAKELONG( hittest, msg->message ));
1847
1848     msg->message = message;
1849     return !eatMsg;
1850 }
1851
1852
1853 /***********************************************************************
1854  *           process_hardware_message
1855  *
1856  * Process a hardware message; return TRUE if message should be passed on to the app
1857  */
1858 static BOOL process_hardware_message( MSG *msg, UINT hw_id, ULONG_PTR extra_info, HWND hwnd_filter,
1859                                       UINT first, UINT last, BOOL remove )
1860 {
1861     if (is_keyboard_message( msg->message ))
1862         return process_keyboard_message( msg, hw_id, hwnd_filter, first, last, remove );
1863
1864     if (is_mouse_message( msg->message ))
1865         return process_mouse_message( msg, hw_id, extra_info, hwnd_filter, first, last, remove );
1866
1867     ERR( "unknown message type %x\n", msg->message );
1868     return FALSE;
1869 }
1870
1871
1872 /***********************************************************************
1873  *           call_sendmsg_callback
1874  *
1875  * Call the callback function of SendMessageCallback.
1876  */
1877 static inline void call_sendmsg_callback( SENDASYNCPROC callback, HWND hwnd, UINT msg,
1878                                           ULONG_PTR data, LRESULT result )
1879 {
1880     if (TRACE_ON(relay))
1881         DPRINTF( "%04lx:Call message callback %p (hwnd=%p,msg=%s,data=%08lx,result=%08lx)\n",
1882                  GetCurrentThreadId(), callback, hwnd, SPY_GetMsgName( msg, hwnd ),
1883                  data, result );
1884     callback( hwnd, msg, data, result );
1885     if (TRACE_ON(relay))
1886         DPRINTF( "%04lx:Ret  message callback %p (hwnd=%p,msg=%s,data=%08lx,result=%08lx)\n",
1887                  GetCurrentThreadId(), callback, hwnd, SPY_GetMsgName( msg, hwnd ),
1888                  data, result );
1889 }
1890
1891
1892 /***********************************************************************
1893  *              get_hook_proc
1894  *
1895  * Retrieve the hook procedure real value for a module-relative proc
1896  */
1897 static void *get_hook_proc( void *proc, const WCHAR *module )
1898 {
1899     HMODULE mod;
1900
1901     if (!(mod = GetModuleHandleW(module)))
1902     {
1903         TRACE( "loading %s\n", debugstr_w(module) );
1904         /* FIXME: the library will never be freed */
1905         if (!(mod = LoadLibraryW(module))) return NULL;
1906     }
1907     return (char *)mod + (ULONG_PTR)proc;
1908 }
1909
1910
1911 /***********************************************************************
1912  *           peek_message
1913  *
1914  * Peek for a message matching the given parameters. Return FALSE if none available.
1915  * All pending sent messages are processed before returning.
1916  */
1917 static BOOL peek_message( MSG *msg, HWND hwnd, UINT first, UINT last, int flags )
1918 {
1919     LRESULT result;
1920     ULONG_PTR extra_info = 0;
1921     struct user_thread_info *thread_info = get_user_thread_info();
1922     struct received_message_info info, *old_info;
1923     unsigned int hw_id = 0;  /* id of previous hardware message */
1924
1925     if (!first && !last) last = ~0;
1926
1927     for (;;)
1928     {
1929         NTSTATUS res;
1930         void *buffer = NULL;
1931         size_t size = 0, buffer_size = 0;
1932
1933         do  /* loop while buffer is too small */
1934         {
1935             if (buffer_size && !(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
1936                 return FALSE;
1937             SERVER_START_REQ( get_message )
1938             {
1939                 req->flags     = flags;
1940                 req->get_win   = hwnd;
1941                 req->get_first = first;
1942                 req->get_last  = last;
1943                 req->hw_id     = hw_id;
1944                 if (buffer_size) wine_server_set_reply( req, buffer, buffer_size );
1945                 if (!(res = wine_server_call( req )))
1946                 {
1947                     size = wine_server_reply_size( reply );
1948                     info.type        = reply->type;
1949                     info.msg.hwnd    = reply->win;
1950                     info.msg.message = reply->msg;
1951                     info.msg.wParam  = reply->wparam;
1952                     info.msg.lParam  = reply->lparam;
1953                     info.msg.time    = reply->time;
1954                     info.msg.pt.x    = reply->x;
1955                     info.msg.pt.y    = reply->y;
1956                     info.hook        = reply->hook;
1957                     info.hook_proc   = reply->hook_proc;
1958                     hw_id            = reply->hw_id;
1959                     extra_info       = reply->info;
1960                     thread_info->active_hooks = reply->active_hooks;
1961                 }
1962                 else
1963                 {
1964                     HeapFree( GetProcessHeap(), 0, buffer );
1965                     buffer_size = reply->total;
1966                 }
1967             }
1968             SERVER_END_REQ;
1969         } while (res == STATUS_BUFFER_OVERFLOW);
1970
1971         if (res) return FALSE;
1972
1973         TRACE( "got type %d msg %x (%s) hwnd %p wp %x lp %lx\n",
1974                info.type, info.msg.message,
1975                (info.type == MSG_WINEVENT) ? "MSG_WINEVENT" : SPY_GetMsgName(info.msg.message, info.msg.hwnd),
1976                info.msg.hwnd, info.msg.wParam, info.msg.lParam );
1977
1978         switch(info.type)
1979         {
1980         case MSG_ASCII:
1981         case MSG_UNICODE:
1982             info.flags = ISMEX_SEND;
1983             break;
1984         case MSG_NOTIFY:
1985             info.flags = ISMEX_NOTIFY;
1986             break;
1987         case MSG_CALLBACK:
1988             info.flags = ISMEX_CALLBACK;
1989             break;
1990         case MSG_CALLBACK_RESULT:
1991             call_sendmsg_callback( (SENDASYNCPROC)info.msg.wParam, info.msg.hwnd,
1992                                    info.msg.message, extra_info, info.msg.lParam );
1993             goto next;
1994         case MSG_WINEVENT:
1995             if (size)
1996             {
1997                 WCHAR module[MAX_PATH];
1998                 size = min( size, (MAX_PATH - 1) * sizeof(WCHAR) );
1999                 memcpy( module, buffer, size );
2000                 module[size / sizeof(WCHAR)] = 0;
2001                 if (!(info.hook_proc = get_hook_proc( info.hook_proc, module )))
2002                 {
2003                     ERR( "invalid winevent hook module name %s\n", debugstr_w(module) );
2004                     goto next;
2005                 }
2006             }
2007             if (TRACE_ON(relay))
2008                 DPRINTF( "%04lx:Call winevent proc %p (hook=%p,event=%x,hwnd=%p,object_id=%x,child_id=%lx,tid=%04lx,time=%lx)\n",
2009                          GetCurrentThreadId(), info.hook_proc,
2010                          info.hook, info.msg.message, info.msg.hwnd, info.msg.wParam,
2011                          info.msg.lParam, extra_info, info.msg.time);
2012
2013             info.hook_proc( info.hook, info.msg.message, info.msg.hwnd, info.msg.wParam,
2014                             info.msg.lParam, extra_info, info.msg.time );
2015
2016             if (TRACE_ON(relay))
2017                 DPRINTF( "%04lx:Ret  winevent proc %p (hook=%p,event=%x,hwnd=%p,object_id=%x,child_id=%lx,tid=%04lx,time=%lx)\n",
2018                          GetCurrentThreadId(), info.hook_proc,
2019                          info.hook, info.msg.message, info.msg.hwnd, info.msg.wParam,
2020                          info.msg.lParam, extra_info, info.msg.time);
2021             goto next;
2022         case MSG_OTHER_PROCESS:
2023             info.flags = ISMEX_SEND;
2024             if (!unpack_message( info.msg.hwnd, info.msg.message, &info.msg.wParam,
2025                                  &info.msg.lParam, &buffer, size ))
2026             {
2027                 ERR( "invalid packed message %x (%s) hwnd %p wp %x lp %lx size %d\n",
2028                      info.msg.message, SPY_GetMsgName(info.msg.message, info.msg.hwnd), info.msg.hwnd,
2029                      info.msg.wParam, info.msg.lParam, size );
2030                 /* ignore it */
2031                 reply_message( &info, 0, TRUE );
2032                 goto next;
2033             }
2034             break;
2035         case MSG_HARDWARE:
2036             if (!process_hardware_message( &info.msg, hw_id, extra_info,
2037                                            hwnd, first, last, flags & GET_MSG_REMOVE ))
2038             {
2039                 TRACE("dropping msg %x\n", info.msg.message );
2040                 goto next;  /* ignore it */
2041             }
2042             thread_info->GetMessagePosVal = MAKELONG( info.msg.pt.x, info.msg.pt.y );
2043             /* fall through */
2044         case MSG_POSTED:
2045             thread_info->GetMessageExtraInfoVal = extra_info;
2046             if (info.msg.message >= WM_DDE_FIRST && info.msg.message <= WM_DDE_LAST)
2047             {
2048                 if (!unpack_dde_message( info.msg.hwnd, info.msg.message, &info.msg.wParam,
2049                                          &info.msg.lParam, &buffer, size ))
2050                 {
2051                     ERR( "invalid packed dde-message %x (%s) hwnd %p wp %x lp %lx size %d\n",
2052                          info.msg.message, SPY_GetMsgName(info.msg.message, info.msg.hwnd),
2053                          info.msg.hwnd, info.msg.wParam, info.msg.lParam, size );
2054                     goto next;  /* ignore it */
2055                 }
2056             }
2057             *msg = info.msg;
2058             HeapFree( GetProcessHeap(), 0, buffer );
2059             return TRUE;
2060         }
2061
2062         /* if we get here, we have a sent message; call the window procedure */
2063         old_info = thread_info->receive_info;
2064         thread_info->receive_info = &info;
2065         result = call_window_proc( info.msg.hwnd, info.msg.message, info.msg.wParam,
2066                                    info.msg.lParam, (info.type != MSG_ASCII), FALSE );
2067         reply_message( &info, result, TRUE );
2068         thread_info->receive_info = old_info;
2069     next:
2070         HeapFree( GetProcessHeap(), 0, buffer );
2071     }
2072 }
2073
2074
2075 /***********************************************************************
2076  *           process_sent_messages
2077  *
2078  * Process all pending sent messages.
2079  */
2080 inline static void process_sent_messages(void)
2081 {
2082     MSG msg;
2083     peek_message( &msg, 0, 0, 0, GET_MSG_REMOVE | GET_MSG_SENT_ONLY );
2084 }
2085
2086
2087 /***********************************************************************
2088  *           get_server_queue_handle
2089  *
2090  * Get a handle to the server message queue for the current thread.
2091  */
2092 static HANDLE get_server_queue_handle(void)
2093 {
2094     struct user_thread_info *thread_info = get_user_thread_info();
2095     HANDLE ret;
2096
2097     if (!(ret = thread_info->server_queue))
2098     {
2099         SERVER_START_REQ( get_msg_queue )
2100         {
2101             wine_server_call( req );
2102             ret = reply->handle;
2103         }
2104         SERVER_END_REQ;
2105         thread_info->server_queue = ret;
2106         if (!ret) ERR( "Cannot get server thread queue\n" );
2107     }
2108     return ret;
2109 }
2110
2111
2112 /***********************************************************************
2113  *           wait_message_reply
2114  *
2115  * Wait until a sent message gets replied to.
2116  */
2117 static void wait_message_reply( UINT flags )
2118 {
2119     HANDLE server_queue = get_server_queue_handle();
2120
2121     for (;;)
2122     {
2123         unsigned int wake_bits = 0, changed_bits = 0;
2124         DWORD dwlc, res;
2125
2126         SERVER_START_REQ( set_queue_mask )
2127         {
2128             req->wake_mask    = QS_SMRESULT | ((flags & SMTO_BLOCK) ? 0 : QS_SENDMESSAGE);
2129             req->changed_mask = req->wake_mask;
2130             req->skip_wait    = 1;
2131             if (!wine_server_call( req ))
2132             {
2133                 wake_bits    = reply->wake_bits;
2134                 changed_bits = reply->changed_bits;
2135             }
2136         }
2137         SERVER_END_REQ;
2138
2139         if (wake_bits & QS_SMRESULT) return;  /* got a result */
2140         if (wake_bits & QS_SENDMESSAGE)
2141         {
2142             /* Process the sent message immediately */
2143             process_sent_messages();
2144             continue;
2145         }
2146
2147         /* now wait for it */
2148
2149         ReleaseThunkLock( &dwlc );
2150         res = USER_Driver->pMsgWaitForMultipleObjectsEx( 1, &server_queue,
2151                                                          INFINITE, QS_SENDMESSAGE, 0 );
2152         if (dwlc) RestoreThunkLock( dwlc );
2153     }
2154 }
2155
2156 /***********************************************************************
2157  *              put_message_in_queue
2158  *
2159  * Put a sent message into the destination queue.
2160  * For inter-process message, reply_size is set to expected size of reply data.
2161  */
2162 static BOOL put_message_in_queue( DWORD dest_tid, const struct send_message_info *info,
2163                                   size_t *reply_size )
2164 {
2165     struct packed_message data;
2166     unsigned int res;
2167     int i, timeout = 0;
2168
2169     /* Check for INFINITE timeout for compatibility with Win9x,
2170      * although Windows >= NT does not do so
2171      */
2172     if (info->type != MSG_NOTIFY &&
2173         info->type != MSG_CALLBACK &&
2174         info->type != MSG_POSTED &&
2175         info->timeout != INFINITE)
2176         timeout = info->timeout;
2177
2178     data.count = 0;
2179     if (info->type == MSG_OTHER_PROCESS)
2180     {
2181         *reply_size = pack_message( info->hwnd, info->msg, info->wparam, info->lparam, &data );
2182         if (data.count == -1)
2183         {
2184             WARN( "cannot pack message %x\n", info->msg );
2185             return FALSE;
2186         }
2187     }
2188     else if (info->type == MSG_POSTED && info->msg >= WM_DDE_FIRST && info->msg <= WM_DDE_LAST)
2189     {
2190         return post_dde_message( dest_tid, &data, info );
2191     }
2192
2193     SERVER_START_REQ( send_message )
2194     {
2195         req->id      = dest_tid;
2196         req->type    = info->type;
2197         req->flags   = 0;
2198         req->win     = info->hwnd;
2199         req->msg     = info->msg;
2200         req->wparam  = info->wparam;
2201         req->lparam  = info->lparam;
2202         req->time    = GetCurrentTime();
2203         req->timeout = timeout;
2204
2205         if (info->type == MSG_CALLBACK)
2206         {
2207             req->callback = info->callback;
2208             req->info     = info->data;
2209         }
2210
2211         if (info->flags & SMTO_ABORTIFHUNG) req->flags |= SEND_MSG_ABORT_IF_HUNG;
2212         for (i = 0; i < data.count; i++) wine_server_add_data( req, data.data[i], data.size[i] );
2213         if ((res = wine_server_call( req )))
2214         {
2215             if (res == STATUS_INVALID_PARAMETER)
2216                 /* FIXME: find a STATUS_ value for this one */
2217                 SetLastError( ERROR_INVALID_THREAD_ID );
2218             else
2219                 SetLastError( RtlNtStatusToDosError(res) );
2220         }
2221     }
2222     SERVER_END_REQ;
2223     return !res;
2224 }
2225
2226
2227 /***********************************************************************
2228  *              retrieve_reply
2229  *
2230  * Retrieve a message reply from the server.
2231  */
2232 static LRESULT retrieve_reply( const struct send_message_info *info,
2233                                size_t reply_size, LRESULT *result )
2234 {
2235     NTSTATUS status;
2236     void *reply_data = NULL;
2237
2238     if (reply_size)
2239     {
2240         if (!(reply_data = HeapAlloc( GetProcessHeap(), 0, reply_size )))
2241         {
2242             WARN( "no memory for reply %d bytes, will be truncated\n", reply_size );
2243             reply_size = 0;
2244         }
2245     }
2246     SERVER_START_REQ( get_message_reply )
2247     {
2248         req->cancel = 1;
2249         if (reply_size) wine_server_set_reply( req, reply_data, reply_size );
2250         if (!(status = wine_server_call( req ))) *result = reply->result;
2251         reply_size = wine_server_reply_size( reply );
2252     }
2253     SERVER_END_REQ;
2254     if (!status && reply_size)
2255         unpack_reply( info->hwnd, info->msg, info->wparam, info->lparam, reply_data, reply_size );
2256
2257     HeapFree( GetProcessHeap(), 0, reply_data );
2258
2259     TRACE( "hwnd %p msg %x (%s) wp %x lp %lx got reply %lx (err=%ld)\n",
2260            info->hwnd, info->msg, SPY_GetMsgName(info->msg, info->hwnd), info->wparam,
2261            info->lparam, *result, status );
2262
2263     /* MSDN states that last error is 0 on timeout, but at least NT4 returns ERROR_TIMEOUT */
2264     if (status) SetLastError( RtlNtStatusToDosError(status) );
2265     return !status;
2266 }
2267
2268
2269 /***********************************************************************
2270  *              send_inter_thread_message
2271  */
2272 static LRESULT send_inter_thread_message( DWORD dest_tid, const struct send_message_info *info,
2273                                           LRESULT *res_ptr )
2274 {
2275     size_t reply_size = 0;
2276
2277     TRACE( "hwnd %p msg %x (%s) wp %x lp %lx\n",
2278            info->hwnd, info->msg, SPY_GetMsgName(info->msg, info->hwnd), info->wparam, info->lparam );
2279
2280     USER_CheckNotLock();
2281
2282     if (!put_message_in_queue( dest_tid, info, &reply_size )) return 0;
2283
2284     /* there's no reply to wait for on notify/callback messages */
2285     if (info->type == MSG_NOTIFY || info->type == MSG_CALLBACK) return 1;
2286
2287     wait_message_reply( info->flags );
2288     return retrieve_reply( info, reply_size, res_ptr );
2289 }
2290
2291
2292 /***********************************************************************
2293  *              MSG_SendInternalMessageTimeout
2294  *
2295  * Same as SendMessageTimeoutW but sends the message to a specific thread
2296  * without requiring a window handle. Only works for internal Wine messages.
2297  */
2298 LRESULT MSG_SendInternalMessageTimeout( DWORD dest_pid, DWORD dest_tid,
2299                                         UINT msg, WPARAM wparam, LPARAM lparam,
2300                                         UINT flags, UINT timeout, PDWORD_PTR res_ptr )
2301 {
2302     struct send_message_info info;
2303     LRESULT ret, result;
2304
2305     assert( msg & 0x80000000 );  /* must be an internal Wine message */
2306
2307     info.type    = MSG_UNICODE;
2308     info.hwnd    = 0;
2309     info.msg     = msg;
2310     info.wparam  = wparam;
2311     info.lparam  = lparam;
2312     info.flags   = flags;
2313     info.timeout = timeout;
2314
2315     if (USER_IsExitingThread( dest_tid )) return 0;
2316
2317     if (dest_tid == GetCurrentThreadId())
2318     {
2319         result = handle_internal_message( 0, msg, wparam, lparam );
2320         ret = 1;
2321     }
2322     else
2323     {
2324         if (dest_pid != GetCurrentProcessId()) info.type = MSG_OTHER_PROCESS;
2325         ret = send_inter_thread_message( dest_tid, &info, &result );
2326     }
2327     if (ret && res_ptr) *res_ptr = result;
2328     return ret;
2329 }
2330
2331
2332 /***********************************************************************
2333  *              SendMessageTimeoutW  (USER32.@)
2334  */
2335 LRESULT WINAPI SendMessageTimeoutW( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam,
2336                                     UINT flags, UINT timeout, PDWORD_PTR res_ptr )
2337 {
2338     struct send_message_info info;
2339     DWORD dest_tid, dest_pid;
2340     LRESULT ret, result;
2341
2342     info.type    = MSG_UNICODE;
2343     info.hwnd    = hwnd;
2344     info.msg     = msg;
2345     info.wparam  = wparam;
2346     info.lparam  = lparam;
2347     info.flags   = flags;
2348     info.timeout = timeout;
2349
2350     if (is_broadcast(hwnd))
2351     {
2352         EnumWindows( broadcast_message_callback, (LPARAM)&info );
2353         if (res_ptr) *res_ptr = 1;
2354         return 1;
2355     }
2356
2357     if (!(dest_tid = GetWindowThreadProcessId( hwnd, &dest_pid ))) return 0;
2358
2359     if (USER_IsExitingThread( dest_tid )) return 0;
2360
2361     SPY_EnterMessage( SPY_SENDMESSAGE, hwnd, msg, wparam, lparam );
2362
2363     if (dest_tid == GetCurrentThreadId())
2364     {
2365         result = call_window_proc( hwnd, msg, wparam, lparam, TRUE, TRUE );
2366         ret = 1;
2367     }
2368     else
2369     {
2370         if (dest_pid != GetCurrentProcessId()) info.type = MSG_OTHER_PROCESS;
2371         ret = send_inter_thread_message( dest_tid, &info, &result );
2372     }
2373
2374     SPY_ExitMessage( SPY_RESULT_OK, hwnd, msg, result, wparam, lparam );
2375     if (ret && res_ptr) *res_ptr = result;
2376     return ret;
2377 }
2378
2379
2380 /***********************************************************************
2381  *              SendMessageTimeoutA  (USER32.@)
2382  */
2383 LRESULT WINAPI SendMessageTimeoutA( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam,
2384                                     UINT flags, UINT timeout, PDWORD_PTR res_ptr )
2385 {
2386     struct send_message_info info;
2387     DWORD dest_tid, dest_pid;
2388     LRESULT ret, result;
2389
2390     info.type    = MSG_ASCII;
2391     info.hwnd    = hwnd;
2392     info.msg     = msg;
2393     info.wparam  = wparam;
2394     info.lparam  = lparam;
2395     info.flags   = flags;
2396     info.timeout = timeout;
2397
2398     if (is_broadcast(hwnd))
2399     {
2400         EnumWindows( broadcast_message_callback, (LPARAM)&info );
2401         if (res_ptr) *res_ptr = 1;
2402         return 1;
2403     }
2404
2405     if (!(dest_tid = GetWindowThreadProcessId( hwnd, &dest_pid ))) return 0;
2406
2407     if (USER_IsExitingThread( dest_tid )) return 0;
2408
2409     SPY_EnterMessage( SPY_SENDMESSAGE, hwnd, msg, wparam, lparam );
2410
2411     if (dest_tid == GetCurrentThreadId())
2412     {
2413         result = call_window_proc( hwnd, msg, wparam, lparam, FALSE, TRUE );
2414         ret = 1;
2415     }
2416     else if (dest_pid == GetCurrentProcessId())
2417     {
2418         ret = send_inter_thread_message( dest_tid, &info, &result );
2419     }
2420     else
2421     {
2422         /* inter-process message: need to map to Unicode */
2423         info.type = MSG_OTHER_PROCESS;
2424         if (is_unicode_message( info.msg ))
2425         {
2426             if (WINPROC_MapMsg32ATo32W( info.hwnd, info.msg, &info.wparam, &info.lparam ) == -1)
2427                 return 0;
2428             ret = send_inter_thread_message( dest_tid, &info, &result );
2429             result = WINPROC_UnmapMsg32ATo32W( info.hwnd, info.msg, info.wparam,
2430                                                info.lparam, result, NULL );
2431         }
2432         else ret = send_inter_thread_message( dest_tid, &info, &result );
2433     }
2434     SPY_ExitMessage( SPY_RESULT_OK, hwnd, msg, result, wparam, lparam );
2435     if (ret && res_ptr) *res_ptr = result;
2436     return ret;
2437 }
2438
2439
2440 /***********************************************************************
2441  *              SendMessageW  (USER32.@)
2442  */
2443 LRESULT WINAPI SendMessageW( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
2444 {
2445     DWORD_PTR res = 0;
2446     SendMessageTimeoutW( hwnd, msg, wparam, lparam, SMTO_NORMAL, 0, &res );
2447     return res;
2448 }
2449
2450
2451 /***********************************************************************
2452  *              SendMessageA  (USER32.@)
2453  */
2454 LRESULT WINAPI SendMessageA( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
2455 {
2456     DWORD_PTR res = 0;
2457     SendMessageTimeoutA( hwnd, msg, wparam, lparam, SMTO_NORMAL, 0, &res );
2458     return res;
2459 }
2460
2461
2462 /***********************************************************************
2463  *              SendNotifyMessageA  (USER32.@)
2464  */
2465 BOOL WINAPI SendNotifyMessageA( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
2466 {
2467     return SendNotifyMessageW( hwnd, msg, map_wparam_AtoW( msg, wparam ), lparam );
2468 }
2469
2470
2471 /***********************************************************************
2472  *              SendNotifyMessageW  (USER32.@)
2473  */
2474 BOOL WINAPI SendNotifyMessageW( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
2475 {
2476     struct send_message_info info;
2477     DWORD dest_tid;
2478     LRESULT result;
2479
2480     if (is_pointer_message(msg))
2481     {
2482         SetLastError( ERROR_MESSAGE_SYNC_ONLY );
2483         return FALSE;
2484     }
2485
2486     info.type    = MSG_NOTIFY;
2487     info.hwnd    = hwnd;
2488     info.msg     = msg;
2489     info.wparam  = wparam;
2490     info.lparam  = lparam;
2491     info.flags   = 0;
2492
2493     if (is_broadcast(hwnd))
2494     {
2495         EnumWindows( broadcast_message_callback, (LPARAM)&info );
2496         return TRUE;
2497     }
2498
2499     if (!(dest_tid = GetWindowThreadProcessId( hwnd, NULL ))) return FALSE;
2500
2501     if (USER_IsExitingThread( dest_tid )) return TRUE;
2502
2503     if (dest_tid == GetCurrentThreadId())
2504     {
2505         call_window_proc( hwnd, msg, wparam, lparam, TRUE, TRUE );
2506         return TRUE;
2507     }
2508     return send_inter_thread_message( dest_tid, &info, &result );
2509 }
2510
2511
2512 /***********************************************************************
2513  *              SendMessageCallbackA  (USER32.@)
2514  */
2515 BOOL WINAPI SendMessageCallbackA( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam,
2516                                   SENDASYNCPROC callback, ULONG_PTR data )
2517 {
2518     return SendMessageCallbackW( hwnd, msg, map_wparam_AtoW( msg, wparam ),
2519                                  lparam, callback, data );
2520 }
2521
2522
2523 /***********************************************************************
2524  *              SendMessageCallbackW  (USER32.@)
2525  */
2526 BOOL WINAPI SendMessageCallbackW( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam,
2527                                   SENDASYNCPROC callback, ULONG_PTR data )
2528 {
2529     struct send_message_info info;
2530     LRESULT result;
2531     DWORD dest_tid;
2532
2533     if (is_pointer_message(msg))
2534     {
2535         SetLastError( ERROR_MESSAGE_SYNC_ONLY );
2536         return FALSE;
2537     }
2538
2539     info.type     = MSG_CALLBACK;
2540     info.hwnd     = hwnd;
2541     info.msg      = msg;
2542     info.wparam   = wparam;
2543     info.lparam   = lparam;
2544     info.callback = callback;
2545     info.data     = data;
2546     info.flags    = 0;
2547
2548     if (is_broadcast(hwnd))
2549     {
2550         EnumWindows( broadcast_message_callback, (LPARAM)&info );
2551         return TRUE;
2552     }
2553
2554     if (!(dest_tid = GetWindowThreadProcessId( hwnd, NULL ))) return FALSE;
2555
2556     if (USER_IsExitingThread( dest_tid )) return TRUE;
2557
2558     if (dest_tid == GetCurrentThreadId())
2559     {
2560         result = call_window_proc( hwnd, msg, wparam, lparam, TRUE, TRUE );
2561         call_sendmsg_callback( callback, hwnd, msg, data, result );
2562         return TRUE;
2563     }
2564     FIXME( "callback will not be called\n" );
2565     return send_inter_thread_message( dest_tid, &info, &result );
2566 }
2567
2568
2569 /***********************************************************************
2570  *              ReplyMessage  (USER32.@)
2571  */
2572 BOOL WINAPI ReplyMessage( LRESULT result )
2573 {
2574     struct received_message_info *info = get_user_thread_info()->receive_info;
2575
2576     if (!info) return FALSE;
2577     reply_message( info, result, FALSE );
2578     return TRUE;
2579 }
2580
2581
2582 /***********************************************************************
2583  *              InSendMessage  (USER32.@)
2584  */
2585 BOOL WINAPI InSendMessage(void)
2586 {
2587     return (InSendMessageEx(NULL) & (ISMEX_SEND|ISMEX_REPLIED)) == ISMEX_SEND;
2588 }
2589
2590
2591 /***********************************************************************
2592  *              InSendMessageEx  (USER32.@)
2593  */
2594 DWORD WINAPI InSendMessageEx( LPVOID reserved )
2595 {
2596     struct received_message_info *info = get_user_thread_info()->receive_info;
2597
2598     if (info) return info->flags;
2599     return ISMEX_NOSEND;
2600 }
2601
2602
2603 /***********************************************************************
2604  *              PostMessageA  (USER32.@)
2605  */
2606 BOOL WINAPI PostMessageA( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
2607 {
2608     return PostMessageW( hwnd, msg, map_wparam_AtoW( msg, wparam ), lparam );
2609 }
2610
2611
2612 /***********************************************************************
2613  *              PostMessageW  (USER32.@)
2614  */
2615 BOOL WINAPI PostMessageW( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
2616 {
2617     struct send_message_info info;
2618     DWORD dest_tid;
2619
2620     if (is_pointer_message( msg ))
2621     {
2622         SetLastError( ERROR_MESSAGE_SYNC_ONLY );
2623         return FALSE;
2624     }
2625
2626     TRACE( "hwnd %p msg %x (%s) wp %x lp %lx\n",
2627            hwnd, msg, SPY_GetMsgName(msg, hwnd), wparam, lparam );
2628
2629     info.type   = MSG_POSTED;
2630     info.hwnd   = hwnd;
2631     info.msg    = msg;
2632     info.wparam = wparam;
2633     info.lparam = lparam;
2634     info.flags  = 0;
2635
2636     if (is_broadcast(hwnd))
2637     {
2638         EnumWindows( broadcast_message_callback, (LPARAM)&info );
2639         return TRUE;
2640     }
2641
2642     if (!hwnd) return PostThreadMessageW( GetCurrentThreadId(), msg, wparam, lparam );
2643
2644     if (!(dest_tid = GetWindowThreadProcessId( hwnd, NULL ))) return FALSE;
2645
2646     if (USER_IsExitingThread( dest_tid )) return TRUE;
2647
2648     return put_message_in_queue( dest_tid, &info, NULL );
2649 }
2650
2651
2652 /**********************************************************************
2653  *              PostThreadMessageA  (USER32.@)
2654  */
2655 BOOL WINAPI PostThreadMessageA( DWORD thread, UINT msg, WPARAM wparam, LPARAM lparam )
2656 {
2657     return PostThreadMessageW( thread, msg, map_wparam_AtoW( msg, wparam ), lparam );
2658 }
2659
2660
2661 /**********************************************************************
2662  *              PostThreadMessageW  (USER32.@)
2663  */
2664 BOOL WINAPI PostThreadMessageW( DWORD thread, UINT msg, WPARAM wparam, LPARAM lparam )
2665 {
2666     struct send_message_info info;
2667
2668     if (is_pointer_message( msg ))
2669     {
2670         SetLastError( ERROR_MESSAGE_SYNC_ONLY );
2671         return FALSE;
2672     }
2673     if (USER_IsExitingThread( thread )) return TRUE;
2674
2675     info.type   = MSG_POSTED;
2676     info.hwnd   = 0;
2677     info.msg    = msg;
2678     info.wparam = wparam;
2679     info.lparam = lparam;
2680     info.flags  = 0;
2681     return put_message_in_queue( thread, &info, NULL );
2682 }
2683
2684
2685 /***********************************************************************
2686  *              PostQuitMessage  (USER32.@)
2687  *
2688  * Posts a quit message to the current thread's message queue.
2689  *
2690  * PARAMS
2691  *  exit_code [I] Exit code to return from message loop.
2692  *
2693  * RETURNS
2694  *  Nothing.
2695  *
2696  * NOTES
2697  *  This function is not the same as calling:
2698  *|PostThreadMessage(GetCurrentThreadId(), WM_QUIT, exit_code, 0);
2699  *  It instead sets a flag in the message queue that signals it to generate
2700  *  a WM_QUIT message when there are no other pending sent or posted messages
2701  *  in the queue.
2702  */
2703 void WINAPI PostQuitMessage( INT exit_code )
2704 {
2705     SERVER_START_REQ( post_quit_message )
2706     {
2707         req->exit_code = exit_code;
2708         wine_server_call( req );
2709     }
2710     SERVER_END_REQ;
2711 }
2712
2713
2714 /***********************************************************************
2715  *              PeekMessageW  (USER32.@)
2716  */
2717 BOOL WINAPI PeekMessageW( MSG *msg_out, HWND hwnd, UINT first, UINT last, UINT flags )
2718 {
2719     struct user_thread_info *thread_info = get_user_thread_info();
2720     MSG msg;
2721
2722     if (HIWORD(flags))
2723         FIXME("PM_QS_xxxx flags (%04x) are not handled\n", flags >> 16);
2724
2725     USER_CheckNotLock();
2726
2727     /* check for graphics events */
2728     USER_Driver->pMsgWaitForMultipleObjectsEx( 0, NULL, 0, QS_ALLINPUT, 0 );
2729
2730     hwnd = WIN_GetFullHandle( hwnd );
2731
2732     for (;;)
2733     {
2734         if (!peek_message( &msg, hwnd, first, last, (flags & PM_REMOVE) ? GET_MSG_REMOVE : 0 ))
2735         {
2736             if (!(flags & PM_NOYIELD))
2737             {
2738                 DWORD count;
2739                 ReleaseThunkLock(&count);
2740                 NtYieldExecution();
2741                 if (count) RestoreThunkLock(count);
2742             }
2743             return FALSE;
2744         }
2745         if (msg.message & 0x80000000)
2746         {
2747             if (!(flags & PM_REMOVE))
2748             {
2749                 /* Have to remove the message explicitly.
2750                    Do this before handling it, because the message handler may
2751                    call PeekMessage again */
2752                 peek_message( &msg, msg.hwnd, msg.message, msg.message, GET_MSG_REMOVE );
2753             }
2754             handle_internal_message( msg.hwnd, msg.message, msg.wParam, msg.lParam );
2755         }
2756         else break;
2757     }
2758
2759     thread_info->GetMessageTimeVal = msg.time;
2760     msg.pt.x = LOWORD( thread_info->GetMessagePosVal );
2761     msg.pt.y = HIWORD( thread_info->GetMessagePosVal );
2762
2763     HOOK_CallHooks( WH_GETMESSAGE, HC_ACTION, flags & PM_REMOVE, (LPARAM)&msg, TRUE );
2764
2765     /* copy back our internal safe copy of message data to msg_out.
2766      * msg_out is a variable from the *program*, so it can't be used
2767      * internally as it can get "corrupted" by our use of SendMessage()
2768      * (back to the program) inside the message handling itself. */
2769     if (!msg_out)
2770     {
2771         SetLastError( ERROR_NOACCESS );
2772         return FALSE;
2773     }
2774     *msg_out = msg;
2775     return TRUE;
2776 }
2777
2778
2779 /***********************************************************************
2780  *              PeekMessageA  (USER32.@)
2781  */
2782 BOOL WINAPI PeekMessageA( MSG *msg, HWND hwnd, UINT first, UINT last, UINT flags )
2783 {
2784     BOOL ret = PeekMessageW( msg, hwnd, first, last, flags );
2785     if (ret) msg->wParam = map_wparam_WtoA( msg->message, msg->wParam );
2786     return ret;
2787 }
2788
2789
2790 /***********************************************************************
2791  *              GetMessageW  (USER32.@)
2792  */
2793 BOOL WINAPI GetMessageW( MSG *msg, HWND hwnd, UINT first, UINT last )
2794 {
2795     HANDLE server_queue = get_server_queue_handle();
2796     int mask = QS_POSTMESSAGE | QS_SENDMESSAGE;  /* Always selected */
2797
2798     if (first || last)
2799     {
2800         if ((first <= WM_KEYLAST) && (last >= WM_KEYFIRST)) mask |= QS_KEY;
2801         if ( ((first <= WM_MOUSELAST) && (last >= WM_MOUSEFIRST)) ||
2802              ((first <= WM_NCMOUSELAST) && (last >= WM_NCMOUSEFIRST)) ) mask |= QS_MOUSE;
2803         if ((first <= WM_TIMER) && (last >= WM_TIMER)) mask |= QS_TIMER;
2804         if ((first <= WM_SYSTIMER) && (last >= WM_SYSTIMER)) mask |= QS_TIMER;
2805         if ((first <= WM_PAINT) && (last >= WM_PAINT)) mask |= QS_PAINT;
2806     }
2807     else mask |= QS_MOUSE | QS_KEY | QS_TIMER | QS_PAINT;
2808
2809     while (!PeekMessageW( msg, hwnd, first, last, PM_REMOVE ))
2810     {
2811         /* wait until one of the bits is set */
2812         unsigned int wake_bits = 0, changed_bits = 0;
2813         DWORD dwlc;
2814
2815         SERVER_START_REQ( set_queue_mask )
2816         {
2817             req->wake_mask    = QS_SENDMESSAGE;
2818             req->changed_mask = mask;
2819             req->skip_wait    = 1;
2820             if (!wine_server_call( req ))
2821             {
2822                 wake_bits    = reply->wake_bits;
2823                 changed_bits = reply->changed_bits;
2824             }
2825         }
2826         SERVER_END_REQ;
2827
2828         if (changed_bits & mask) continue;
2829         if (wake_bits & QS_SENDMESSAGE) continue;
2830
2831         TRACE( "(%04lx) mask=%08x, bits=%08x, changed=%08x, waiting\n",
2832                GetCurrentThreadId(), mask, wake_bits, changed_bits );
2833
2834         ReleaseThunkLock( &dwlc );
2835         USER_Driver->pMsgWaitForMultipleObjectsEx( 1, &server_queue, INFINITE, QS_ALLINPUT, 0 );
2836         if (dwlc) RestoreThunkLock( dwlc );
2837     }
2838
2839     return (msg->message != WM_QUIT);
2840 }
2841
2842
2843 /***********************************************************************
2844  *              GetMessageA  (USER32.@)
2845  */
2846 BOOL WINAPI GetMessageA( MSG *msg, HWND hwnd, UINT first, UINT last )
2847 {
2848     GetMessageW( msg, hwnd, first, last );
2849     msg->wParam = map_wparam_WtoA( msg->message, msg->wParam );
2850     return (msg->message != WM_QUIT);
2851 }
2852
2853
2854 /***********************************************************************
2855  *              IsDialogMessageA (USER32.@)
2856  *              IsDialogMessage  (USER32.@)
2857  */
2858 BOOL WINAPI IsDialogMessageA( HWND hwndDlg, LPMSG pmsg )
2859 {
2860     MSG msg = *pmsg;
2861     msg.wParam = map_wparam_AtoW( msg.message, msg.wParam );
2862     return IsDialogMessageW( hwndDlg, &msg );
2863 }
2864
2865
2866 /***********************************************************************
2867  *              TranslateMessage (USER32.@)
2868  *
2869  * Implementation of TranslateMessage.
2870  *
2871  * TranslateMessage translates virtual-key messages into character-messages,
2872  * as follows :
2873  * WM_KEYDOWN/WM_KEYUP combinations produce a WM_CHAR or WM_DEADCHAR message.
2874  * ditto replacing WM_* with WM_SYS*
2875  * This produces WM_CHAR messages only for keys mapped to ASCII characters
2876  * by the keyboard driver.
2877  *
2878  * If the message is WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, or WM_SYSKEYUP, the
2879  * return value is nonzero, regardless of the translation.
2880  *
2881  */
2882 BOOL WINAPI TranslateMessage( const MSG *msg )
2883 {
2884     UINT message;
2885     WCHAR wp[2];
2886     BYTE state[256];
2887
2888     if (msg->message < WM_KEYFIRST || msg->message > WM_KEYLAST) return FALSE;
2889     if (msg->message != WM_KEYDOWN && msg->message != WM_SYSKEYDOWN) return TRUE;
2890
2891     TRACE_(key)("Translating key %s (%04x), scancode %02x\n",
2892                  SPY_GetVKeyName(msg->wParam), msg->wParam, LOBYTE(HIWORD(msg->lParam)));
2893
2894     GetKeyboardState( state );
2895     /* FIXME : should handle ToUnicode yielding 2 */
2896     switch (ToUnicode(msg->wParam, HIWORD(msg->lParam), state, wp, 2, 0))
2897     {
2898     case 1:
2899         message = (msg->message == WM_KEYDOWN) ? WM_CHAR : WM_SYSCHAR;
2900         TRACE_(key)("1 -> PostMessageW(%p,%s,%04x,%08lx)\n",
2901             msg->hwnd, SPY_GetMsgName(message, msg->hwnd), wp[0], msg->lParam);
2902         PostMessageW( msg->hwnd, message, wp[0], msg->lParam );
2903         break;
2904
2905     case -1:
2906         message = (msg->message == WM_KEYDOWN) ? WM_DEADCHAR : WM_SYSDEADCHAR;
2907         TRACE_(key)("-1 -> PostMessageW(%p,%s,%04x,%08lx)\n",
2908             msg->hwnd, SPY_GetMsgName(message, msg->hwnd), wp[0], msg->lParam);
2909         PostMessageW( msg->hwnd, message, wp[0], msg->lParam );
2910         break;
2911     }
2912     return TRUE;
2913 }
2914
2915
2916 /***********************************************************************
2917  *              DispatchMessageA (USER32.@)
2918  *
2919  * See DispatchMessageW.
2920  */
2921 LONG WINAPI DispatchMessageA( const MSG* msg )
2922 {
2923     WND * wndPtr;
2924     LONG retval;
2925     WNDPROC winproc;
2926
2927       /* Process timer messages */
2928     if ((msg->message == WM_TIMER) || (msg->message == WM_SYSTIMER))
2929     {
2930         if (msg->lParam) return CallWindowProcA( (WNDPROC)msg->lParam, msg->hwnd,
2931                                                  msg->message, msg->wParam, GetTickCount() );
2932     }
2933
2934     if (!(wndPtr = WIN_GetPtr( msg->hwnd )))
2935     {
2936         if (msg->hwnd) SetLastError( ERROR_INVALID_WINDOW_HANDLE );
2937         return 0;
2938     }
2939     if (wndPtr == WND_OTHER_PROCESS || wndPtr == WND_DESKTOP)
2940     {
2941         if (IsWindow( msg->hwnd )) SetLastError( ERROR_MESSAGE_SYNC_ONLY );
2942         else SetLastError( ERROR_INVALID_WINDOW_HANDLE );
2943         return 0;
2944     }
2945     if (wndPtr->tid != GetCurrentThreadId())
2946     {
2947         SetLastError( ERROR_MESSAGE_SYNC_ONLY );
2948         WIN_ReleasePtr( wndPtr );
2949         return 0;
2950     }
2951     winproc = wndPtr->winproc;
2952     WIN_ReleasePtr( wndPtr );
2953
2954     SPY_EnterMessage( SPY_DISPATCHMESSAGE, msg->hwnd, msg->message,
2955                       msg->wParam, msg->lParam );
2956     retval = CallWindowProcA( winproc, msg->hwnd, msg->message,
2957                               msg->wParam, msg->lParam );
2958     SPY_ExitMessage( SPY_RESULT_OK, msg->hwnd, msg->message, retval,
2959                      msg->wParam, msg->lParam );
2960
2961     if (msg->message == WM_PAINT)
2962     {
2963         /* send a WM_NCPAINT and WM_ERASEBKGND if the non-client area is still invalid */
2964         HRGN hrgn = CreateRectRgn( 0, 0, 0, 0 );
2965         GetUpdateRgn( msg->hwnd, hrgn, TRUE );
2966         DeleteObject( hrgn );
2967     }
2968     return retval;
2969 }
2970
2971
2972 /***********************************************************************
2973  *              DispatchMessageW (USER32.@) Process a message
2974  *
2975  * Process the message specified in the structure *_msg_.
2976  *
2977  * If the lpMsg parameter points to a WM_TIMER message and the
2978  * parameter of the WM_TIMER message is not NULL, the lParam parameter
2979  * points to the function that is called instead of the window
2980  * procedure.
2981  *
2982  * The message must be valid.
2983  *
2984  * RETURNS
2985  *
2986  *   DispatchMessage() returns the result of the window procedure invoked.
2987  *
2988  * CONFORMANCE
2989  *
2990  *   ECMA-234, Win32
2991  *
2992  */
2993 LONG WINAPI DispatchMessageW( const MSG* msg )
2994 {
2995     WND * wndPtr;
2996     LONG retval;
2997     WNDPROC winproc;
2998
2999       /* Process timer messages */
3000     if ((msg->message == WM_TIMER) || (msg->message == WM_SYSTIMER))
3001     {
3002         if (msg->lParam) return CallWindowProcW( (WNDPROC)msg->lParam, msg->hwnd,
3003                                                  msg->message, msg->wParam, GetTickCount() );
3004     }
3005
3006     if (!(wndPtr = WIN_GetPtr( msg->hwnd )))
3007     {
3008         if (msg->hwnd) SetLastError( ERROR_INVALID_WINDOW_HANDLE );
3009         return 0;
3010     }
3011     if (wndPtr == WND_OTHER_PROCESS || wndPtr == WND_DESKTOP)
3012     {
3013         if (IsWindow( msg->hwnd )) SetLastError( ERROR_MESSAGE_SYNC_ONLY );
3014         else SetLastError( ERROR_INVALID_WINDOW_HANDLE );
3015         return 0;
3016     }
3017     if (wndPtr->tid != GetCurrentThreadId())
3018     {
3019         SetLastError( ERROR_MESSAGE_SYNC_ONLY );
3020         WIN_ReleasePtr( wndPtr );
3021         return 0;
3022     }
3023     winproc = wndPtr->winproc;
3024     WIN_ReleasePtr( wndPtr );
3025
3026     SPY_EnterMessage( SPY_DISPATCHMESSAGE, msg->hwnd, msg->message,
3027                       msg->wParam, msg->lParam );
3028     retval = CallWindowProcW( winproc, msg->hwnd, msg->message,
3029                               msg->wParam, msg->lParam );
3030     SPY_ExitMessage( SPY_RESULT_OK, msg->hwnd, msg->message, retval,
3031                      msg->wParam, msg->lParam );
3032
3033     if (msg->message == WM_PAINT)
3034     {
3035         /* send a WM_NCPAINT and WM_ERASEBKGND if the non-client area is still invalid */
3036         HRGN hrgn = CreateRectRgn( 0, 0, 0, 0 );
3037         GetUpdateRgn( msg->hwnd, hrgn, TRUE );
3038         DeleteObject( hrgn );
3039     }
3040     return retval;
3041 }
3042
3043
3044 /***********************************************************************
3045  *              GetMessagePos (USER.119)
3046  *              GetMessagePos (USER32.@)
3047  *
3048  * The GetMessagePos() function returns a long value representing a
3049  * cursor position, in screen coordinates, when the last message
3050  * retrieved by the GetMessage() function occurs. The x-coordinate is
3051  * in the low-order word of the return value, the y-coordinate is in
3052  * the high-order word. The application can use the MAKEPOINT()
3053  * macro to obtain a POINT structure from the return value.
3054  *
3055  * For the current cursor position, use GetCursorPos().
3056  *
3057  * RETURNS
3058  *
3059  * Cursor position of last message on success, zero on failure.
3060  *
3061  * CONFORMANCE
3062  *
3063  * ECMA-234, Win32
3064  *
3065  */
3066 DWORD WINAPI GetMessagePos(void)
3067 {
3068     return get_user_thread_info()->GetMessagePosVal;
3069 }
3070
3071
3072 /***********************************************************************
3073  *              GetMessageTime (USER.120)
3074  *              GetMessageTime (USER32.@)
3075  *
3076  * GetMessageTime() returns the message time for the last message
3077  * retrieved by the function. The time is measured in milliseconds with
3078  * the same offset as GetTickCount().
3079  *
3080  * Since the tick count wraps, this is only useful for moderately short
3081  * relative time comparisons.
3082  *
3083  * RETURNS
3084  *
3085  * Time of last message on success, zero on failure.
3086  */
3087 LONG WINAPI GetMessageTime(void)
3088 {
3089     return get_user_thread_info()->GetMessageTimeVal;
3090 }
3091
3092
3093 /***********************************************************************
3094  *              GetMessageExtraInfo (USER.288)
3095  *              GetMessageExtraInfo (USER32.@)
3096  */
3097 LPARAM WINAPI GetMessageExtraInfo(void)
3098 {
3099     return get_user_thread_info()->GetMessageExtraInfoVal;
3100 }
3101
3102
3103 /***********************************************************************
3104  *              SetMessageExtraInfo (USER32.@)
3105  */
3106 LPARAM WINAPI SetMessageExtraInfo(LPARAM lParam)
3107 {
3108     struct user_thread_info *thread_info = get_user_thread_info();
3109     LONG old_value = thread_info->GetMessageExtraInfoVal;
3110     thread_info->GetMessageExtraInfoVal = lParam;
3111     return old_value;
3112 }
3113
3114
3115 /***********************************************************************
3116  *              WaitMessage (USER.112) Suspend thread pending messages
3117  *              WaitMessage (USER32.@) Suspend thread pending messages
3118  *
3119  * WaitMessage() suspends a thread until events appear in the thread's
3120  * queue.
3121  */
3122 BOOL WINAPI WaitMessage(void)
3123 {
3124     return (MsgWaitForMultipleObjectsEx( 0, NULL, INFINITE, QS_ALLINPUT, 0 ) != WAIT_FAILED);
3125 }
3126
3127
3128 /***********************************************************************
3129  *              MsgWaitForMultipleObjectsEx   (USER32.@)
3130  */
3131 DWORD WINAPI MsgWaitForMultipleObjectsEx( DWORD count, CONST HANDLE *pHandles,
3132                                           DWORD timeout, DWORD mask, DWORD flags )
3133 {
3134     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
3135     DWORD i, ret, lock;
3136
3137     if (count > MAXIMUM_WAIT_OBJECTS-1)
3138     {
3139         SetLastError( ERROR_INVALID_PARAMETER );
3140         return WAIT_FAILED;
3141     }
3142
3143     /* set the queue mask */
3144     SERVER_START_REQ( set_queue_mask )
3145     {
3146         req->wake_mask    = (flags & MWMO_INPUTAVAILABLE) ? mask : 0;
3147         req->changed_mask = mask;
3148         req->skip_wait    = 0;
3149         wine_server_call( req );
3150     }
3151     SERVER_END_REQ;
3152
3153     /* Add the thread event to the handle list */
3154     for (i = 0; i < count; i++) handles[i] = pHandles[i];
3155     handles[count] = get_server_queue_handle();
3156
3157     ReleaseThunkLock( &lock );
3158     ret = USER_Driver->pMsgWaitForMultipleObjectsEx( count+1, handles, timeout, mask, flags );
3159     if (ret == count+1) ret = count; /* pretend the msg queue is ready */
3160     if (lock) RestoreThunkLock( lock );
3161     return ret;
3162 }
3163
3164
3165 /***********************************************************************
3166  *              MsgWaitForMultipleObjects (USER32.@)
3167  */
3168 DWORD WINAPI MsgWaitForMultipleObjects( DWORD count, CONST HANDLE *handles,
3169                                         BOOL wait_all, DWORD timeout, DWORD mask )
3170 {
3171     return MsgWaitForMultipleObjectsEx( count, handles, timeout, mask,
3172                                         wait_all ? MWMO_WAITALL : 0 );
3173 }
3174
3175
3176 /***********************************************************************
3177  *              WaitForInputIdle (USER32.@)
3178  */
3179 DWORD WINAPI WaitForInputIdle( HANDLE hProcess, DWORD dwTimeOut )
3180 {
3181     DWORD start_time, elapsed, ret;
3182     HANDLE idle_event = (HANDLE)-1;
3183
3184     SERVER_START_REQ( wait_input_idle )
3185     {
3186         req->handle = hProcess;
3187         req->timeout = dwTimeOut;
3188         if (!(ret = wine_server_call_err( req ))) idle_event = reply->event;
3189     }
3190     SERVER_END_REQ;
3191     if (ret) return WAIT_FAILED;  /* error */
3192     if (!idle_event) return 0;  /* no event to wait on */
3193
3194     start_time = GetTickCount();
3195     elapsed = 0;
3196
3197     TRACE("waiting for %p\n", idle_event );
3198     do
3199     {
3200         ret = MsgWaitForMultipleObjects ( 1, &idle_event, FALSE, dwTimeOut - elapsed, QS_SENDMESSAGE );
3201         switch (ret)
3202         {
3203         case WAIT_OBJECT_0+1:
3204             process_sent_messages();
3205             break;
3206         case WAIT_TIMEOUT:
3207         case WAIT_FAILED:
3208             TRACE("timeout or error\n");
3209             return ret;
3210         default:
3211             TRACE("finished\n");
3212             return 0;
3213         }
3214         if (dwTimeOut != INFINITE)
3215         {
3216             elapsed = GetTickCount() - start_time;
3217             if (elapsed > dwTimeOut)
3218                 break;
3219         }
3220     }
3221     while (1);
3222
3223     return WAIT_TIMEOUT;
3224 }
3225
3226
3227 /***********************************************************************
3228  *              UserYield (USER.332)
3229  */
3230 void WINAPI UserYield16(void)
3231 {
3232    DWORD count;
3233
3234     /* Handle sent messages */
3235     process_sent_messages();
3236
3237     /* Yield */
3238     ReleaseThunkLock(&count);
3239
3240     if (count)
3241     {
3242         RestoreThunkLock(count);
3243         /* Handle sent messages again */
3244         process_sent_messages();
3245     }
3246 }
3247
3248
3249 /***********************************************************************
3250  *              RegisterWindowMessageA (USER32.@)
3251  *              RegisterWindowMessage (USER.118)
3252  */
3253 UINT WINAPI RegisterWindowMessageA( LPCSTR str )
3254 {
3255     UINT ret = GlobalAddAtomA(str);
3256     TRACE("%s, ret=%x\n", str, ret);
3257     return ret;
3258 }
3259
3260
3261 /***********************************************************************
3262  *              RegisterWindowMessageW (USER32.@)
3263  */
3264 UINT WINAPI RegisterWindowMessageW( LPCWSTR str )
3265 {
3266     UINT ret = GlobalAddAtomW(str);
3267     TRACE("%s ret=%x\n", debugstr_w(str), ret);
3268     return ret;
3269 }
3270
3271
3272 /***********************************************************************
3273  *              BroadcastSystemMessageA (USER32.@)
3274  *              BroadcastSystemMessage  (USER32.@)
3275  */
3276 LONG WINAPI BroadcastSystemMessageA( DWORD flags, LPDWORD recipients, UINT msg, WPARAM wp, LPARAM lp )
3277 {
3278     if ((*recipients & BSM_APPLICATIONS) || (*recipients == BSM_ALLCOMPONENTS))
3279     {
3280         FIXME( "(%08lx,%08lx,%08x,%08x,%08lx): semi-stub!\n", flags, *recipients, msg, wp, lp );
3281         PostMessageA( HWND_BROADCAST, msg, wp, lp );
3282         return 1;
3283     }
3284     else
3285     {
3286         FIXME( "(%08lx,%08lx,%08x,%08x,%08lx): stub!\n", flags, *recipients, msg, wp, lp);
3287         return -1;
3288     }
3289 }
3290
3291
3292 /***********************************************************************
3293  *              BroadcastSystemMessageW (USER32.@)
3294  */
3295 LONG WINAPI BroadcastSystemMessageW( DWORD flags, LPDWORD recipients, UINT msg, WPARAM wp, LPARAM lp )
3296 {
3297     if ((*recipients & BSM_APPLICATIONS) || (*recipients == BSM_ALLCOMPONENTS))
3298     {
3299         FIXME( "(%08lx,%08lx,%08x,%08x,%08lx): semi-stub!\n", flags, *recipients, msg, wp, lp );
3300         PostMessageW( HWND_BROADCAST, msg, wp, lp );
3301         return 1;
3302     }
3303     else
3304     {
3305         FIXME( "(%08lx,%08lx,%08x,%08x,%08lx): stub!\n", flags, *recipients, msg, wp, lp );
3306         return -1;
3307     }
3308 }
3309
3310
3311 /***********************************************************************
3312  *              SetMessageQueue (USER32.@)
3313  */
3314 BOOL WINAPI SetMessageQueue( INT size )
3315 {
3316     /* now obsolete the message queue will be expanded dynamically as necessary */
3317     return TRUE;
3318 }
3319
3320
3321 /***********************************************************************
3322  *              MessageBeep (USER32.@)
3323  */
3324 BOOL WINAPI MessageBeep( UINT i )
3325 {
3326     BOOL active = TRUE;
3327     SystemParametersInfoA( SPI_GETBEEP, 0, &active, FALSE );
3328     if (active) USER_Driver->pBeep();
3329     return TRUE;
3330 }
3331
3332
3333 /***********************************************************************
3334  *              SetTimer (USER32.@)
3335  */
3336 UINT_PTR WINAPI SetTimer( HWND hwnd, UINT_PTR id, UINT timeout, TIMERPROC proc )
3337 {
3338     UINT_PTR ret;
3339     WNDPROC winproc = 0;
3340
3341     if (proc) winproc = WINPROC_AllocProc( (WNDPROC)proc, WIN_PROC_32A );
3342
3343     SERVER_START_REQ( set_win_timer )
3344     {
3345         req->win    = hwnd;
3346         req->msg    = WM_TIMER;
3347         req->id     = id;
3348         req->rate   = max( timeout, SYS_TIMER_RATE );
3349         req->lparam = (unsigned int)winproc;
3350         if (!wine_server_call_err( req ))
3351         {
3352             ret = reply->id;
3353             if (!ret) ret = TRUE;
3354         }
3355         else ret = 0;
3356     }
3357     SERVER_END_REQ;
3358
3359     TRACE("Added %p %x %p timeout %d\n", hwnd, id, winproc, timeout );
3360     return ret;
3361 }
3362
3363
3364 /***********************************************************************
3365  *              SetSystemTimer (USER32.@)
3366  */
3367 UINT_PTR WINAPI SetSystemTimer( HWND hwnd, UINT_PTR id, UINT timeout, TIMERPROC proc )
3368 {
3369     UINT_PTR ret;
3370     WNDPROC winproc = 0;
3371
3372     if (proc) winproc = WINPROC_AllocProc( (WNDPROC)proc, WIN_PROC_32A );
3373
3374     SERVER_START_REQ( set_win_timer )
3375     {
3376         req->win    = hwnd;
3377         req->msg    = WM_SYSTIMER;
3378         req->id     = id;
3379         req->rate   = max( timeout, SYS_TIMER_RATE );
3380         req->lparam = (unsigned int)winproc;
3381         if (!wine_server_call_err( req ))
3382         {
3383             ret = reply->id;
3384             if (!ret) ret = TRUE;
3385         }
3386         else ret = 0;
3387     }
3388     SERVER_END_REQ;
3389
3390     TRACE("Added %p %x %p timeout %d\n", hwnd, id, winproc, timeout );
3391     return ret;
3392 }
3393
3394
3395 /***********************************************************************
3396  *              KillTimer (USER32.@)
3397  */
3398 BOOL WINAPI KillTimer( HWND hwnd, UINT_PTR id )
3399 {
3400     BOOL ret;
3401
3402     TRACE("%p %d\n", hwnd, id );
3403
3404     SERVER_START_REQ( kill_win_timer )
3405     {
3406         req->win = hwnd;
3407         req->msg = WM_TIMER;
3408         req->id  = id;
3409         ret = !wine_server_call_err( req );
3410     }
3411     SERVER_END_REQ;
3412     return ret;
3413 }
3414
3415
3416 /***********************************************************************
3417  *              KillSystemTimer (USER32.@)
3418  */
3419 BOOL WINAPI KillSystemTimer( HWND hwnd, UINT_PTR id )
3420 {
3421     BOOL ret;
3422
3423     TRACE("%p %d\n", hwnd, id );
3424
3425     SERVER_START_REQ( kill_win_timer )
3426     {
3427         req->win = hwnd;
3428         req->msg = WM_SYSTIMER;
3429         req->id  = id;
3430         ret = !wine_server_call_err( req );
3431     }
3432     SERVER_END_REQ;
3433     return ret;
3434 }
3435
3436
3437 /**********************************************************************
3438  *              GetGUIThreadInfo  (USER32.@)
3439  */
3440 BOOL WINAPI GetGUIThreadInfo( DWORD id, GUITHREADINFO *info )
3441 {
3442     BOOL ret;
3443
3444     SERVER_START_REQ( get_thread_input )
3445     {
3446         req->tid = id;
3447         if ((ret = !wine_server_call_err( req )))
3448         {
3449             info->flags          = 0;
3450             info->hwndActive     = reply->active;
3451             info->hwndFocus      = reply->focus;
3452             info->hwndCapture    = reply->capture;
3453             info->hwndMenuOwner  = reply->menu_owner;
3454             info->hwndMoveSize   = reply->move_size;
3455             info->hwndCaret      = reply->caret;
3456             info->rcCaret.left   = reply->rect.left;
3457             info->rcCaret.top    = reply->rect.top;
3458             info->rcCaret.right  = reply->rect.right;
3459             info->rcCaret.bottom = reply->rect.bottom;
3460             if (reply->menu_owner) info->flags |= GUI_INMENUMODE;
3461             if (reply->move_size) info->flags |= GUI_INMOVESIZE;
3462             if (reply->caret) info->flags |= GUI_CARETBLINKING;
3463         }
3464     }
3465     SERVER_END_REQ;
3466     return ret;
3467 }
3468
3469
3470 /******************************************************************
3471  *              IsHungAppWindow (USER32.@)
3472  *
3473  */
3474 BOOL WINAPI IsHungAppWindow( HWND hWnd )
3475 {
3476     DWORD_PTR dwResult;
3477     return !SendMessageTimeoutA(hWnd, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 5000, &dwResult);
3478 }