Start using the exported TEB structure from winternl.h where
[wine] / windows / message.c
1 /*
2  * Message queues related functions
3  *
4  * Copyright 1993, 1994 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #ifdef HAVE_SYS_TIME_H
27 # include <sys/time.h>
28 #endif
29 #include <sys/types.h>
30
31 #include "winbase.h"
32 #include "wingdi.h"
33 #include "winuser.h"
34 #include "message.h"
35 #include "winerror.h"
36 #include "wine/server.h"
37 #include "controls.h"
38 #include "dde.h"
39 #include "message.h"
40 #include "user.h"
41 #include "win.h"
42 #include "winpos.h"
43 #include "winproc.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(msg);
47 WINE_DECLARE_DEBUG_CHANNEL(key);
48
49 #define WM_NCMOUSEFIRST         WM_NCMOUSEMOVE
50 #define WM_NCMOUSELAST          WM_NCMBUTTONDBLCLK
51
52
53 /***********************************************************************
54  *           is_keyboard_message
55  */
56 inline static BOOL is_keyboard_message( UINT message )
57 {
58     return (message >= WM_KEYFIRST && message <= WM_KEYLAST);
59 }
60
61
62 /***********************************************************************
63  *           is_mouse_message
64  */
65 inline static BOOL is_mouse_message( UINT message )
66 {
67     return ((message >= WM_NCMOUSEFIRST && message <= WM_NCMOUSELAST) ||
68             (message >= WM_MOUSEFIRST && message <= WM_MOUSELAST));
69 }
70
71
72 /***********************************************************************
73  *           check_message_filter
74  */
75 inline static BOOL check_message_filter( const MSG *msg, HWND hwnd, UINT first, UINT last )
76 {
77     if (hwnd)
78     {
79         if (msg->hwnd != hwnd && !IsChild( hwnd, msg->hwnd )) return FALSE;
80     }
81     if (first || last)
82     {
83        return (msg->message >= first && msg->message <= last);
84     }
85     return TRUE;
86 }
87
88
89 /***********************************************************************
90  *           process_sent_messages
91  *
92  * Process all pending sent messages.
93  */
94 inline static void process_sent_messages(void)
95 {
96     MSG msg;
97     MSG_peek_message( &msg, 0, 0, 0, GET_MSG_REMOVE | GET_MSG_SENT_ONLY );
98 }
99
100
101 /***********************************************************************
102  *           queue_hardware_message
103  *
104  * store a hardware message in the thread queue
105  */
106 #if 0
107 static void queue_hardware_message( MSG *msg, ULONG_PTR extra_info )
108 {
109     SERVER_START_REQ( send_message )
110     {
111         req->type   = MSG_HARDWARE;
112         req->id     = GetWindowThreadProcessId( msg->hwnd, NULL );
113         req->win    = msg->hwnd;
114         req->msg    = msg->message;
115         req->wparam = msg->wParam;
116         req->lparam = msg->lParam;
117         req->x      = msg->pt.x;
118         req->y      = msg->pt.y;
119         req->time   = msg->time;
120         req->info   = extra_info;
121         req->timeout = 0;
122         wine_server_call( req );
123     }
124     SERVER_END_REQ;
125 }
126 #endif
127
128
129 /***********************************************************************
130  *           MSG_SendParentNotify
131  *
132  * Send a WM_PARENTNOTIFY to all ancestors of the given window, unless
133  * the window has the WS_EX_NOPARENTNOTIFY style.
134  */
135 static void MSG_SendParentNotify( HWND hwnd, WORD event, WORD idChild, POINT pt )
136 {
137     /* pt has to be in the client coordinates of the parent window */
138     MapWindowPoints( 0, hwnd, &pt, 1 );
139     for (;;)
140     {
141         HWND parent;
142
143         if (!(GetWindowLongA( hwnd, GWL_STYLE ) & WS_CHILD)) break;
144         if (GetWindowLongA( hwnd, GWL_EXSTYLE ) & WS_EX_NOPARENTNOTIFY) break;
145         if (!(parent = GetParent(hwnd))) break;
146         MapWindowPoints( hwnd, parent, &pt, 1 );
147         hwnd = parent;
148         SendMessageA( hwnd, WM_PARENTNOTIFY,
149                       MAKEWPARAM( event, idChild ), MAKELPARAM( pt.x, pt.y ) );
150     }
151 }
152
153
154 #if 0  /* this is broken for now, will require proper support in the server */
155
156 /***********************************************************************
157  *          MSG_JournalPlayBackMsg
158  *
159  * Get an EVENTMSG struct via call JOURNALPLAYBACK hook function
160  */
161 void MSG_JournalPlayBackMsg(void)
162 {
163     EVENTMSG tmpMsg;
164     MSG msg;
165     LRESULT wtime;
166     int keyDown,i;
167
168     wtime=HOOK_CallHooks( WH_JOURNALPLAYBACK, HC_GETNEXT, 0, (LPARAM)&tmpMsg, TRUE );
169     /*  TRACE(msg,"Playback wait time =%ld\n",wtime); */
170     if (wtime<=0)
171     {
172         wtime=0;
173         msg.message = tmpMsg.message;
174         msg.hwnd    = tmpMsg.hwnd;
175         msg.time    = tmpMsg.time;
176         if ((tmpMsg.message >= WM_KEYFIRST) && (tmpMsg.message <= WM_KEYLAST))
177         {
178             msg.wParam  = tmpMsg.paramL & 0xFF;
179             msg.lParam  = MAKELONG(tmpMsg.paramH&0x7ffff,tmpMsg.paramL>>8);
180             if (tmpMsg.message == WM_KEYDOWN || tmpMsg.message == WM_SYSKEYDOWN)
181             {
182                 for (keyDown=i=0; i<256 && !keyDown; i++)
183                     if (InputKeyStateTable[i] & 0x80)
184                         keyDown++;
185                 if (!keyDown)
186                     msg.lParam |= 0x40000000;
187                 InputKeyStateTable[msg.wParam] |= 0x80;
188                 AsyncKeyStateTable[msg.wParam] |= 0x80;
189             }
190             else                                       /* WM_KEYUP, WM_SYSKEYUP */
191             {
192                 msg.lParam |= 0xC0000000;
193                 InputKeyStateTable[msg.wParam] &= ~0x80;
194             }
195             if (InputKeyStateTable[VK_MENU] & 0x80)
196                 msg.lParam |= 0x20000000;
197             if (tmpMsg.paramH & 0x8000)              /*special_key bit*/
198                 msg.lParam |= 0x01000000;
199
200             msg.pt.x = msg.pt.y = 0;
201             queue_hardware_message( &msg, 0 );
202         }
203         else if ((tmpMsg.message>= WM_MOUSEFIRST) && (tmpMsg.message <= WM_MOUSELAST))
204         {
205             switch (tmpMsg.message)
206             {
207             case WM_LBUTTONDOWN:
208                 InputKeyStateTable[VK_LBUTTON] |= 0x80;
209                 AsyncKeyStateTable[VK_LBUTTON] |= 0x80;
210                 break;
211             case WM_LBUTTONUP:
212                 InputKeyStateTable[VK_LBUTTON] &= ~0x80;
213                 break;
214             case WM_MBUTTONDOWN:
215                 InputKeyStateTable[VK_MBUTTON] |= 0x80;
216                 AsyncKeyStateTable[VK_MBUTTON] |= 0x80;
217                 break;
218             case WM_MBUTTONUP:
219                 InputKeyStateTable[VK_MBUTTON] &= ~0x80;
220                 break;
221             case WM_RBUTTONDOWN:
222                 InputKeyStateTable[VK_RBUTTON] |= 0x80;
223                 AsyncKeyStateTable[VK_RBUTTON] |= 0x80;
224                 break;
225             case WM_RBUTTONUP:
226                 InputKeyStateTable[VK_RBUTTON] &= ~0x80;
227                 break;
228             }
229             SetCursorPos(tmpMsg.paramL,tmpMsg.paramH);
230             msg.lParam=MAKELONG(tmpMsg.paramL,tmpMsg.paramH);
231             msg.wParam=0;
232             if (InputKeyStateTable[VK_LBUTTON] & 0x80) msg.wParam |= MK_LBUTTON;
233             if (InputKeyStateTable[VK_MBUTTON] & 0x80) msg.wParam |= MK_MBUTTON;
234             if (InputKeyStateTable[VK_RBUTTON] & 0x80) msg.wParam |= MK_RBUTTON;
235
236             msg.pt.x = tmpMsg.paramL;
237             msg.pt.y = tmpMsg.paramH;
238             queue_hardware_message( &msg, 0 );
239         }
240         HOOK_CallHooks( WH_JOURNALPLAYBACK, HC_SKIP, 0, (LPARAM)&tmpMsg, TRUE );
241     }
242     else
243     {
244         if( tmpMsg.message == WM_QUEUESYNC ) HOOK_CallHooks( WH_CBT, HCBT_QS, 0, 0, TRUE );
245     }
246 }
247 #endif
248
249
250 /***********************************************************************
251  *          process_raw_keyboard_message
252  *
253  * returns TRUE if the contents of 'msg' should be passed to the application
254  */
255 static void process_raw_keyboard_message( MSG *msg )
256 {
257     EVENTMSG event;
258
259     event.message = msg->message;
260     event.hwnd    = msg->hwnd;
261     event.time    = msg->time;
262     event.paramL  = (msg->wParam & 0xFF) | (HIWORD(msg->lParam) << 8);
263     event.paramH  = msg->lParam & 0x7FFF;
264     if (HIWORD(msg->lParam) & 0x0100) event.paramH |= 0x8000; /* special_key - bit */
265     HOOK_CallHooks( WH_JOURNALRECORD, HC_ACTION, 0, (LPARAM)&event, TRUE );
266 }
267
268
269 /***********************************************************************
270  *          process_cooked_keyboard_message
271  *
272  * returns TRUE if the contents of 'msg' should be passed to the application
273  */
274 static BOOL process_cooked_keyboard_message( MSG *msg, BOOL remove )
275 {
276     if (remove)
277     {
278         /* Handle F1 key by sending out WM_HELP message */
279         if ((msg->message == WM_KEYUP) &&
280             (msg->wParam == VK_F1) &&
281             (msg->hwnd != GetDesktopWindow()) &&
282             !MENU_IsMenuActive())
283         {
284             HELPINFO hi;
285             hi.cbSize = sizeof(HELPINFO);
286             hi.iContextType = HELPINFO_WINDOW;
287             hi.iCtrlId = GetWindowLongA( msg->hwnd, GWL_ID );
288             hi.hItemHandle = msg->hwnd;
289             hi.dwContextId = GetWindowContextHelpId( msg->hwnd );
290             hi.MousePos = msg->pt;
291             SendMessageA(msg->hwnd, WM_HELP, 0, (LPARAM)&hi);
292         }
293     }
294
295     if (HOOK_CallHooks( WH_KEYBOARD, remove ? HC_ACTION : HC_NOREMOVE,
296                         LOWORD(msg->wParam), msg->lParam, TRUE ))
297     {
298         /* skip this message */
299         HOOK_CallHooks( WH_CBT, HCBT_KEYSKIPPED, LOWORD(msg->wParam), msg->lParam, TRUE );
300         return FALSE;
301     }
302     return TRUE;
303 }
304
305
306 /***********************************************************************
307  *          process_raw_mouse_message
308  */
309 static void process_raw_mouse_message( MSG *msg, BOOL remove )
310 {
311     static MSG clk_msg;
312
313     POINT pt;
314     INT hittest;
315     EVENTMSG event;
316     GUITHREADINFO info;
317     HWND hWndScope = msg->hwnd;
318
319     /* find the window to dispatch this mouse message to */
320
321     hittest = HTCLIENT;
322     GetGUIThreadInfo( GetCurrentThreadId(), &info );
323     if (!(msg->hwnd = info.hwndCapture))
324     {
325         /* If no capture HWND, find window which contains the mouse position.
326          * Also find the position of the cursor hot spot (hittest) */
327         if (!IsWindow(hWndScope)) hWndScope = 0;
328         if (!(msg->hwnd = WINPOS_WindowFromPoint( hWndScope, msg->pt, &hittest )))
329             msg->hwnd = GetDesktopWindow();
330     }
331
332     event.message = msg->message;
333     event.time    = msg->time;
334     event.hwnd    = msg->hwnd;
335     event.paramL  = msg->pt.x;
336     event.paramH  = msg->pt.y;
337     HOOK_CallHooks( WH_JOURNALRECORD, HC_ACTION, 0, (LPARAM)&event, TRUE );
338
339     /* translate double clicks */
340
341     if ((msg->message == WM_LBUTTONDOWN) ||
342         (msg->message == WM_RBUTTONDOWN) ||
343         (msg->message == WM_MBUTTONDOWN))
344     {
345         BOOL update = remove;
346         /* translate double clicks -
347          * note that ...MOUSEMOVEs can slip in between
348          * ...BUTTONDOWN and ...BUTTONDBLCLK messages */
349
350         if ((info.flags & (GUI_INMENUMODE|GUI_INMOVESIZE)) ||
351             hittest != HTCLIENT ||
352             (GetClassLongA( msg->hwnd, GCL_STYLE ) & CS_DBLCLKS))
353         {
354            if ((msg->message == clk_msg.message) &&
355                (msg->hwnd == clk_msg.hwnd) &&
356                (msg->time - clk_msg.time < GetDoubleClickTime()) &&
357                (abs(msg->pt.x - clk_msg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
358                (abs(msg->pt.y - clk_msg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
359            {
360                msg->message += (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
361                if (remove)
362                {
363                    clk_msg.message = 0;
364                    update = FALSE;
365                }
366            }
367         }
368         /* update static double click conditions */
369         if (update) clk_msg = *msg;
370     }
371
372     pt = msg->pt;
373     /* Note: windows has no concept of a non-client wheel message */
374     if (hittest != HTCLIENT && msg->message != WM_MOUSEWHEEL)
375     {
376         msg->message += WM_NCMOUSEMOVE - WM_MOUSEMOVE;
377         msg->wParam = hittest;
378     }
379     else
380     {
381         /* coordinates don't get translated while tracking a menu */
382         /* FIXME: should differentiate popups and top-level menus */
383         if (!(info.flags & GUI_INMENUMODE)) ScreenToClient( msg->hwnd, &pt );
384     }
385     msg->lParam = MAKELONG( pt.x, pt.y );
386 }
387
388
389 /***********************************************************************
390  *          process_cooked_mouse_message
391  *
392  * returns TRUE if the contents of 'msg' should be passed to the application
393  */
394 static BOOL process_cooked_mouse_message( MSG *msg, ULONG_PTR extra_info, BOOL remove )
395 {
396     MOUSEHOOKSTRUCT hook;
397     INT hittest = HTCLIENT;
398     UINT raw_message = msg->message;
399     BOOL eatMsg;
400
401     if (msg->message >= WM_NCMOUSEFIRST && msg->message <= WM_NCMOUSELAST)
402     {
403         raw_message += WM_MOUSEFIRST - WM_NCMOUSEFIRST;
404         hittest = msg->wParam;
405     }
406     if (raw_message == WM_LBUTTONDBLCLK ||
407         raw_message == WM_RBUTTONDBLCLK ||
408         raw_message == WM_MBUTTONDBLCLK)
409     {
410         raw_message += WM_LBUTTONDOWN - WM_LBUTTONDBLCLK;
411     }
412
413     hook.pt           = msg->pt;
414     hook.hwnd         = msg->hwnd;
415     hook.wHitTestCode = hittest;
416     hook.dwExtraInfo  = extra_info;
417     if (HOOK_CallHooks( WH_MOUSE, remove ? HC_ACTION : HC_NOREMOVE,
418                         msg->message, (LPARAM)&hook, TRUE ))
419     {
420         hook.pt           = msg->pt;
421         hook.hwnd         = msg->hwnd;
422         hook.wHitTestCode = hittest;
423         hook.dwExtraInfo  = extra_info;
424         HOOK_CallHooks( WH_CBT, HCBT_CLICKSKIPPED, msg->message, (LPARAM)&hook, TRUE );
425         return FALSE;
426     }
427
428     if ((hittest == HTERROR) || (hittest == HTNOWHERE))
429     {
430         SendMessageA( msg->hwnd, WM_SETCURSOR, (WPARAM)msg->hwnd,
431                       MAKELONG( hittest, raw_message ));
432         return FALSE;
433     }
434
435     if (!remove || GetCapture()) return TRUE;
436
437     eatMsg = FALSE;
438
439     if ((raw_message == WM_LBUTTONDOWN) ||
440         (raw_message == WM_RBUTTONDOWN) ||
441         (raw_message == WM_MBUTTONDOWN))
442     {
443         /* Send the WM_PARENTNOTIFY,
444          * note that even for double/nonclient clicks
445          * notification message is still WM_L/M/RBUTTONDOWN.
446          */
447         MSG_SendParentNotify( msg->hwnd, raw_message, 0, msg->pt );
448
449         /* Activate the window if needed */
450
451         if (msg->hwnd != GetActiveWindow())
452         {
453             HWND hwndTop = msg->hwnd;
454             while (hwndTop)
455             {
456                 if ((GetWindowLongW( hwndTop, GWL_STYLE ) & (WS_POPUP|WS_CHILD)) != WS_CHILD) break;
457                 hwndTop = GetParent( hwndTop );
458             }
459
460             if (hwndTop && hwndTop != GetDesktopWindow())
461             {
462                 LONG ret = SendMessageA( msg->hwnd, WM_MOUSEACTIVATE, (WPARAM)hwndTop,
463                                          MAKELONG( hittest, raw_message ) );
464                 switch(ret)
465                 {
466                 case MA_NOACTIVATEANDEAT:
467                     eatMsg = TRUE;
468                     /* fall through */
469                 case MA_NOACTIVATE:
470                     break;
471                 case MA_ACTIVATEANDEAT:
472                     eatMsg = TRUE;
473                     /* fall through */
474                 case MA_ACTIVATE:
475                 case 0:
476                     if (!FOCUS_MouseActivate( hwndTop )) eatMsg = TRUE;
477                     break;
478                 default:
479                     WARN( "unknown WM_MOUSEACTIVATE code %ld\n", ret );
480                     break;
481                 }
482             }
483         }
484     }
485
486     /* send the WM_SETCURSOR message */
487
488     /* Windows sends the normal mouse message as the message parameter
489        in the WM_SETCURSOR message even if it's non-client mouse message */
490     SendMessageA( msg->hwnd, WM_SETCURSOR, (WPARAM)msg->hwnd,
491                   MAKELONG( hittest, raw_message ));
492
493     return !eatMsg;
494 }
495
496
497 /***********************************************************************
498  *          process_hardware_message
499  *
500  * returns TRUE if the contents of 'msg' should be passed to the application
501  */
502 BOOL MSG_process_raw_hardware_message( MSG *msg, ULONG_PTR extra_info, HWND hwnd_filter,
503                                        UINT first, UINT last, BOOL remove )
504 {
505     if (is_keyboard_message( msg->message ))
506     {
507         process_raw_keyboard_message( msg );
508     }
509     else if (is_mouse_message( msg->message ))
510     {
511         process_raw_mouse_message( msg, remove );
512     }
513     else
514     {
515         ERR( "unknown message type %x\n", msg->message );
516         return FALSE;
517     }
518     return check_message_filter( msg, hwnd_filter, first, last );
519 }
520
521
522 /***********************************************************************
523  *          MSG_process_cooked_hardware_message
524  *
525  * returns TRUE if the contents of 'msg' should be passed to the application
526  */
527 BOOL MSG_process_cooked_hardware_message( MSG *msg, ULONG_PTR extra_info, BOOL remove )
528 {
529     if (is_keyboard_message( msg->message ))
530         return process_cooked_keyboard_message( msg, remove );
531
532     if (is_mouse_message( msg->message ))
533         return process_cooked_mouse_message( msg, extra_info, remove );
534
535     ERR( "unknown message type %x\n", msg->message );
536     return FALSE;
537 }
538
539
540 /***********************************************************************
541  *              WaitMessage (USER.112) Suspend thread pending messages
542  *              WaitMessage (USER32.@) Suspend thread pending messages
543  *
544  * WaitMessage() suspends a thread until events appear in the thread's
545  * queue.
546  */
547 BOOL WINAPI WaitMessage(void)
548 {
549     return (MsgWaitForMultipleObjectsEx( 0, NULL, INFINITE, QS_ALLINPUT, 0 ) != WAIT_FAILED);
550 }
551
552
553 /***********************************************************************
554  *              MsgWaitForMultipleObjectsEx   (USER32.@)
555  */
556 DWORD WINAPI MsgWaitForMultipleObjectsEx( DWORD count, CONST HANDLE *pHandles,
557                                           DWORD timeout, DWORD mask, DWORD flags )
558 {
559     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
560     DWORD i, ret, lock;
561     MESSAGEQUEUE *msgQueue;
562
563     if (count > MAXIMUM_WAIT_OBJECTS-1)
564     {
565         SetLastError( ERROR_INVALID_PARAMETER );
566         return WAIT_FAILED;
567     }
568
569     if (!(msgQueue = QUEUE_Current())) return WAIT_FAILED;
570
571     /* set the queue mask */
572     SERVER_START_REQ( set_queue_mask )
573     {
574         req->wake_mask    = (flags & MWMO_INPUTAVAILABLE) ? mask : 0;
575         req->changed_mask = mask;
576         req->skip_wait    = 0;
577         wine_server_call( req );
578     }
579     SERVER_END_REQ;
580
581     /* Add the thread event to the handle list */
582     for (i = 0; i < count; i++) handles[i] = pHandles[i];
583     handles[count] = msgQueue->server_queue;
584
585     ReleaseThunkLock( &lock );
586     if (USER_Driver.pMsgWaitForMultipleObjectsEx)
587     {
588         ret = USER_Driver.pMsgWaitForMultipleObjectsEx( count+1, handles, timeout, mask, flags );
589         if (ret == count+1) ret = count; /* pretend the msg queue is ready */
590     }
591     else
592         ret = WaitForMultipleObjectsEx( count+1, handles, flags & MWMO_WAITALL,
593                                         timeout, flags & MWMO_ALERTABLE );
594     if (lock) RestoreThunkLock( lock );
595     return ret;
596 }
597
598
599 /***********************************************************************
600  *              MsgWaitForMultipleObjects (USER32.@)
601  */
602 DWORD WINAPI MsgWaitForMultipleObjects( DWORD count, CONST HANDLE *handles,
603                                         BOOL wait_all, DWORD timeout, DWORD mask )
604 {
605     return MsgWaitForMultipleObjectsEx( count, handles, timeout, mask,
606                                         wait_all ? MWMO_WAITALL : 0 );
607 }
608
609
610 /***********************************************************************
611  *              WaitForInputIdle (USER32.@)
612  */
613 DWORD WINAPI WaitForInputIdle( HANDLE hProcess, DWORD dwTimeOut )
614 {
615     DWORD start_time, elapsed, ret;
616     HANDLE idle_event = (HANDLE)-1;
617
618     SERVER_START_REQ( wait_input_idle )
619     {
620         req->handle = hProcess;
621         req->timeout = dwTimeOut;
622         if (!(ret = wine_server_call_err( req ))) idle_event = reply->event;
623     }
624     SERVER_END_REQ;
625     if (ret) return WAIT_FAILED;  /* error */
626     if (!idle_event) return 0;  /* no event to wait on */
627
628     start_time = GetTickCount();
629     elapsed = 0;
630
631     TRACE("waiting for %p\n", idle_event );
632     do
633     {
634         ret = MsgWaitForMultipleObjects ( 1, &idle_event, FALSE, dwTimeOut - elapsed, QS_SENDMESSAGE );
635         switch (ret)
636         {
637         case WAIT_OBJECT_0+1:
638             process_sent_messages();
639             break;
640         case WAIT_TIMEOUT:
641         case WAIT_FAILED:
642             TRACE("timeout or error\n");
643             return ret;
644         default:
645             TRACE("finished\n");
646             return 0;
647         }
648         if (dwTimeOut != INFINITE)
649         {
650             elapsed = GetTickCount() - start_time;
651             if (elapsed > dwTimeOut)
652                 break;
653         }
654     }
655     while (1);
656
657     return WAIT_TIMEOUT;
658 }
659
660
661 /***********************************************************************
662  *              UserYield (USER.332)
663  */
664 void WINAPI UserYield16(void)
665 {
666    DWORD count;
667
668     /* Handle sent messages */
669     process_sent_messages();
670
671     /* Yield */
672     ReleaseThunkLock(&count);
673     if (count)
674     {
675         RestoreThunkLock(count);
676         /* Handle sent messages again */
677         process_sent_messages();
678     }
679 }
680
681
682 /***********************************************************************
683  *              TranslateMessage (USER32.@)
684  *
685  * Implementation of TranslateMessage.
686  *
687  * TranslateMessage translates virtual-key messages into character-messages,
688  * as follows :
689  * WM_KEYDOWN/WM_KEYUP combinations produce a WM_CHAR or WM_DEADCHAR message.
690  * ditto replacing WM_* with WM_SYS*
691  * This produces WM_CHAR messages only for keys mapped to ASCII characters
692  * by the keyboard driver.
693  *
694  * If the message is WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, or WM_SYSKEYUP, the
695  * return value is nonzero, regardless of the translation.
696  *
697  */
698 BOOL WINAPI TranslateMessage( const MSG *msg )
699 {
700     UINT message;
701     WCHAR wp[2];
702     BOOL rc = FALSE;
703     BYTE state[256];
704
705     if (msg->message >= WM_KEYFIRST && msg->message <= WM_KEYLAST)
706     {
707         TRACE_(key)("(%s, %04X, %08lX)\n",
708                     SPY_GetMsgName(msg->message, msg->hwnd), msg->wParam, msg->lParam );
709
710         /* Return code must be TRUE no matter what! */
711         rc = TRUE;
712     }
713
714     if ((msg->message != WM_KEYDOWN) && (msg->message != WM_SYSKEYDOWN)) return rc;
715
716     TRACE_(key)("Translating key %s (%04x), scancode %02x\n",
717                  SPY_GetVKeyName(msg->wParam), msg->wParam, LOBYTE(HIWORD(msg->lParam)));
718
719     GetKeyboardState( state );
720     /* FIXME : should handle ToUnicode yielding 2 */
721     switch (ToUnicode(msg->wParam, HIWORD(msg->lParam), state, wp, 2, 0))
722     {
723     case 1:
724         message = (msg->message == WM_KEYDOWN) ? WM_CHAR : WM_SYSCHAR;
725         TRACE_(key)("1 -> PostMessageW(%p,%s,%04x,%08lx)\n",
726             msg->hwnd, SPY_GetMsgName(message, msg->hwnd), wp[0], msg->lParam);
727         PostMessageW( msg->hwnd, message, wp[0], msg->lParam );
728         break;
729
730     case -1:
731         message = (msg->message == WM_KEYDOWN) ? WM_DEADCHAR : WM_SYSDEADCHAR;
732         TRACE_(key)("-1 -> PostMessageW(%p,%s,%04x,%08lx)\n",
733             msg->hwnd, SPY_GetMsgName(message, msg->hwnd), wp[0], msg->lParam);
734         PostMessageW( msg->hwnd, message, wp[0], msg->lParam );
735         return TRUE;
736     }
737     return rc;
738 }
739
740
741 /***********************************************************************
742  *              DispatchMessageA (USER32.@)
743  */
744 LONG WINAPI DispatchMessageA( const MSG* msg )
745 {
746     WND * wndPtr;
747     LONG retval;
748     int painting;
749     WNDPROC winproc;
750
751       /* Process timer messages */
752     if ((msg->message == WM_TIMER) || (msg->message == WM_SYSTIMER))
753     {
754         if (msg->lParam)
755         {
756 /*            HOOK_CallHooks32A( WH_CALLWNDPROC, HC_ACTION, 0, FIXME ); */
757
758             /* before calling window proc, verify whether timer is still valid;
759                there's a slim chance that the application kills the timer
760                between GetMessage and DispatchMessage API calls */
761             if (!TIMER_IsTimerValid(msg->hwnd, (UINT) msg->wParam, (WNDPROC)msg->lParam))
762                 return 0; /* invalid winproc */
763
764             return CallWindowProcA( (WNDPROC)msg->lParam, msg->hwnd,
765                                    msg->message, msg->wParam, GetTickCount() );
766         }
767     }
768
769     if (!(wndPtr = WIN_GetPtr( msg->hwnd )))
770     {
771         if (msg->hwnd) SetLastError( ERROR_INVALID_WINDOW_HANDLE );
772         return 0;
773     }
774     if (wndPtr == WND_OTHER_PROCESS)
775     {
776         if (IsWindow( msg->hwnd ))
777             ERR( "cannot dispatch msg to other process window %p\n", msg->hwnd );
778         SetLastError( ERROR_INVALID_WINDOW_HANDLE );
779         return 0;
780     }
781     if (!(winproc = wndPtr->winproc))
782     {
783         WIN_ReleasePtr( wndPtr );
784         return 0;
785     }
786     painting = (msg->message == WM_PAINT);
787     if (painting) wndPtr->flags |= WIN_NEEDS_BEGINPAINT;
788     WIN_ReleasePtr( wndPtr );
789 /*    hook_CallHooks32A( WH_CALLWNDPROC, HC_ACTION, 0, FIXME ); */
790
791     SPY_EnterMessage( SPY_DISPATCHMESSAGE, msg->hwnd, msg->message,
792                       msg->wParam, msg->lParam );
793     retval = CallWindowProcA( winproc, msg->hwnd, msg->message,
794                               msg->wParam, msg->lParam );
795     SPY_ExitMessage( SPY_RESULT_OK, msg->hwnd, msg->message, retval,
796                      msg->wParam, msg->lParam );
797
798     if (painting && (wndPtr = WIN_GetPtr( msg->hwnd )) && (wndPtr != WND_OTHER_PROCESS))
799     {
800         BOOL validate = ((wndPtr->flags & WIN_NEEDS_BEGINPAINT) && wndPtr->hrgnUpdate);
801         wndPtr->flags &= ~WIN_NEEDS_BEGINPAINT;
802         WIN_ReleasePtr( wndPtr );
803         if (validate)
804         {
805             ERR( "BeginPaint not called on WM_PAINT for hwnd %p!\n", msg->hwnd );
806             /* Validate the update region to avoid infinite WM_PAINT loop */
807             RedrawWindow( msg->hwnd, NULL, 0,
808                           RDW_NOFRAME | RDW_VALIDATE | RDW_NOCHILDREN | RDW_NOINTERNALPAINT );
809         }
810     }
811     return retval;
812 }
813
814
815 /***********************************************************************
816  *              DispatchMessageW (USER32.@) Process Message
817  *
818  * Process the message specified in the structure *_msg_.
819  *
820  * If the lpMsg parameter points to a WM_TIMER message and the
821  * parameter of the WM_TIMER message is not NULL, the lParam parameter
822  * points to the function that is called instead of the window
823  * procedure.
824  *
825  * The message must be valid.
826  *
827  * RETURNS
828  *
829  *   DispatchMessage() returns the result of the window procedure invoked.
830  *
831  * CONFORMANCE
832  *
833  *   ECMA-234, Win32
834  *
835  */
836 LONG WINAPI DispatchMessageW( const MSG* msg )
837 {
838     WND * wndPtr;
839     LONG retval;
840     int painting;
841     WNDPROC winproc;
842
843       /* Process timer messages */
844     if ((msg->message == WM_TIMER) || (msg->message == WM_SYSTIMER))
845     {
846         if (msg->lParam)
847         {
848 /*            HOOK_CallHooks32W( WH_CALLWNDPROC, HC_ACTION, 0, FIXME ); */
849
850             /* before calling window proc, verify whether timer is still valid;
851                there's a slim chance that the application kills the timer
852                between GetMessage and DispatchMessage API calls */
853             if (!TIMER_IsTimerValid(msg->hwnd, (UINT) msg->wParam, (WNDPROC)msg->lParam))
854                 return 0; /* invalid winproc */
855
856             return CallWindowProcW( (WNDPROC)msg->lParam, msg->hwnd,
857                                    msg->message, msg->wParam, GetTickCount() );
858         }
859     }
860
861     if (!(wndPtr = WIN_GetPtr( msg->hwnd )))
862     {
863         if (msg->hwnd) SetLastError( ERROR_INVALID_WINDOW_HANDLE );
864         return 0;
865     }
866     if (wndPtr == WND_OTHER_PROCESS)
867     {
868         if (IsWindow( msg->hwnd ))
869             ERR( "cannot dispatch msg to other process window %p\n", msg->hwnd );
870         SetLastError( ERROR_INVALID_WINDOW_HANDLE );
871         return 0;
872     }
873     if (!(winproc = wndPtr->winproc))
874     {
875         WIN_ReleasePtr( wndPtr );
876         return 0;
877     }
878     painting = (msg->message == WM_PAINT);
879     if (painting) wndPtr->flags |= WIN_NEEDS_BEGINPAINT;
880     WIN_ReleasePtr( wndPtr );
881 /*    HOOK_CallHooks32W( WH_CALLWNDPROC, HC_ACTION, 0, FIXME ); */
882
883     SPY_EnterMessage( SPY_DISPATCHMESSAGE, msg->hwnd, msg->message,
884                       msg->wParam, msg->lParam );
885     retval = CallWindowProcW( winproc, msg->hwnd, msg->message,
886                               msg->wParam, msg->lParam );
887     SPY_ExitMessage( SPY_RESULT_OK, msg->hwnd, msg->message, retval,
888                      msg->wParam, msg->lParam );
889
890     if (painting && (wndPtr = WIN_GetPtr( msg->hwnd )) && (wndPtr != WND_OTHER_PROCESS))
891     {
892         BOOL validate = ((wndPtr->flags & WIN_NEEDS_BEGINPAINT) && wndPtr->hrgnUpdate);
893         wndPtr->flags &= ~WIN_NEEDS_BEGINPAINT;
894         WIN_ReleasePtr( wndPtr );
895         if (validate)
896         {
897             ERR( "BeginPaint not called on WM_PAINT for hwnd %p!\n", msg->hwnd );
898             /* Validate the update region to avoid infinite WM_PAINT loop */
899             RedrawWindow( msg->hwnd, NULL, 0,
900                           RDW_NOFRAME | RDW_VALIDATE | RDW_NOCHILDREN | RDW_NOINTERNALPAINT );
901         }
902     }
903     return retval;
904 }
905
906
907 /***********************************************************************
908  *              RegisterWindowMessage (USER.118)
909  *              RegisterWindowMessageA (USER32.@)
910  */
911 WORD WINAPI RegisterWindowMessageA( LPCSTR str )
912 {
913     TRACE("%s\n", str );
914     return GlobalAddAtomA( str );
915 }
916
917
918 /***********************************************************************
919  *              RegisterWindowMessageW (USER32.@)
920  */
921 WORD WINAPI RegisterWindowMessageW( LPCWSTR str )
922 {
923     TRACE("%p\n", str );
924     return GlobalAddAtomW( str );
925 }
926
927
928 /***********************************************************************
929  *              BroadcastSystemMessage  (USER32.@)
930  *              BroadcastSystemMessageA (USER32.@)
931  */
932 LONG WINAPI BroadcastSystemMessage(
933         DWORD dwFlags,LPDWORD recipients,UINT uMessage,WPARAM wParam,
934         LPARAM lParam )
935 {
936     if ((*recipients & BSM_APPLICATIONS)||
937         (*recipients == BSM_ALLCOMPONENTS))
938     {
939         FIXME("(%08lx,%08lx,%08x,%08x,%08lx): semi-stub!\n",
940               dwFlags,*recipients,uMessage,wParam,lParam);
941         PostMessageA(HWND_BROADCAST,uMessage,wParam,lParam);
942         return 1;
943     }
944     else
945     {
946         FIXME("(%08lx,%08lx,%08x,%08x,%08lx): stub!\n",
947               dwFlags,*recipients,uMessage,wParam,lParam);
948         return -1;
949     }
950 }
951
952 /***********************************************************************
953  *              BroadcastSystemMessageW (USER32.@)
954  */
955 LONG WINAPI BroadcastSystemMessageW(
956         DWORD dwFlags,LPDWORD recipients,UINT uMessage,WPARAM wParam,
957         LPARAM lParam )
958 {
959     if ((*recipients & BSM_APPLICATIONS)||
960         (*recipients == BSM_ALLCOMPONENTS))
961     {
962         FIXME("(%08lx,%08lx,%08x,%08x,%08lx): semi-stub!\n",
963               dwFlags,*recipients,uMessage,wParam,lParam);
964         PostMessageW(HWND_BROADCAST,uMessage,wParam,lParam);
965         return 1;
966     }
967     else
968     {
969         FIXME("(%08lx,%08lx,%08x,%08x,%08lx): stub!\n",
970               dwFlags,*recipients,uMessage,wParam,lParam);
971         return -1;
972     }
973 }