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