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