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