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