We don't need to call LPtoDP in here as far as PatBlt does it internally.
[wine] / windows / queue.c
1 /* * Message queues related functions
2  *
3  * Copyright 1993, 1994 Alexandre Julliard
4  */
5
6 #include <string.h>
7 #include <signal.h>
8 #include <assert.h>
9 #include "windef.h"
10 #include "wingdi.h"
11 #include "wine/winbase16.h"
12 #include "wine/winuser16.h"
13 #include "miscemu.h"
14 #include "syslevel.h"
15 #include "module.h"
16 #include "queue.h"
17 #include "task.h"
18 #include "win.h"
19 #include "clipboard.h"
20 #include "hook.h"
21 #include "heap.h"
22 #include "thread.h"
23 #include "process.h"
24 #include "debugtools.h"
25 #include "spy.h"
26
27 DECLARE_DEBUG_CHANNEL(msg)
28 DECLARE_DEBUG_CHANNEL(sendmsg)
29
30 #define MAX_QUEUE_SIZE   120  /* Max. size of a message queue */
31
32 static HQUEUE16 hFirstQueue = 0;
33 static HQUEUE16 hExitingQueue = 0;
34 static HQUEUE16 hmemSysMsgQueue = 0;
35 static MESSAGEQUEUE *sysMsgQueue = NULL;
36 static PERQUEUEDATA *pQDataWin16 = NULL;  /* Global perQData for Win16 tasks */
37
38 static MESSAGEQUEUE *pMouseQueue = NULL;  /* Queue for last mouse message */
39 static MESSAGEQUEUE *pKbdQueue = NULL;    /* Queue for last kbd message */
40
41 HQUEUE16 hCursorQueue = 0;
42 HQUEUE16 hActiveQueue = 0;
43
44
45 /***********************************************************************
46  *           PERQDATA_CreateInstance
47  *
48  * Creates an instance of a reference counted PERQUEUEDATA element
49  * for the message queue. perQData is stored globally for 16 bit tasks.
50  *
51  * Note: We don't implement perQdata exactly the same way Windows does.
52  * Each perQData element is reference counted since it may be potentially
53  * shared by multiple message Queues (via AttachThreadInput).
54  * We only store the current values for Active, Capture and focus windows
55  * currently.
56  */
57 PERQUEUEDATA * PERQDATA_CreateInstance( )
58 {
59     PERQUEUEDATA *pQData;
60     
61     BOOL16 bIsWin16 = 0;
62     
63     TRACE_(msg)("()\n");
64
65     /* Share a single instance of perQData for all 16 bit tasks */
66     if ( ( bIsWin16 = THREAD_IsWin16( NtCurrentTeb() ) ) )
67     {
68         /* If previously allocated, just bump up ref count */
69         if ( pQDataWin16 )
70         {
71             PERQDATA_Addref( pQDataWin16 );
72             return pQDataWin16;
73         }
74     }
75
76     /* Allocate PERQUEUEDATA from the system heap */
77     if (!( pQData = (PERQUEUEDATA *) HeapAlloc( SystemHeap, 0,
78                                                     sizeof(PERQUEUEDATA) ) ))
79         return 0;
80
81     /* Initialize */
82     pQData->hWndCapture = pQData->hWndFocus = pQData->hWndActive = 0;
83     pQData->ulRefCount = 1;
84     pQData->nCaptureHT = HTCLIENT;
85
86     /* Note: We have an independent critical section for the per queue data
87      * since this may be shared by different threads. see AttachThreadInput()
88      */
89     InitializeCriticalSection( &pQData->cSection );
90     /* FIXME: not all per queue data critical sections should be global */
91     MakeCriticalSectionGlobal( &pQData->cSection );
92
93     /* Save perQData globally for 16 bit tasks */
94     if ( bIsWin16 )
95         pQDataWin16 = pQData;
96         
97     return pQData;
98 }
99
100
101 /***********************************************************************
102  *           PERQDATA_Addref
103  *
104  * Increment reference count for the PERQUEUEDATA instance
105  * Returns reference count for debugging purposes
106  */
107 ULONG PERQDATA_Addref( PERQUEUEDATA *pQData )
108 {
109     assert(pQData != 0 );
110     TRACE_(msg)("(): current refcount %lu ...\n", pQData->ulRefCount);
111
112     EnterCriticalSection( &pQData->cSection );
113     ++pQData->ulRefCount;
114     LeaveCriticalSection( &pQData->cSection );
115
116     return pQData->ulRefCount;
117 }
118
119
120 /***********************************************************************
121  *           PERQDATA_Release
122  *
123  * Release a reference to a PERQUEUEDATA instance.
124  * Destroy the instance if no more references exist
125  * Returns reference count for debugging purposes
126  */
127 ULONG PERQDATA_Release( PERQUEUEDATA *pQData )
128 {
129     assert(pQData != 0 );
130     TRACE_(msg)("(): current refcount %lu ...\n",
131           (LONG)pQData->ulRefCount );
132
133     EnterCriticalSection( &pQData->cSection );
134     if ( --pQData->ulRefCount == 0 )
135     {
136         LeaveCriticalSection( &pQData->cSection );
137         DeleteCriticalSection( &pQData->cSection );
138
139         TRACE_(msg)("(): deleting PERQUEUEDATA instance ...\n" );
140
141         /* Deleting our global 16 bit perQData? */
142         if ( pQData == pQDataWin16 )
143             pQDataWin16 = 0;
144             
145         /* Free the PERQUEUEDATA instance */
146         HeapFree( SystemHeap, 0, pQData );
147
148         return 0;
149     }
150     LeaveCriticalSection( &pQData->cSection );
151
152     return pQData->ulRefCount;
153 }
154
155
156 /***********************************************************************
157  *           PERQDATA_GetFocusWnd
158  *
159  * Get the focus hwnd member in a threadsafe manner
160  */
161 HWND PERQDATA_GetFocusWnd( PERQUEUEDATA *pQData )
162 {
163     HWND hWndFocus;
164     assert(pQData != 0 );
165
166     EnterCriticalSection( &pQData->cSection );
167     hWndFocus = pQData->hWndFocus;
168     LeaveCriticalSection( &pQData->cSection );
169
170     return hWndFocus;
171 }
172
173
174 /***********************************************************************
175  *           PERQDATA_SetFocusWnd
176  *
177  * Set the focus hwnd member in a threadsafe manner
178  */
179 HWND PERQDATA_SetFocusWnd( PERQUEUEDATA *pQData, HWND hWndFocus )
180 {
181     HWND hWndFocusPrv;
182     assert(pQData != 0 );
183
184     EnterCriticalSection( &pQData->cSection );
185     hWndFocusPrv = pQData->hWndFocus;
186     pQData->hWndFocus = hWndFocus;
187     LeaveCriticalSection( &pQData->cSection );
188
189     return hWndFocusPrv;
190 }
191
192
193 /***********************************************************************
194  *           PERQDATA_GetActiveWnd
195  *
196  * Get the active hwnd member in a threadsafe manner
197  */
198 HWND PERQDATA_GetActiveWnd( PERQUEUEDATA *pQData )
199 {
200     HWND hWndActive;
201     assert(pQData != 0 );
202
203     EnterCriticalSection( &pQData->cSection );
204     hWndActive = pQData->hWndActive;
205     LeaveCriticalSection( &pQData->cSection );
206
207     return hWndActive;
208 }
209
210
211 /***********************************************************************
212  *           PERQDATA_SetActiveWnd
213  *
214  * Set the active focus hwnd member in a threadsafe manner
215  */
216 HWND PERQDATA_SetActiveWnd( PERQUEUEDATA *pQData, HWND hWndActive )
217 {
218     HWND hWndActivePrv;
219     assert(pQData != 0 );
220
221     EnterCriticalSection( &pQData->cSection );
222     hWndActivePrv = pQData->hWndActive;
223     pQData->hWndActive = hWndActive;
224     LeaveCriticalSection( &pQData->cSection );
225
226     return hWndActivePrv;
227 }
228
229
230 /***********************************************************************
231  *           PERQDATA_GetCaptureWnd
232  *
233  * Get the capture hwnd member in a threadsafe manner
234  */
235 HWND PERQDATA_GetCaptureWnd( PERQUEUEDATA *pQData )
236 {
237     HWND hWndCapture;
238     assert(pQData != 0 );
239
240     EnterCriticalSection( &pQData->cSection );
241     hWndCapture = pQData->hWndCapture;
242     LeaveCriticalSection( &pQData->cSection );
243
244     return hWndCapture;
245 }
246
247
248 /***********************************************************************
249  *           PERQDATA_SetCaptureWnd
250  *
251  * Set the capture hwnd member in a threadsafe manner
252  */
253 HWND PERQDATA_SetCaptureWnd( PERQUEUEDATA *pQData, HWND hWndCapture )
254 {
255     HWND hWndCapturePrv;
256     assert(pQData != 0 );
257
258     EnterCriticalSection( &pQData->cSection );
259     hWndCapturePrv = pQData->hWndCapture;
260     pQData->hWndCapture = hWndCapture;
261     LeaveCriticalSection( &pQData->cSection );
262
263     return hWndCapturePrv;
264 }
265
266
267 /***********************************************************************
268  *           PERQDATA_GetCaptureInfo
269  *
270  * Get the capture info member in a threadsafe manner
271  */
272 INT16 PERQDATA_GetCaptureInfo( PERQUEUEDATA *pQData )
273 {
274     INT16 nCaptureHT;
275     assert(pQData != 0 );
276
277     EnterCriticalSection( &pQData->cSection );
278     nCaptureHT = pQData->nCaptureHT;
279     LeaveCriticalSection( &pQData->cSection );
280
281     return nCaptureHT;
282 }
283
284
285 /***********************************************************************
286  *           PERQDATA_SetCaptureInfo
287  *
288  * Set the capture info member in a threadsafe manner
289  */
290 INT16 PERQDATA_SetCaptureInfo( PERQUEUEDATA *pQData, INT16 nCaptureHT )
291 {
292     INT16 nCaptureHTPrv;
293     assert(pQData != 0 );
294
295     EnterCriticalSection( &pQData->cSection );
296     nCaptureHTPrv = pQData->nCaptureHT;
297     pQData->nCaptureHT = nCaptureHT;
298     LeaveCriticalSection( &pQData->cSection );
299
300     return nCaptureHTPrv;
301 }
302
303
304 /***********************************************************************
305  *           QUEUE_Lock
306  *
307  * Function for getting a 32 bit pointer on queue strcture. For thread
308  * safeness programmers should use this function instead of GlobalLock to
309  * retrieve a pointer on the structure. QUEUE_Unlock should also be called
310  * when access to the queue structure is not required anymore.
311  */
312 MESSAGEQUEUE *QUEUE_Lock( HQUEUE16 hQueue )
313 {
314     MESSAGEQUEUE *queue;
315
316     HeapLock( SystemHeap );  /* FIXME: a bit overkill */
317     queue = GlobalLock16( hQueue );
318     if ( !queue || (queue->magic != QUEUE_MAGIC) )
319     {
320         HeapUnlock( SystemHeap );
321         return NULL;
322     }
323
324     queue->lockCount++;
325     HeapUnlock( SystemHeap );
326     return queue;
327 }
328
329
330 /***********************************************************************
331  *           QUEUE_Unlock
332  *
333  * Use with QUEUE_Lock to get a thread safe access to message queue
334  * structure
335  */
336 void QUEUE_Unlock( MESSAGEQUEUE *queue )
337 {
338     if (queue)
339     {
340         HeapLock( SystemHeap );  /* FIXME: a bit overkill */
341
342         if ( --queue->lockCount == 0 )
343         {
344             DeleteCriticalSection ( &queue->cSection );
345             if (queue->hEvent)
346                 CloseHandle( queue->hEvent );
347             GlobalFree16( queue->self );
348         }
349     
350         HeapUnlock( SystemHeap );
351     }
352 }
353
354
355 /***********************************************************************
356  *           QUEUE_DumpQueue
357  */
358 void QUEUE_DumpQueue( HQUEUE16 hQueue )
359 {
360     MESSAGEQUEUE *pq; 
361
362     if (!(pq = (MESSAGEQUEUE*) QUEUE_Lock( hQueue )) )
363     {
364         WARN_(msg)("%04x is not a queue handle\n", hQueue );
365         return;
366     }
367
368     DPRINTF( "next: %12.4x  Intertask SendMessage:\n"
369              "thread: %10p  ----------------------\n"
370              "firstMsg: %8p   smWaiting:     %10p\n"
371              "lastMsg:  %8p   smPending:     %10p\n"
372              "msgCount: %8.4x   smProcessing:  %10p\n"
373              "lockCount: %7.4x\n"
374              "wWinVer: %9.4x\n"
375              "paints: %10.4x\n"
376              "timers: %10.4x\n"
377              "wakeBits: %8.4x\n"
378              "wakeMask: %8.4x\n"
379              "hCurHook: %8.4x\n",
380              pq->next, pq->teb, pq->firstMsg, pq->smWaiting, pq->lastMsg,
381              pq->smPending, pq->msgCount, pq->smProcessing,
382              (unsigned)pq->lockCount, pq->wWinVersion,
383              pq->wPaintCount, pq->wTimerCount,
384              pq->wakeBits, pq->wakeMask, pq->hCurHook);
385
386     QUEUE_Unlock( pq );
387 }
388
389
390 /***********************************************************************
391  *           QUEUE_WalkQueues
392  */
393 void QUEUE_WalkQueues(void)
394 {
395     char module[10];
396     HQUEUE16 hQueue = hFirstQueue;
397
398     DPRINTF( "Queue Msgs Thread   Task Module\n" );
399     while (hQueue)
400     {
401         MESSAGEQUEUE *queue = (MESSAGEQUEUE *)QUEUE_Lock( hQueue );
402         if (!queue)
403         {
404             WARN_(msg)("Bad queue handle %04x\n", hQueue );
405             return;
406         }
407         if (!GetModuleName16( queue->teb->process->task, module, sizeof(module )))
408             strcpy( module, "???" );
409         DPRINTF( "%04x %4d %p %04x %s\n", hQueue,queue->msgCount,
410                  queue->teb, queue->teb->process->task, module );
411         hQueue = queue->next;
412         QUEUE_Unlock( queue );
413     }
414     DPRINTF( "\n" );
415 }
416
417
418 /***********************************************************************
419  *           QUEUE_IsExitingQueue
420  */
421 BOOL QUEUE_IsExitingQueue( HQUEUE16 hQueue )
422 {
423     return (hExitingQueue && (hQueue == hExitingQueue));
424 }
425
426
427 /***********************************************************************
428  *           QUEUE_SetExitingQueue
429  */
430 void QUEUE_SetExitingQueue( HQUEUE16 hQueue )
431 {
432     hExitingQueue = hQueue;
433 }
434
435
436 /***********************************************************************
437  *           QUEUE_CreateMsgQueue
438  *
439  * Creates a message queue. Doesn't link it into queue list!
440  */
441 static HQUEUE16 QUEUE_CreateMsgQueue( BOOL16 bCreatePerQData )
442 {
443     HQUEUE16 hQueue;
444     MESSAGEQUEUE * msgQueue;
445     TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
446
447     TRACE_(msg)("(): Creating message queue...\n");
448
449     if (!(hQueue = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT,
450                                   sizeof(MESSAGEQUEUE) )))
451         return 0;
452
453     msgQueue = (MESSAGEQUEUE *) GlobalLock16( hQueue );
454     if ( !msgQueue )
455         return 0;
456
457     msgQueue->self        = hQueue;
458     msgQueue->wakeBits    = msgQueue->changeBits = 0;
459     msgQueue->wWinVersion = pTask ? pTask->version : 0;
460     
461     InitializeCriticalSection( &msgQueue->cSection );
462     MakeCriticalSectionGlobal( &msgQueue->cSection );
463
464     /* Create an Event object for waiting on message, used by win32 thread
465        only */
466     if ( !THREAD_IsWin16( NtCurrentTeb() ) )
467     {
468         msgQueue->hEvent = CreateEventA( NULL, FALSE, FALSE, NULL);
469
470         if (msgQueue->hEvent == 0)
471         {
472             WARN_(msg)("CreateEventA is not able to create an event object");
473             return 0;
474         }
475         msgQueue->hEvent = ConvertToGlobalHandle( msgQueue->hEvent );
476     }
477     else
478         msgQueue->hEvent = 0;
479          
480     msgQueue->lockCount = 1;
481     msgQueue->magic = QUEUE_MAGIC;
482     
483     /* Create and initialize our per queue data */
484     msgQueue->pQData = bCreatePerQData ? PERQDATA_CreateInstance() : NULL;
485     
486     return hQueue;
487 }
488
489
490 /***********************************************************************
491  *           QUEUE_FlushMessage
492  * 
493  * Try to reply to all pending sent messages on exit.
494  */
495 static void QUEUE_FlushMessages( MESSAGEQUEUE *queue )
496 {
497     SMSG *smsg;
498     MESSAGEQUEUE *senderQ = 0;
499
500     if( queue )
501     {
502         EnterCriticalSection( &queue->cSection );
503
504         /* empty the list of pending SendMessage waiting to be received */
505         while (queue->smPending)
506         {
507             smsg = QUEUE_RemoveSMSG( queue, SM_PENDING_LIST, 0);
508
509             senderQ = (MESSAGEQUEUE*)QUEUE_Lock( smsg->hSrcQueue );
510             if ( !senderQ )
511                 continue;
512
513             /* return 0, to unblock other thread */
514             smsg->lResult = 0;
515             smsg->flags |= SMSG_HAVE_RESULT;
516             QUEUE_SetWakeBit( senderQ, QS_SMRESULT);
517             
518             QUEUE_Unlock( senderQ );
519         }
520
521         QUEUE_ClearWakeBit( queue, QS_SENDMESSAGE );
522         
523         LeaveCriticalSection( &queue->cSection );
524     }
525 }
526
527
528 /***********************************************************************
529  *           QUEUE_DeleteMsgQueue
530  *
531  * Unlinks and deletes a message queue.
532  *
533  * Note: We need to mask asynchronous events to make sure PostMessage works
534  * even in the signal handler.
535  */
536 BOOL QUEUE_DeleteMsgQueue( HQUEUE16 hQueue )
537 {
538     MESSAGEQUEUE * msgQueue = (MESSAGEQUEUE*)QUEUE_Lock(hQueue);
539     HQUEUE16 *pPrev;
540
541     TRACE_(msg)("(): Deleting message queue %04x\n", hQueue);
542
543     if (!hQueue || !msgQueue)
544     {
545         WARN_(msg)("invalid argument.\n");
546         return 0;
547     }
548
549     msgQueue->magic = 0;
550     
551     if( hCursorQueue == hQueue ) hCursorQueue = 0;
552     if( hActiveQueue == hQueue ) hActiveQueue = 0;
553
554     /* flush sent messages */
555     QUEUE_FlushMessages( msgQueue );
556
557     HeapLock( SystemHeap );  /* FIXME: a bit overkill */
558
559     /* Release per queue data if present */
560     if ( msgQueue->pQData )
561     {
562         PERQDATA_Release( msgQueue->pQData );
563         msgQueue->pQData = 0;
564     }
565     
566     /* remove the message queue from the global link list */
567     pPrev = &hFirstQueue;
568     while (*pPrev && (*pPrev != hQueue))
569     {
570         MESSAGEQUEUE *msgQ = (MESSAGEQUEUE*)GlobalLock16(*pPrev);
571
572         /* sanity check */
573         if ( !msgQ || (msgQ->magic != QUEUE_MAGIC) )
574         {
575             /* HQUEUE link list is corrupted, try to exit gracefully */
576             WARN_(msg)("HQUEUE link list corrupted!\n");
577             pPrev = 0;
578             break;
579         }
580         pPrev = &msgQ->next;
581     }
582     if (pPrev && *pPrev) *pPrev = msgQueue->next;
583     msgQueue->self = 0;
584
585     HeapUnlock( SystemHeap );
586
587     /* free up resource used by MESSAGEQUEUE strcture */
588     msgQueue->lockCount--;
589     QUEUE_Unlock( msgQueue );
590     
591     return 1;
592 }
593
594
595 /***********************************************************************
596  *           QUEUE_CreateSysMsgQueue
597  *
598  * Create the system message queue, and set the double-click speed.
599  * Must be called only once.
600  */
601 BOOL QUEUE_CreateSysMsgQueue( int size )
602 {
603     /* Note: We dont need perQ data for the system message queue */
604     if (!(hmemSysMsgQueue = QUEUE_CreateMsgQueue( FALSE )))
605         return FALSE;
606     
607     sysMsgQueue = (MESSAGEQUEUE *) GlobalLock16( hmemSysMsgQueue );
608     return TRUE;
609 }
610
611
612 /***********************************************************************
613  *           QUEUE_GetSysQueue
614  */
615 MESSAGEQUEUE *QUEUE_GetSysQueue(void)
616 {
617     return sysMsgQueue;
618 }
619
620
621 /***********************************************************************
622  *           QUEUE_SetWakeBit
623  *
624  * See "Windows Internals", p.449
625  */
626 void QUEUE_SetWakeBit( MESSAGEQUEUE *queue, WORD bit )
627 {
628     TRACE_(msg)("queue = %04x (wm=%04x), bit = %04x\n", 
629                         queue->self, queue->wakeMask, bit );
630
631     if (bit & QS_MOUSE) pMouseQueue = queue;
632     if (bit & QS_KEY) pKbdQueue = queue;
633     queue->changeBits |= bit;
634     queue->wakeBits   |= bit;
635     if (queue->wakeMask & bit)
636     {
637         queue->wakeMask = 0;
638         
639         /* Wake up thread waiting for message */
640         if ( THREAD_IsWin16( queue->teb ) )
641         {
642             int iWndsLock = WIN_SuspendWndsLock();
643             PostEvent16( queue->teb->process->task );
644             WIN_RestoreWndsLock( iWndsLock );
645         }
646         else
647         {
648             SetEvent( queue->hEvent );
649         }
650     }
651 }
652
653
654 /***********************************************************************
655  *           QUEUE_ClearWakeBit
656  */
657 void QUEUE_ClearWakeBit( MESSAGEQUEUE *queue, WORD bit )
658 {
659     queue->changeBits &= ~bit;
660     queue->wakeBits   &= ~bit;
661 }
662
663
664 /***********************************************************************
665  *           QUEUE_WaitBits
666  *
667  * See "Windows Internals", p.447
668  *
669  * return values:
670  *    0 if exit with timeout
671  *    1 otherwise
672  */
673 int QUEUE_WaitBits( WORD bits, DWORD timeout )
674 {
675     MESSAGEQUEUE *queue;
676     DWORD curTime = 0;
677     HQUEUE16 hQueue;
678     PDB * pdb;
679
680     TRACE_(msg)("q %04x waiting for %04x\n", GetFastQueue16(), bits);
681
682     if ( THREAD_IsWin16( NtCurrentTeb() ) && (timeout != INFINITE) )
683         curTime = GetTickCount();
684
685     hQueue = GetFastQueue16();
686     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( hQueue ))) return 0;
687     
688     pdb = PROCESS_Current();
689
690     for (;;)
691     {
692         if (queue->changeBits & bits)
693         {
694             /* One of the bits is set; we can return */
695             queue->wakeMask = 0;
696             QUEUE_Unlock( queue );
697             return 1;
698         }
699         if (queue->wakeBits & QS_SENDMESSAGE)
700         {
701             /* Process the sent message immediately */
702
703             queue->wakeMask = 0;
704             QUEUE_ReceiveMessage( queue );
705             continue;                           /* nested sm crux */
706         }
707
708         queue->wakeMask = bits | QS_SENDMESSAGE;
709         if(queue->changeBits & bits)
710         {
711             continue;
712         }
713         
714         TRACE_(msg)("%04x) wakeMask is %04x, waiting\n", queue->self, queue->wakeMask);
715
716         if ( !THREAD_IsWin16( NtCurrentTeb() ) )
717         {
718             BOOL                bHasWin16Lock;
719             DWORD               dwlc;
720
721             if ( (bHasWin16Lock = _ConfirmWin16Lock()) )
722             {
723                 TRACE_(msg)("bHasWin16Lock=TRUE\n");
724                 ReleaseThunkLock( &dwlc );
725             }
726
727
728             if ( pdb->main_queue == INVALID_HANDLE_VALUE16 ) 
729             {
730                 pdb->main_queue = hQueue;
731             }
732             if ( pdb->main_queue == hQueue ) 
733             {
734                 SetEvent ( pdb->idle_event );
735             }
736
737             WaitForSingleObject( queue->hEvent, timeout );
738
739             if ( pdb->main_queue == hQueue ) 
740             {
741                 ResetEvent ( pdb->idle_event );
742             }
743
744             if ( bHasWin16Lock ) 
745             {
746                 RestoreThunkLock( dwlc );
747             }
748         }
749         else
750         {
751             SetEvent ( pdb->idle_event );
752
753             if ( timeout == INFINITE )
754                 WaitEvent16( 0 );  /* win 16 thread, use WaitEvent */
755             else
756             {
757                 /* check for timeout, then give control to other tasks */
758                 if (GetTickCount() - curTime > timeout)
759                 {
760
761                     QUEUE_Unlock( queue );
762                     return 0;   /* exit with timeout */
763                 }
764                 Yield16();
765             }
766         }
767     }
768 }
769
770
771 /***********************************************************************
772  *           QUEUE_AddSMSG
773  *
774  * This routine is called when a SMSG need to be added to one of the three
775  * SM list.  (SM_PROCESSING_LIST, SM_PENDING_LIST, SM_WAITING_LIST)
776  */
777 BOOL QUEUE_AddSMSG( MESSAGEQUEUE *queue, int list, SMSG *smsg )
778 {
779     TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
780           smsg, SPY_GetMsgName(smsg->msg));
781     
782     switch (list)
783     {
784         case SM_PROCESSING_LIST:
785             /* don't need to be thread safe, only accessed by the
786              thread associated with the sender queue */
787             smsg->nextProcessing = queue->smProcessing;
788             queue->smProcessing = smsg;
789             break;
790             
791         case SM_WAITING_LIST:
792             /* don't need to be thread safe, only accessed by the
793              thread associated with the receiver queue */
794             smsg->nextWaiting = queue->smWaiting;
795             queue->smWaiting = smsg;
796             break;
797             
798         case SM_PENDING_LIST:
799         {
800             /* make it thread safe, could be accessed by the sender and
801              receiver thread */
802             SMSG **prev;
803
804             EnterCriticalSection( &queue->cSection );
805             smsg->nextPending = NULL;
806             prev = &queue->smPending;
807             while ( *prev )
808                 prev = &(*prev)->nextPending;
809             *prev = smsg;
810             LeaveCriticalSection( &queue->cSection );
811
812             QUEUE_SetWakeBit( queue, QS_SENDMESSAGE );
813             break;
814         }
815
816         default:
817             WARN_(sendmsg)("Invalid list: %d", list);
818             break;
819     }
820
821     return TRUE;
822 }
823
824
825 /***********************************************************************
826  *           QUEUE_RemoveSMSG
827  *
828  * This routine is called when a SMSG need to be remove from one of the three
829  * SM list.  (SM_PROCESSING_LIST, SM_PENDING_LIST, SM_WAITING_LIST)
830  * If smsg == 0, remove the first smsg from the specified list
831  */
832 SMSG *QUEUE_RemoveSMSG( MESSAGEQUEUE *queue, int list, SMSG *smsg )
833 {
834
835     switch (list)
836     {
837         case SM_PROCESSING_LIST:
838             /* don't need to be thread safe, only accessed by the
839              thread associated with the sender queue */
840
841             /* if smsg is equal to null, it means the first in the list */
842             if (!smsg)
843                 smsg = queue->smProcessing;
844
845             TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
846                   smsg, SPY_GetMsgName(smsg->msg));
847             /* In fact SM_PROCESSING_LIST is a stack, and smsg
848              should be always at the top of the list */
849             if ( (smsg != queue->smProcessing) || !queue->smProcessing )
850         {
851                 ERR_(sendmsg)("smsg not at the top of Processing list, smsg=0x%p queue=0x%p", smsg, queue);
852                 return 0;
853             }
854             else
855             {
856                 queue->smProcessing = smsg->nextProcessing;
857                 smsg->nextProcessing = 0;
858         }
859             return smsg;
860
861         case SM_WAITING_LIST:
862             /* don't need to be thread safe, only accessed by the
863              thread associated with the receiver queue */
864
865             /* if smsg is equal to null, it means the first in the list */
866             if (!smsg)
867                 smsg = queue->smWaiting;
868             
869             TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
870                   smsg, SPY_GetMsgName(smsg->msg));
871             /* In fact SM_WAITING_LIST is a stack, and smsg
872              should be always at the top of the list */
873             if ( (smsg != queue->smWaiting) || !queue->smWaiting )
874             {
875                 ERR_(sendmsg)("smsg not at the top of Waiting list, smsg=0x%p queue=0x%p", smsg, queue);
876                 return 0;
877             }
878             else
879             {
880                 queue->smWaiting = smsg->nextWaiting;
881                 smsg->nextWaiting = 0;
882     }
883             return smsg;
884
885         case SM_PENDING_LIST:
886             /* make it thread safe, could be accessed by the sender and
887              receiver thread */
888             EnterCriticalSection( &queue->cSection );
889     
890             if (!smsg || !queue->smPending)
891                 smsg = queue->smPending;
892             else
893             {
894                 ERR_(sendmsg)("should always remove the top one in Pending list, smsg=0x%p queue=0x%p", smsg, queue);
895                                 LeaveCriticalSection( &queue->cSection );
896                 return 0;
897             }
898             
899             TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
900                   smsg, SPY_GetMsgName(smsg->msg));
901
902             queue->smPending = smsg->nextPending;
903             smsg->nextPending = 0;
904
905             /* if no more SMSG in Pending list, clear QS_SENDMESSAGE flag */
906             if (!queue->smPending)
907                 QUEUE_ClearWakeBit( queue, QS_SENDMESSAGE );
908             
909             LeaveCriticalSection( &queue->cSection );
910             return smsg;
911
912         default:
913             WARN_(sendmsg)("Invalid list: %d", list);
914             break;
915     }
916
917     return 0;
918 }
919
920
921 /***********************************************************************
922  *           QUEUE_ReceiveMessage
923  * 
924  * This routine is called when a sent message is waiting for the queue.
925  */
926 void QUEUE_ReceiveMessage( MESSAGEQUEUE *queue )
927 {
928     LRESULT       result = 0;
929     SMSG          *smsg;
930     MESSAGEQUEUE  *senderQ;
931
932     TRACE_(sendmsg)("queue %04x\n", queue->self );
933
934     if ( !(queue->wakeBits & QS_SENDMESSAGE) && queue->smPending )
935     {
936         TRACE_(sendmsg)("\trcm: nothing to do\n");
937         return;
938     }
939
940     /* remove smsg on the top of the pending list and put it in the processing list */
941     smsg = QUEUE_RemoveSMSG(queue, SM_PENDING_LIST, 0);
942     QUEUE_AddSMSG(queue, SM_WAITING_LIST, smsg);
943
944     TRACE_(sendmsg)("RM: %s [%04x] (%04x -> %04x)\n",
945             SPY_GetMsgName(smsg->msg), smsg->msg, smsg->hSrcQueue, smsg->hDstQueue );
946
947     if (IsWindow( smsg->hWnd ))
948     {
949         WND *wndPtr = WIN_FindWndPtr( smsg->hWnd );
950         DWORD extraInfo = queue->GetMessageExtraInfoVal; /* save ExtraInfo */
951
952         /* use sender queue extra info value while calling the window proc */
953         senderQ = (MESSAGEQUEUE*)QUEUE_Lock( smsg->hSrcQueue );
954         if (senderQ)
955   {
956             queue->GetMessageExtraInfoVal = senderQ->GetMessageExtraInfoVal;
957             QUEUE_Unlock( senderQ );
958         }
959
960         /* call the right version of CallWindowProcXX */
961         if (smsg->flags & SMSG_WIN32)
962         {
963             TRACE_(sendmsg)("\trcm: msg is Win32\n" );
964             if (smsg->flags & SMSG_UNICODE)
965                 result = CallWindowProcW( wndPtr->winproc,
966                                             smsg->hWnd, smsg->msg,
967                                             smsg->wParam, smsg->lParam );
968             else
969                 result = CallWindowProcA( wndPtr->winproc,
970                                             smsg->hWnd, smsg->msg,
971                                             smsg->wParam, smsg->lParam );
972         }
973         else  /* Win16 message */
974             result = CallWindowProc16( (WNDPROC16)wndPtr->winproc,
975                                        (HWND16) smsg->hWnd,
976                                        (UINT16) smsg->msg,
977                                        LOWORD (smsg->wParam),
978                                        smsg->lParam );
979
980         queue->GetMessageExtraInfoVal = extraInfo;  /* Restore extra info */
981         WIN_ReleaseWndPtr(wndPtr);
982         TRACE_(sendmsg)("result =  %08x\n", (unsigned)result );
983     }
984     else WARN_(sendmsg)("\trcm: bad hWnd\n");
985
986     
987         /* set SMSG_SENDING_REPLY flag to tell ReplyMessage16, it's not
988          an early reply */
989         smsg->flags |= SMSG_SENDING_REPLY;
990         ReplyMessage( result );
991
992     TRACE_(sendmsg)("done! \n" );
993 }
994
995
996
997 /***********************************************************************
998  *           QUEUE_AddMsg
999  *
1000  * Add a message to the queue. Return FALSE if queue is full.
1001  */
1002 BOOL QUEUE_AddMsg( HQUEUE16 hQueue, int type, MSG *msg, DWORD extraInfo )
1003 {
1004     MESSAGEQUEUE *msgQueue;
1005     QMSG         *qmsg;
1006
1007
1008     if (!(msgQueue = (MESSAGEQUEUE *)QUEUE_Lock( hQueue ))) return FALSE;
1009
1010     /* allocate new message in global heap for now */
1011     if (!(qmsg = (QMSG *) HeapAlloc( SystemHeap, 0, sizeof(QMSG) ) ))
1012     {
1013         QUEUE_Unlock( msgQueue );
1014         return 0;
1015     }
1016
1017     EnterCriticalSection( &msgQueue->cSection );
1018
1019       /* Store message */
1020     qmsg->type = type;
1021     qmsg->msg = *msg;
1022     qmsg->extraInfo = extraInfo;
1023
1024     /* insert the message in the link list */
1025     qmsg->nextMsg = 0;
1026     qmsg->prevMsg = msgQueue->lastMsg;
1027
1028     if (msgQueue->lastMsg)
1029         msgQueue->lastMsg->nextMsg = qmsg;
1030
1031     /* update first and last anchor in message queue */
1032     msgQueue->lastMsg = qmsg;
1033     if (!msgQueue->firstMsg)
1034         msgQueue->firstMsg = qmsg;
1035     
1036     msgQueue->msgCount++;
1037
1038     LeaveCriticalSection( &msgQueue->cSection );
1039
1040     QUEUE_SetWakeBit( msgQueue, QS_POSTMESSAGE );
1041     QUEUE_Unlock( msgQueue );
1042     
1043     return TRUE;
1044 }
1045
1046
1047
1048 /***********************************************************************
1049  *           QUEUE_FindMsg
1050  *
1051  * Find a message matching the given parameters. Return -1 if none available.
1052  */
1053 QMSG* QUEUE_FindMsg( MESSAGEQUEUE * msgQueue, HWND hwnd, int first, int last )
1054 {
1055     QMSG* qmsg;
1056
1057     EnterCriticalSection( &msgQueue->cSection );
1058
1059     if (!msgQueue->msgCount)
1060         qmsg = 0;
1061     else if (!hwnd && !first && !last)
1062         qmsg = msgQueue->firstMsg;
1063     else
1064     {
1065         /* look in linked list for message matching first and last criteria */
1066         for (qmsg = msgQueue->firstMsg; qmsg; qmsg = qmsg->nextMsg)
1067     {
1068             MSG *msg = &(qmsg->msg);
1069
1070         if (!hwnd || (msg->hwnd == hwnd))
1071         {
1072                 if (!first && !last)
1073                     break;   /* found it */
1074                 
1075                 if ((msg->message >= first) && (!last || (msg->message <= last)))
1076                     break;   /* found it */
1077             }
1078         }
1079     }
1080     
1081     LeaveCriticalSection( &msgQueue->cSection );
1082
1083     return qmsg;
1084 }
1085
1086
1087
1088 /***********************************************************************
1089  *           QUEUE_RemoveMsg
1090  *
1091  * Remove a message from the queue (pos must be a valid position).
1092  */
1093 void QUEUE_RemoveMsg( MESSAGEQUEUE * msgQueue, QMSG *qmsg )
1094 {
1095     EnterCriticalSection( &msgQueue->cSection );
1096
1097     /* set the linked list */
1098     if (qmsg->prevMsg)
1099         qmsg->prevMsg->nextMsg = qmsg->nextMsg;
1100
1101     if (qmsg->nextMsg)
1102         qmsg->nextMsg->prevMsg = qmsg->prevMsg;
1103
1104     if (msgQueue->firstMsg == qmsg)
1105         msgQueue->firstMsg = qmsg->nextMsg;
1106
1107     if (msgQueue->lastMsg == qmsg)
1108         msgQueue->lastMsg = qmsg->prevMsg;
1109
1110     /* deallocate the memory for the message */
1111     HeapFree( SystemHeap, 0, qmsg );
1112     
1113     msgQueue->msgCount--;
1114     if (!msgQueue->msgCount) msgQueue->wakeBits &= ~QS_POSTMESSAGE;
1115
1116     LeaveCriticalSection( &msgQueue->cSection );
1117 }
1118
1119
1120 /***********************************************************************
1121  *           QUEUE_WakeSomeone
1122  *
1123  * Wake a queue upon reception of a hardware event.
1124  */
1125 static void QUEUE_WakeSomeone( UINT message )
1126 {
1127     WND*          wndPtr = NULL;
1128     WORD          wakeBit;
1129     HWND hwnd;
1130     HQUEUE16     hQueue = 0;
1131     MESSAGEQUEUE *queue = NULL;
1132
1133     if (hCursorQueue)
1134         hQueue = hCursorQueue;
1135
1136     if( (message >= WM_KEYFIRST) && (message <= WM_KEYLAST) )
1137     {
1138        wakeBit = QS_KEY;
1139        if( hActiveQueue )
1140            hQueue = hActiveQueue;
1141     }
1142     else 
1143     {
1144        wakeBit = (message == WM_MOUSEMOVE) ? QS_MOUSEMOVE : QS_MOUSEBUTTON;
1145        if( (hwnd = GetCapture()) )
1146          if( (wndPtr = WIN_FindWndPtr( hwnd )) ) 
1147            {
1148                hQueue = wndPtr->hmemTaskQ;
1149                WIN_ReleaseWndPtr(wndPtr);
1150            }
1151     }
1152
1153     if( (hwnd = GetSysModalWindow16()) )
1154     {
1155       if( (wndPtr = WIN_FindWndPtr( hwnd )) )
1156         {
1157             hQueue = wndPtr->hmemTaskQ;
1158             WIN_ReleaseWndPtr(wndPtr);
1159         }
1160     }
1161
1162     if (hQueue)
1163         queue = QUEUE_Lock( hQueue );
1164     
1165     if( !queue ) 
1166     {
1167         queue = QUEUE_Lock( hFirstQueue );
1168       while( queue )
1169       {
1170         if (queue->wakeMask & wakeBit) break;
1171           
1172             QUEUE_Unlock(queue);
1173             queue = QUEUE_Lock( queue->next );
1174       }
1175       if( !queue )
1176       { 
1177         WARN_(msg)("couldn't find queue\n"); 
1178         return; 
1179       }
1180     }
1181
1182     QUEUE_SetWakeBit( queue, wakeBit );
1183
1184     QUEUE_Unlock( queue );
1185 }
1186
1187
1188 /***********************************************************************
1189  *           hardware_event
1190  *
1191  * Add an event to the system message queue.
1192  * Note: the position is relative to the desktop window.
1193  */
1194 void hardware_event( UINT message, WPARAM wParam, LPARAM lParam,
1195                      int xPos, int yPos, DWORD time, DWORD extraInfo )
1196 {
1197     MSG *msg;
1198     QMSG  *qmsg;
1199     int  mergeMsg = 0;
1200
1201     if (!sysMsgQueue) return;
1202
1203     EnterCriticalSection( &sysMsgQueue->cSection );
1204
1205     /* Merge with previous event if possible */
1206     qmsg = sysMsgQueue->lastMsg;
1207
1208     if ((message == WM_MOUSEMOVE) && sysMsgQueue->lastMsg)
1209     {
1210         msg = &(sysMsgQueue->lastMsg->msg);
1211         
1212         if ((msg->message == message) && (msg->wParam == wParam))
1213         {
1214             /* Merge events */
1215             qmsg = sysMsgQueue->lastMsg;
1216             mergeMsg = 1;
1217     }
1218     }
1219
1220     if (!mergeMsg)
1221     {
1222         /* Should I limit the number of message in
1223           the system message queue??? */
1224
1225         /* Don't merge allocate a new msg in the global heap */
1226         
1227         if (!(qmsg = (QMSG *) HeapAlloc( SystemHeap, 0, sizeof(QMSG) ) ))
1228         {
1229             LeaveCriticalSection( &sysMsgQueue->cSection );
1230             return;
1231         }
1232         
1233         /* put message at the end of the linked list */
1234         qmsg->nextMsg = 0;
1235         qmsg->prevMsg = sysMsgQueue->lastMsg;
1236
1237         if (sysMsgQueue->lastMsg)
1238             sysMsgQueue->lastMsg->nextMsg = qmsg;
1239
1240         /* set last and first anchor index in system message queue */
1241         sysMsgQueue->lastMsg = qmsg;
1242         if (!sysMsgQueue->firstMsg)
1243             sysMsgQueue->firstMsg = qmsg;
1244         
1245         sysMsgQueue->msgCount++;
1246     }
1247
1248       /* Store message */
1249     msg = &(qmsg->msg);
1250     msg->hwnd    = 0;
1251     msg->message = message;
1252     msg->wParam  = wParam;
1253     msg->lParam  = lParam;
1254     msg->time    = time;
1255     msg->pt.x    = xPos;
1256     msg->pt.y    = yPos;
1257     qmsg->extraInfo = extraInfo;
1258     qmsg->type      = QMSG_HARDWARE;
1259
1260     LeaveCriticalSection( &sysMsgQueue->cSection );
1261
1262     QUEUE_WakeSomeone( message );
1263 }
1264
1265                     
1266 /***********************************************************************
1267  *           QUEUE_GetQueueTask
1268  */
1269 HTASK16 QUEUE_GetQueueTask( HQUEUE16 hQueue )
1270 {
1271     HTASK16 hTask = 0;
1272     
1273     MESSAGEQUEUE *queue = QUEUE_Lock( hQueue );
1274
1275     if (queue)
1276 {
1277         hTask = queue->teb->process->task;
1278         QUEUE_Unlock( queue );
1279 }
1280
1281     return hTask;
1282 }
1283
1284
1285
1286 /***********************************************************************
1287  *           QUEUE_IncPaintCount
1288  */
1289 void QUEUE_IncPaintCount( HQUEUE16 hQueue )
1290 {
1291     MESSAGEQUEUE *queue;
1292
1293     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( hQueue ))) return;
1294     queue->wPaintCount++;
1295     QUEUE_SetWakeBit( queue, QS_PAINT );
1296     QUEUE_Unlock( queue );
1297 }
1298
1299
1300 /***********************************************************************
1301  *           QUEUE_DecPaintCount
1302  */
1303 void QUEUE_DecPaintCount( HQUEUE16 hQueue )
1304 {
1305     MESSAGEQUEUE *queue;
1306
1307     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( hQueue ))) return;
1308     queue->wPaintCount--;
1309     if (!queue->wPaintCount) queue->wakeBits &= ~QS_PAINT;
1310     QUEUE_Unlock( queue );
1311 }
1312
1313
1314 /***********************************************************************
1315  *           QUEUE_IncTimerCount
1316  */
1317 void QUEUE_IncTimerCount( HQUEUE16 hQueue )
1318 {
1319     MESSAGEQUEUE *queue;
1320
1321     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( hQueue ))) return;
1322     queue->wTimerCount++;
1323     QUEUE_SetWakeBit( queue, QS_TIMER );
1324     QUEUE_Unlock( queue );
1325 }
1326
1327
1328 /***********************************************************************
1329  *           QUEUE_DecTimerCount
1330  */
1331 void QUEUE_DecTimerCount( HQUEUE16 hQueue )
1332 {
1333     MESSAGEQUEUE *queue;
1334
1335     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( hQueue ))) return;
1336     queue->wTimerCount--;
1337     if (!queue->wTimerCount) queue->wakeBits &= ~QS_TIMER;
1338     QUEUE_Unlock( queue );
1339 }
1340
1341
1342 /***********************************************************************
1343  *           PostQuitMessage16   (USER.6)
1344  */
1345 void WINAPI PostQuitMessage16( INT16 exitCode )
1346 {
1347     PostQuitMessage( exitCode );
1348 }
1349
1350
1351 /***********************************************************************
1352  *           PostQuitMessage32   (USER32.421)
1353  *
1354  * PostQuitMessage() posts a message to the system requesting an
1355  * application to terminate execution. As a result of this function,
1356  * the WM_QUIT message is posted to the application, and
1357  * PostQuitMessage() returns immediately.  The exitCode parameter
1358  * specifies an application-defined exit code, which appears in the
1359  * _wParam_ parameter of the WM_QUIT message posted to the application.  
1360  *
1361  * CONFORMANCE
1362  *
1363  *  ECMA-234, Win32
1364  */
1365 void WINAPI PostQuitMessage( INT exitCode )
1366 {
1367     MESSAGEQUEUE *queue;
1368
1369     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() ))) return;
1370     queue->wPostQMsg = TRUE;
1371     queue->wExitCode = (WORD)exitCode;
1372     QUEUE_Unlock( queue );
1373 }
1374
1375
1376 /***********************************************************************
1377  *           GetWindowTask16   (USER.224)
1378  */
1379 HTASK16 WINAPI GetWindowTask16( HWND16 hwnd )
1380 {
1381     HTASK16 retvalue;
1382     WND *wndPtr = WIN_FindWndPtr( hwnd );
1383
1384     if (!wndPtr) return 0;
1385     retvalue = QUEUE_GetQueueTask( wndPtr->hmemTaskQ );
1386     WIN_ReleaseWndPtr(wndPtr);
1387     return retvalue;
1388 }
1389
1390 /***********************************************************************
1391  *           GetWindowThreadProcessId   (USER32.313)
1392  */
1393 DWORD WINAPI GetWindowThreadProcessId( HWND hwnd, LPDWORD process )
1394 {
1395     DWORD retvalue;
1396     MESSAGEQUEUE *queue;
1397
1398     WND *wndPtr = WIN_FindWndPtr( hwnd );
1399     if (!wndPtr) return 0;
1400
1401     queue = QUEUE_Lock( wndPtr->hmemTaskQ );
1402     WIN_ReleaseWndPtr(wndPtr);
1403
1404     if (!queue) return 0;
1405
1406     if ( process ) *process = (DWORD)queue->teb->process->server_pid;
1407     retvalue = (DWORD)queue->teb->tid;
1408
1409     QUEUE_Unlock( queue );
1410     return retvalue;
1411 }
1412
1413
1414 /***********************************************************************
1415  *           SetMessageQueue16   (USER.266)
1416  */
1417 BOOL16 WINAPI SetMessageQueue16( INT16 size )
1418 {
1419     return SetMessageQueue( size );
1420 }
1421
1422
1423 /***********************************************************************
1424  *           SetMessageQueue   (USER32.494)
1425  */
1426 BOOL WINAPI SetMessageQueue( INT size )
1427 {
1428     /* now obsolete the message queue will be expanded dynamically
1429      as necessary */
1430
1431     /* access the queue to create it if it's not existing */
1432     GetFastQueue16();
1433
1434     return TRUE;
1435 }
1436
1437 /***********************************************************************
1438  *           InitThreadInput16   (USER.409)
1439  */
1440 HQUEUE16 WINAPI InitThreadInput16( WORD unknown, WORD flags )
1441 {
1442     HQUEUE16 hQueue;
1443     MESSAGEQUEUE *queuePtr;
1444
1445     TEB *teb = NtCurrentTeb();
1446
1447     if (!teb)
1448         return 0;
1449
1450     hQueue = teb->queue;
1451     
1452     if ( !hQueue )
1453     {
1454         /* Create thread message queue */
1455         if( !(hQueue = QUEUE_CreateMsgQueue( TRUE )))
1456         {
1457             WARN_(msg)("failed!\n");
1458             return FALSE;
1459         }
1460         
1461         /* Link new queue into list */
1462         queuePtr = (MESSAGEQUEUE *)QUEUE_Lock( hQueue );
1463         queuePtr->teb = NtCurrentTeb();
1464
1465         HeapLock( SystemHeap );  /* FIXME: a bit overkill */
1466         SetThreadQueue16( 0, hQueue );
1467         teb->queue = hQueue;
1468             
1469         queuePtr->next  = hFirstQueue;
1470         hFirstQueue = hQueue;
1471         HeapUnlock( SystemHeap );
1472         
1473         QUEUE_Unlock( queuePtr );
1474     }
1475
1476     return hQueue;
1477 }
1478
1479 /***********************************************************************
1480  *           GetQueueStatus16   (USER.334)
1481  */
1482 DWORD WINAPI GetQueueStatus16( UINT16 flags )
1483 {
1484     MESSAGEQUEUE *queue;
1485     DWORD ret;
1486
1487     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() ))) return 0;
1488     ret = MAKELONG( queue->changeBits, queue->wakeBits );
1489     queue->changeBits = 0;
1490     QUEUE_Unlock( queue );
1491     
1492     return ret & MAKELONG( flags, flags );
1493 }
1494
1495 /***********************************************************************
1496  *           GetQueueStatus32   (USER32.283)
1497  */
1498 DWORD WINAPI GetQueueStatus( UINT flags )
1499 {
1500     MESSAGEQUEUE *queue;
1501     DWORD ret;
1502
1503     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() ))) return 0;
1504     ret = MAKELONG( queue->changeBits, queue->wakeBits );
1505     queue->changeBits = 0;
1506     QUEUE_Unlock( queue );
1507     
1508     return ret & MAKELONG( flags, flags );
1509 }
1510
1511
1512 /***********************************************************************
1513  *           GetInputState16   (USER.335)
1514  */
1515 BOOL16 WINAPI GetInputState16(void)
1516 {
1517     return GetInputState();
1518 }
1519
1520 /***********************************************************************
1521  *           WaitForInputIdle   (USER32.577)
1522  */
1523 DWORD WINAPI WaitForInputIdle (HANDLE hProcess, DWORD dwTimeOut)
1524 {
1525   PDB * pdb;
1526   DWORD cur_time, ret, pid = MapProcessHandle ( hProcess );
1527
1528   /* Check whether the calling process is a command line application */
1529   if (!THREAD_IsWin16(NtCurrentTeb() ) &&
1530       (PROCESS_Current()->flags & PDB32_CONSOLE_PROC))
1531   {
1532     TRACE_(msg)("not a win32 GUI application!\n" );
1533     return 0; 
1534   }
1535   
1536   pdb = PROCESS_IdToPDB( pid );
1537
1538   /* check whether we are waiting for a win32 process or the win16 subsystem */
1539   if ( pdb->flags & PDB32_WIN16_PROC ) {
1540     if ( THREAD_IsWin16(NtCurrentTeb()) ) return 0;
1541   }
1542     else { /* target is win32 */
1543     if ( pdb->flags & PDB32_CONSOLE_PROC ) return 0;
1544     if ( GetFastQueue16() == pdb->main_queue ) return 0;
1545   }
1546
1547   cur_time = GetTickCount();
1548   
1549   TRACE_(msg)("waiting for %x\n", pdb->idle_event );
1550   while ( dwTimeOut > GetTickCount() - cur_time || dwTimeOut == INFINITE ) {
1551
1552     ret = MsgWaitForMultipleObjects ( 1, &pdb->idle_event, FALSE, dwTimeOut, QS_SENDMESSAGE );
1553     if ( ret == ( WAIT_OBJECT_0 + 1 )) {
1554       MESSAGEQUEUE * queue;
1555       if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() ))) return 0xFFFFFFFF;
1556       QUEUE_ReceiveMessage ( queue );
1557       QUEUE_Unlock ( queue );
1558       continue; 
1559     }
1560     if ( ret == WAIT_TIMEOUT || ret == 0xFFFFFFFF ) {
1561       TRACE_(msg)("timeout or error\n");
1562       return ret;
1563     }
1564     else {
1565       TRACE_(msg)("finished\n");
1566       return 0;
1567     }
1568     
1569   }
1570   return WAIT_TIMEOUT;
1571 }
1572
1573 /***********************************************************************
1574  *           GetInputState32   (USER32.244)
1575  */
1576 BOOL WINAPI GetInputState(void)
1577 {
1578     MESSAGEQUEUE *queue;
1579     BOOL ret;
1580
1581     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() )))
1582         return FALSE;
1583     ret = queue->wakeBits & (QS_KEY | QS_MOUSEBUTTON);
1584     QUEUE_Unlock( queue );
1585
1586     return ret;
1587 }
1588
1589 /***********************************************************************
1590  *           UserYield  (USER.332)
1591  */
1592 void WINAPI UserYield16(void)
1593 {
1594     MESSAGEQUEUE *queue;
1595
1596     /* Handle sent messages */
1597     queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() );
1598
1599     while (queue && (queue->wakeBits & QS_SENDMESSAGE))
1600         QUEUE_ReceiveMessage( queue );
1601
1602     QUEUE_Unlock( queue );
1603     
1604     /* Yield */
1605     if ( THREAD_IsWin16( NtCurrentTeb() ) )
1606         OldYield16();
1607     else
1608         WIN32_OldYield16();
1609
1610     /* Handle sent messages again */
1611     queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() );
1612
1613     while (queue && (queue->wakeBits & QS_SENDMESSAGE))
1614         QUEUE_ReceiveMessage( queue );
1615
1616     QUEUE_Unlock( queue );
1617 }
1618
1619 /***********************************************************************
1620  *           GetMessagePos   (USER.119) (USER32.272)
1621  * 
1622  * The GetMessagePos() function returns a long value representing a
1623  * cursor position, in screen coordinates, when the last message
1624  * retrieved by the GetMessage() function occurs. The x-coordinate is
1625  * in the low-order word of the return value, the y-coordinate is in
1626  * the high-order word. The application can use the MAKEPOINT()
1627  * macro to obtain a POINT structure from the return value. 
1628  *
1629  * For the current cursor position, use GetCursorPos().
1630  *
1631  * RETURNS
1632  *
1633  * Cursor position of last message on success, zero on failure.
1634  *
1635  * CONFORMANCE
1636  *
1637  * ECMA-234, Win32
1638  *
1639  */
1640 DWORD WINAPI GetMessagePos(void)
1641 {
1642     MESSAGEQUEUE *queue;
1643     DWORD ret;
1644
1645     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() ))) return 0;
1646     ret = queue->GetMessagePosVal;
1647     QUEUE_Unlock( queue );
1648
1649     return ret;
1650 }
1651
1652
1653 /***********************************************************************
1654  *           GetMessageTime   (USER.120) (USER32.273)
1655  *
1656  * GetMessageTime() returns the message time for the last message
1657  * retrieved by the function. The time is measured in milliseconds with
1658  * the same offset as GetTickCount().
1659  *
1660  * Since the tick count wraps, this is only useful for moderately short
1661  * relative time comparisons.
1662  *
1663  * RETURNS
1664  *
1665  * Time of last message on success, zero on failure.
1666  *
1667  * CONFORMANCE
1668  *
1669  * ECMA-234, Win32
1670  *  
1671  */
1672 LONG WINAPI GetMessageTime(void)
1673 {
1674     MESSAGEQUEUE *queue;
1675     LONG ret;
1676
1677     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() ))) return 0;
1678     ret = queue->GetMessageTimeVal;
1679     QUEUE_Unlock( queue );
1680     
1681     return ret;
1682 }
1683
1684
1685 /***********************************************************************
1686  *           GetMessageExtraInfo   (USER.288) (USER32.271)
1687  */
1688 LONG WINAPI GetMessageExtraInfo(void)
1689 {
1690     MESSAGEQUEUE *queue;
1691     LONG ret;
1692
1693     if (!(queue = (MESSAGEQUEUE *)QUEUE_Lock( GetFastQueue16() ))) return 0;
1694     ret = queue->GetMessageExtraInfoVal;
1695     QUEUE_Unlock( queue );
1696
1697     return ret;
1698 }