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