Unified 16-bit and 32-bit scheduling a bit more.
[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 "queue.h"
15 #include "win.h"
16 #include "hook.h"
17 #include "thread.h"
18 #include "debugtools.h"
19 #include "server.h"
20 #include "spy.h"
21
22 DECLARE_DEBUG_CHANNEL(msg);
23 DECLARE_DEBUG_CHANNEL(sendmsg);
24
25 #define MAX_QUEUE_SIZE   120  /* Max. size of a message queue */
26
27 static HQUEUE16 hFirstQueue = 0;
28 static HQUEUE16 hExitingQueue = 0;
29 static HQUEUE16 hmemSysMsgQueue = 0;
30 static MESSAGEQUEUE *sysMsgQueue = NULL;
31 static PERQUEUEDATA *pQDataWin16 = NULL;  /* Global perQData for Win16 tasks */
32
33 static MESSAGEQUEUE *pMouseQueue = NULL;  /* Queue for last mouse message */
34 static MESSAGEQUEUE *pKbdQueue = NULL;    /* Queue for last kbd message */
35
36 HQUEUE16 hCursorQueue = 0;
37 HQUEUE16 hActiveQueue = 0;
38
39
40 /***********************************************************************
41  *           PERQDATA_CreateInstance
42  *
43  * Creates an instance of a reference counted PERQUEUEDATA element
44  * for the message queue. perQData is stored globally for 16 bit tasks.
45  *
46  * Note: We don't implement perQdata exactly the same way Windows does.
47  * Each perQData element is reference counted since it may be potentially
48  * shared by multiple message Queues (via AttachThreadInput).
49  * We only store the current values for Active, Capture and focus windows
50  * currently.
51  */
52 PERQUEUEDATA * PERQDATA_CreateInstance( )
53 {
54     PERQUEUEDATA *pQData;
55     
56     BOOL16 bIsWin16 = 0;
57     
58     TRACE_(msg)("()\n");
59
60     /* Share a single instance of perQData for all 16 bit tasks */
61     if ( ( bIsWin16 = THREAD_IsWin16( NtCurrentTeb() ) ) )
62     {
63         /* If previously allocated, just bump up ref count */
64         if ( pQDataWin16 )
65         {
66             PERQDATA_Addref( pQDataWin16 );
67             return pQDataWin16;
68         }
69     }
70
71     /* Allocate PERQUEUEDATA from the system heap */
72     if (!( pQData = (PERQUEUEDATA *) HeapAlloc( GetProcessHeap(), 0,
73                                                     sizeof(PERQUEUEDATA) ) ))
74         return 0;
75
76     /* Initialize */
77     pQData->hWndCapture = pQData->hWndFocus = pQData->hWndActive = 0;
78     pQData->ulRefCount = 1;
79     pQData->nCaptureHT = HTCLIENT;
80
81     /* Note: We have an independent critical section for the per queue data
82      * since this may be shared by different threads. see AttachThreadInput()
83      */
84     InitializeCriticalSection( &pQData->cSection );
85     /* FIXME: not all per queue data critical sections should be global */
86     MakeCriticalSectionGlobal( &pQData->cSection );
87
88     /* Save perQData globally for 16 bit tasks */
89     if ( bIsWin16 )
90         pQDataWin16 = pQData;
91         
92     return pQData;
93 }
94
95
96 /***********************************************************************
97  *           PERQDATA_Addref
98  *
99  * Increment reference count for the PERQUEUEDATA instance
100  * Returns reference count for debugging purposes
101  */
102 ULONG PERQDATA_Addref( PERQUEUEDATA *pQData )
103 {
104     assert(pQData != 0 );
105     TRACE_(msg)("(): current refcount %lu ...\n", pQData->ulRefCount);
106
107     EnterCriticalSection( &pQData->cSection );
108     ++pQData->ulRefCount;
109     LeaveCriticalSection( &pQData->cSection );
110
111     return pQData->ulRefCount;
112 }
113
114
115 /***********************************************************************
116  *           PERQDATA_Release
117  *
118  * Release a reference to a PERQUEUEDATA instance.
119  * Destroy the instance if no more references exist
120  * Returns reference count for debugging purposes
121  */
122 ULONG PERQDATA_Release( PERQUEUEDATA *pQData )
123 {
124     assert(pQData != 0 );
125     TRACE_(msg)("(): current refcount %lu ...\n",
126           (LONG)pQData->ulRefCount );
127
128     EnterCriticalSection( &pQData->cSection );
129     if ( --pQData->ulRefCount == 0 )
130     {
131         LeaveCriticalSection( &pQData->cSection );
132         DeleteCriticalSection( &pQData->cSection );
133
134         TRACE_(msg)("(): deleting PERQUEUEDATA instance ...\n" );
135
136         /* Deleting our global 16 bit perQData? */
137         if ( pQData == pQDataWin16 )
138             pQDataWin16 = 0;
139             
140         /* Free the PERQUEUEDATA instance */
141         HeapFree( GetProcessHeap(), 0, pQData );
142
143         return 0;
144     }
145     LeaveCriticalSection( &pQData->cSection );
146
147     return pQData->ulRefCount;
148 }
149
150
151 /***********************************************************************
152  *           PERQDATA_GetFocusWnd
153  *
154  * Get the focus hwnd member in a threadsafe manner
155  */
156 HWND PERQDATA_GetFocusWnd( PERQUEUEDATA *pQData )
157 {
158     HWND hWndFocus;
159     assert(pQData != 0 );
160
161     EnterCriticalSection( &pQData->cSection );
162     hWndFocus = pQData->hWndFocus;
163     LeaveCriticalSection( &pQData->cSection );
164
165     return hWndFocus;
166 }
167
168
169 /***********************************************************************
170  *           PERQDATA_SetFocusWnd
171  *
172  * Set the focus hwnd member in a threadsafe manner
173  */
174 HWND PERQDATA_SetFocusWnd( PERQUEUEDATA *pQData, HWND hWndFocus )
175 {
176     HWND hWndFocusPrv;
177     assert(pQData != 0 );
178
179     EnterCriticalSection( &pQData->cSection );
180     hWndFocusPrv = pQData->hWndFocus;
181     pQData->hWndFocus = hWndFocus;
182     LeaveCriticalSection( &pQData->cSection );
183
184     return hWndFocusPrv;
185 }
186
187
188 /***********************************************************************
189  *           PERQDATA_GetActiveWnd
190  *
191  * Get the active hwnd member in a threadsafe manner
192  */
193 HWND PERQDATA_GetActiveWnd( PERQUEUEDATA *pQData )
194 {
195     HWND hWndActive;
196     assert(pQData != 0 );
197
198     EnterCriticalSection( &pQData->cSection );
199     hWndActive = pQData->hWndActive;
200     LeaveCriticalSection( &pQData->cSection );
201
202     return hWndActive;
203 }
204
205
206 /***********************************************************************
207  *           PERQDATA_SetActiveWnd
208  *
209  * Set the active focus hwnd member in a threadsafe manner
210  */
211 HWND PERQDATA_SetActiveWnd( PERQUEUEDATA *pQData, HWND hWndActive )
212 {
213     HWND hWndActivePrv;
214     assert(pQData != 0 );
215
216     EnterCriticalSection( &pQData->cSection );
217     hWndActivePrv = pQData->hWndActive;
218     pQData->hWndActive = hWndActive;
219     LeaveCriticalSection( &pQData->cSection );
220
221     return hWndActivePrv;
222 }
223
224
225 /***********************************************************************
226  *           PERQDATA_GetCaptureWnd
227  *
228  * Get the capture hwnd member in a threadsafe manner
229  */
230 HWND PERQDATA_GetCaptureWnd( PERQUEUEDATA *pQData )
231 {
232     HWND hWndCapture;
233     assert(pQData != 0 );
234
235     EnterCriticalSection( &pQData->cSection );
236     hWndCapture = pQData->hWndCapture;
237     LeaveCriticalSection( &pQData->cSection );
238
239     return hWndCapture;
240 }
241
242
243 /***********************************************************************
244  *           PERQDATA_SetCaptureWnd
245  *
246  * Set the capture hwnd member in a threadsafe manner
247  */
248 HWND PERQDATA_SetCaptureWnd( PERQUEUEDATA *pQData, HWND hWndCapture )
249 {
250     HWND hWndCapturePrv;
251     assert(pQData != 0 );
252
253     EnterCriticalSection( &pQData->cSection );
254     hWndCapturePrv = pQData->hWndCapture;
255     pQData->hWndCapture = hWndCapture;
256     LeaveCriticalSection( &pQData->cSection );
257
258     return hWndCapturePrv;
259 }
260
261
262 /***********************************************************************
263  *           PERQDATA_GetCaptureInfo
264  *
265  * Get the capture info member in a threadsafe manner
266  */
267 INT16 PERQDATA_GetCaptureInfo( PERQUEUEDATA *pQData )
268 {
269     INT16 nCaptureHT;
270     assert(pQData != 0 );
271
272     EnterCriticalSection( &pQData->cSection );
273     nCaptureHT = pQData->nCaptureHT;
274     LeaveCriticalSection( &pQData->cSection );
275
276     return nCaptureHT;
277 }
278
279
280 /***********************************************************************
281  *           PERQDATA_SetCaptureInfo
282  *
283  * Set the capture info member in a threadsafe manner
284  */
285 INT16 PERQDATA_SetCaptureInfo( PERQUEUEDATA *pQData, INT16 nCaptureHT )
286 {
287     INT16 nCaptureHTPrv;
288     assert(pQData != 0 );
289
290     EnterCriticalSection( &pQData->cSection );
291     nCaptureHTPrv = pQData->nCaptureHT;
292     pQData->nCaptureHT = nCaptureHT;
293     LeaveCriticalSection( &pQData->cSection );
294
295     return nCaptureHTPrv;
296 }
297
298
299 /***********************************************************************
300  *           QUEUE_Lock
301  *
302  * Function for getting a 32 bit pointer on queue structure. For thread
303  * safeness programmers should use this function instead of GlobalLock to
304  * retrieve a pointer on the structure. QUEUE_Unlock should also be called
305  * when access to the queue structure is not required anymore.
306  */
307 MESSAGEQUEUE *QUEUE_Lock( HQUEUE16 hQueue )
308 {
309     MESSAGEQUEUE *queue;
310
311     HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
312     queue = GlobalLock16( hQueue );
313     if ( !queue || (queue->magic != QUEUE_MAGIC) )
314     {
315         HeapUnlock( GetProcessHeap() );
316         return NULL;
317     }
318
319     queue->lockCount++;
320     HeapUnlock( GetProcessHeap() );
321     return queue;
322 }
323
324
325 /***********************************************************************
326  *           QUEUE_Unlock
327  *
328  * Use with QUEUE_Lock to get a thread safe access to message queue
329  * structure
330  */
331 void QUEUE_Unlock( MESSAGEQUEUE *queue )
332 {
333     if (queue)
334     {
335         HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
336
337         if ( --queue->lockCount == 0 )
338         {
339             DeleteCriticalSection ( &queue->cSection );
340             if (queue->server_queue)
341                 CloseHandle( queue->server_queue );
342             GlobalFree16( queue->self );
343         }
344     
345         HeapUnlock( GetProcessHeap() );
346     }
347 }
348
349
350 /***********************************************************************
351  *           QUEUE_DumpQueue
352  */
353 void QUEUE_DumpQueue( HQUEUE16 hQueue )
354 {
355     MESSAGEQUEUE *pq; 
356
357     if (!(pq = QUEUE_Lock( hQueue )) )
358     {
359         WARN_(msg)("%04x is not a queue handle\n", hQueue );
360         return;
361     }
362
363     EnterCriticalSection( &pq->cSection );
364
365     DPRINTF( "next: %12.4x  Intertask SendMessage:\n"
366              "thread: %10p  ----------------------\n"
367              "firstMsg: %8p   smWaiting:     %10p\n"
368              "lastMsg:  %8p   smPending:     %10p\n"
369              "msgCount: %8.4x   smProcessing:  %10p\n"
370              "lockCount: %7.4x\n"
371              "paints: %10.4x\n"
372              "timers: %10.4x\n"
373              "wakeBits: %8.4x\n"
374              "wakeMask: %8.4x\n"
375              "hCurHook: %8.4x\n",
376              pq->next, pq->teb, pq->firstMsg, pq->smWaiting, pq->lastMsg,
377              pq->smPending, pq->msgCount, pq->smProcessing,
378              (unsigned)pq->lockCount, pq->wPaintCount, pq->wTimerCount,
379              pq->wakeBits, pq->wakeMask, pq->hCurHook);
380
381     LeaveCriticalSection( &pq->cSection );
382
383     QUEUE_Unlock( pq );
384 }
385
386
387 /***********************************************************************
388  *           QUEUE_WalkQueues
389  */
390 void QUEUE_WalkQueues(void)
391 {
392     char module[10];
393     HQUEUE16 hQueue = hFirstQueue;
394
395     DPRINTF( "Queue Msgs Thread   Task Module\n" );
396     while (hQueue)
397     {
398         MESSAGEQUEUE *queue = QUEUE_Lock( hQueue );
399         if (!queue)
400         {
401             WARN_(msg)("Bad queue handle %04x\n", hQueue );
402             return;
403         }
404         if (!GetModuleName16( queue->teb->htask16, module, sizeof(module )))
405             strcpy( module, "???" );
406         DPRINTF( "%04x %4d %p %04x %s\n", hQueue,queue->msgCount,
407                  queue->teb, queue->teb->htask16, module );
408         hQueue = queue->next;
409         QUEUE_Unlock( queue );
410     }
411     DPRINTF( "\n" );
412 }
413
414
415 /***********************************************************************
416  *           QUEUE_IsExitingQueue
417  */
418 BOOL QUEUE_IsExitingQueue( HQUEUE16 hQueue )
419 {
420     return (hExitingQueue && (hQueue == hExitingQueue));
421 }
422
423
424 /***********************************************************************
425  *           QUEUE_SetExitingQueue
426  */
427 void QUEUE_SetExitingQueue( HQUEUE16 hQueue )
428 {
429     hExitingQueue = hQueue;
430 }
431
432
433 /***********************************************************************
434  *           QUEUE_CreateMsgQueue
435  *
436  * Creates a message queue. Doesn't link it into queue list!
437  */
438 static HQUEUE16 QUEUE_CreateMsgQueue( BOOL16 bCreatePerQData )
439 {
440     HQUEUE16 hQueue;
441     HANDLE handle;
442     MESSAGEQUEUE * msgQueue;
443
444     TRACE_(msg)("(): Creating message queue...\n");
445
446     if (!(hQueue = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT,
447                                   sizeof(MESSAGEQUEUE) )))
448         return 0;
449
450     msgQueue = (MESSAGEQUEUE *) GlobalLock16( hQueue );
451     if ( !msgQueue )
452         return 0;
453
454     SERVER_START_REQ( get_msg_queue )
455     {
456         SERVER_CALL_ERR();
457         handle = req->handle;
458     }
459     SERVER_END_REQ;
460     if (!handle)
461     {
462         ERR_(msg)("Cannot get thread queue");
463         GlobalFree16( hQueue );
464         return 0;
465     }
466     msgQueue->server_queue = handle;
467     msgQueue->server_queue = ConvertToGlobalHandle( msgQueue->server_queue );
468
469     msgQueue->self        = hQueue;
470     msgQueue->wakeBits    = msgQueue->changeBits = 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 = 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 = QUEUE_Lock(hQueue);
534     HQUEUE16 *pPrev;
535
536     TRACE_(msg)("(): Deleting message queue %04x\n", hQueue);
537
538     if (!hQueue || !msgQueue)
539     {
540         ERR_(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( GetProcessHeap() );  /* 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             ERR_(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( GetProcessHeap() );
581
582     /* free up resource used by MESSAGEQUEUE structure */
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 static BOOL QUEUE_TrySetWakeBit( MESSAGEQUEUE *queue, WORD bit, BOOL always )
622 {
623     BOOL wake = FALSE;
624
625     EnterCriticalSection( &queue->cSection );
626
627     TRACE_(msg)("queue = %04x (wm=%04x), bit = %04x, always = %d\n", 
628                         queue->self, queue->wakeMask, bit, always );
629
630     if ((queue->wakeMask & bit) || always)
631     {
632         if (bit & QS_MOUSE) pMouseQueue = queue;
633         if (bit & QS_KEY) pKbdQueue = queue;
634         queue->changeBits |= bit;
635         queue->wakeBits   |= bit;
636     }
637     if (queue->wakeMask & bit)
638     {
639         queue->wakeMask = 0;
640         wake = TRUE;
641     }
642
643     LeaveCriticalSection( &queue->cSection );
644
645     if ( wake )
646     {
647         /* Wake up thread waiting for message */
648         SERVER_START_REQ( wake_queue )
649         {
650             req->handle = queue->server_queue;
651             req->bits   = bit;
652             SERVER_CALL();
653         }
654         SERVER_END_REQ;
655     }
656
657     return wake;
658 }
659 void QUEUE_SetWakeBit( MESSAGEQUEUE *queue, WORD bit )
660 {
661     QUEUE_TrySetWakeBit( queue, bit, TRUE );
662 }
663
664
665 /***********************************************************************
666  *           QUEUE_ClearWakeBit
667  */
668 void QUEUE_ClearWakeBit( MESSAGEQUEUE *queue, WORD bit )
669 {
670     EnterCriticalSection( &queue->cSection );
671     queue->changeBits &= ~bit;
672     queue->wakeBits   &= ~bit;
673     LeaveCriticalSection( &queue->cSection );
674 }
675
676 /***********************************************************************
677  *           QUEUE_TestWakeBit
678  */
679 WORD QUEUE_TestWakeBit( MESSAGEQUEUE *queue, WORD bit )
680 {
681     WORD ret;
682     EnterCriticalSection( &queue->cSection );
683     ret = queue->wakeBits & bit;
684     LeaveCriticalSection( &queue->cSection );
685     return ret;
686 }
687
688
689 /***********************************************************************
690  *           QUEUE_WaitBits
691  *
692  * See "Windows Internals", p.447
693  *
694  * return values:
695  *    0 if exit with timeout
696  *    1 otherwise
697  */
698 int QUEUE_WaitBits( WORD bits, DWORD timeout )
699 {
700     MESSAGEQUEUE *queue;
701     HQUEUE16 hQueue;
702
703     TRACE_(msg)("q %04x waiting for %04x\n", GetFastQueue16(), bits);
704
705     hQueue = GetFastQueue16();
706     if (!(queue = QUEUE_Lock( hQueue ))) return 0;
707     
708     for (;;)
709     {
710         DWORD dwlc;
711
712         EnterCriticalSection( &queue->cSection );
713
714         if (queue->changeBits & bits)
715         {
716             /* One of the bits is set; we can return */
717             queue->wakeMask = 0;
718
719             LeaveCriticalSection( &queue->cSection );
720             QUEUE_Unlock( queue );
721             return 1;
722         }
723         if (queue->wakeBits & QS_SENDMESSAGE)
724         {
725             /* Process the sent message immediately */
726             queue->wakeMask = 0;
727
728             LeaveCriticalSection( &queue->cSection );
729             QUEUE_ReceiveMessage( queue );
730             continue;                           /* nested sm crux */
731         }
732
733         queue->wakeMask = bits | QS_SENDMESSAGE;
734         TRACE_(msg)("%04x) wakeMask is %04x, waiting\n", queue->self, queue->wakeMask);
735         LeaveCriticalSection( &queue->cSection );
736
737         ReleaseThunkLock( &dwlc );
738         if (dwlc) TRACE_(msg)("had win16 lock\n");
739         WaitForSingleObject( queue->server_queue, timeout );
740         if (dwlc) RestoreThunkLock( dwlc );
741     }
742 }
743
744
745 /***********************************************************************
746  *           QUEUE_AddSMSG
747  *
748  * This routine is called when a SMSG need to be added to one of the three
749  * SM list.  (SM_PROCESSING_LIST, SM_PENDING_LIST, SM_WAITING_LIST)
750  */
751 BOOL QUEUE_AddSMSG( MESSAGEQUEUE *queue, int list, SMSG *smsg )
752 {
753     TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
754           smsg, SPY_GetMsgName(smsg->msg));
755     
756     switch (list)
757     {
758         case SM_PROCESSING_LIST:
759             /* don't need to be thread safe, only accessed by the
760              thread associated with the sender queue */
761             smsg->nextProcessing = queue->smProcessing;
762             queue->smProcessing = smsg;
763             break;
764             
765         case SM_WAITING_LIST:
766             /* don't need to be thread safe, only accessed by the
767              thread associated with the receiver queue */
768             smsg->nextWaiting = queue->smWaiting;
769             queue->smWaiting = smsg;
770             break;
771             
772         case SM_PENDING_LIST:
773         {
774             /* make it thread safe, could be accessed by the sender and
775              receiver thread */
776             SMSG **prev;
777
778             EnterCriticalSection( &queue->cSection );
779             smsg->nextPending = NULL;
780             prev = &queue->smPending;
781             while ( *prev )
782                 prev = &(*prev)->nextPending;
783             *prev = smsg;
784             LeaveCriticalSection( &queue->cSection );
785
786             QUEUE_SetWakeBit( queue, QS_SENDMESSAGE );
787             break;
788         }
789
790         default:
791             ERR_(sendmsg)("Invalid list: %d", list);
792             break;
793     }
794
795     return TRUE;
796 }
797
798
799 /***********************************************************************
800  *           QUEUE_RemoveSMSG
801  *
802  * This routine is called when a SMSG needs to be removed from one of the three
803  * SM lists (SM_PROCESSING_LIST, SM_PENDING_LIST, SM_WAITING_LIST).
804  * If smsg == 0, remove the first smsg from the specified list
805  */
806 SMSG *QUEUE_RemoveSMSG( MESSAGEQUEUE *queue, int list, SMSG *smsg )
807 {
808
809     switch (list)
810     {
811         case SM_PROCESSING_LIST:
812             /* don't need to be thread safe, only accessed by the
813              thread associated with the sender queue */
814
815             /* if smsg is equal to null, it means the first in the list */
816             if (!smsg)
817                 smsg = queue->smProcessing;
818
819             TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
820                   smsg, SPY_GetMsgName(smsg->msg));
821             /* In fact SM_PROCESSING_LIST is a stack, and smsg
822              should be always at the top of the list */
823             if ( (smsg != queue->smProcessing) || !queue->smProcessing )
824             {
825                 ERR_(sendmsg)("smsg not at the top of Processing list, smsg=0x%p queue=0x%p\n", smsg, queue);
826                 return 0;
827             }
828             else
829             {
830                 queue->smProcessing = smsg->nextProcessing;
831                 smsg->nextProcessing = 0;
832             }
833             return smsg;
834
835         case SM_WAITING_LIST:
836             /* don't need to be thread safe, only accessed by the
837              thread associated with the receiver queue */
838
839             /* if smsg is equal to null, it means the first in the list */
840             if (!smsg)
841                 smsg = queue->smWaiting;
842             
843             TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
844                   smsg, SPY_GetMsgName(smsg->msg));
845             /* In fact SM_WAITING_LIST is a stack, and smsg
846              should be always at the top of the list */
847             if ( (smsg != queue->smWaiting) || !queue->smWaiting )
848             {
849                 ERR_(sendmsg)("smsg not at the top of Waiting list, smsg=0x%p queue=0x%p\n", smsg, queue);
850                 return 0;
851             }
852             else
853             {
854                 queue->smWaiting = smsg->nextWaiting;
855                 smsg->nextWaiting = 0;
856             }
857             return smsg;
858
859         case SM_PENDING_LIST:
860             /* make it thread safe, could be accessed by the sender and
861              receiver thread */
862             EnterCriticalSection( &queue->cSection );
863     
864             if (!smsg)
865                 smsg = queue->smPending;
866             if ( (smsg != queue->smPending) || !queue->smPending )
867             {
868                 ERR_(sendmsg)("should always remove the top one in Pending list, smsg=0x%p queue=0x%p\n", smsg, queue);
869                 LeaveCriticalSection( &queue->cSection );
870                 return 0;
871             }
872             
873             TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
874                   smsg, SPY_GetMsgName(smsg->msg));
875
876             queue->smPending = smsg->nextPending;
877             smsg->nextPending = 0;
878
879             /* if no more SMSG in Pending list, clear QS_SENDMESSAGE flag */
880             if (!queue->smPending)
881                 QUEUE_ClearWakeBit( queue, QS_SENDMESSAGE );
882             
883             LeaveCriticalSection( &queue->cSection );
884             return smsg;
885
886         default:
887             ERR_(sendmsg)("Invalid list: %d\n", list);
888             break;
889     }
890
891     return 0;
892 }
893
894
895 /***********************************************************************
896  *           QUEUE_ReceiveMessage
897  * 
898  * This routine is called to check whether a sent message is waiting 
899  * for the queue.  If so, it is received and processed.
900  */
901 BOOL QUEUE_ReceiveMessage( MESSAGEQUEUE *queue )
902 {
903     LRESULT       result = 0;
904     SMSG          *smsg;
905     MESSAGEQUEUE  *senderQ;
906
907     EnterCriticalSection( &queue->cSection );
908     if ( !((queue->wakeBits & QS_SENDMESSAGE) && queue->smPending) )
909     {
910         LeaveCriticalSection( &queue->cSection );
911         return FALSE;
912     }
913     LeaveCriticalSection( &queue->cSection );
914
915     TRACE_(sendmsg)("queue %04x\n", queue->self );
916
917     /* remove smsg on the top of the pending list and put it in the processing list */
918     smsg = QUEUE_RemoveSMSG(queue, SM_PENDING_LIST, 0);
919     QUEUE_AddSMSG(queue, SM_WAITING_LIST, smsg);
920
921     TRACE_(sendmsg)("RM: %s [%04x] (%04x -> %04x)\n",
922             SPY_GetMsgName(smsg->msg), smsg->msg, smsg->hSrcQueue, smsg->hDstQueue );
923
924     if (IsWindow( smsg->hWnd ))
925     {
926         WND *wndPtr = WIN_FindWndPtr( smsg->hWnd );
927         DWORD extraInfo = queue->GetMessageExtraInfoVal; /* save ExtraInfo */
928
929         /* use sender queue extra info value while calling the window proc */
930         senderQ = QUEUE_Lock( smsg->hSrcQueue );
931         if (senderQ)
932         {
933             queue->GetMessageExtraInfoVal = senderQ->GetMessageExtraInfoVal;
934             QUEUE_Unlock( senderQ );
935         }
936
937         /* call the right version of CallWindowProcXX */
938         if (smsg->flags & SMSG_WIN32)
939         {
940             TRACE_(sendmsg)("\trcm: msg is Win32\n" );
941             if (smsg->flags & SMSG_UNICODE)
942                 result = CallWindowProcW( wndPtr->winproc,
943                                             smsg->hWnd, smsg->msg,
944                                             smsg->wParam, smsg->lParam );
945             else
946                 result = CallWindowProcA( wndPtr->winproc,
947                                             smsg->hWnd, smsg->msg,
948                                             smsg->wParam, smsg->lParam );
949         }
950         else  /* Win16 message */
951             result = CallWindowProc16( (WNDPROC16)wndPtr->winproc,
952                                        (HWND16) smsg->hWnd,
953                                        (UINT16) smsg->msg,
954                                        LOWORD (smsg->wParam),
955                                        smsg->lParam );
956
957         queue->GetMessageExtraInfoVal = extraInfo;  /* Restore extra info */
958         WIN_ReleaseWndPtr(wndPtr);
959         TRACE_(sendmsg)("result =  %08x\n", (unsigned)result );
960     }
961     else WARN_(sendmsg)("\trcm: bad hWnd\n");
962
963     
964     /* set SMSG_SENDING_REPLY flag to tell ReplyMessage16, it's not
965        an early reply */
966     smsg->flags |= SMSG_SENDING_REPLY;
967     ReplyMessage( result );
968
969     TRACE_(sendmsg)("done!\n" );
970     return TRUE;
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 = QUEUE_Lock( hQueue ))) return FALSE;
987
988     /* allocate new message in global heap for now */
989     if (!(qmsg = (QMSG *) HeapAlloc( GetProcessHeap(), 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( GetProcessHeap(), 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     {
1142         queue = QUEUE_Lock( hQueue );
1143         QUEUE_SetWakeBit( queue, wakeBit );
1144         QUEUE_Unlock( queue );
1145         return;
1146     }
1147
1148     /* Search for someone to wake */
1149     hQueue = hFirstQueue;
1150     while ( (queue = QUEUE_Lock( hQueue )) )
1151     {
1152         if (QUEUE_TrySetWakeBit( queue, wakeBit, FALSE )) 
1153         {
1154             QUEUE_Unlock( queue );
1155             return;
1156         }
1157         
1158         hQueue = queue->next; 
1159         QUEUE_Unlock( queue );
1160     }
1161
1162     WARN_(msg)("couldn't find queue\n"); 
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 messages 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( GetProcessHeap(), 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 = QUEUE_Lock( hQueue ))) return;
1272     EnterCriticalSection( &queue->cSection );
1273     queue->wPaintCount++;
1274     LeaveCriticalSection( &queue->cSection );
1275     QUEUE_SetWakeBit( queue, QS_PAINT );
1276     QUEUE_Unlock( queue );
1277 }
1278
1279
1280 /***********************************************************************
1281  *           QUEUE_DecPaintCount
1282  */
1283 void QUEUE_DecPaintCount( HQUEUE16 hQueue )
1284 {
1285     MESSAGEQUEUE *queue;
1286
1287     if (!(queue = QUEUE_Lock( hQueue ))) return;
1288     EnterCriticalSection( &queue->cSection );
1289     queue->wPaintCount--;
1290     if (!queue->wPaintCount) queue->wakeBits &= ~QS_PAINT;
1291     LeaveCriticalSection( &queue->cSection );
1292     QUEUE_Unlock( queue );
1293 }
1294
1295
1296 /***********************************************************************
1297  *           QUEUE_IncTimerCount
1298  */
1299 void QUEUE_IncTimerCount( HQUEUE16 hQueue )
1300 {
1301     MESSAGEQUEUE *queue;
1302
1303     if (!(queue = QUEUE_Lock( hQueue ))) return;
1304     EnterCriticalSection( &queue->cSection );
1305     queue->wTimerCount++;
1306     LeaveCriticalSection( &queue->cSection );
1307     QUEUE_SetWakeBit( queue, QS_TIMER );
1308     QUEUE_Unlock( queue );
1309 }
1310
1311
1312 /***********************************************************************
1313  *           QUEUE_DecTimerCount
1314  */
1315 void QUEUE_DecTimerCount( HQUEUE16 hQueue )
1316 {
1317     MESSAGEQUEUE *queue;
1318
1319     if (!(queue = QUEUE_Lock( hQueue ))) return;
1320     EnterCriticalSection( &queue->cSection );
1321     queue->wTimerCount--;
1322     if (!queue->wTimerCount) queue->wakeBits &= ~QS_TIMER;
1323     LeaveCriticalSection( &queue->cSection );
1324     QUEUE_Unlock( queue );
1325 }
1326
1327
1328 /***********************************************************************
1329  *              PostQuitMessage (USER.6)
1330  */
1331 void WINAPI PostQuitMessage16( INT16 exitCode )
1332 {
1333     PostQuitMessage( exitCode );
1334 }
1335
1336
1337 /***********************************************************************
1338  *              PostQuitMessage (USER32.@)
1339  *
1340  * PostQuitMessage() posts a message to the system requesting an
1341  * application to terminate execution. As a result of this function,
1342  * the WM_QUIT message is posted to the application, and
1343  * PostQuitMessage() returns immediately.  The exitCode parameter
1344  * specifies an application-defined exit code, which appears in the
1345  * _wParam_ parameter of the WM_QUIT message posted to the application.  
1346  *
1347  * CONFORMANCE
1348  *
1349  *  ECMA-234, Win32
1350  */
1351 void WINAPI PostQuitMessage( INT exitCode )
1352 {
1353     MESSAGEQUEUE *queue;
1354
1355     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return;
1356     EnterCriticalSection( &queue->cSection );
1357     queue->wPostQMsg = TRUE;
1358     queue->wExitCode = (WORD)exitCode;
1359     LeaveCriticalSection( &queue->cSection );
1360     QUEUE_Unlock( queue );
1361 }
1362
1363
1364 /***********************************************************************
1365  *              GetWindowTask (USER.224)
1366  */
1367 HTASK16 WINAPI GetWindowTask16( HWND16 hwnd )
1368 {
1369     HTASK16 retvalue;
1370     WND *wndPtr = WIN_FindWndPtr( hwnd );
1371
1372     if (!wndPtr) return 0;
1373     retvalue = QUEUE_GetQueueTask( wndPtr->hmemTaskQ );
1374     WIN_ReleaseWndPtr(wndPtr);
1375     return retvalue;
1376 }
1377
1378 /***********************************************************************
1379  *              GetWindowThreadProcessId (USER32.@)
1380  */
1381 DWORD WINAPI GetWindowThreadProcessId( HWND hwnd, LPDWORD process )
1382 {
1383     DWORD retvalue;
1384     MESSAGEQUEUE *queue;
1385
1386     WND *wndPtr = WIN_FindWndPtr( hwnd );
1387     if (!wndPtr) return 0;
1388
1389     queue = QUEUE_Lock( wndPtr->hmemTaskQ );
1390     WIN_ReleaseWndPtr(wndPtr);
1391
1392     if (!queue) return 0;
1393
1394     if ( process ) *process = (DWORD)queue->teb->pid;
1395     retvalue = (DWORD)queue->teb->tid;
1396
1397     QUEUE_Unlock( queue );
1398     return retvalue;
1399 }
1400
1401
1402 /***********************************************************************
1403  *              SetMessageQueue (USER.266)
1404  */
1405 BOOL16 WINAPI SetMessageQueue16( INT16 size )
1406 {
1407     return SetMessageQueue( size );
1408 }
1409
1410
1411 /***********************************************************************
1412  *              SetMessageQueue (USER32.@)
1413  */
1414 BOOL WINAPI SetMessageQueue( INT size )
1415 {
1416     /* now obsolete the message queue will be expanded dynamically
1417      as necessary */
1418
1419     /* access the queue to create it if it's not existing */
1420     GetFastQueue16();
1421
1422     return TRUE;
1423 }
1424
1425 /***********************************************************************
1426  *              InitThreadInput (USER.409)
1427  */
1428 HQUEUE16 WINAPI InitThreadInput16( WORD unknown, WORD flags )
1429 {
1430     HQUEUE16 hQueue;
1431     MESSAGEQUEUE *queuePtr;
1432
1433     TEB *teb = NtCurrentTeb();
1434
1435     if (!teb)
1436         return 0;
1437
1438     hQueue = teb->queue;
1439     
1440     if ( !hQueue )
1441     {
1442         /* Create thread message queue */
1443         if( !(hQueue = QUEUE_CreateMsgQueue( TRUE )))
1444         {
1445             ERR_(msg)("failed!\n");
1446             return FALSE;
1447         }
1448         
1449         /* Link new queue into list */
1450         queuePtr = QUEUE_Lock( hQueue );
1451         queuePtr->teb = NtCurrentTeb();
1452
1453         HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
1454         SetThreadQueue16( 0, hQueue );
1455         teb->queue = hQueue;
1456             
1457         queuePtr->next  = hFirstQueue;
1458         hFirstQueue = hQueue;
1459         HeapUnlock( GetProcessHeap() );
1460         
1461         QUEUE_Unlock( queuePtr );
1462     }
1463
1464     return hQueue;
1465 }
1466
1467 /***********************************************************************
1468  *              GetQueueStatus (USER.334)
1469  */
1470 DWORD WINAPI GetQueueStatus16( UINT16 flags )
1471 {
1472     MESSAGEQUEUE *queue;
1473     DWORD ret;
1474
1475     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1476     EnterCriticalSection( &queue->cSection );
1477     ret = MAKELONG( queue->changeBits, queue->wakeBits );
1478     queue->changeBits = 0;
1479     LeaveCriticalSection( &queue->cSection );
1480     QUEUE_Unlock( queue );
1481     
1482     return ret & MAKELONG( flags, flags );
1483 }
1484
1485 /***********************************************************************
1486  *              GetQueueStatus (USER32.@)
1487  */
1488 DWORD WINAPI GetQueueStatus( UINT flags )
1489 {
1490     MESSAGEQUEUE *queue;
1491     DWORD ret;
1492
1493     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1494     EnterCriticalSection( &queue->cSection );
1495     ret = MAKELONG( queue->changeBits, queue->wakeBits );
1496     queue->changeBits = 0;
1497     LeaveCriticalSection( &queue->cSection );
1498     QUEUE_Unlock( queue );
1499     
1500     return ret & MAKELONG( flags, flags );
1501 }
1502
1503
1504 /***********************************************************************
1505  *              GetInputState (USER.335)
1506  */
1507 BOOL16 WINAPI GetInputState16(void)
1508 {
1509     return GetInputState();
1510 }
1511
1512 /***********************************************************************
1513  *              WaitForInputIdle (USER32.@)
1514  */
1515 DWORD WINAPI WaitForInputIdle (HANDLE hProcess, DWORD dwTimeOut)
1516 {
1517     DWORD cur_time, ret;
1518     HANDLE idle_event = -1;
1519
1520     SERVER_START_REQ( wait_input_idle )
1521     {
1522         req->handle = hProcess;
1523         req->timeout = dwTimeOut;
1524         if (!(ret = SERVER_CALL_ERR())) idle_event = req->event;
1525     }
1526     SERVER_END_REQ;
1527     if (ret) return 0xffffffff;  /* error */
1528     if (!idle_event) return 0;  /* no event to wait on */
1529
1530     cur_time = GetTickCount();
1531
1532     TRACE_(msg)("waiting for %x\n", idle_event );
1533     while ( dwTimeOut > GetTickCount() - cur_time || dwTimeOut == INFINITE ) 
1534     {
1535         ret = MsgWaitForMultipleObjects ( 1, &idle_event, FALSE, dwTimeOut, QS_SENDMESSAGE );
1536         if ( ret == ( WAIT_OBJECT_0 + 1 )) 
1537         {
1538             MESSAGEQUEUE * queue;
1539             if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0xFFFFFFFF;
1540             QUEUE_ReceiveMessage ( queue );
1541             QUEUE_Unlock ( queue );
1542             continue; 
1543         }
1544         if ( ret == WAIT_TIMEOUT || ret == 0xFFFFFFFF ) 
1545         {
1546             TRACE_(msg)("timeout or error\n");
1547             return ret;
1548         }
1549         else 
1550         {
1551             TRACE_(msg)("finished\n");
1552             return 0;
1553         }
1554     }
1555
1556     return WAIT_TIMEOUT;
1557 }
1558
1559 /***********************************************************************
1560  *              GetInputState (USER32.@)
1561  */
1562 BOOL WINAPI GetInputState(void)
1563 {
1564     MESSAGEQUEUE *queue;
1565     BOOL ret;
1566
1567     if (!(queue = QUEUE_Lock( GetFastQueue16() )))
1568         return FALSE;
1569     EnterCriticalSection( &queue->cSection );
1570     ret = queue->wakeBits & (QS_KEY | QS_MOUSEBUTTON);
1571     LeaveCriticalSection( &queue->cSection );
1572     QUEUE_Unlock( queue );
1573
1574     return ret;
1575 }
1576
1577 /***********************************************************************
1578  *              UserYield (USER.332)
1579  *              UserYield16 (USER32.@)
1580  */
1581 void WINAPI UserYield16(void)
1582 {
1583     MESSAGEQUEUE *queue;
1584
1585     /* Handle sent messages */
1586     queue = QUEUE_Lock( GetFastQueue16() );
1587
1588     while ( queue && QUEUE_ReceiveMessage( queue ) )
1589         ;
1590
1591     QUEUE_Unlock( queue );
1592
1593     /* Yield */
1594     OldYield16();
1595
1596     /* Handle sent messages again */
1597     queue = QUEUE_Lock( GetFastQueue16() );
1598
1599     while ( queue && QUEUE_ReceiveMessage( queue ) )
1600         ;
1601
1602     QUEUE_Unlock( queue );
1603 }
1604
1605 /***********************************************************************
1606  *              GetMessagePos (USER.119) (USER32.@)
1607  * 
1608  * The GetMessagePos() function returns a long value representing a
1609  * cursor position, in screen coordinates, when the last message
1610  * retrieved by the GetMessage() function occurs. The x-coordinate is
1611  * in the low-order word of the return value, the y-coordinate is in
1612  * the high-order word. The application can use the MAKEPOINT()
1613  * macro to obtain a POINT structure from the return value. 
1614  *
1615  * For the current cursor position, use GetCursorPos().
1616  *
1617  * RETURNS
1618  *
1619  * Cursor position of last message on success, zero on failure.
1620  *
1621  * CONFORMANCE
1622  *
1623  * ECMA-234, Win32
1624  *
1625  */
1626 DWORD WINAPI GetMessagePos(void)
1627 {
1628     MESSAGEQUEUE *queue;
1629     DWORD ret;
1630
1631     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1632     ret = queue->GetMessagePosVal;
1633     QUEUE_Unlock( queue );
1634
1635     return ret;
1636 }
1637
1638
1639 /***********************************************************************
1640  *              GetMessageTime (USER.120) (USER32.@)
1641  *
1642  * GetMessageTime() returns the message time for the last message
1643  * retrieved by the function. The time is measured in milliseconds with
1644  * the same offset as GetTickCount().
1645  *
1646  * Since the tick count wraps, this is only useful for moderately short
1647  * relative time comparisons.
1648  *
1649  * RETURNS
1650  *
1651  * Time of last message on success, zero on failure.
1652  *
1653  * CONFORMANCE
1654  *
1655  * ECMA-234, Win32
1656  *  
1657  */
1658 LONG WINAPI GetMessageTime(void)
1659 {
1660     MESSAGEQUEUE *queue;
1661     LONG ret;
1662
1663     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1664     ret = queue->GetMessageTimeVal;
1665     QUEUE_Unlock( queue );
1666     
1667     return ret;
1668 }
1669
1670
1671 /***********************************************************************
1672  *              GetMessageExtraInfo (USER.288) (USER32.@)
1673  */
1674 LONG WINAPI GetMessageExtraInfo(void)
1675 {
1676     MESSAGEQUEUE *queue;
1677     LONG ret;
1678
1679     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1680     ret = queue->GetMessageExtraInfoVal;
1681     QUEUE_Unlock( queue );
1682
1683     return ret;
1684 }
1685
1686
1687 /**********************************************************************
1688  *              AttachThreadInput (USER32.@) Attaches input of 1 thread to other
1689  *
1690  * Attaches the input processing mechanism of one thread to that of
1691  * another thread.
1692  *
1693  * RETURNS
1694  *    Success: TRUE
1695  *    Failure: FALSE
1696  *
1697  * TODO:
1698  *    1. Reset the Key State (currenly per thread key state is not maintained)
1699  */
1700 BOOL WINAPI AttachThreadInput( 
1701     DWORD idAttach,   /* [in] Thread to attach */
1702     DWORD idAttachTo, /* [in] Thread to attach to */
1703     BOOL fAttach)   /* [in] Attach or detach */
1704 {
1705     MESSAGEQUEUE *pSrcMsgQ = 0, *pTgtMsgQ = 0;
1706     BOOL16 bRet = 0;
1707
1708     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1709
1710     /* A thread cannot attach to itself */
1711     if ( idAttach == idAttachTo )
1712         goto CLEANUP;
1713
1714     /* According to the docs this method should fail if a
1715      * "Journal record" hook is installed. (attaches all input queues together)
1716      */
1717     if ( HOOK_IsHooked( WH_JOURNALRECORD ) )
1718         goto CLEANUP;
1719         
1720     /* Retrieve message queues corresponding to the thread id's */
1721     pTgtMsgQ = QUEUE_Lock( GetThreadQueue16( idAttach ) );
1722     pSrcMsgQ = QUEUE_Lock( GetThreadQueue16( idAttachTo ) );
1723
1724     /* Ensure we have message queues and that Src and Tgt threads
1725      * are not system threads.
1726      */
1727     if ( !pSrcMsgQ || !pTgtMsgQ || !pSrcMsgQ->pQData || !pTgtMsgQ->pQData )
1728         goto CLEANUP;
1729
1730     if (fAttach)   /* Attach threads */
1731     {
1732         /* Only attach if currently detached  */
1733         if ( pTgtMsgQ->pQData != pSrcMsgQ->pQData )
1734         {
1735             /* First release the target threads perQData */
1736             PERQDATA_Release( pTgtMsgQ->pQData );
1737         
1738             /* Share a reference to the source threads perQDATA */
1739             PERQDATA_Addref( pSrcMsgQ->pQData );
1740             pTgtMsgQ->pQData = pSrcMsgQ->pQData;
1741         }
1742     }
1743     else    /* Detach threads */
1744     {
1745         /* Only detach if currently attached */
1746         if ( pTgtMsgQ->pQData == pSrcMsgQ->pQData )
1747         {
1748             /* First release the target threads perQData */
1749             PERQDATA_Release( pTgtMsgQ->pQData );
1750         
1751             /* Give the target thread its own private perQDATA once more */
1752             pTgtMsgQ->pQData = PERQDATA_CreateInstance();
1753         }
1754     }
1755
1756     /* TODO: Reset the Key State */
1757
1758     bRet = 1;      /* Success */
1759     
1760 CLEANUP:
1761
1762     /* Unlock the queues before returning */
1763     if ( pSrcMsgQ )
1764         QUEUE_Unlock( pSrcMsgQ );
1765     if ( pTgtMsgQ )
1766         QUEUE_Unlock( pTgtMsgQ );
1767     
1768     return bRet;
1769 }