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