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