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