Always generate unicode CHAR messages.
[wine] / windows / message.c
1 /*
2  * Message queues related functions
3  *
4  * Copyright 1993, 1994 Alexandre Julliard
5  */
6
7 #include <stdlib.h>
8 #include <string.h>
9 #include <ctype.h>
10 #include <sys/time.h>
11 #include <sys/types.h>
12
13 #include "wine/winbase16.h"
14 #include "message.h"
15 #include "winerror.h"
16 #include "win.h"
17 #include "heap.h"
18 #include "hook.h"
19 #include "input.h"
20 #include "spy.h"
21 #include "winpos.h"
22 #include "dde.h"
23 #include "queue.h"
24 #include "winproc.h"
25 #include "task.h"
26 #include "selectors.h"
27 #include "thread.h"
28 #include "options.h"
29 #include "menu.h"
30 #include "struct32.h"
31 #include "debugtools.h"
32
33 DEFAULT_DEBUG_CHANNEL(msg);
34 DECLARE_DEBUG_CHANNEL(key);
35 DECLARE_DEBUG_CHANNEL(sendmsg);
36
37 #define WM_NCMOUSEFIRST         WM_NCMOUSEMOVE
38 #define WM_NCMOUSELAST          WM_NCMBUTTONDBLCLK
39
40     
41 typedef enum { SYSQ_MSG_ABANDON, SYSQ_MSG_SKIP, 
42                SYSQ_MSG_ACCEPT, SYSQ_MSG_CONTINUE } SYSQ_STATUS;
43
44 extern HQUEUE16 hCursorQueue;                    /* queue.c */
45
46 static UINT doubleClickSpeed = 452;
47
48 /***********************************************************************
49  *           MSG_CheckFilter
50  */
51 static BOOL MSG_CheckFilter(DWORD uMsg, DWORD first, DWORD last)
52 {
53    if( first || last )
54        return (uMsg >= first && uMsg <= last);
55    return TRUE;
56 }
57
58 /***********************************************************************
59  *           MSG_SendParentNotify
60  *
61  * Send a WM_PARENTNOTIFY to all ancestors of the given window, unless
62  * the window has the WS_EX_NOPARENTNOTIFY style.
63  */
64 static void MSG_SendParentNotify(WND* wndPtr, WORD event, WORD idChild, LPARAM lValue)
65 {
66 #define lppt ((LPPOINT16)&lValue)
67
68     /* pt has to be in the client coordinates of the parent window */
69     WND *tmpWnd = WIN_LockWndPtr(wndPtr);
70
71     MapWindowPoints16( 0, tmpWnd->hwndSelf, lppt, 1 );
72     while (tmpWnd)
73     {
74         if (!(tmpWnd->dwStyle & WS_CHILD) || (tmpWnd->dwExStyle & WS_EX_NOPARENTNOTIFY))
75     {
76             WIN_ReleaseWndPtr(tmpWnd);
77             break;
78         }
79         lppt->x += tmpWnd->rectClient.left;
80         lppt->y += tmpWnd->rectClient.top;
81         WIN_UpdateWndPtr(&tmpWnd,tmpWnd->parent);
82         SendMessageA( tmpWnd->hwndSelf, WM_PARENTNOTIFY,
83                         MAKEWPARAM( event, idChild ), lValue );
84     }
85
86 #undef lppt
87 }
88
89
90 /***********************************************************************
91  *           MSG_TranslateMouseMsg
92  *
93  * Translate a mouse hardware event into a real mouse message.
94  *
95  * Returns:
96  *
97  *  SYSQ_MSG_ABANDON  - abandon the peek message loop
98  *  SYSQ_MSG_CONTINUE - leave the message in the queue and
99  *                      continue with the translation loop
100  *  SYSQ_MSG_ACCEPT   - proceed to process the translated message
101  */
102 static DWORD MSG_TranslateMouseMsg( HWND hTopWnd, DWORD first, DWORD last,
103                                     MSG *msg, BOOL remove, WND* pWndScope,
104                                     INT16 *pHitTest, POINT16 *pScreen_pt, BOOL *pmouseClick )
105 {
106     static DWORD   dblclk_time_limit = 0;
107     static UINT16     clk_message = 0;
108     static HWND16     clk_hwnd = 0;
109     static POINT16    clk_pos = { 0, 0 };
110
111     WND *pWnd;
112     HWND hWnd;
113     INT16 ht, hittest;
114     UINT message = msg->message;
115     POINT16 screen_pt, pt;
116     HANDLE16 hQ = GetFastQueue16();
117     MESSAGEQUEUE *queue = (MESSAGEQUEUE *)QUEUE_Lock(hQ);
118     BOOL mouseClick = ((message == WM_LBUTTONDOWN) ||
119                          (message == WM_RBUTTONDOWN) ||
120                          (message == WM_MBUTTONDOWN))?1:0;
121     DWORD retvalue;
122
123     /* Find the window to dispatch this mouse message to */
124
125     CONV_POINT32TO16( &msg->pt, &pt );
126     
127     hWnd = GetCapture();
128
129     /* If no capture HWND, find window which contains the mouse position.
130      * Also find the position of the cursor hot spot (hittest) */
131     if( !hWnd )
132     {
133         ht = hittest = WINPOS_WindowFromPoint( pWndScope, pt, &pWnd );
134         if( !pWnd ) pWnd = WIN_GetDesktop();
135         else WIN_LockWndPtr(pWnd);
136         hWnd = pWnd->hwndSelf;
137     } 
138     else 
139     {
140         ht = hittest = HTCLIENT;
141         pWnd = WIN_FindWndPtr(hWnd);
142         if (queue)
143             ht = PERQDATA_GetCaptureInfo( queue->pQData );
144     }
145
146     /* Save hittest for return */
147     *pHitTest = hittest;
148         
149         /* stop if not the right queue */
150
151     if (pWnd->hmemTaskQ != hQ)
152     {
153         /* Not for the current task */
154         if (queue) QUEUE_ClearWakeBit( queue, QS_MOUSE );
155         /* Wake up the other task */
156         QUEUE_Unlock( queue );
157         queue = (MESSAGEQUEUE *)QUEUE_Lock( pWnd->hmemTaskQ );
158         if (queue) QUEUE_SetWakeBit( queue, QS_MOUSE );
159
160         QUEUE_Unlock( queue );
161         retvalue = SYSQ_MSG_ABANDON;
162         goto END;
163     }
164
165         /* check if hWnd is within hWndScope */
166
167     if( hTopWnd && hWnd != hTopWnd )
168         if( !IsChild(hTopWnd, hWnd) )
169         {
170             QUEUE_Unlock( queue );
171             retvalue = SYSQ_MSG_CONTINUE;
172             goto END;
173         }
174
175     /* Was it a mouse click message */
176     if( mouseClick )
177     {
178         /* translate double clicks -
179          * note that ...MOUSEMOVEs can slip in between
180          * ...BUTTONDOWN and ...BUTTONDBLCLK messages */
181
182         if(GetClassLongA(hWnd, GCL_STYLE) & CS_DBLCLKS || ht != HTCLIENT )
183         {
184            if ((message == clk_message) && (hWnd == clk_hwnd) &&
185                (msg->time - dblclk_time_limit < doubleClickSpeed) &&
186                (abs(msg->pt.x - clk_pos.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
187                (abs(msg->pt.y - clk_pos.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
188            {
189               message += (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
190               mouseClick++;   /* == 2 */
191            }
192         }
193     }
194     /* save mouse position */
195     screen_pt = pt;
196     *pScreen_pt = pt;
197
198     if (hittest != HTCLIENT)
199     {
200         message += WM_NCMOUSEMOVE - WM_MOUSEMOVE;
201         msg->wParam = hittest;
202     }
203     else
204         ScreenToClient16( hWnd, &pt );
205
206         /* check message filter */
207
208     if (!MSG_CheckFilter(message, first, last))
209     {
210         QUEUE_Unlock(queue);
211         retvalue = SYSQ_MSG_CONTINUE;
212         goto END;
213     }
214
215     /* Update global hCursorQueue */
216     hCursorQueue = queue->self;
217     
218     /* Update static double click conditions */
219     if( remove && mouseClick )
220     {
221         if( mouseClick == 1 )
222         {
223             /* set conditions */
224             dblclk_time_limit = msg->time;
225                clk_message = msg->message;
226                clk_hwnd = hWnd;
227                clk_pos = screen_pt;
228         } else 
229             /* got double click - zero them out */
230             dblclk_time_limit = clk_hwnd = 0;
231     }
232
233     QUEUE_Unlock(queue);
234
235     /* Update message params */
236     msg->hwnd    = hWnd;
237     msg->message = message;
238     msg->lParam  = MAKELONG( pt.x, pt.y );
239     retvalue = SYSQ_MSG_ACCEPT;
240
241 END:
242     WIN_ReleaseWndPtr(pWnd);
243
244     /* Return mouseclick flag */
245     *pmouseClick = mouseClick;
246     
247     return retvalue;
248 }
249
250
251 /***********************************************************************
252  *           MSG_ProcessMouseMsg
253  *
254  * Processes a translated mouse hardware event.
255  * The passed in msg structure should contain the updated hWnd, 
256  * lParam, wParam and message fields from MSG_TranslateMouseMsg.
257  *
258  * Returns:
259  *
260  *  SYSQ_MSG_SKIP     - Message should be skipped entirely (in this case
261  *                      HIWORD contains hit test code). Continue translating..
262  *  SYSQ_MSG_ACCEPT   - the translated message must be passed to the user
263  *                      MSG_PeekHardwareMsg should return TRUE.
264  */
265 static DWORD MSG_ProcessMouseMsg( MSG *msg, BOOL remove, INT16 hittest,
266                                   POINT16 screen_pt, BOOL mouseClick )
267 {
268     WND *pWnd;
269     HWND hWnd = msg->hwnd;
270     INT16 sendSC = (GetCapture() == 0);
271     UINT message = msg->message;
272     BOOL eatMsg = FALSE;
273     DWORD retvalue;
274
275     pWnd = WIN_FindWndPtr(hWnd);
276     
277         /* call WH_MOUSE */
278
279     if (HOOK_IsHooked( WH_MOUSE ))
280     { 
281         SYSQ_STATUS ret = 0;
282         MOUSEHOOKSTRUCT16 *hook = SEGPTR_NEW(MOUSEHOOKSTRUCT16);
283         if( hook )
284         {
285             hook->pt           = screen_pt;
286             hook->hwnd         = hWnd;
287             hook->wHitTestCode = hittest;
288             hook->dwExtraInfo  = 0;
289             ret = HOOK_CallHooks16( WH_MOUSE, remove ? HC_ACTION : HC_NOREMOVE,
290                                     message, (LPARAM)SEGPTR_GET(hook) );
291             SEGPTR_FREE(hook);
292         }
293         if( ret )
294         {
295             retvalue = MAKELONG((INT16)SYSQ_MSG_SKIP, hittest);
296             goto END;
297         }
298     }
299
300     if (message >= WM_NCMOUSEFIRST && message <= WM_NCMOUSELAST)
301         message += WM_MOUSEFIRST - WM_NCMOUSEFIRST;
302
303     if ((hittest == HTERROR) || (hittest == HTNOWHERE)) 
304         eatMsg = sendSC = 1;
305     else if( remove && mouseClick )
306     {
307         HWND hwndTop = WIN_GetTopParent( hWnd );
308
309         if( sendSC )
310         {
311             /* Send the WM_PARENTNOTIFY,
312              * note that even for double/nonclient clicks
313              * notification message is still WM_L/M/RBUTTONDOWN.
314              */
315
316             MSG_SendParentNotify( pWnd, message, 0, MAKELPARAM(screen_pt.x, screen_pt.y) );
317
318             /* Activate the window if needed */
319
320             if (hWnd != GetActiveWindow() && hWnd != GetDesktopWindow())
321             {
322                 LONG ret = SendMessageA( hWnd, WM_MOUSEACTIVATE, hwndTop,
323                                           MAKELONG( hittest, message ) );
324
325                 if ((ret == MA_ACTIVATEANDEAT) || (ret == MA_NOACTIVATEANDEAT))
326                          eatMsg = TRUE;
327
328                 if (((ret == MA_ACTIVATE) || (ret == MA_ACTIVATEANDEAT))
329                         && hwndTop != GetForegroundWindow() )
330                 {
331                       if (!WINPOS_SetActiveWindow( hwndTop, TRUE , TRUE ))
332                          eatMsg = TRUE;
333                 }
334             }
335         }
336     } else sendSC = (remove && sendSC);
337
338      /* Send the WM_SETCURSOR message */
339
340     if (sendSC)
341     {
342         /* Windows sends the normal mouse message as the message parameter
343            in the WM_SETCURSOR message even if it's non-client mouse message */
344         SendMessageA( hWnd, WM_SETCURSOR, hWnd,
345                        MAKELONG( hittest, message ));
346     }
347     if (eatMsg)
348     {
349         retvalue = MAKELONG( (UINT16)SYSQ_MSG_SKIP, hittest);
350         goto END;
351     }
352
353     retvalue = SYSQ_MSG_ACCEPT;
354 END:
355     WIN_ReleaseWndPtr(pWnd);
356
357     return retvalue;
358 }
359
360
361 /***********************************************************************
362  *           MSG_TranslateKbdMsg
363  *
364  * Translate an keyboard hardware event into a real message.
365  */
366 static DWORD MSG_TranslateKbdMsg( HWND hTopWnd, DWORD first, DWORD last,
367                                   MSG *msg, BOOL remove )
368 {
369     WORD message = msg->message;
370     HWND hWnd = GetFocus();
371     WND *pWnd;
372
373       /* Should check Ctrl-Esc and PrintScreen here */
374
375     if (!hWnd)
376     {
377           /* Send the message to the active window instead,  */
378           /* translating messages to their WM_SYS equivalent */
379
380         hWnd = GetActiveWindow();
381
382         if( message < WM_SYSKEYDOWN )
383             message += WM_SYSKEYDOWN - WM_KEYDOWN;
384     }
385     if ( !hWnd ) return SYSQ_MSG_ABANDON;
386     pWnd = WIN_FindWndPtr( hWnd );
387
388     if (pWnd && (pWnd->hmemTaskQ != GetFastQueue16()))
389     {
390         /* Not for the current task */
391         MESSAGEQUEUE *queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() );
392         if (queue) QUEUE_ClearWakeBit( queue, QS_KEY );
393         QUEUE_Unlock( queue );
394         
395         /* Wake up the other task */
396         queue = (MESSAGEQUEUE *)QUEUE_Lock( pWnd->hmemTaskQ );
397         if (queue) QUEUE_SetWakeBit( queue, QS_KEY );
398         QUEUE_Unlock( queue );
399         WIN_ReleaseWndPtr(pWnd);
400         return SYSQ_MSG_ABANDON;
401     }
402     WIN_ReleaseWndPtr(pWnd);
403
404     if (hTopWnd && hWnd != hTopWnd)
405         if (!IsChild(hTopWnd, hWnd)) return SYSQ_MSG_CONTINUE;
406     if (!MSG_CheckFilter(message, first, last)) return SYSQ_MSG_CONTINUE;
407
408     msg->hwnd = hWnd;
409     msg->message = message;
410
411     return SYSQ_MSG_ACCEPT;
412 }
413
414
415 /***********************************************************************
416  *           MSG_ProcessKbdMsg
417  *
418  *  Processes a translated keyboard message
419  */
420 static DWORD MSG_ProcessKbdMsg( MSG *msg, BOOL remove )
421 {
422     /* Handle F1 key by sending out WM_HELP message */
423     if ((msg->message == WM_KEYUP) && 
424         (msg->wParam == VK_F1) &&
425         remove &&
426         (msg->hwnd != GetDesktopWindow()) &&
427         !MENU_IsMenuActive())
428     {   
429         HELPINFO hi;
430         WND *pWnd = WIN_FindWndPtr(msg->hwnd);
431
432         if (NULL != pWnd)
433         {
434             hi.cbSize = sizeof(HELPINFO);
435             hi.iContextType = HELPINFO_WINDOW;
436             hi.iCtrlId = pWnd->wIDmenu; 
437             hi.hItemHandle = msg->hwnd;
438             hi.dwContextId = pWnd->helpContext;
439             hi.MousePos = msg->pt;
440             SendMessageA(msg->hwnd, WM_HELP, 0, (LPARAM)&hi);
441         }
442         WIN_ReleaseWndPtr(pWnd);
443     }
444
445     return (HOOK_CallHooks16( WH_KEYBOARD, remove ? HC_ACTION : HC_NOREMOVE,
446                               LOWORD (msg->wParam), msg->lParam )
447             ? SYSQ_MSG_SKIP : SYSQ_MSG_ACCEPT);
448 }
449
450
451 /***********************************************************************
452  *           MSG_JournalRecordMsg
453  *
454  * Build an EVENTMSG structure and call JOURNALRECORD hook
455  */
456 static void MSG_JournalRecordMsg( MSG *msg )
457 {
458     EVENTMSG *event = (EVENTMSG *) HeapAlloc(SystemHeap, 0, sizeof(EVENTMSG));
459     if (!event) return;
460     event->message = msg->message;
461     event->time = msg->time;
462     if ((msg->message >= WM_KEYFIRST) && (msg->message <= WM_KEYLAST))
463     {
464         event->paramL = (msg->wParam & 0xFF) | (HIWORD(msg->lParam) << 8);
465         event->paramH = msg->lParam & 0x7FFF;  
466         if (HIWORD(msg->lParam) & 0x0100)
467             event->paramH |= 0x8000;               /* special_key - bit */
468         HOOK_CallHooksA( WH_JOURNALRECORD, HC_ACTION, 0, (LPARAM)event );
469     }
470     else if ((msg->message >= WM_MOUSEFIRST) && (msg->message <= WM_MOUSELAST))
471     {
472         event->paramL = LOWORD(msg->lParam);       /* X pos */
473         event->paramH = HIWORD(msg->lParam);       /* Y pos */ 
474         ClientToScreen16( msg->hwnd, (LPPOINT16)&event->paramL );
475         HOOK_CallHooksA( WH_JOURNALRECORD, HC_ACTION, 0, (LPARAM)event );
476     }
477     else if ((msg->message >= WM_NCMOUSEFIRST) &&
478              (msg->message <= WM_NCMOUSELAST))
479     {
480         event->paramL = LOWORD(msg->lParam);       /* X pos */
481         event->paramH = HIWORD(msg->lParam);       /* Y pos */ 
482         event->message += WM_MOUSEMOVE-WM_NCMOUSEMOVE;/* give no info about NC area */
483         HOOK_CallHooksA( WH_JOURNALRECORD, HC_ACTION, 0, (LPARAM)event );
484     }
485     
486     HeapFree(SystemHeap, 0, event);
487 }
488
489 /***********************************************************************
490  *          MSG_JournalPlayBackMsg
491  *
492  * Get an EVENTMSG struct via call JOURNALPLAYBACK hook function 
493  */
494 static int MSG_JournalPlayBackMsg(void)
495 {
496  EVENTMSG *tmpMsg;
497  long wtime,lParam,wParam;
498  WORD keyDown,i,result=0;
499
500  if ( HOOK_IsHooked( WH_JOURNALPLAYBACK ) )
501  {
502   tmpMsg = (EVENTMSG *) HeapAlloc(SystemHeap, 0, sizeof(EVENTMSG));
503   if (!tmpMsg) return result;
504   
505   wtime=HOOK_CallHooksA( WH_JOURNALPLAYBACK, HC_GETNEXT, 0,
506                            (LPARAM) tmpMsg );
507   /*  TRACE(msg,"Playback wait time =%ld\n",wtime); */
508   if (wtime<=0)
509   {
510    wtime=0;
511    if ((tmpMsg->message>= WM_KEYFIRST) && (tmpMsg->message <= WM_KEYLAST))
512    {
513      wParam=tmpMsg->paramL & 0xFF;
514      lParam=MAKELONG(tmpMsg->paramH&0x7ffff,tmpMsg->paramL>>8);
515      if (tmpMsg->message == WM_KEYDOWN || tmpMsg->message == WM_SYSKEYDOWN)
516      {
517        for (keyDown=i=0; i<256 && !keyDown; i++)
518           if (InputKeyStateTable[i] & 0x80)
519             keyDown++;
520        if (!keyDown)
521          lParam |= 0x40000000;       
522        AsyncKeyStateTable[wParam]=InputKeyStateTable[wParam] |= 0x80;
523      }  
524      else                                       /* WM_KEYUP, WM_SYSKEYUP */
525      {
526        lParam |= 0xC0000000;      
527        AsyncKeyStateTable[wParam]=InputKeyStateTable[wParam] &= ~0x80;
528      }
529      if (InputKeyStateTable[VK_MENU] & 0x80)
530        lParam |= 0x20000000;     
531      if (tmpMsg->paramH & 0x8000)              /*special_key bit*/
532        lParam |= 0x01000000;
533      hardware_event( tmpMsg->message & 0xffff, LOWORD(wParam), lParam,
534                      0, 0, tmpMsg->time, 0 );
535    }
536    else
537    {
538     if ((tmpMsg->message>= WM_MOUSEFIRST) && (tmpMsg->message <= WM_MOUSELAST))
539     {
540      switch (tmpMsg->message)
541      {
542       case WM_LBUTTONDOWN:
543           MouseButtonsStates[0]=AsyncMouseButtonsStates[0]=TRUE;break;
544       case WM_LBUTTONUP:
545           MouseButtonsStates[0]=AsyncMouseButtonsStates[0]=FALSE;break;
546       case WM_MBUTTONDOWN:
547           MouseButtonsStates[1]=AsyncMouseButtonsStates[1]=TRUE;break;
548       case WM_MBUTTONUP:
549           MouseButtonsStates[1]=AsyncMouseButtonsStates[1]=FALSE;break;
550       case WM_RBUTTONDOWN:
551           MouseButtonsStates[2]=AsyncMouseButtonsStates[2]=TRUE;break;
552       case WM_RBUTTONUP:
553           MouseButtonsStates[2]=AsyncMouseButtonsStates[2]=FALSE;break;      
554      }
555      AsyncKeyStateTable[VK_LBUTTON]= InputKeyStateTable[VK_LBUTTON] = MouseButtonsStates[0] ? 0x80 : 0;
556      AsyncKeyStateTable[VK_MBUTTON]= InputKeyStateTable[VK_MBUTTON] = MouseButtonsStates[1] ? 0x80 : 0;
557      AsyncKeyStateTable[VK_RBUTTON]= InputKeyStateTable[VK_RBUTTON] = MouseButtonsStates[2] ? 0x80 : 0;
558      SetCursorPos(tmpMsg->paramL,tmpMsg->paramH);
559      lParam=MAKELONG(tmpMsg->paramL,tmpMsg->paramH);
560      wParam=0;             
561      if (MouseButtonsStates[0]) wParam |= MK_LBUTTON;
562      if (MouseButtonsStates[1]) wParam |= MK_MBUTTON;
563      if (MouseButtonsStates[2]) wParam |= MK_RBUTTON;
564      hardware_event( tmpMsg->message & 0xffff, LOWORD (wParam), lParam,
565                      tmpMsg->paramL, tmpMsg->paramH, tmpMsg->time, 0 );
566     }
567    }
568    HOOK_CallHooksA( WH_JOURNALPLAYBACK, HC_SKIP, 0,
569                       (LPARAM) tmpMsg);
570   }
571   else
572   {
573       
574     if( tmpMsg->message == WM_QUEUESYNC )
575         if (HOOK_IsHooked( WH_CBT ))
576             HOOK_CallHooksA( WH_CBT, HCBT_QS, 0, 0L);
577
578     result= QS_MOUSE | QS_KEY; /* ? */
579   }
580   HeapFree(SystemHeap, 0, tmpMsg);
581  }
582  return result;
583
584
585 /***********************************************************************
586  *           MSG_PeekHardwareMsg
587  *
588  * Peek for a hardware message matching the hwnd and message filters.
589  */
590 static BOOL MSG_PeekHardwareMsg( MSG *msg, HWND hwnd, DWORD first, DWORD last,
591                                    BOOL remove )
592 {
593     /* FIXME: should deal with MSG32 instead of MSG16 */
594     
595     DWORD status = SYSQ_MSG_ACCEPT;
596     MESSAGEQUEUE *sysMsgQueue = QUEUE_GetSysQueue();
597     enum { MOUSE_MSG = 0, KEYBOARD_MSG, HARDWARE_MSG } msgType;
598     QMSG *nextqmsg, *qmsg = 0;
599     BOOL bRet = FALSE;
600
601     EnterCriticalSection(&sysMsgQueue->cSection);
602
603     /* Loop through the Q and translate the message we wish to process
604      * while we own the lock. Based on the translation status (abandon/cont/accept)
605      * we then process the message accordingly
606      */
607
608     for ( qmsg = sysMsgQueue->firstMsg; qmsg; qmsg = nextqmsg )
609     {
610         INT16 hittest;
611         POINT16 screen_pt;
612         BOOL mouseClick;
613
614         *msg = qmsg->msg;
615
616         nextqmsg = qmsg->nextMsg;
617
618           /* Translate message */
619
620         if ((msg->message >= WM_MOUSEFIRST) && (msg->message <= WM_MOUSELAST))
621         {
622             HWND hWndScope = (HWND)qmsg->extraInfo;
623             WND *tmpWnd = (Options.managed && IsWindow(hWndScope) ) 
624                            ? WIN_FindWndPtr(hWndScope) : WIN_GetDesktop();
625
626             status = MSG_TranslateMouseMsg(hwnd, first, last, msg, remove, tmpWnd,
627                                            &hittest, &screen_pt, &mouseClick );
628             msgType = MOUSE_MSG;
629             
630             WIN_ReleaseWndPtr(tmpWnd);
631
632         }
633         else if ((msg->message >= WM_KEYFIRST) && (msg->message <= WM_KEYLAST))
634         {
635             status = MSG_TranslateKbdMsg(hwnd, first, last, msg, remove);
636             msgType = KEYBOARD_MSG;
637         }
638         else /* Non-standard hardware event */
639         {
640             HARDWAREHOOKSTRUCT16 *hook;
641             msgType = HARDWARE_MSG;
642             if ((hook = SEGPTR_NEW(HARDWAREHOOKSTRUCT16)))
643             {
644                 BOOL ret;
645                 hook->hWnd     = msg->hwnd;
646                 hook->wMessage = msg->message & 0xffff;
647                 hook->wParam   = LOWORD (msg->wParam);
648                 hook->lParam   = msg->lParam;
649                 ret = HOOK_CallHooks16( WH_HARDWARE,
650                                         remove ? HC_ACTION : HC_NOREMOVE,
651                                         0, (LPARAM)SEGPTR_GET(hook) );
652                 SEGPTR_FREE(hook);
653                 if (ret) 
654                 {
655                     QUEUE_RemoveMsg( sysMsgQueue, qmsg );
656                     continue;
657                 }
658                 status = SYSQ_MSG_ACCEPT; 
659             }
660         }
661
662         
663         switch (LOWORD(status))
664         {
665            case SYSQ_MSG_ACCEPT:
666            {
667                /* Remove the message from the system msg Q while it is still locked,
668                 * before accepting it */
669                if (remove)
670                {
671                    if (HOOK_IsHooked( WH_JOURNALRECORD )) MSG_JournalRecordMsg( msg );
672                    QUEUE_RemoveMsg( sysMsgQueue, qmsg );
673                }
674                /* Now actually process the message, after we unlock the system msg Q.
675                 * We should not hold on to the crst since SendMessage calls during processing 
676                 * will potentially cause callbacks to PeekMessage from the application.
677                 * If we're holding the crst and QUEUE_WaitBits is called with a
678                 * QS_SENDMESSAGE mask we will deadlock in hardware_event() when a
679                 * message is being posted to the Q.
680                 */
681                LeaveCriticalSection(&sysMsgQueue->cSection);
682                if( msgType == KEYBOARD_MSG )
683                    status = MSG_ProcessKbdMsg( msg, remove );
684                else if ( msgType == MOUSE_MSG )
685                    status = MSG_ProcessMouseMsg( msg, remove, hittest, screen_pt, mouseClick );
686
687                /* Reclaim the sys msg Q crst */
688                EnterCriticalSection(&sysMsgQueue->cSection);
689                
690                /* Pass the translated message to the user if it was accepted */
691                if (status == SYSQ_MSG_ACCEPT)
692                 break;
693
694                /* If not accepted, fall through into the SYSQ_MSG_SKIP case */
695            }
696                 
697            case SYSQ_MSG_SKIP:
698                 if (HOOK_IsHooked( WH_CBT ))
699                 {
700                    if( msgType == KEYBOARD_MSG )
701                        HOOK_CallHooks16( WH_CBT, HCBT_KEYSKIPPED, 
702                                          LOWORD (msg->wParam), msg->lParam );
703                    else if ( msgType == MOUSE_MSG )
704                    {
705                        MOUSEHOOKSTRUCT16 *hook = SEGPTR_NEW(MOUSEHOOKSTRUCT16);
706                        if (hook)
707                        {
708                            CONV_POINT32TO16( &msg->pt,&hook->pt );
709                            hook->hwnd         = msg->hwnd;
710                            hook->wHitTestCode = HIWORD(status);
711                            hook->dwExtraInfo  = 0;
712                            HOOK_CallHooks16( WH_CBT, HCBT_CLICKSKIPPED ,msg->message & 0xffff,
713                                           (LPARAM)SEGPTR_GET(hook) );
714                            SEGPTR_FREE(hook);
715                        }
716                    }
717                 }
718
719                 /* If the message was removed earlier set up nextqmsg so that we start 
720                  * at the top of the queue again.  We need to do this since our next pointer
721                  * could be invalid due to us unlocking the system message Q to process the message.
722                  * If not removed just refresh nextqmsg to point to the next msg.
723                  */
724                 if (remove)
725                     nextqmsg = sysMsgQueue->firstMsg;
726                 else
727                     nextqmsg = qmsg->nextMsg;
728
729                 continue;
730                 
731            case SYSQ_MSG_CONTINUE:
732                 continue;
733
734            case SYSQ_MSG_ABANDON: 
735                bRet = FALSE;
736                goto END;
737         }
738
739         bRet = TRUE;
740         goto END;
741     }
742
743 END:
744     LeaveCriticalSection(&sysMsgQueue->cSection);
745     return bRet;
746 }
747
748
749 /**********************************************************************
750  *           SetDoubleClickTime16   (USER.20)
751  */
752 void WINAPI SetDoubleClickTime16( UINT16 interval )
753 {
754     SetDoubleClickTime( interval );
755 }               
756
757
758 /**********************************************************************
759  *           SetDoubleClickTime   (USER32.480)
760  */
761 BOOL WINAPI SetDoubleClickTime( UINT interval )
762 {
763     doubleClickSpeed = interval ? interval : 500;
764     return TRUE;
765 }               
766
767
768 /**********************************************************************
769  *           GetDoubleClickTime16   (USER.21)
770  */
771 UINT16 WINAPI GetDoubleClickTime16(void)
772 {
773     return doubleClickSpeed;
774 }               
775
776
777 /**********************************************************************
778  *           GetDoubleClickTime   (USER32.239)
779  */
780 UINT WINAPI GetDoubleClickTime(void)
781 {
782     return doubleClickSpeed;
783 }               
784
785
786 /***********************************************************************
787  *           MSG_SendMessageInterThread
788  *
789  * Implementation of an inter-task SendMessage.
790  * Return values:
791  *    0 if error or timeout
792  *    1 if successflul
793  */
794 static LRESULT MSG_SendMessageInterThread( HQUEUE16 hDestQueue,
795                                            HWND hwnd, UINT msg,
796                                            WPARAM wParam, LPARAM lParam,
797                                            DWORD timeout, WORD flags,
798                                            LRESULT *pRes)
799 {
800     MESSAGEQUEUE *queue, *destQ;
801     SMSG         *smsg;
802     LRESULT      retVal = 1;
803     int          iWndsLocks;
804     
805     if (pRes) *pRes = 0;
806
807     if (IsTaskLocked16() || !IsWindow(hwnd))
808         return 0;
809
810     /* create a SMSG structure to hold SendMessage() parameters */
811     if (! (smsg = (SMSG *) HeapAlloc( SystemHeap, 0, sizeof(SMSG) )) )
812         return 0;
813     if (!(queue = (MESSAGEQUEUE*)QUEUE_Lock( GetFastQueue16() ))) return 0;
814
815     if (!(destQ = (MESSAGEQUEUE*)QUEUE_Lock( hDestQueue )))
816     {
817         QUEUE_Unlock( queue );
818         return 0;
819     }
820
821     TRACE_(sendmsg)("SM: %s [%04x] (%04x -> %04x)\n",
822                     SPY_GetMsgName(msg), msg, queue->self, hDestQueue );
823
824     /* fill up SMSG structure */
825     smsg->hWnd = hwnd;
826     smsg->msg = msg;
827     smsg->wParam = wParam;
828     smsg->lParam = lParam;
829     
830     smsg->lResult = 0;
831     smsg->hSrcQueue = pRes ? GetFastQueue16() : 0;
832     smsg->hDstQueue = hDestQueue;
833     smsg->flags = flags;
834
835     if (pRes) {
836         /* add smsg struct in the processing SM list of the source queue */
837         QUEUE_AddSMSG(queue, SM_PROCESSING_LIST, smsg);
838     } else {
839         /* this is a notification message, we don't need a reply */
840         smsg->flags |= SMSG_ALREADY_REPLIED | SMSG_RECEIVER_CLEANS;
841     }
842
843     /* add smsg struct in the pending list of the destination queue */
844     if (QUEUE_AddSMSG(destQ, SM_PENDING_LIST, smsg) == FALSE)
845     {
846         retVal = 0;
847         goto CLEANUP;
848     }
849
850     if (!pRes) goto CLEANUP; /* don't need a reply */
851
852     iWndsLocks = WIN_SuspendWndsLock();
853
854     /* force destination task to run next, if 16 bit threads */
855     if ( THREAD_IsWin16(NtCurrentTeb()) && THREAD_IsWin16(destQ->teb) )
856         DirectedYield16( destQ->teb->htask16 );
857
858     /* wait for the result, note that 16-bit apps almost always get out of
859      * DirectedYield() with SMSG_HAVE_RESULT flag already set */
860
861     while ( TRUE )
862     {
863         /*
864          * The sequence is crucial to avoid deadlock situations:
865          * - first, we clear the QS_SMRESULT bit
866          * - then, we check the SMSG_HAVE_RESULT bit
867          * - only if this isn't set, we enter the wait state.
868          *
869          * As the receiver first sets the SMSG_HAVE_RESULT and then wakes us,
870          * we are guaranteed that -should we now clear the QS_SMRESULT that
871          * was signalled already by the receiver- we will not start waiting.
872          */
873
874         if ( smsg->flags & SMSG_HAVE_RESULT )
875         {
876 got:
877              *pRes = smsg->lResult;
878              TRACE_(sendmsg)("smResult = %08x\n", (unsigned)*pRes );
879              break;
880         }
881
882         QUEUE_ClearWakeBit( queue, QS_SMRESULT );
883
884         if ( smsg->flags & SMSG_HAVE_RESULT )
885              goto got;
886
887         if(  QUEUE_WaitBits( QS_SMRESULT, timeout ) == 0 )
888         {
889              /* return with timeout */
890              SetLastError( 0 );
891              retVal = 0;
892              break;
893         }
894     }
895     WIN_RestoreWndsLock(iWndsLocks);
896
897     /* remove the smsg from the processing list of the source queue */
898     QUEUE_RemoveSMSG( queue, SM_PROCESSING_LIST, smsg );
899
900     /* Note: the destination thread is in charge of removing the smsg from
901        the pending list */
902
903     /* In the case of an early reply (or a timeout), sender thread will
904        released the smsg structure if the receiver thread is done
905        (SMSG_RECEIVED set). If the receiver thread isn't done,
906        SMSG_RECEIVER_CLEANS_UP flag is set, and it will be the receiver
907        responsibility to release smsg */
908         EnterCriticalSection( &queue->cSection );
909     
910         if (smsg->flags & SMSG_RECEIVED)
911             HeapFree(SystemHeap, 0, smsg);
912         else
913             smsg->flags |= SMSG_RECEIVER_CLEANS;
914         
915         LeaveCriticalSection( &queue->cSection );
916
917
918 CLEANUP:
919     QUEUE_Unlock( queue );
920     QUEUE_Unlock( destQ );
921     
922     TRACE_(sendmsg)("done!\n");
923     return retVal;
924 }
925
926
927 /***********************************************************************
928  *           ReplyMessage16   (USER.115)
929  */
930 void WINAPI ReplyMessage16( LRESULT result )
931 {
932     ReplyMessage( result );
933 }
934
935 /***********************************************************************
936  *           ReplyMessage   (USER.115)
937  */
938 BOOL WINAPI ReplyMessage( LRESULT result )
939 {
940     MESSAGEQUEUE *senderQ = 0;
941     MESSAGEQUEUE *queue = 0;
942     SMSG         *smsg;
943     BOOL       ret = FALSE;
944
945     if (!(queue = (MESSAGEQUEUE*)QUEUE_Lock( GetFastQueue16() )))
946         return FALSE;
947
948     TRACE_(sendmsg)("ReplyMessage, queue %04x\n", queue->self);
949
950
951     if (    !(smsg = queue->smWaiting)
952          || !(  (senderQ = QUEUE_Lock( smsg->hSrcQueue ))
953               || (smsg->flags & SMSG_ALREADY_REPLIED)) )
954         goto ReplyMessageEnd;
955
956     if ( !(smsg->flags & SMSG_ALREADY_REPLIED) )
957     {
958         /* This is the first reply, so pass result to sender */
959
960         TRACE_(sendmsg)("\trpm: smResult = %08lx\n", (long) result );
961
962         EnterCriticalSection(&senderQ->cSection);
963         
964         smsg->lResult = result;
965         smsg->flags |= SMSG_ALREADY_REPLIED;
966
967         /* check if it's an early reply (called by the application) or
968            a regular reply (called by ReceiveMessage) */
969         if ( !(smsg->flags & SMSG_SENDING_REPLY) )
970             smsg->flags |= SMSG_EARLY_REPLY;
971
972         smsg->flags |= SMSG_HAVE_RESULT;
973
974         LeaveCriticalSection(&senderQ->cSection);
975
976         /* tell the sending task that its reply is ready */
977         QUEUE_SetWakeBit( senderQ, QS_SMRESULT );
978
979         /* switch directly to sending task (16 bit thread only) */
980         if ( THREAD_IsWin16( NtCurrentTeb() ) && THREAD_IsWin16( senderQ->teb ) )
981             DirectedYield16( senderQ->teb->htask16 );
982
983         ret = TRUE;
984     }
985     
986     if (smsg->flags & SMSG_SENDING_REPLY)
987     {
988         /* remove msg from the waiting list, since this is the last
989           ReplyMessage */
990         QUEUE_RemoveSMSG( queue, SM_WAITING_LIST, smsg );
991         
992         EnterCriticalSection(&senderQ->cSection);
993         
994         /* tell the sender we're all done with smsg structure */
995         smsg->flags |= SMSG_RECEIVED;
996
997         /* sender will set SMSG_RECEIVER_CLEANS_UP if it wants the
998          receiver to clean up smsg, it could only happen when there is
999          an early reply or a timeout */
1000         if ( smsg->flags & SMSG_RECEIVER_CLEANS )
1001         {
1002             TRACE_(sendmsg)("Receiver cleans up!\n" );
1003             HeapFree( SystemHeap, 0, smsg );
1004         }
1005         
1006         LeaveCriticalSection(&senderQ->cSection);
1007     }
1008
1009 ReplyMessageEnd:
1010     if ( senderQ )
1011     QUEUE_Unlock( senderQ );
1012     if ( queue )
1013     QUEUE_Unlock( queue );
1014
1015     return ret;
1016 }
1017
1018 /***********************************************************************
1019  *           MSG_ConvertMsg
1020  */
1021 static BOOL MSG_ConvertMsg( MSG *msg, int srcType, int dstType )
1022 {
1023     UINT16 msg16;
1024     MSGPARAM16 mp16;
1025
1026     switch ( MAKELONG( srcType, dstType ) )
1027     {
1028     case MAKELONG( QMSG_WIN16,  QMSG_WIN16 ):
1029     case MAKELONG( QMSG_WIN32A, QMSG_WIN32A ):
1030     case MAKELONG( QMSG_WIN32W, QMSG_WIN32W ):
1031         return TRUE;
1032
1033     case MAKELONG( QMSG_WIN16, QMSG_WIN32A ):
1034         switch ( WINPROC_MapMsg16To32A( msg->message, msg->wParam,
1035                                        &msg->message, &msg->wParam, &msg->lParam ) )
1036         {
1037         case 0:
1038             return TRUE;
1039         case 1:
1040             /* Pointer messages were mapped --> need to free allocated memory and fail */
1041             WINPROC_UnmapMsg16To32A( msg->hwnd, msg->message, msg->wParam, msg->lParam, 0 );
1042         default:
1043             return FALSE;
1044         }
1045
1046     case MAKELONG( QMSG_WIN16, QMSG_WIN32W ):
1047         switch ( WINPROC_MapMsg16To32W( msg->hwnd, msg->message, msg->wParam,
1048                                        &msg->message, &msg->wParam, &msg->lParam ) )
1049         {
1050         case 0:
1051             return TRUE;
1052         case 1:
1053             /* Pointer messages were mapped --> need to free allocated memory and fail */
1054             WINPROC_UnmapMsg16To32W( msg->hwnd, msg->message, msg->wParam, msg->lParam, 0 );
1055         default:
1056             return FALSE;
1057         }
1058
1059     case MAKELONG( QMSG_WIN32A, QMSG_WIN16 ):
1060         mp16.lParam = msg->lParam;
1061         switch ( WINPROC_MapMsg32ATo16( msg->hwnd, msg->message, msg->wParam,
1062                                         &msg16, &mp16.wParam, &mp16.lParam ) )
1063         {
1064         case 0:
1065             msg->message = msg16; 
1066             msg->wParam  = mp16.wParam;
1067             msg->lParam  = mp16.lParam;
1068             return TRUE;
1069         case 1:
1070             /* Pointer messages were mapped --> need to free allocated memory and fail */
1071             WINPROC_UnmapMsg32ATo16( msg->hwnd, msg->message, msg->wParam, msg->lParam, &mp16 );
1072         default:
1073             return FALSE;
1074         }
1075
1076     case MAKELONG( QMSG_WIN32W, QMSG_WIN16 ):
1077         mp16.lParam = msg->lParam;
1078         switch ( WINPROC_MapMsg32WTo16( msg->hwnd, msg->message, msg->wParam,
1079                                         &msg16, &mp16.wParam, &mp16.lParam ) )
1080         {
1081         case 0:
1082             msg->message = msg16; 
1083             msg->wParam  = mp16.wParam;
1084             msg->lParam  = mp16.lParam;
1085             return TRUE;
1086         case 1:
1087             /* Pointer messages were mapped --> need to free allocated memory and fail */
1088             WINPROC_UnmapMsg32WTo16( msg->hwnd, msg->message, msg->wParam, msg->lParam, &mp16 );
1089         default:
1090             return FALSE;
1091         }
1092
1093     case MAKELONG( QMSG_WIN32A, QMSG_WIN32W ):
1094         switch ( WINPROC_MapMsg32ATo32W( msg->hwnd, msg->message, &msg->wParam, &msg->lParam ) )
1095         {
1096         case 0:
1097             return TRUE;
1098         case 1:
1099             /* Pointer messages were mapped --> need to free allocated memory and fail */
1100             WINPROC_UnmapMsg32ATo32W( msg->hwnd, msg->message, msg->wParam, msg->lParam );
1101         default:
1102             return FALSE;
1103         }
1104
1105     case MAKELONG( QMSG_WIN32W, QMSG_WIN32A ):
1106         switch ( WINPROC_MapMsg32WTo32A( msg->hwnd, msg->message, &msg->wParam, &msg->lParam ) )
1107         {
1108         case 0:
1109             return TRUE;
1110         case 1:
1111             /* Pointer messages were mapped --> need to free allocated memory and fail */
1112             WINPROC_UnmapMsg32WTo32A( msg->hwnd, msg->message, msg->wParam, msg->lParam );
1113         default:
1114             return FALSE;
1115         }
1116
1117     default:    
1118         FIXME( "Invalid message type(s): %d / %d\n", srcType, dstType );
1119         return FALSE;
1120     }
1121 }
1122
1123 /***********************************************************************
1124  *           MSG_PeekMessage
1125  */
1126 static BOOL MSG_PeekMessage( int type, LPMSG msg, HWND hwnd, 
1127                              DWORD first, DWORD last, WORD flags, BOOL peek )
1128 {
1129     int mask;
1130     MESSAGEQUEUE *msgQueue;
1131     HQUEUE16 hQueue;
1132     POINT16 pt16;
1133     int iWndsLocks;
1134
1135     mask = QS_POSTMESSAGE | QS_SENDMESSAGE;  /* Always selected */
1136     if (first || last)
1137     {
1138         if ((first <= WM_KEYLAST) && (last >= WM_KEYFIRST)) mask |= QS_KEY;
1139         if ( ((first <= WM_MOUSELAST) && (last >= WM_MOUSEFIRST)) ||
1140              ((first <= WM_NCMOUSELAST) && (last >= WM_NCMOUSEFIRST)) ) mask |= QS_MOUSE;
1141         if ((first <= WM_TIMER) && (last >= WM_TIMER)) mask |= QS_TIMER;
1142         if ((first <= WM_SYSTIMER) && (last >= WM_SYSTIMER)) mask |= QS_TIMER;
1143         if ((first <= WM_PAINT) && (last >= WM_PAINT)) mask |= QS_PAINT;
1144     }
1145     else mask |= QS_MOUSE | QS_KEY | QS_TIMER | QS_PAINT;
1146
1147     if (IsTaskLocked16()) flags |= PM_NOYIELD;
1148
1149     /* Never yield on Win32 threads */
1150     if (!THREAD_IsWin16(NtCurrentTeb())) flags |= PM_NOYIELD;
1151
1152     iWndsLocks = WIN_SuspendWndsLock();
1153
1154     while(1)
1155     {    
1156         QMSG *qmsg;
1157         
1158         hQueue   = GetFastQueue16();
1159         msgQueue = (MESSAGEQUEUE *)QUEUE_Lock( hQueue );
1160         if (!msgQueue)
1161         {
1162             WIN_RestoreWndsLock(iWndsLocks);
1163             return FALSE;
1164         }
1165         msgQueue->changeBits = 0;
1166
1167         /* First handle a message put by SendMessage() */
1168
1169         while (msgQueue->wakeBits & QS_SENDMESSAGE)
1170             QUEUE_ReceiveMessage( msgQueue );
1171
1172         /* Now handle a WM_QUIT message */
1173
1174         if (msgQueue->wPostQMsg &&
1175            (!first || WM_QUIT >= first) && 
1176            (!last || WM_QUIT <= last) )
1177         {
1178             msg->hwnd    = hwnd;
1179             msg->message = WM_QUIT;
1180             msg->wParam  = msgQueue->wExitCode;
1181             msg->lParam  = 0;
1182             if (flags & PM_REMOVE) msgQueue->wPostQMsg = 0;
1183             break;
1184         }
1185     
1186         /* Now find a normal message */
1187
1188   retry:
1189         if (((msgQueue->wakeBits & mask) & QS_POSTMESSAGE) &&
1190             ((qmsg = QUEUE_FindMsg( msgQueue, hwnd, first, last )) != 0))
1191         {
1192             /* Try to convert message to requested type */
1193             MSG tmpMsg = qmsg->msg;
1194             if ( !MSG_ConvertMsg( &tmpMsg, qmsg->type, type ) )
1195             {
1196                 ERR( "Message %s of wrong type contains pointer parameters. Skipped!\n",
1197                     SPY_GetMsgName(tmpMsg.message));
1198                 QUEUE_RemoveMsg( msgQueue, qmsg );
1199                 goto retry;
1200             }
1201
1202             *msg = tmpMsg;
1203             msgQueue->GetMessageTimeVal      = msg->time;
1204             CONV_POINT32TO16(&msg->pt, &pt16);
1205             msgQueue->GetMessagePosVal       = *(DWORD *)&pt16;
1206             msgQueue->GetMessageExtraInfoVal = qmsg->extraInfo;
1207
1208             if (flags & PM_REMOVE) QUEUE_RemoveMsg( msgQueue, qmsg );
1209             break;
1210         }
1211
1212         msgQueue->changeBits |= MSG_JournalPlayBackMsg();
1213
1214         /* Now find a hardware event */
1215
1216         if (MSG_PeekHardwareMsg( msg, hwnd, first, last, flags & PM_REMOVE ))
1217         {
1218             /* Got one */
1219             msgQueue->GetMessageTimeVal      = msg->time;
1220             CONV_POINT32TO16(&msg->pt, &pt16);
1221             msgQueue->GetMessagePosVal       = *(DWORD *)&pt16;
1222             msgQueue->GetMessageExtraInfoVal = 0;  /* Always 0 for now */
1223             break;
1224         }
1225
1226         /* Check again for SendMessage */
1227
1228         while (msgQueue->wakeBits & QS_SENDMESSAGE)
1229             QUEUE_ReceiveMessage( msgQueue );
1230
1231         /* Now find a WM_PAINT message */
1232
1233         if ((msgQueue->wakeBits & mask) & QS_PAINT)
1234         {
1235             WND* wndPtr;
1236             msg->hwnd = WIN_FindWinToRepaint( hwnd , hQueue );
1237             msg->message = WM_PAINT;
1238             msg->wParam = 0;
1239             msg->lParam = 0;
1240
1241             if ((wndPtr = WIN_FindWndPtr(msg->hwnd)))
1242             {
1243                 if( wndPtr->dwStyle & WS_MINIMIZE &&
1244                     (HICON) GetClassLongA(wndPtr->hwndSelf, GCL_HICON) )
1245                 {
1246                     msg->message = WM_PAINTICON;
1247                     msg->wParam = 1;
1248                 }
1249
1250                 if( !hwnd || msg->hwnd == hwnd || IsChild16(hwnd,msg->hwnd) )
1251                 {
1252                     if( wndPtr->flags & WIN_INTERNAL_PAINT && !wndPtr->hrgnUpdate)
1253                     {
1254                         wndPtr->flags &= ~WIN_INTERNAL_PAINT;
1255                         QUEUE_DecPaintCount( hQueue );
1256                     }
1257                     WIN_ReleaseWndPtr(wndPtr);
1258                     break;
1259                 }
1260                 WIN_ReleaseWndPtr(wndPtr);
1261             }
1262         }
1263
1264         /* Check for timer messages, but yield first */
1265
1266         if (!(flags & PM_NOYIELD))
1267         {
1268             UserYield16();
1269             while (msgQueue->wakeBits & QS_SENDMESSAGE)
1270                 QUEUE_ReceiveMessage( msgQueue );
1271         }
1272         if ((msgQueue->wakeBits & mask) & QS_TIMER)
1273         {
1274             if (TIMER_GetTimerMsg(msg, hwnd, hQueue, flags & PM_REMOVE)) break;
1275         }
1276
1277         if (peek)
1278         {
1279             if (!(flags & PM_NOYIELD)) UserYield16();
1280             
1281             QUEUE_Unlock( msgQueue );
1282             WIN_RestoreWndsLock(iWndsLocks);
1283             return FALSE;
1284         }
1285         msgQueue->wakeMask = mask;
1286         QUEUE_WaitBits( mask, INFINITE );
1287         QUEUE_Unlock( msgQueue );
1288     }
1289
1290     WIN_RestoreWndsLock(iWndsLocks);
1291     
1292     /* instead of unlocking queue for every break condition, all break
1293        condition will fall here */
1294     QUEUE_Unlock( msgQueue );
1295     
1296       /* We got a message */
1297     if (flags & PM_REMOVE)
1298     {
1299         WORD message = msg->message;
1300
1301         if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN)
1302         {
1303             BYTE *p = &QueueKeyStateTable[msg->wParam & 0xff];
1304
1305             if (!(*p & 0x80))
1306                 *p ^= 0x01;
1307             *p |= 0x80;
1308         }
1309         else if (message == WM_KEYUP || message == WM_SYSKEYUP)
1310             QueueKeyStateTable[msg->wParam & 0xff] &= ~0x80;
1311     }
1312
1313     if (peek)
1314         return TRUE;
1315
1316     else
1317         return (msg->message != WM_QUIT);
1318 }
1319
1320 /***********************************************************************
1321  *           MSG_InternalGetMessage
1322  *
1323  * GetMessage() function for internal use. Behave like GetMessage(),
1324  * but also call message filters and optionally send WM_ENTERIDLE messages.
1325  * 'hwnd' must be the handle of the dialog or menu window.
1326  * 'code' is the message filter value (MSGF_??? codes).
1327  */
1328 BOOL MSG_InternalGetMessage( int type, MSG *msg, HWND hwnd, HWND hwndOwner,
1329                              WPARAM code, WORD flags, BOOL sendIdle, BOOL* idleSent ) 
1330 {
1331     for (;;)
1332     {
1333         if (sendIdle)
1334         {
1335             if (!MSG_PeekMessage( type, msg, 0, 0, 0, flags, TRUE ))
1336             {
1337                   /* No message present -> send ENTERIDLE and wait */
1338                 if (IsWindow(hwndOwner))
1339                 {
1340                     SendMessageA( hwndOwner, WM_ENTERIDLE,
1341                                    code, (LPARAM)hwnd );
1342
1343                     if (idleSent!=NULL)
1344                       *idleSent=TRUE;
1345                 }
1346                 MSG_PeekMessage( type, msg, 0, 0, 0, flags, FALSE );
1347             }
1348         }
1349         else  /* Always wait for a message */
1350             MSG_PeekMessage( type, msg, 0, 0, 0, flags, FALSE );
1351
1352         /* Call message filters */
1353
1354         if (HOOK_IsHooked( WH_SYSMSGFILTER ) || HOOK_IsHooked( WH_MSGFILTER ))
1355         {
1356             MSG *pmsg = HeapAlloc( SystemHeap, 0, sizeof(MSG) );
1357             if (pmsg)
1358             {
1359                 BOOL ret;
1360                 *pmsg = *msg;
1361                 ret = (HOOK_CallHooksA( WH_SYSMSGFILTER, code, 0,
1362                                           (LPARAM) pmsg ) ||
1363                        HOOK_CallHooksA( WH_MSGFILTER, code, 0,
1364                                           (LPARAM) pmsg ));
1365                        
1366                 HeapFree( SystemHeap, 0, pmsg );
1367                 if (ret)
1368                 {
1369                     /* Message filtered -> remove it from the queue */
1370                     /* if it's still there. */
1371                     if (!(flags & PM_REMOVE))
1372                         MSG_PeekMessage( type, msg, 0, 0, 0, PM_REMOVE, TRUE );
1373                     continue;
1374                 }
1375             }
1376         }
1377
1378         return (msg->message != WM_QUIT);
1379     }
1380 }
1381
1382
1383 /***********************************************************************
1384  *         PeekMessage32_16   (USER.819)
1385  */
1386 BOOL16 WINAPI PeekMessage32_16( SEGPTR msg16_32, HWND16 hwnd,
1387                                 UINT16 first, UINT16 last, UINT16 flags, 
1388                                 BOOL16 wHaveParamHigh )
1389 {
1390     BOOL ret;
1391     MSG32_16 *lpmsg16_32 = (MSG32_16 *)PTR_SEG_TO_LIN(msg16_32);
1392     MSG msg;
1393
1394     ret = MSG_PeekMessage( QMSG_WIN16, &msg, hwnd, first, last, flags, TRUE );
1395
1396     lpmsg16_32->msg.hwnd    = msg.hwnd;
1397     lpmsg16_32->msg.message = msg.message;
1398     lpmsg16_32->msg.wParam  = LOWORD(msg.wParam);
1399     lpmsg16_32->msg.lParam  = msg.lParam;
1400     lpmsg16_32->msg.time    = msg.time;
1401     lpmsg16_32->msg.pt.x    = (INT16)msg.pt.x;
1402     lpmsg16_32->msg.pt.y    = (INT16)msg.pt.y;
1403
1404     if ( wHaveParamHigh )
1405         lpmsg16_32->wParamHigh = HIWORD(msg.wParam);
1406
1407     HOOK_CallHooks16( WH_GETMESSAGE, HC_ACTION, flags & PM_REMOVE, (LPARAM)msg16_32 );
1408     return ret;
1409 }
1410
1411 /***********************************************************************
1412  *           PeekMessage16   (USER.109)
1413  */
1414 BOOL16 WINAPI PeekMessage16( SEGPTR msg, HWND16 hwnd,
1415                              UINT16 first, UINT16 last, UINT16 flags )
1416 {
1417     return PeekMessage32_16( msg, hwnd, first, last, flags, FALSE );
1418 }
1419
1420 /***********************************************************************
1421  *         PeekMessageA
1422  */
1423 BOOL WINAPI PeekMessageA( LPMSG lpmsg, HWND hwnd,
1424                           UINT min, UINT max, UINT wRemoveMsg)
1425 {
1426     BOOL ret = MSG_PeekMessage( QMSG_WIN32A, lpmsg, hwnd, min, max, wRemoveMsg, TRUE );
1427
1428     TRACE( "peekmessage %04x, hwnd %04x, filter(%04x - %04x)\n", 
1429            lpmsg->message, hwnd, min, max );
1430
1431     if (ret) HOOK_CallHooksA( WH_GETMESSAGE, HC_ACTION,
1432                               wRemoveMsg & PM_REMOVE, (LPARAM)lpmsg );
1433     return ret;
1434 }
1435
1436 /***********************************************************************
1437  *         PeekMessageW             Check queue for messages
1438  *
1439  * Checks for a message in the thread's queue, filtered as for
1440  * GetMessage(). Returns immediately whether a message is available
1441  * or not.
1442  *
1443  * Whether a retrieved message is removed from the queue is set by the
1444  * _wRemoveMsg_ flags, which should be one of the following values:
1445  *
1446  *    PM_NOREMOVE    Do not remove the message from the queue. 
1447  *
1448  *    PM_REMOVE      Remove the message from the queue.
1449  *
1450  * In addition, PM_NOYIELD may be combined into _wRemoveMsg_ to
1451  * request that the system not yield control during PeekMessage();
1452  * however applications may not rely on scheduling behavior.
1453  * 
1454  * RETURNS
1455  *
1456  *  Nonzero if a message is available and is retrieved, zero otherwise.
1457  *
1458  * CONFORMANCE
1459  *
1460  * ECMA-234, Win32
1461  *
1462  */
1463 BOOL WINAPI PeekMessageW( 
1464   LPMSG lpmsg,    /* buffer to receive message */
1465   HWND hwnd,      /* restrict to messages for hwnd */
1466   UINT min,       /* minimum message to receive */
1467   UINT max,       /* maximum message to receive */
1468   UINT wRemoveMsg /* removal flags */ 
1469
1470 {
1471     BOOL ret = MSG_PeekMessage( QMSG_WIN32W, lpmsg, hwnd, min, max, wRemoveMsg, TRUE );
1472     if (ret) HOOK_CallHooksW( WH_GETMESSAGE, HC_ACTION,
1473                               wRemoveMsg & PM_REMOVE, (LPARAM)lpmsg );
1474     return ret;
1475 }
1476
1477
1478 /***********************************************************************
1479  *          GetMessage32_16   (USER.820)
1480  */
1481 BOOL16 WINAPI GetMessage32_16( SEGPTR msg16_32, HWND16 hWnd, UINT16 first,
1482                                UINT16 last, BOOL16 wHaveParamHigh )
1483 {
1484     MSG32_16 *lpmsg16_32 = (MSG32_16 *)PTR_SEG_TO_LIN(msg16_32);
1485     MSG msg;
1486
1487     MSG_PeekMessage( QMSG_WIN16, &msg, hWnd, first, last, PM_REMOVE, FALSE );
1488
1489     lpmsg16_32->msg.hwnd    = msg.hwnd;
1490     lpmsg16_32->msg.message = msg.message;
1491     lpmsg16_32->msg.wParam  = LOWORD(msg.wParam);
1492     lpmsg16_32->msg.lParam  = msg.lParam;
1493     lpmsg16_32->msg.time    = msg.time;
1494     lpmsg16_32->msg.pt.x    = (INT16)msg.pt.x;
1495     lpmsg16_32->msg.pt.y    = (INT16)msg.pt.y;
1496
1497     if ( wHaveParamHigh )
1498         lpmsg16_32->wParamHigh = HIWORD(msg.wParam);
1499
1500     TRACE( "message %04x, hwnd %04x, filter(%04x - %04x)\n",
1501            lpmsg16_32->msg.message, hWnd, first, last );
1502
1503     HOOK_CallHooks16( WH_GETMESSAGE, HC_ACTION, PM_REMOVE, (LPARAM)msg16_32 );
1504     return lpmsg16_32->msg.message != WM_QUIT;
1505 }
1506
1507 /***********************************************************************
1508  *           GetMessage16   (USER.108)
1509  */
1510 BOOL16 WINAPI GetMessage16( SEGPTR msg, HWND16 hwnd, UINT16 first, UINT16 last)
1511 {
1512     return GetMessage32_16( msg, hwnd, first, last, FALSE );
1513 }
1514
1515 /***********************************************************************
1516  *          GetMessageA   (USER32.270)
1517  */
1518 BOOL WINAPI GetMessageA( MSG *lpmsg, HWND hwnd, UINT min, UINT max )
1519 {
1520     MSG_PeekMessage( QMSG_WIN32A, lpmsg, hwnd, min, max, PM_REMOVE, FALSE );
1521     
1522     TRACE( "message %04x, hwnd %04x, filter(%04x - %04x)\n", 
1523            lpmsg->message, hwnd, min, max );
1524     
1525     HOOK_CallHooksA( WH_GETMESSAGE, HC_ACTION, PM_REMOVE, (LPARAM)lpmsg );
1526     return lpmsg->message != WM_QUIT;
1527 }
1528
1529 /***********************************************************************
1530  *          GetMessageW   (USER32.274) Retrieve next message
1531  *
1532  * GetMessage retrieves the next event from the calling thread's
1533  * queue and deposits it in *lpmsg.
1534  *
1535  * If _hwnd_ is not NULL, only messages for window _hwnd_ and its
1536  * children as specified by IsChild() are retrieved. If _hwnd_ is NULL
1537  * all application messages are retrieved.
1538  *
1539  * _min_ and _max_ specify the range of messages of interest. If
1540  * min==max==0, no filtering is performed. Useful examples are
1541  * WM_KEYFIRST and WM_KEYLAST to retrieve keyboard input, and
1542  * WM_MOUSEFIRST and WM_MOUSELAST to retrieve mouse input.
1543  *
1544  * WM_PAINT messages are not removed from the queue; they remain until
1545  * processed. Other messages are removed from the queue.
1546  *
1547  * RETURNS
1548  *
1549  * -1 on error, 0 if message is WM_QUIT, nonzero otherwise.
1550  *
1551  * CONFORMANCE
1552  *
1553  * ECMA-234, Win32
1554  * 
1555  */
1556 BOOL WINAPI GetMessageW(
1557   MSG* lpmsg, /* buffer to receive message */
1558   HWND hwnd,  /* restrict to messages for hwnd */
1559   UINT min,   /* minimum message to receive */
1560   UINT max    /* maximum message to receive */
1561
1562 {
1563     MSG_PeekMessage( QMSG_WIN32W, lpmsg, hwnd, min, max, PM_REMOVE, FALSE );
1564     
1565     TRACE( "message %04x, hwnd %04x, filter(%04x - %04x)\n", 
1566            lpmsg->message, hwnd, min, max );
1567     
1568     HOOK_CallHooksW( WH_GETMESSAGE, HC_ACTION, PM_REMOVE, (LPARAM)lpmsg );
1569     return lpmsg->message != WM_QUIT;
1570 }
1571
1572 /***********************************************************************
1573  *           MSG_PostToQueue
1574  */
1575 static BOOL MSG_PostToQueue( HQUEUE16 hQueue, int type, HWND hwnd, 
1576                              UINT message, WPARAM wParam, LPARAM lParam )
1577 {
1578     MSG msg;
1579
1580     if ( !hQueue ) return FALSE;
1581
1582     msg.hwnd    = hwnd;
1583     msg.message = message;
1584     msg.wParam  = wParam;
1585     msg.lParam  = lParam;
1586     msg.time    = GetTickCount();
1587     GetCursorPos(&msg.pt);
1588
1589     return QUEUE_AddMsg( hQueue, type, &msg, 0 );
1590 }
1591
1592 /***********************************************************************
1593  *           MSG_PostMessage
1594  */
1595 static BOOL MSG_PostMessage( int type, HWND hwnd, UINT message, 
1596                              WPARAM wParam, LPARAM lParam )
1597 {
1598     HQUEUE16 hQueue;
1599     WND *wndPtr;
1600
1601     if (hwnd == HWND_BROADCAST)
1602     {
1603         WND *pDesktop = WIN_GetDesktop();
1604         TRACE("HWND_BROADCAST !\n");
1605         
1606         for (wndPtr=WIN_LockWndPtr(pDesktop->child); wndPtr; WIN_UpdateWndPtr(&wndPtr,wndPtr->next))
1607         {
1608             if (wndPtr->dwStyle & WS_POPUP || wndPtr->dwStyle & WS_CAPTION)
1609             {
1610                 TRACE("BROADCAST Message to hWnd=%04x m=%04X w=%04X l=%08lX !\n",
1611                       wndPtr->hwndSelf, message, wParam, lParam);
1612                 MSG_PostToQueue( wndPtr->hmemTaskQ, type, 
1613                                  wndPtr->hwndSelf, message, wParam, lParam );
1614             }
1615         }
1616         WIN_ReleaseDesktop();
1617         TRACE("End of HWND_BROADCAST !\n");
1618         return TRUE;
1619     }
1620
1621     wndPtr = WIN_FindWndPtr( hwnd );
1622     hQueue = wndPtr? wndPtr->hmemTaskQ : 0;
1623     WIN_ReleaseWndPtr(wndPtr);
1624
1625     return MSG_PostToQueue( hQueue, type, hwnd, message, wParam, lParam );
1626 }
1627
1628 /***********************************************************************
1629  *           PostMessage16   (USER.110)
1630  */
1631 BOOL16 WINAPI PostMessage16( HWND16 hwnd, UINT16 message, WPARAM16 wParam,
1632                              LPARAM lParam )
1633 {
1634     return (BOOL16) MSG_PostMessage( QMSG_WIN16, hwnd, message, wParam, lParam );
1635 }
1636
1637 /***********************************************************************
1638  *           PostMessageA   (USER32.419)
1639  */
1640 BOOL WINAPI PostMessageA( HWND hwnd, UINT message, WPARAM wParam,
1641                           LPARAM lParam )
1642 {
1643     return MSG_PostMessage( QMSG_WIN32A, hwnd, message, wParam, lParam );
1644 }
1645
1646 /***********************************************************************
1647  *           PostMessageW   (USER32.420)
1648  */
1649 BOOL WINAPI PostMessageW( HWND hwnd, UINT message, WPARAM wParam,
1650                           LPARAM lParam )
1651 {
1652     return MSG_PostMessage( QMSG_WIN32W, hwnd, message, wParam, lParam );
1653 }
1654
1655 /***********************************************************************
1656  *           PostAppMessage16   (USER.116)
1657  */
1658 BOOL16 WINAPI PostAppMessage16( HTASK16 hTask, UINT16 message, 
1659                                 WPARAM16 wParam, LPARAM lParam )
1660 {
1661     return MSG_PostToQueue( GetTaskQueue16(hTask), QMSG_WIN16, 
1662                             0, message, wParam, lParam );
1663 }
1664
1665 /**********************************************************************
1666  *           PostThreadMessageA    (USER32.422)
1667  */
1668 BOOL WINAPI PostThreadMessageA( DWORD idThread, UINT message,
1669                                 WPARAM wParam, LPARAM lParam )
1670 {
1671     return MSG_PostToQueue( GetThreadQueue16(idThread), QMSG_WIN32A, 
1672                             0, message, wParam, lParam );
1673 }
1674
1675 /**********************************************************************
1676  *           PostThreadMessageW    (USER32.423)
1677  */
1678 BOOL WINAPI PostThreadMessageW( DWORD idThread, UINT message,
1679                                  WPARAM wParam, LPARAM lParam )
1680 {
1681     return MSG_PostToQueue( GetThreadQueue16(idThread), QMSG_WIN32W, 
1682                             0, message, wParam, lParam );
1683 }
1684
1685
1686 /************************************************************************
1687  *           MSG_CallWndProcHook32
1688  */
1689 static void  MSG_CallWndProcHook( LPMSG pmsg, BOOL bUnicode )
1690 {
1691    CWPSTRUCT cwp;
1692
1693    cwp.lParam = pmsg->lParam;
1694    cwp.wParam = pmsg->wParam;
1695    cwp.message = pmsg->message;
1696    cwp.hwnd = pmsg->hwnd;
1697
1698    if (bUnicode) HOOK_CallHooksW(WH_CALLWNDPROC, HC_ACTION, 1, (LPARAM)&cwp);
1699    else HOOK_CallHooksA( WH_CALLWNDPROC, HC_ACTION, 1, (LPARAM)&cwp );
1700
1701    pmsg->lParam = cwp.lParam;
1702    pmsg->wParam = cwp.wParam;
1703    pmsg->message = cwp.message;
1704    pmsg->hwnd = cwp.hwnd;
1705 }
1706
1707
1708 /***********************************************************************
1709  *           MSG_SendMessage
1710  *
1711  * return values: 0 if timeout occurs
1712  *                1 otherwise
1713  */
1714 static LRESULT MSG_SendMessage( HWND hwnd, UINT msg, WPARAM wParam,
1715                          LPARAM lParam, DWORD timeout, WORD flags,
1716                          LRESULT *pRes)
1717 {
1718     WND * wndPtr = 0;
1719     WND **list, **ppWnd;
1720     LRESULT ret = 1;
1721
1722     if (pRes) *pRes = 0;
1723
1724     if (hwnd == HWND_BROADCAST|| hwnd == HWND_TOPMOST)
1725     {
1726         if (pRes) *pRes = 1;
1727         
1728         if (!(list = WIN_BuildWinArray( WIN_GetDesktop(), 0, NULL )))
1729         {
1730             WIN_ReleaseDesktop();
1731             return 1;
1732         }
1733         WIN_ReleaseDesktop();
1734
1735         TRACE("HWND_BROADCAST !\n");
1736         for (ppWnd = list; *ppWnd; ppWnd++)
1737         {
1738             WIN_UpdateWndPtr(&wndPtr,*ppWnd);
1739             if (!IsWindow(wndPtr->hwndSelf)) continue;
1740             if (wndPtr->dwStyle & WS_POPUP || wndPtr->dwStyle & WS_CAPTION)
1741             {
1742                 TRACE("BROADCAST Message to hWnd=%04x m=%04X w=%04lX l=%08lX !\n",
1743                       wndPtr->hwndSelf, msg, (DWORD)wParam, lParam);
1744                 MSG_SendMessage( wndPtr->hwndSelf, msg, wParam, lParam,
1745                                timeout, flags, pRes);
1746             }
1747         }
1748         WIN_ReleaseWndPtr(wndPtr);
1749         WIN_ReleaseWinArray(list);
1750         TRACE("End of HWND_BROADCAST !\n");
1751         return 1;
1752     }
1753
1754     if (HOOK_IsHooked( WH_CALLWNDPROC ))
1755     {
1756         if (flags & SMSG_UNICODE)
1757             MSG_CallWndProcHook( (LPMSG)&hwnd, TRUE);
1758         else if (flags & SMSG_WIN32)
1759             MSG_CallWndProcHook( (LPMSG)&hwnd, FALSE);
1760         else
1761         {
1762         LPCWPSTRUCT16 pmsg;
1763
1764         if ((pmsg = SEGPTR_NEW(CWPSTRUCT16)))
1765         {
1766                 pmsg->hwnd   = hwnd & 0xffff;
1767                 pmsg->message= msg & 0xffff;
1768                 pmsg->wParam = wParam & 0xffff;
1769             pmsg->lParam = lParam;
1770             HOOK_CallHooks16( WH_CALLWNDPROC, HC_ACTION, 1,
1771                               (LPARAM)SEGPTR_GET(pmsg) );
1772             hwnd   = pmsg->hwnd;
1773             msg    = pmsg->message;
1774             wParam = pmsg->wParam;
1775             lParam = pmsg->lParam;
1776             SEGPTR_FREE( pmsg );
1777         }
1778     }
1779     }
1780
1781     if (!(wndPtr = WIN_FindWndPtr( hwnd )))
1782     {
1783         WARN("invalid hwnd %04x\n", hwnd );
1784         return 0;
1785     }
1786     if (QUEUE_IsExitingQueue(wndPtr->hmemTaskQ))
1787     {
1788         ret = 0;  /* Don't send anything if the task is dying */
1789         goto END;
1790     }
1791     if (flags & SMSG_WIN32)
1792         SPY_EnterMessage( SPY_SENDMESSAGE, hwnd, msg, wParam, lParam );
1793     else
1794         SPY_EnterMessage( SPY_SENDMESSAGE16, hwnd, msg, wParam, lParam );
1795
1796     if (wndPtr->hmemTaskQ != GetFastQueue16())
1797         ret = MSG_SendMessageInterThread( wndPtr->hmemTaskQ, hwnd, msg,
1798                                           wParam, lParam, timeout, flags, pRes );
1799     else
1800     {
1801         LRESULT res;
1802
1803         /* Call the right CallWindowProc flavor */
1804         if (flags & SMSG_UNICODE)
1805             res = CallWindowProcW( (WNDPROC)wndPtr->winproc,
1806                                    hwnd, msg, wParam, lParam );
1807         else if (flags & SMSG_WIN32)
1808             res = CallWindowProcA( (WNDPROC)wndPtr->winproc,
1809                                    hwnd, msg, wParam, lParam );
1810         else
1811             res = CallWindowProc16( (WNDPROC16)wndPtr->winproc,
1812                                     (HWND16) hwnd, (UINT16) msg,
1813                                     (WPARAM16) wParam, lParam );
1814         if (pRes) *pRes = res;
1815     }
1816
1817     if (flags & SMSG_WIN32)
1818         SPY_ExitMessage( SPY_RESULT_OK, hwnd, msg, pRes?*pRes:0, wParam, lParam );
1819     else
1820         SPY_ExitMessage( SPY_RESULT_OK16, hwnd, msg, pRes?*pRes:0, wParam, lParam );
1821 END:
1822     WIN_ReleaseWndPtr(wndPtr);
1823     return ret;
1824 }
1825
1826
1827 /***********************************************************************
1828  *           SendMessage16   (USER.111)
1829  */
1830 LRESULT WINAPI SendMessage16( HWND16 hwnd, UINT16 msg, WPARAM16 wParam,
1831                               LPARAM lParam)
1832 {
1833     LRESULT res;
1834     MSG_SendMessage(hwnd, msg, wParam, lParam, INFINITE, 0, &res);
1835     return res;
1836 }
1837
1838
1839 /***********************************************************************
1840  *           SendMessageA   (USER32.454)
1841  */
1842 LRESULT WINAPI SendMessageA( HWND hwnd, UINT msg, WPARAM wParam,
1843                                LPARAM lParam )
1844         {
1845     LRESULT res;
1846
1847     MSG_SendMessage(hwnd, msg, wParam, lParam, INFINITE,
1848                     SMSG_WIN32, &res);
1849
1850     return res;
1851 }
1852
1853
1854 /***********************************************************************
1855  *           SendMessageW   (USER32.459)  Send Window Message
1856  *
1857  *  Sends a message to the window procedure of the specified window.
1858  *  SendMessage() will not return until the called window procedure
1859  *  either returns or calls ReplyMessage().
1860  *
1861  *  Use PostMessage() to send message and return immediately. A window
1862  *  procedure may use InSendMessage() to detect
1863  *  SendMessage()-originated messages.
1864  *
1865  *  Applications which communicate via HWND_BROADCAST may use
1866  *  RegisterWindowMessage() to obtain a unique message to avoid conflicts
1867  *  with other applications.
1868  *
1869  * CONFORMANCE
1870  * 
1871  *  ECMA-234, Win32 
1872  */
1873 LRESULT WINAPI SendMessageW( 
1874   HWND hwnd,    /* Window to send message to. If HWND_BROADCAST, 
1875                  the message will be sent to all top-level windows. */
1876
1877   UINT msg,      /* message */
1878   WPARAM wParam, /* message parameter */
1879   LPARAM lParam    /* additional message parameter */
1880 ) {
1881     LRESULT res;
1882
1883     MSG_SendMessage(hwnd, msg, wParam, lParam, INFINITE,
1884                     SMSG_WIN32 | SMSG_UNICODE, &res);
1885
1886     return res;
1887 }
1888
1889
1890 /***********************************************************************
1891  *           SendMessageTimeout16    (not a WINAPI)
1892  */
1893 LRESULT WINAPI SendMessageTimeout16( HWND16 hwnd, UINT16 msg, WPARAM16 wParam,
1894                                      LPARAM lParam, UINT16 flags,
1895                                      UINT16 timeout, LPWORD resultp)
1896 {
1897     LRESULT ret;
1898     LRESULT msgRet;
1899     
1900     /* FIXME: need support for SMTO_BLOCK */
1901     
1902     ret = MSG_SendMessage(hwnd, msg, wParam, lParam, timeout, 0, &msgRet);
1903     if (resultp) *resultp = (WORD) msgRet;
1904     return ret;
1905 }
1906
1907
1908 /***********************************************************************
1909  *           SendMessageTimeoutA   (USER32.457)
1910  */
1911 LRESULT WINAPI SendMessageTimeoutA( HWND hwnd, UINT msg, WPARAM wParam,
1912                                       LPARAM lParam, UINT flags,
1913                                       UINT timeout, LPDWORD resultp)
1914 {
1915     LRESULT ret;
1916     LRESULT msgRet;
1917
1918     /* FIXME: need support for SMTO_BLOCK */
1919     
1920     ret = MSG_SendMessage(hwnd, msg, wParam, lParam, timeout, SMSG_WIN32,
1921                           &msgRet);
1922
1923     if (resultp) *resultp = (DWORD) msgRet;
1924     return ret;
1925 }
1926
1927
1928 /***********************************************************************
1929  *           SendMessageTimeoutW   (USER32.458)
1930  */
1931 LRESULT WINAPI SendMessageTimeoutW( HWND hwnd, UINT msg, WPARAM wParam,
1932                                       LPARAM lParam, UINT flags,
1933                                       UINT timeout, LPDWORD resultp)
1934 {
1935     LRESULT ret;
1936     LRESULT msgRet;
1937     
1938     /* FIXME: need support for SMTO_BLOCK */
1939
1940     ret = MSG_SendMessage(hwnd, msg, wParam, lParam, timeout,
1941                           SMSG_WIN32 | SMSG_UNICODE, &msgRet);
1942     
1943     if (resultp) *resultp = (DWORD) msgRet;
1944     return ret;
1945 }
1946
1947
1948 /***********************************************************************
1949  *  WaitMessage    (USER.112) (USER32.578)  Suspend thread pending messages
1950  *
1951  * WaitMessage() suspends a thread until events appear in the thread's
1952  * queue.
1953  *
1954  * BUGS
1955  *
1956  * Is supposed to return BOOL under Win32.
1957  *
1958  * Thread-local message queues are not supported.
1959  *
1960  * CONFORMANCE
1961  *
1962  * ECMA-234, Win32
1963  * 
1964  */
1965 void WINAPI WaitMessage( void )
1966 {
1967     QUEUE_WaitBits( QS_ALLINPUT, INFINITE );
1968 }
1969
1970 /***********************************************************************
1971  *           MsgWaitForMultipleObjects    (USER32.400)
1972  */
1973 DWORD WINAPI MsgWaitForMultipleObjects( DWORD nCount, HANDLE *pHandles,
1974                                         BOOL fWaitAll, DWORD dwMilliseconds,
1975                                         DWORD dwWakeMask )
1976 {
1977     DWORD i;
1978     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1979     DWORD ret;
1980
1981     HQUEUE16 hQueue = GetFastQueue16();
1982     MESSAGEQUEUE *msgQueue = (MESSAGEQUEUE *)QUEUE_Lock( hQueue );
1983     if (!msgQueue) return WAIT_FAILED;
1984
1985     if (nCount > MAXIMUM_WAIT_OBJECTS-1)
1986     {
1987         SetLastError( ERROR_INVALID_PARAMETER );
1988         QUEUE_Unlock( msgQueue );
1989         return WAIT_FAILED;
1990     }
1991
1992     msgQueue->changeBits = 0;
1993     msgQueue->wakeMask = dwWakeMask;
1994
1995     if (THREAD_IsWin16(NtCurrentTeb()))
1996     {
1997       /*
1998        * This is a temporary solution to a big problem.
1999        * You see, the main thread of all Win32 programs is created as a 16 bit
2000        * task. This means that if you wait on an event using Win32 synchronization
2001        * methods, the 16 bit scheduler is stopped and things might just stop happening.
2002        * This implements a semi-busy loop that checks the handles to wait on and
2003        * also the message queue. When either one is ready, the wait function returns.
2004        *
2005        * This will all go away when the real Win32 threads are implemented for all
2006        * the threads of an applications. Including the main thread.
2007        */
2008       DWORD curTime = GetCurrentTime();
2009
2010       do
2011       {
2012         /*
2013          * Check the handles in the list.
2014          */
2015         ret = WaitForMultipleObjects(nCount, pHandles, fWaitAll, 5L);
2016
2017         /*
2018          * If the handles have been triggered, return.
2019          */
2020         if (ret != WAIT_TIMEOUT)
2021           break;
2022
2023         /*
2024          * Then, let the 16 bit scheduler do it's thing.
2025          */
2026         Yield16();
2027
2028         /*
2029          * If a message matching the wait mask has arrived, return.
2030          */
2031         if (msgQueue->changeBits & dwWakeMask)
2032         {
2033           ret = nCount;
2034           break;
2035         }
2036
2037         /*
2038          * And continue doing this until we hit the timeout.
2039          */
2040       } while ((dwMilliseconds == INFINITE) || (GetCurrentTime()-curTime < dwMilliseconds) );
2041     }
2042     else
2043     {
2044     /* Add the thread event to the handle list */
2045       for (i = 0; i < nCount; i++)
2046         handles[i] = pHandles[i];
2047       handles[nCount] = msgQueue->server_queue;
2048       ret = WaitForMultipleObjects( nCount+1, handles, fWaitAll, dwMilliseconds );
2049     } 
2050     QUEUE_Unlock( msgQueue );
2051     return ret;
2052 }
2053
2054
2055
2056 struct accent_char
2057 {
2058     BYTE ac_accent;
2059     BYTE ac_char;
2060     BYTE ac_result;
2061 };
2062
2063 static const struct accent_char accent_chars[] =
2064 {
2065 /* A good idea should be to read /usr/X11/lib/X11/locale/iso8859-x/Compose */
2066     {'`', 'A', '\300'},  {'`', 'a', '\340'},
2067     {'\'', 'A', '\301'}, {'\'', 'a', '\341'},
2068     {'^', 'A', '\302'},  {'^', 'a', '\342'},
2069     {'~', 'A', '\303'},  {'~', 'a', '\343'},
2070     {'"', 'A', '\304'},  {'"', 'a', '\344'},
2071     {'O', 'A', '\305'},  {'o', 'a', '\345'},
2072     {'0', 'A', '\305'},  {'0', 'a', '\345'},
2073     {'A', 'A', '\305'},  {'a', 'a', '\345'},
2074     {'A', 'E', '\306'},  {'a', 'e', '\346'},
2075     {',', 'C', '\307'},  {',', 'c', '\347'},
2076     {'`', 'E', '\310'},  {'`', 'e', '\350'},
2077     {'\'', 'E', '\311'}, {'\'', 'e', '\351'},
2078     {'^', 'E', '\312'},  {'^', 'e', '\352'},
2079     {'"', 'E', '\313'},  {'"', 'e', '\353'},
2080     {'`', 'I', '\314'},  {'`', 'i', '\354'},
2081     {'\'', 'I', '\315'}, {'\'', 'i', '\355'},
2082     {'^', 'I', '\316'},  {'^', 'i', '\356'},
2083     {'"', 'I', '\317'},  {'"', 'i', '\357'},
2084     {'-', 'D', '\320'},  {'-', 'd', '\360'},
2085     {'~', 'N', '\321'},  {'~', 'n', '\361'},
2086     {'`', 'O', '\322'},  {'`', 'o', '\362'},
2087     {'\'', 'O', '\323'}, {'\'', 'o', '\363'},
2088     {'^', 'O', '\324'},  {'^', 'o', '\364'},
2089     {'~', 'O', '\325'},  {'~', 'o', '\365'},
2090     {'"', 'O', '\326'},  {'"', 'o', '\366'},
2091     {'/', 'O', '\330'},  {'/', 'o', '\370'},
2092     {'`', 'U', '\331'},  {'`', 'u', '\371'},
2093     {'\'', 'U', '\332'}, {'\'', 'u', '\372'},
2094     {'^', 'U', '\333'},  {'^', 'u', '\373'},
2095     {'"', 'U', '\334'},  {'"', 'u', '\374'},
2096     {'\'', 'Y', '\335'}, {'\'', 'y', '\375'},
2097     {'T', 'H', '\336'},  {'t', 'h', '\376'},
2098     {'s', 's', '\337'},  {'"', 'y', '\377'},
2099     {'s', 'z', '\337'},  {'i', 'j', '\377'},
2100         /* iso-8859-2 uses this */
2101     {'<', 'L', '\245'},  {'<', 'l', '\265'},    /* caron */
2102     {'<', 'S', '\251'},  {'<', 's', '\271'},
2103     {'<', 'T', '\253'},  {'<', 't', '\273'},
2104     {'<', 'Z', '\256'},  {'<', 'z', '\276'},
2105     {'<', 'C', '\310'},  {'<', 'c', '\350'},
2106     {'<', 'E', '\314'},  {'<', 'e', '\354'},
2107     {'<', 'D', '\317'},  {'<', 'd', '\357'},
2108     {'<', 'N', '\322'},  {'<', 'n', '\362'},
2109     {'<', 'R', '\330'},  {'<', 'r', '\370'},
2110     {';', 'A', '\241'},  {';', 'a', '\261'},    /* ogonek */
2111     {';', 'E', '\312'},  {';', 'e', '\332'},
2112     {'\'', 'Z', '\254'}, {'\'', 'z', '\274'},   /* acute */
2113     {'\'', 'R', '\300'}, {'\'', 'r', '\340'},
2114     {'\'', 'L', '\305'}, {'\'', 'l', '\345'},
2115     {'\'', 'C', '\306'}, {'\'', 'c', '\346'},
2116     {'\'', 'N', '\321'}, {'\'', 'n', '\361'},
2117 /*  collision whith S, from iso-8859-9 !!! */
2118     {',', 'S', '\252'},  {',', 's', '\272'},    /* cedilla */
2119     {',', 'T', '\336'},  {',', 't', '\376'},
2120     {'.', 'Z', '\257'},  {'.', 'z', '\277'},    /* dot above */
2121     {'/', 'L', '\243'},  {'/', 'l', '\263'},    /* slash */
2122     {'/', 'D', '\320'},  {'/', 'd', '\360'},
2123     {'(', 'A', '\303'},  {'(', 'a', '\343'},    /* breve */
2124     {'\275', 'O', '\325'}, {'\275', 'o', '\365'},       /* double acute */
2125     {'\275', 'U', '\334'}, {'\275', 'u', '\374'},
2126     {'0', 'U', '\332'},  {'0', 'u', '\372'},    /* ring above */
2127         /* iso-8859-3 uses this */
2128     {'/', 'H', '\241'},  {'/', 'h', '\261'},    /* slash */
2129     {'>', 'H', '\246'},  {'>', 'h', '\266'},    /* circumflex */
2130     {'>', 'J', '\254'},  {'>', 'j', '\274'},
2131     {'>', 'C', '\306'},  {'>', 'c', '\346'},
2132     {'>', 'G', '\330'},  {'>', 'g', '\370'},
2133     {'>', 'S', '\336'},  {'>', 's', '\376'},
2134 /*  collision whith G( from iso-8859-9 !!!   */
2135     {'(', 'G', '\253'},  {'(', 'g', '\273'},    /* breve */
2136     {'(', 'U', '\335'},  {'(', 'u', '\375'},
2137 /*  collision whith I. from iso-8859-3 !!!   */
2138     {'.', 'I', '\251'},  {'.', 'i', '\271'},    /* dot above */
2139     {'.', 'C', '\305'},  {'.', 'c', '\345'},
2140     {'.', 'G', '\325'},  {'.', 'g', '\365'},
2141         /* iso-8859-4 uses this */
2142     {',', 'R', '\243'},  {',', 'r', '\263'},    /* cedilla */
2143     {',', 'L', '\246'},  {',', 'l', '\266'},
2144     {',', 'G', '\253'},  {',', 'g', '\273'},
2145     {',', 'N', '\321'},  {',', 'n', '\361'},
2146     {',', 'K', '\323'},  {',', 'k', '\363'},
2147     {'~', 'I', '\245'},  {'~', 'i', '\265'},    /* tilde */
2148     {'-', 'E', '\252'},  {'-', 'e', '\272'},    /* macron */
2149     {'-', 'A', '\300'},  {'-', 'a', '\340'},
2150     {'-', 'I', '\317'},  {'-', 'i', '\357'},
2151     {'-', 'O', '\322'},  {'-', 'o', '\362'},
2152     {'-', 'U', '\336'},  {'-', 'u', '\376'},
2153     {'/', 'T', '\254'},  {'/', 't', '\274'},    /* slash */
2154     {'.', 'E', '\314'},  {'.', 'e', '\344'},    /* dot above */
2155     {';', 'I', '\307'},  {';', 'i', '\347'},    /* ogonek */
2156     {';', 'U', '\331'},  {';', 'u', '\371'},
2157         /* iso-8859-9 uses this */
2158         /* iso-8859-9 has really bad choosen G( S, and I. as they collide
2159          * whith the same letters on other iso-8859-x (that is they are on
2160          * different places :-( ), if you use turkish uncomment these and
2161          * comment out the lines in iso-8859-2 and iso-8859-3 sections
2162          * FIXME: should be dynamic according to chosen language
2163          *        if/when Wine has turkish support.  
2164          */ 
2165 /*  collision whith G( from iso-8859-3 !!!   */
2166 /*  {'(', 'G', '\320'},  {'(', 'g', '\360'}, */ /* breve */
2167 /*  collision whith S, from iso-8859-2 !!! */
2168 /*  {',', 'S', '\336'},  {',', 's', '\376'}, */ /* cedilla */
2169 /*  collision whith I. from iso-8859-3 !!!   */
2170 /*  {'.', 'I', '\335'},  {'.', 'i', '\375'}, */ /* dot above */
2171 };
2172
2173
2174 /***********************************************************************
2175  *           MSG_DoTranslateMessage
2176  *
2177  * Implementation of TranslateMessage.
2178  *
2179  * TranslateMessage translates virtual-key messages into character-messages,
2180  * as follows :
2181  * WM_KEYDOWN/WM_KEYUP combinations produce a WM_CHAR or WM_DEADCHAR message.
2182  * ditto replacing WM_* with WM_SYS*
2183  * This produces WM_CHAR messages only for keys mapped to ASCII characters
2184  * by the keyboard driver.
2185  */
2186 static BOOL MSG_DoTranslateMessage( UINT message, HWND hwnd,
2187                                       WPARAM wParam, LPARAM lParam )
2188 {
2189     static int dead_char;
2190     WCHAR wp[2];
2191     
2192     if (message != WM_MOUSEMOVE && message != WM_TIMER)
2193         TRACE("(%s, %04X, %08lX)\n",
2194                      SPY_GetMsgName(message), wParam, lParam );
2195     if(message >= WM_KEYFIRST && message <= WM_KEYLAST)
2196         TRACE_(key)("(%s, %04X, %08lX)\n",
2197                      SPY_GetMsgName(message), wParam, lParam );
2198
2199     if ((message != WM_KEYDOWN) && (message != WM_SYSKEYDOWN))  return FALSE;
2200
2201     TRACE_(key)("Translating key %s (%04x), scancode %02x\n",
2202                  SPY_GetVKeyName(wParam), wParam, LOBYTE(HIWORD(lParam)));
2203
2204     /* FIXME : should handle ToUnicode yielding 2 */
2205     switch (ToUnicode(wParam, HIWORD(lParam), QueueKeyStateTable, wp, 2, 0)) 
2206     {
2207     case 1 :
2208         message = (message == WM_KEYDOWN) ? WM_CHAR : WM_SYSCHAR;
2209         /* Should dead chars handling go in ToAscii ? */
2210         if (dead_char)
2211         {
2212             int i;
2213
2214             if (wp[0] == ' ') wp[0] =  dead_char;
2215             if (dead_char == 0xa2) dead_char = '(';
2216             else if (dead_char == 0xa8) dead_char = '"';
2217             else if (dead_char == 0xb2) dead_char = ';';
2218             else if (dead_char == 0xb4) dead_char = '\'';
2219             else if (dead_char == 0xb7) dead_char = '<';
2220             else if (dead_char == 0xb8) dead_char = ',';
2221             else if (dead_char == 0xff) dead_char = '.';
2222             for (i = 0; i < sizeof(accent_chars)/sizeof(accent_chars[0]); i++)
2223                 if ((accent_chars[i].ac_accent == dead_char) &&
2224                     (accent_chars[i].ac_char == wp[0]))
2225                 {
2226                     wp[0] = accent_chars[i].ac_result;
2227                     break;
2228                 }
2229             dead_char = 0;
2230         }
2231         TRACE_(key)("1 -> PostMessage(%s)\n", SPY_GetMsgName(message));
2232         PostMessageW( hwnd, message, wp[0], lParam );
2233         return TRUE;
2234
2235     case -1 :
2236         message = (message == WM_KEYDOWN) ? WM_DEADCHAR : WM_SYSDEADCHAR;
2237         dead_char = wp[0];
2238         TRACE_(key)("-1 -> PostMessage(%s)\n", SPY_GetMsgName(message));
2239         PostMessageW( hwnd, message, wp[0], lParam );
2240         return TRUE;
2241     }
2242     return FALSE;
2243 }
2244
2245
2246 /***********************************************************************
2247  *           TranslateMessage16   (USER.113)
2248  */
2249 BOOL16 WINAPI TranslateMessage16( const MSG16 *msg )
2250 {
2251     return MSG_DoTranslateMessage( msg->message, msg->hwnd,
2252                                    msg->wParam, msg->lParam );
2253 }
2254
2255
2256 /***********************************************************************
2257  *           TranslateMessage32   (USER.821)
2258  */
2259 BOOL16 WINAPI TranslateMessage32_16( const MSG32_16 *msg, BOOL16 wHaveParamHigh )
2260 {
2261     WPARAM wParam;
2262
2263     if (wHaveParamHigh)
2264         wParam = MAKELONG(msg->msg.wParam, msg->wParamHigh);
2265     else
2266         wParam = (WPARAM)msg->msg.wParam;
2267
2268     return MSG_DoTranslateMessage( msg->msg.message, msg->msg.hwnd,
2269                                    wParam, msg->msg.lParam );
2270 }
2271
2272 /***********************************************************************
2273  *           TranslateMessage   (USER32.556)
2274  */
2275 BOOL WINAPI TranslateMessage( const MSG *msg )
2276 {
2277     return MSG_DoTranslateMessage( msg->message, msg->hwnd,
2278                                    msg->wParam, msg->lParam );
2279 }
2280
2281
2282 /***********************************************************************
2283  *           DispatchMessage16   (USER.114)
2284  */
2285 LONG WINAPI DispatchMessage16( const MSG16* msg )
2286 {
2287     WND * wndPtr;
2288     LONG retval;
2289     int painting;
2290     
2291       /* Process timer messages */
2292     if ((msg->message == WM_TIMER) || (msg->message == WM_SYSTIMER))
2293     {
2294         if (msg->lParam)
2295         {
2296             /* before calling window proc, verify it the timer is still valid,
2297                there's a slim chance the application kill the timer between
2298                getMessage and DisaptachMessage API calls */
2299             if (!TIMER_IsTimerValid(msg->hwnd, (UINT) msg->wParam, (HWINDOWPROC) msg->lParam))
2300                 return 0; /* invalid winproc */
2301
2302             return CallWindowProc16( (WNDPROC16)msg->lParam, msg->hwnd,
2303                                    msg->message, msg->wParam, GetTickCount() );
2304         }
2305     }
2306
2307     if (!msg->hwnd) return 0;
2308     if (!(wndPtr = WIN_FindWndPtr( msg->hwnd ))) return 0;
2309     if (!wndPtr->winproc)
2310     {
2311         retval = 0;
2312         goto END;
2313     }
2314     painting = (msg->message == WM_PAINT);
2315     if (painting) wndPtr->flags |= WIN_NEEDS_BEGINPAINT;
2316
2317     SPY_EnterMessage( SPY_DISPATCHMESSAGE16, msg->hwnd, msg->message,
2318                       msg->wParam, msg->lParam );
2319     retval = CallWindowProc16( (WNDPROC16)wndPtr->winproc,
2320                                msg->hwnd, msg->message,
2321                                msg->wParam, msg->lParam );
2322     SPY_ExitMessage( SPY_RESULT_OK16, msg->hwnd, msg->message, retval, 
2323                      msg->wParam, msg->lParam );
2324
2325     WIN_ReleaseWndPtr(wndPtr);
2326     wndPtr = WIN_FindWndPtr(msg->hwnd);
2327     if (painting && wndPtr &&
2328         (wndPtr->flags & WIN_NEEDS_BEGINPAINT) && wndPtr->hrgnUpdate)
2329     {
2330         ERR("BeginPaint not called on WM_PAINT for hwnd %04x!\n", 
2331             msg->hwnd);
2332         wndPtr->flags &= ~WIN_NEEDS_BEGINPAINT;
2333         /* Validate the update region to avoid infinite WM_PAINT loop */
2334         ValidateRect( msg->hwnd, NULL );
2335     }
2336 END:
2337     WIN_ReleaseWndPtr(wndPtr);
2338     return retval;
2339 }
2340
2341
2342 /***********************************************************************
2343  *           DispatchMessage32   (USER.822)
2344  */
2345 LONG WINAPI DispatchMessage32_16( const MSG32_16* lpmsg16_32, BOOL16 wHaveParamHigh )
2346 {
2347     if (wHaveParamHigh == FALSE)
2348         return DispatchMessage16(&(lpmsg16_32->msg));
2349     else
2350     {
2351         MSG msg;
2352
2353         msg.hwnd = lpmsg16_32->msg.hwnd;
2354         msg.message = lpmsg16_32->msg.message;
2355         msg.wParam = MAKELONG(lpmsg16_32->msg.wParam, lpmsg16_32->wParamHigh);
2356         msg.lParam = lpmsg16_32->msg.lParam;
2357         msg.time = lpmsg16_32->msg.time;
2358         msg.pt.x = (INT)lpmsg16_32->msg.pt.x;
2359         msg.pt.y = (INT)lpmsg16_32->msg.pt.y;
2360         return DispatchMessageA(&msg);
2361     }
2362 }
2363
2364 /***********************************************************************
2365  *           DispatchMessageA   (USER32.141)
2366  */
2367 LONG WINAPI DispatchMessageA( const MSG* msg )
2368 {
2369     WND * wndPtr;
2370     LONG retval;
2371     int painting;
2372     
2373       /* Process timer messages */
2374     if ((msg->message == WM_TIMER) || (msg->message == WM_SYSTIMER))
2375     {
2376         if (msg->lParam)
2377         {
2378 /*            HOOK_CallHooks32A( WH_CALLWNDPROC, HC_ACTION, 0, FIXME ); */
2379
2380             /* before calling window proc, verify it the timer is still valid,
2381                there's a slim chance the application kill the timer between
2382                getMessage and DisaptachMessage API calls */
2383             if (!TIMER_IsTimerValid(msg->hwnd, (UINT) msg->wParam, (HWINDOWPROC) msg->lParam))
2384                 return 0; /* invalid winproc */
2385
2386             return CallWindowProcA( (WNDPROC)msg->lParam, msg->hwnd,
2387                                    msg->message, msg->wParam, GetTickCount() );
2388         }
2389     }
2390
2391     if (!msg->hwnd) return 0;
2392     if (!(wndPtr = WIN_FindWndPtr( msg->hwnd ))) return 0;
2393     if (!wndPtr->winproc)
2394     {
2395         retval = 0;
2396         goto END;
2397     }
2398     painting = (msg->message == WM_PAINT);
2399     if (painting) wndPtr->flags |= WIN_NEEDS_BEGINPAINT;
2400 /*    HOOK_CallHooks32A( WH_CALLWNDPROC, HC_ACTION, 0, FIXME ); */
2401
2402     SPY_EnterMessage( SPY_DISPATCHMESSAGE, msg->hwnd, msg->message,
2403                       msg->wParam, msg->lParam );
2404     retval = CallWindowProcA( (WNDPROC)wndPtr->winproc,
2405                                 msg->hwnd, msg->message,
2406                                 msg->wParam, msg->lParam );
2407     SPY_ExitMessage( SPY_RESULT_OK, msg->hwnd, msg->message, retval,
2408                      msg->wParam, msg->lParam );
2409
2410     WIN_ReleaseWndPtr(wndPtr);
2411     wndPtr = WIN_FindWndPtr(msg->hwnd);
2412
2413     if (painting && wndPtr &&
2414         (wndPtr->flags & WIN_NEEDS_BEGINPAINT) && wndPtr->hrgnUpdate)
2415     {
2416         ERR("BeginPaint not called on WM_PAINT for hwnd %04x!\n", 
2417             msg->hwnd);
2418         wndPtr->flags &= ~WIN_NEEDS_BEGINPAINT;
2419         /* Validate the update region to avoid infinite WM_PAINT loop */
2420         PAINT_RedrawWindow( wndPtr->hwndSelf, NULL, 0,
2421                         RDW_FRAME | RDW_VALIDATE | RDW_NOCHILDREN | RDW_NOINTERNALPAINT, 0 );  
2422     }
2423 END:
2424     WIN_ReleaseWndPtr(wndPtr);
2425     return retval;
2426 }
2427
2428
2429 /***********************************************************************
2430  *           DispatchMessageW   (USER32.142)     Process Message
2431  *
2432  * Process the message specified in the structure *_msg_.
2433  *
2434  * If the lpMsg parameter points to a WM_TIMER message and the
2435  * parameter of the WM_TIMER message is not NULL, the lParam parameter
2436  * points to the function that is called instead of the window
2437  * procedure.
2438  *  
2439  * The message must be valid.
2440  *
2441  * RETURNS
2442  *
2443  *   DispatchMessage() returns the result of the window procedure invoked.
2444  *
2445  * CONFORMANCE
2446  *
2447  *   ECMA-234, Win32 
2448  *
2449  */
2450 LONG WINAPI DispatchMessageW( const MSG* msg )
2451 {
2452     WND * wndPtr;
2453     LONG retval;
2454     int painting;
2455     
2456       /* Process timer messages */
2457     if ((msg->message == WM_TIMER) || (msg->message == WM_SYSTIMER))
2458     {
2459         if (msg->lParam)
2460         {
2461 /*            HOOK_CallHooks32W( WH_CALLWNDPROC, HC_ACTION, 0, FIXME ); */
2462
2463             /* before calling window proc, verify it the timer is still valid,
2464                there's a slim chance the application kill the timer between
2465                getMessage and DisaptachMessage API calls */
2466             if (!TIMER_IsTimerValid(msg->hwnd, (UINT) msg->wParam, (HWINDOWPROC) msg->lParam))
2467                 return 0; /* invalid winproc */
2468
2469             return CallWindowProcW( (WNDPROC)msg->lParam, msg->hwnd,
2470                                    msg->message, msg->wParam, GetTickCount() );
2471         }
2472     }
2473
2474     if (!msg->hwnd) return 0;
2475     if (!(wndPtr = WIN_FindWndPtr( msg->hwnd ))) return 0;
2476     if (!wndPtr->winproc)
2477     {
2478         retval = 0;
2479         goto END;
2480     }
2481     painting = (msg->message == WM_PAINT);
2482     if (painting) wndPtr->flags |= WIN_NEEDS_BEGINPAINT;
2483 /*    HOOK_CallHooks32W( WH_CALLWNDPROC, HC_ACTION, 0, FIXME ); */
2484
2485     SPY_EnterMessage( SPY_DISPATCHMESSAGE, msg->hwnd, msg->message,
2486                       msg->wParam, msg->lParam );
2487     retval = CallWindowProcW( (WNDPROC)wndPtr->winproc,
2488                                 msg->hwnd, msg->message,
2489                                 msg->wParam, msg->lParam );
2490     SPY_ExitMessage( SPY_RESULT_OK, msg->hwnd, msg->message, retval,
2491                      msg->wParam, msg->lParam );
2492
2493     WIN_ReleaseWndPtr(wndPtr);
2494     wndPtr = WIN_FindWndPtr(msg->hwnd);
2495
2496     if (painting && wndPtr &&
2497         (wndPtr->flags & WIN_NEEDS_BEGINPAINT) && wndPtr->hrgnUpdate)
2498     {
2499         ERR("BeginPaint not called on WM_PAINT for hwnd %04x!\n", 
2500             msg->hwnd);
2501         wndPtr->flags &= ~WIN_NEEDS_BEGINPAINT;
2502         /* Validate the update region to avoid infinite WM_PAINT loop */
2503         ValidateRect( msg->hwnd, NULL );
2504     }
2505 END:
2506     WIN_ReleaseWndPtr(wndPtr);
2507     return retval;
2508 }
2509
2510
2511 /***********************************************************************
2512  *           RegisterWindowMessageA   (USER.118) (USER32.437)
2513  */
2514 WORD WINAPI RegisterWindowMessageA( LPCSTR str )
2515 {
2516     TRACE("%s\n", str );
2517     return GlobalAddAtomA( str );
2518 }
2519
2520
2521 /***********************************************************************
2522  *           RegisterWindowMessageW   (USER32.438)
2523  */
2524 WORD WINAPI RegisterWindowMessageW( LPCWSTR str )
2525 {
2526     TRACE("%p\n", str );
2527     return GlobalAddAtomW( str );
2528 }
2529
2530
2531 /***********************************************************************
2532  *           GetCurrentTime16    (USER.15)
2533  *
2534  * (effectively identical to GetTickCount)
2535  */
2536 DWORD WINAPI GetCurrentTime16(void)
2537 {
2538     return GetTickCount();
2539 }
2540
2541
2542 /***********************************************************************
2543  *           InSendMessage16    (USER.192)
2544  */
2545 BOOL16 WINAPI InSendMessage16(void)
2546 {
2547     return InSendMessage();
2548 }
2549
2550
2551 /***********************************************************************
2552  *           InSendMessage    (USER32.320)
2553  */
2554 BOOL WINAPI InSendMessage(void)
2555 {
2556     MESSAGEQUEUE *queue;
2557     BOOL ret;
2558
2559     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() )))
2560         return 0;
2561     ret = (BOOL)queue->smWaiting;
2562
2563     QUEUE_Unlock( queue );
2564     return ret;
2565 }
2566
2567 /***********************************************************************
2568  *           BroadcastSystemMessage    (USER32.12)
2569  */
2570 LONG WINAPI BroadcastSystemMessage(
2571         DWORD dwFlags,LPDWORD recipients,UINT uMessage,WPARAM wParam,
2572         LPARAM lParam
2573 ) {
2574         FIXME_(sendmsg)("(%08lx,%08lx,%08x,%08x,%08lx): stub!\n",
2575               dwFlags,*recipients,uMessage,wParam,lParam
2576         );
2577         return 0;
2578 }
2579
2580 /***********************************************************************
2581  *           SendNotifyMessageA    (USER32.460)
2582  */
2583 BOOL WINAPI SendNotifyMessageA(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
2584 {
2585    return MSG_SendMessage(hwnd, msg, wParam, lParam, INFINITE,
2586                           SMSG_WIN32, NULL);
2587 }
2588
2589 /***********************************************************************
2590  *           SendNotifyMessageW    (USER32.461)
2591  */
2592 BOOL WINAPI SendNotifyMessageW(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
2593 {
2594    return MSG_SendMessage(hwnd, msg, wParam, lParam, INFINITE,
2595                           SMSG_WIN32 | SMSG_UNICODE, NULL);
2596 }
2597
2598 /***********************************************************************
2599  *           SendMessageCallbackA
2600  * FIXME: It's like PostMessage. The callback gets called when the message
2601  * is processed. We have to modify the message processing for a exact
2602  * implementation...
2603  */
2604 BOOL WINAPI SendMessageCallbackA(
2605         HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam,
2606         FARPROC lpResultCallBack,DWORD dwData)
2607 {       
2608         FIXME("(0x%04x,0x%04x,0x%08x,0x%08lx,%p,0x%08lx),stub!\n",
2609               hWnd,Msg,wParam,lParam,lpResultCallBack,dwData);
2610         if ( hWnd == HWND_BROADCAST)
2611         {       PostMessageA( hWnd, Msg, wParam, lParam);
2612                 FIXME("Broadcast: Callback will not be called!\n");
2613                 return TRUE;
2614         }
2615         (lpResultCallBack)( hWnd, Msg, dwData, SendMessageA ( hWnd, Msg, wParam, lParam ));
2616                 return TRUE;
2617 }
2618 /***********************************************************************
2619  *           SendMessageCallbackW
2620  * FIXME: It's like PostMessage. The callback gets called when the message
2621  * is processed. We have to modify the message processing for a exact
2622  * implementation...
2623  */
2624 BOOL WINAPI SendMessageCallbackW(
2625         HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam,
2626         FARPROC lpResultCallBack,DWORD dwData)
2627 {       
2628         FIXME("(0x%04x,0x%04x,0x%08x,0x%08lx,%p,0x%08lx),stub!\n",
2629               hWnd,Msg,wParam,lParam,lpResultCallBack,dwData);
2630         if ( hWnd == HWND_BROADCAST)
2631         {       PostMessageW( hWnd, Msg, wParam, lParam);
2632                 FIXME("Broadcast: Callback will not be called!\n");
2633                 return TRUE;
2634         }
2635         (lpResultCallBack)( hWnd, Msg, dwData, SendMessageA ( hWnd, Msg, wParam, lParam ));
2636                 return TRUE;
2637 }