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