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