Do not allocate any USER data on the system heap.
[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
455     {
456         struct get_msg_queue_request *req = server_alloc_req( sizeof(*req), 0 );
457         server_call( REQ_GET_MSG_QUEUE );
458         handle = req->handle;
459     }
460     SERVER_END_REQ;
461     if (!handle)
462     {
463         ERR_(msg)("Cannot get thread queue");
464         GlobalFree16( hQueue );
465         return 0;
466     }
467     msgQueue->server_queue = handle;
468     msgQueue->server_queue = ConvertToGlobalHandle( msgQueue->server_queue );
469
470     msgQueue->self        = hQueue;
471     msgQueue->wakeBits    = msgQueue->changeBits = 0;
472     
473     InitializeCriticalSection( &msgQueue->cSection );
474     MakeCriticalSectionGlobal( &msgQueue->cSection );
475
476     msgQueue->lockCount = 1;
477     msgQueue->magic = QUEUE_MAGIC;
478     
479     /* Create and initialize our per queue data */
480     msgQueue->pQData = bCreatePerQData ? PERQDATA_CreateInstance() : NULL;
481     
482     return hQueue;
483 }
484
485
486 /***********************************************************************
487  *           QUEUE_FlushMessage
488  * 
489  * Try to reply to all pending sent messages on exit.
490  */
491 static void QUEUE_FlushMessages( MESSAGEQUEUE *queue )
492 {
493     SMSG *smsg;
494     MESSAGEQUEUE *senderQ = 0;
495
496     if( queue )
497     {
498         EnterCriticalSection( &queue->cSection );
499
500         /* empty the list of pending SendMessage waiting to be received */
501         while (queue->smPending)
502         {
503             smsg = QUEUE_RemoveSMSG( queue, SM_PENDING_LIST, 0);
504
505             senderQ = QUEUE_Lock( smsg->hSrcQueue );
506             if ( !senderQ )
507                 continue;
508
509             /* return 0, to unblock other thread */
510             smsg->lResult = 0;
511             smsg->flags |= SMSG_HAVE_RESULT;
512             QUEUE_SetWakeBit( senderQ, QS_SMRESULT);
513             
514             QUEUE_Unlock( senderQ );
515         }
516
517         QUEUE_ClearWakeBit( queue, QS_SENDMESSAGE );
518         
519         LeaveCriticalSection( &queue->cSection );
520     }
521 }
522
523
524 /***********************************************************************
525  *           QUEUE_DeleteMsgQueue
526  *
527  * Unlinks and deletes a message queue.
528  *
529  * Note: We need to mask asynchronous events to make sure PostMessage works
530  * even in the signal handler.
531  */
532 BOOL QUEUE_DeleteMsgQueue( HQUEUE16 hQueue )
533 {
534     MESSAGEQUEUE * msgQueue = QUEUE_Lock(hQueue);
535     HQUEUE16 *pPrev;
536
537     TRACE_(msg)("(): Deleting message queue %04x\n", hQueue);
538
539     if (!hQueue || !msgQueue)
540     {
541         ERR_(msg)("invalid argument.\n");
542         return 0;
543     }
544
545     msgQueue->magic = 0;
546     
547     if( hCursorQueue == hQueue ) hCursorQueue = 0;
548     if( hActiveQueue == hQueue ) hActiveQueue = 0;
549
550     /* flush sent messages */
551     QUEUE_FlushMessages( msgQueue );
552
553     HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
554
555     /* Release per queue data if present */
556     if ( msgQueue->pQData )
557     {
558         PERQDATA_Release( msgQueue->pQData );
559         msgQueue->pQData = 0;
560     }
561     
562     /* remove the message queue from the global link list */
563     pPrev = &hFirstQueue;
564     while (*pPrev && (*pPrev != hQueue))
565     {
566         MESSAGEQUEUE *msgQ = (MESSAGEQUEUE*)GlobalLock16(*pPrev);
567
568         /* sanity check */
569         if ( !msgQ || (msgQ->magic != QUEUE_MAGIC) )
570         {
571             /* HQUEUE link list is corrupted, try to exit gracefully */
572             ERR_(msg)("HQUEUE link list corrupted!\n");
573             pPrev = 0;
574             break;
575         }
576         pPrev = &msgQ->next;
577     }
578     if (pPrev && *pPrev) *pPrev = msgQueue->next;
579     msgQueue->self = 0;
580
581     HeapUnlock( GetProcessHeap() );
582
583     /* free up resource used by MESSAGEQUEUE structure */
584     msgQueue->lockCount--;
585     QUEUE_Unlock( msgQueue );
586     
587     return 1;
588 }
589
590
591 /***********************************************************************
592  *           QUEUE_CreateSysMsgQueue
593  *
594  * Create the system message queue, and set the double-click speed.
595  * Must be called only once.
596  */
597 BOOL QUEUE_CreateSysMsgQueue( int size )
598 {
599     /* Note: We dont need perQ data for the system message queue */
600     if (!(hmemSysMsgQueue = QUEUE_CreateMsgQueue( FALSE )))
601         return FALSE;
602     
603     sysMsgQueue = (MESSAGEQUEUE *) GlobalLock16( hmemSysMsgQueue );
604     return TRUE;
605 }
606
607
608 /***********************************************************************
609  *           QUEUE_GetSysQueue
610  */
611 MESSAGEQUEUE *QUEUE_GetSysQueue(void)
612 {
613     return sysMsgQueue;
614 }
615
616
617 /***********************************************************************
618  *           QUEUE_SetWakeBit
619  *
620  * See "Windows Internals", p.449
621  */
622 static BOOL QUEUE_TrySetWakeBit( MESSAGEQUEUE *queue, WORD bit, BOOL always )
623 {
624     BOOL wake = FALSE;
625
626     EnterCriticalSection( &queue->cSection );
627
628     TRACE_(msg)("queue = %04x (wm=%04x), bit = %04x, always = %d\n", 
629                         queue->self, queue->wakeMask, bit, always );
630
631     if ((queue->wakeMask & bit) || always)
632     {
633         if (bit & QS_MOUSE) pMouseQueue = queue;
634         if (bit & QS_KEY) pKbdQueue = queue;
635         queue->changeBits |= bit;
636         queue->wakeBits   |= bit;
637     }
638     if (queue->wakeMask & bit)
639     {
640         queue->wakeMask = 0;
641         wake = TRUE;
642     }
643
644     LeaveCriticalSection( &queue->cSection );
645
646     if ( wake )
647     {
648         /* Wake up thread waiting for message */
649         if ( THREAD_IsWin16( queue->teb ) )
650         {
651             int iWndsLock = WIN_SuspendWndsLock();
652             PostEvent16( queue->teb->htask16 );
653             WIN_RestoreWndsLock( iWndsLock );
654         }
655         else
656         {
657             SERVER_START_REQ
658             {
659                 struct wake_queue_request *req = server_alloc_req( sizeof(*req), 0 );
660                 req->handle = queue->server_queue;
661                 req->bits   = bit;
662                 server_call( REQ_WAKE_QUEUE );
663             }
664             SERVER_END_REQ;
665         }
666     }
667
668     return wake;
669 }
670 void QUEUE_SetWakeBit( MESSAGEQUEUE *queue, WORD bit )
671 {
672     QUEUE_TrySetWakeBit( queue, bit, TRUE );
673 }
674
675
676 /***********************************************************************
677  *           QUEUE_ClearWakeBit
678  */
679 void QUEUE_ClearWakeBit( MESSAGEQUEUE *queue, WORD bit )
680 {
681     EnterCriticalSection( &queue->cSection );
682     queue->changeBits &= ~bit;
683     queue->wakeBits   &= ~bit;
684     LeaveCriticalSection( &queue->cSection );
685 }
686
687 /***********************************************************************
688  *           QUEUE_TestWakeBit
689  */
690 WORD QUEUE_TestWakeBit( MESSAGEQUEUE *queue, WORD bit )
691 {
692     WORD ret;
693     EnterCriticalSection( &queue->cSection );
694     ret = queue->wakeBits & bit;
695     LeaveCriticalSection( &queue->cSection );
696     return ret;
697 }
698
699
700 /***********************************************************************
701  *           QUEUE_WaitBits
702  *
703  * See "Windows Internals", p.447
704  *
705  * return values:
706  *    0 if exit with timeout
707  *    1 otherwise
708  */
709 int QUEUE_WaitBits( WORD bits, DWORD timeout )
710 {
711     MESSAGEQUEUE *queue;
712     DWORD curTime = 0;
713     HQUEUE16 hQueue;
714
715     TRACE_(msg)("q %04x waiting for %04x\n", GetFastQueue16(), bits);
716
717     if ( THREAD_IsWin16( NtCurrentTeb() ) && (timeout != INFINITE) )
718         curTime = GetTickCount();
719
720     hQueue = GetFastQueue16();
721     if (!(queue = QUEUE_Lock( hQueue ))) return 0;
722     
723     for (;;)
724     {
725         EnterCriticalSection( &queue->cSection );
726
727         if (queue->changeBits & bits)
728         {
729             /* One of the bits is set; we can return */
730             queue->wakeMask = 0;
731
732             LeaveCriticalSection( &queue->cSection );
733             QUEUE_Unlock( queue );
734             return 1;
735         }
736         if (queue->wakeBits & QS_SENDMESSAGE)
737         {
738             /* Process the sent message immediately */
739             queue->wakeMask = 0;
740
741             LeaveCriticalSection( &queue->cSection );
742             QUEUE_ReceiveMessage( queue );
743             continue;                           /* nested sm crux */
744         }
745
746         queue->wakeMask = bits | QS_SENDMESSAGE;
747         TRACE_(msg)("%04x) wakeMask is %04x, waiting\n", queue->self, queue->wakeMask);
748         LeaveCriticalSection( &queue->cSection );
749
750         if ( !THREAD_IsWin16( NtCurrentTeb() ) )
751         {
752             BOOL                bHasWin16Lock;
753             DWORD               dwlc;
754
755             if ( (bHasWin16Lock = _ConfirmWin16Lock()) )
756             {
757                 TRACE_(msg)("bHasWin16Lock=TRUE\n");
758                 ReleaseThunkLock( &dwlc );
759             }
760
761             WaitForSingleObject( queue->server_queue, timeout );
762
763             if ( bHasWin16Lock ) 
764             {
765                 RestoreThunkLock( dwlc );
766             }
767         }
768         else
769         {
770             if ( timeout == INFINITE )
771                 WaitEvent16( 0 );  /* win 16 thread, use WaitEvent */
772             else
773             {
774                 /* check for timeout, then give control to other tasks */
775                 if (GetTickCount() - curTime > timeout)
776                 {
777
778                     QUEUE_Unlock( queue );
779                     return 0;   /* exit with timeout */
780                 }
781                 K32WOWYield16();
782             }
783         }
784     }
785 }
786
787
788 /***********************************************************************
789  *           QUEUE_AddSMSG
790  *
791  * This routine is called when a SMSG need to be added to one of the three
792  * SM list.  (SM_PROCESSING_LIST, SM_PENDING_LIST, SM_WAITING_LIST)
793  */
794 BOOL QUEUE_AddSMSG( MESSAGEQUEUE *queue, int list, SMSG *smsg )
795 {
796     TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
797           smsg, SPY_GetMsgName(smsg->msg));
798     
799     switch (list)
800     {
801         case SM_PROCESSING_LIST:
802             /* don't need to be thread safe, only accessed by the
803              thread associated with the sender queue */
804             smsg->nextProcessing = queue->smProcessing;
805             queue->smProcessing = smsg;
806             break;
807             
808         case SM_WAITING_LIST:
809             /* don't need to be thread safe, only accessed by the
810              thread associated with the receiver queue */
811             smsg->nextWaiting = queue->smWaiting;
812             queue->smWaiting = smsg;
813             break;
814             
815         case SM_PENDING_LIST:
816         {
817             /* make it thread safe, could be accessed by the sender and
818              receiver thread */
819             SMSG **prev;
820
821             EnterCriticalSection( &queue->cSection );
822             smsg->nextPending = NULL;
823             prev = &queue->smPending;
824             while ( *prev )
825                 prev = &(*prev)->nextPending;
826             *prev = smsg;
827             LeaveCriticalSection( &queue->cSection );
828
829             QUEUE_SetWakeBit( queue, QS_SENDMESSAGE );
830             break;
831         }
832
833         default:
834             ERR_(sendmsg)("Invalid list: %d", list);
835             break;
836     }
837
838     return TRUE;
839 }
840
841
842 /***********************************************************************
843  *           QUEUE_RemoveSMSG
844  *
845  * This routine is called when a SMSG needs to be removed from one of the three
846  * SM lists (SM_PROCESSING_LIST, SM_PENDING_LIST, SM_WAITING_LIST).
847  * If smsg == 0, remove the first smsg from the specified list
848  */
849 SMSG *QUEUE_RemoveSMSG( MESSAGEQUEUE *queue, int list, SMSG *smsg )
850 {
851
852     switch (list)
853     {
854         case SM_PROCESSING_LIST:
855             /* don't need to be thread safe, only accessed by the
856              thread associated with the sender queue */
857
858             /* if smsg is equal to null, it means the first in the list */
859             if (!smsg)
860                 smsg = queue->smProcessing;
861
862             TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
863                   smsg, SPY_GetMsgName(smsg->msg));
864             /* In fact SM_PROCESSING_LIST is a stack, and smsg
865              should be always at the top of the list */
866             if ( (smsg != queue->smProcessing) || !queue->smProcessing )
867             {
868                 ERR_(sendmsg)("smsg not at the top of Processing list, smsg=0x%p queue=0x%p\n", smsg, queue);
869                 return 0;
870             }
871             else
872             {
873                 queue->smProcessing = smsg->nextProcessing;
874                 smsg->nextProcessing = 0;
875             }
876             return smsg;
877
878         case SM_WAITING_LIST:
879             /* don't need to be thread safe, only accessed by the
880              thread associated with the receiver queue */
881
882             /* if smsg is equal to null, it means the first in the list */
883             if (!smsg)
884                 smsg = queue->smWaiting;
885             
886             TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
887                   smsg, SPY_GetMsgName(smsg->msg));
888             /* In fact SM_WAITING_LIST is a stack, and smsg
889              should be always at the top of the list */
890             if ( (smsg != queue->smWaiting) || !queue->smWaiting )
891             {
892                 ERR_(sendmsg)("smsg not at the top of Waiting list, smsg=0x%p queue=0x%p\n", smsg, queue);
893                 return 0;
894             }
895             else
896             {
897                 queue->smWaiting = smsg->nextWaiting;
898                 smsg->nextWaiting = 0;
899             }
900             return smsg;
901
902         case SM_PENDING_LIST:
903             /* make it thread safe, could be accessed by the sender and
904              receiver thread */
905             EnterCriticalSection( &queue->cSection );
906     
907             if (!smsg)
908                 smsg = queue->smPending;
909             if ( (smsg != queue->smPending) || !queue->smPending )
910             {
911                 ERR_(sendmsg)("should always remove the top one in Pending list, smsg=0x%p queue=0x%p\n", smsg, queue);
912                 LeaveCriticalSection( &queue->cSection );
913                 return 0;
914             }
915             
916             TRACE_(sendmsg)("queue=%x, list=%d, smsg=%p msg=%s\n", queue->self, list,
917                   smsg, SPY_GetMsgName(smsg->msg));
918
919             queue->smPending = smsg->nextPending;
920             smsg->nextPending = 0;
921
922             /* if no more SMSG in Pending list, clear QS_SENDMESSAGE flag */
923             if (!queue->smPending)
924                 QUEUE_ClearWakeBit( queue, QS_SENDMESSAGE );
925             
926             LeaveCriticalSection( &queue->cSection );
927             return smsg;
928
929         default:
930             ERR_(sendmsg)("Invalid list: %d\n", list);
931             break;
932     }
933
934     return 0;
935 }
936
937
938 /***********************************************************************
939  *           QUEUE_ReceiveMessage
940  * 
941  * This routine is called to check whether a sent message is waiting 
942  * for the queue.  If so, it is received and processed.
943  */
944 BOOL QUEUE_ReceiveMessage( MESSAGEQUEUE *queue )
945 {
946     LRESULT       result = 0;
947     SMSG          *smsg;
948     MESSAGEQUEUE  *senderQ;
949
950     EnterCriticalSection( &queue->cSection );
951     if ( !((queue->wakeBits & QS_SENDMESSAGE) && queue->smPending) )
952     {
953         LeaveCriticalSection( &queue->cSection );
954         return FALSE;
955     }
956     LeaveCriticalSection( &queue->cSection );
957
958     TRACE_(sendmsg)("queue %04x\n", queue->self );
959
960     /* remove smsg on the top of the pending list and put it in the processing list */
961     smsg = QUEUE_RemoveSMSG(queue, SM_PENDING_LIST, 0);
962     QUEUE_AddSMSG(queue, SM_WAITING_LIST, smsg);
963
964     TRACE_(sendmsg)("RM: %s [%04x] (%04x -> %04x)\n",
965             SPY_GetMsgName(smsg->msg), smsg->msg, smsg->hSrcQueue, smsg->hDstQueue );
966
967     if (IsWindow( smsg->hWnd ))
968     {
969         WND *wndPtr = WIN_FindWndPtr( smsg->hWnd );
970         DWORD extraInfo = queue->GetMessageExtraInfoVal; /* save ExtraInfo */
971
972         /* use sender queue extra info value while calling the window proc */
973         senderQ = QUEUE_Lock( smsg->hSrcQueue );
974         if (senderQ)
975         {
976             queue->GetMessageExtraInfoVal = senderQ->GetMessageExtraInfoVal;
977             QUEUE_Unlock( senderQ );
978         }
979
980         /* call the right version of CallWindowProcXX */
981         if (smsg->flags & SMSG_WIN32)
982         {
983             TRACE_(sendmsg)("\trcm: msg is Win32\n" );
984             if (smsg->flags & SMSG_UNICODE)
985                 result = CallWindowProcW( wndPtr->winproc,
986                                             smsg->hWnd, smsg->msg,
987                                             smsg->wParam, smsg->lParam );
988             else
989                 result = CallWindowProcA( wndPtr->winproc,
990                                             smsg->hWnd, smsg->msg,
991                                             smsg->wParam, smsg->lParam );
992         }
993         else  /* Win16 message */
994             result = CallWindowProc16( (WNDPROC16)wndPtr->winproc,
995                                        (HWND16) smsg->hWnd,
996                                        (UINT16) smsg->msg,
997                                        LOWORD (smsg->wParam),
998                                        smsg->lParam );
999
1000         queue->GetMessageExtraInfoVal = extraInfo;  /* Restore extra info */
1001         WIN_ReleaseWndPtr(wndPtr);
1002         TRACE_(sendmsg)("result =  %08x\n", (unsigned)result );
1003     }
1004     else WARN_(sendmsg)("\trcm: bad hWnd\n");
1005
1006     
1007     /* set SMSG_SENDING_REPLY flag to tell ReplyMessage16, it's not
1008        an early reply */
1009     smsg->flags |= SMSG_SENDING_REPLY;
1010     ReplyMessage( result );
1011
1012     TRACE_(sendmsg)("done!\n" );
1013     return TRUE;
1014 }
1015
1016
1017
1018 /***********************************************************************
1019  *           QUEUE_AddMsg
1020  *
1021  * Add a message to the queue. Return FALSE if queue is full.
1022  */
1023 BOOL QUEUE_AddMsg( HQUEUE16 hQueue, int type, MSG *msg, DWORD extraInfo )
1024 {
1025     MESSAGEQUEUE *msgQueue;
1026     QMSG         *qmsg;
1027
1028
1029     if (!(msgQueue = QUEUE_Lock( hQueue ))) return FALSE;
1030
1031     /* allocate new message in global heap for now */
1032     if (!(qmsg = (QMSG *) HeapAlloc( GetProcessHeap(), 0, sizeof(QMSG) ) ))
1033     {
1034         QUEUE_Unlock( msgQueue );
1035         return 0;
1036     }
1037
1038     EnterCriticalSection( &msgQueue->cSection );
1039
1040       /* Store message */
1041     qmsg->type = type;
1042     qmsg->msg = *msg;
1043     qmsg->extraInfo = extraInfo;
1044
1045     /* insert the message in the link list */
1046     qmsg->nextMsg = 0;
1047     qmsg->prevMsg = msgQueue->lastMsg;
1048
1049     if (msgQueue->lastMsg)
1050         msgQueue->lastMsg->nextMsg = qmsg;
1051
1052     /* update first and last anchor in message queue */
1053     msgQueue->lastMsg = qmsg;
1054     if (!msgQueue->firstMsg)
1055         msgQueue->firstMsg = qmsg;
1056     
1057     msgQueue->msgCount++;
1058
1059     LeaveCriticalSection( &msgQueue->cSection );
1060
1061     QUEUE_SetWakeBit( msgQueue, QS_POSTMESSAGE );
1062     QUEUE_Unlock( msgQueue );
1063     
1064     return TRUE;
1065 }
1066
1067
1068
1069 /***********************************************************************
1070  *           QUEUE_FindMsg
1071  *
1072  * Find a message matching the given parameters. Return -1 if none available.
1073  */
1074 QMSG* QUEUE_FindMsg( MESSAGEQUEUE * msgQueue, HWND hwnd, int first, int last )
1075 {
1076     QMSG* qmsg;
1077
1078     EnterCriticalSection( &msgQueue->cSection );
1079
1080     if (!msgQueue->msgCount)
1081         qmsg = 0;
1082     else if (!hwnd && !first && !last)
1083         qmsg = msgQueue->firstMsg;
1084     else
1085     {
1086         /* look in linked list for message matching first and last criteria */
1087         for (qmsg = msgQueue->firstMsg; qmsg; qmsg = qmsg->nextMsg)
1088         {
1089             MSG *msg = &(qmsg->msg);
1090
1091             if (!hwnd || (msg->hwnd == hwnd))
1092             {
1093                 if (!first && !last)
1094                     break;   /* found it */
1095                 
1096                 if ((msg->message >= first) && (!last || (msg->message <= last)))
1097                     break;   /* found it */
1098             }
1099         }
1100     }
1101     
1102     LeaveCriticalSection( &msgQueue->cSection );
1103
1104     return qmsg;
1105 }
1106
1107
1108
1109 /***********************************************************************
1110  *           QUEUE_RemoveMsg
1111  *
1112  * Remove a message from the queue (pos must be a valid position).
1113  */
1114 void QUEUE_RemoveMsg( MESSAGEQUEUE * msgQueue, QMSG *qmsg )
1115 {
1116     EnterCriticalSection( &msgQueue->cSection );
1117
1118     /* set the linked list */
1119     if (qmsg->prevMsg)
1120         qmsg->prevMsg->nextMsg = qmsg->nextMsg;
1121
1122     if (qmsg->nextMsg)
1123         qmsg->nextMsg->prevMsg = qmsg->prevMsg;
1124
1125     if (msgQueue->firstMsg == qmsg)
1126         msgQueue->firstMsg = qmsg->nextMsg;
1127
1128     if (msgQueue->lastMsg == qmsg)
1129         msgQueue->lastMsg = qmsg->prevMsg;
1130
1131     /* deallocate the memory for the message */
1132     HeapFree( GetProcessHeap(), 0, qmsg );
1133     
1134     msgQueue->msgCount--;
1135     if (!msgQueue->msgCount) msgQueue->wakeBits &= ~QS_POSTMESSAGE;
1136
1137     LeaveCriticalSection( &msgQueue->cSection );
1138 }
1139
1140
1141 /***********************************************************************
1142  *           QUEUE_WakeSomeone
1143  *
1144  * Wake a queue upon reception of a hardware event.
1145  */
1146 static void QUEUE_WakeSomeone( UINT message )
1147 {
1148     WND*          wndPtr = NULL;
1149     WORD          wakeBit;
1150     HWND hwnd;
1151     HQUEUE16     hQueue = 0;
1152     MESSAGEQUEUE *queue = NULL;
1153
1154     if (hCursorQueue)
1155         hQueue = hCursorQueue;
1156
1157     if( (message >= WM_KEYFIRST) && (message <= WM_KEYLAST) )
1158     {
1159        wakeBit = QS_KEY;
1160        if( hActiveQueue )
1161            hQueue = hActiveQueue;
1162     }
1163     else 
1164     {
1165        wakeBit = (message == WM_MOUSEMOVE) ? QS_MOUSEMOVE : QS_MOUSEBUTTON;
1166        if( (hwnd = GetCapture()) )
1167          if( (wndPtr = WIN_FindWndPtr( hwnd )) ) 
1168            {
1169                hQueue = wndPtr->hmemTaskQ;
1170                WIN_ReleaseWndPtr(wndPtr);
1171            }
1172     }
1173
1174     if( (hwnd = GetSysModalWindow16()) )
1175     {
1176       if( (wndPtr = WIN_FindWndPtr( hwnd )) )
1177         {
1178             hQueue = wndPtr->hmemTaskQ;
1179             WIN_ReleaseWndPtr(wndPtr);
1180         }
1181     }
1182
1183     if (hQueue)
1184     {
1185         queue = QUEUE_Lock( hQueue );
1186         QUEUE_SetWakeBit( queue, wakeBit );
1187         QUEUE_Unlock( queue );
1188         return;
1189     }
1190
1191     /* Search for someone to wake */
1192     hQueue = hFirstQueue;
1193     while ( (queue = QUEUE_Lock( hQueue )) )
1194     {
1195         if (QUEUE_TrySetWakeBit( queue, wakeBit, FALSE )) 
1196         {
1197             QUEUE_Unlock( queue );
1198             return;
1199         }
1200         
1201         hQueue = queue->next; 
1202         QUEUE_Unlock( queue );
1203     }
1204
1205     WARN_(msg)("couldn't find queue\n"); 
1206 }
1207
1208
1209 /***********************************************************************
1210  *           hardware_event
1211  *
1212  * Add an event to the system message queue.
1213  * Note: the position is relative to the desktop window.
1214  */
1215 void hardware_event( UINT message, WPARAM wParam, LPARAM lParam,
1216                      int xPos, int yPos, DWORD time, DWORD extraInfo )
1217 {
1218     MSG *msg;
1219     QMSG  *qmsg;
1220     int  mergeMsg = 0;
1221
1222     if (!sysMsgQueue) return;
1223
1224     EnterCriticalSection( &sysMsgQueue->cSection );
1225
1226     /* Merge with previous event if possible */
1227     qmsg = sysMsgQueue->lastMsg;
1228
1229     if ((message == WM_MOUSEMOVE) && sysMsgQueue->lastMsg)
1230     {
1231         msg = &(sysMsgQueue->lastMsg->msg);
1232         
1233         if ((msg->message == message) && (msg->wParam == wParam))
1234         {
1235             /* Merge events */
1236             qmsg = sysMsgQueue->lastMsg;
1237             mergeMsg = 1;
1238         }
1239     }
1240
1241     if (!mergeMsg)
1242     {
1243         /* Should I limit the number of messages in
1244           the system message queue??? */
1245
1246         /* Don't merge allocate a new msg in the global heap */
1247         
1248         if (!(qmsg = (QMSG *) HeapAlloc( GetProcessHeap(), 0, sizeof(QMSG) ) ))
1249         {
1250             LeaveCriticalSection( &sysMsgQueue->cSection );
1251             return;
1252         }
1253         
1254         /* put message at the end of the linked list */
1255         qmsg->nextMsg = 0;
1256         qmsg->prevMsg = sysMsgQueue->lastMsg;
1257
1258         if (sysMsgQueue->lastMsg)
1259             sysMsgQueue->lastMsg->nextMsg = qmsg;
1260
1261         /* set last and first anchor index in system message queue */
1262         sysMsgQueue->lastMsg = qmsg;
1263         if (!sysMsgQueue->firstMsg)
1264             sysMsgQueue->firstMsg = qmsg;
1265         
1266         sysMsgQueue->msgCount++;
1267     }
1268
1269       /* Store message */
1270     msg = &(qmsg->msg);
1271     msg->hwnd    = 0;
1272     msg->message = message;
1273     msg->wParam  = wParam;
1274     msg->lParam  = lParam;
1275     msg->time    = time;
1276     msg->pt.x    = xPos;
1277     msg->pt.y    = yPos;
1278     qmsg->extraInfo = extraInfo;
1279     qmsg->type      = QMSG_HARDWARE;
1280
1281     LeaveCriticalSection( &sysMsgQueue->cSection );
1282
1283     QUEUE_WakeSomeone( message );
1284 }
1285
1286                     
1287 /***********************************************************************
1288  *           QUEUE_GetQueueTask
1289  */
1290 HTASK16 QUEUE_GetQueueTask( HQUEUE16 hQueue )
1291 {
1292     HTASK16 hTask = 0;
1293     
1294     MESSAGEQUEUE *queue = QUEUE_Lock( hQueue );
1295
1296     if (queue)
1297     {
1298         hTask = queue->teb->htask16;
1299         QUEUE_Unlock( queue );
1300     }
1301
1302     return hTask;
1303 }
1304
1305
1306
1307 /***********************************************************************
1308  *           QUEUE_IncPaintCount
1309  */
1310 void QUEUE_IncPaintCount( HQUEUE16 hQueue )
1311 {
1312     MESSAGEQUEUE *queue;
1313
1314     if (!(queue = QUEUE_Lock( hQueue ))) return;
1315     EnterCriticalSection( &queue->cSection );
1316     queue->wPaintCount++;
1317     LeaveCriticalSection( &queue->cSection );
1318     QUEUE_SetWakeBit( queue, QS_PAINT );
1319     QUEUE_Unlock( queue );
1320 }
1321
1322
1323 /***********************************************************************
1324  *           QUEUE_DecPaintCount
1325  */
1326 void QUEUE_DecPaintCount( HQUEUE16 hQueue )
1327 {
1328     MESSAGEQUEUE *queue;
1329
1330     if (!(queue = QUEUE_Lock( hQueue ))) return;
1331     EnterCriticalSection( &queue->cSection );
1332     queue->wPaintCount--;
1333     if (!queue->wPaintCount) queue->wakeBits &= ~QS_PAINT;
1334     LeaveCriticalSection( &queue->cSection );
1335     QUEUE_Unlock( queue );
1336 }
1337
1338
1339 /***********************************************************************
1340  *           QUEUE_IncTimerCount
1341  */
1342 void QUEUE_IncTimerCount( HQUEUE16 hQueue )
1343 {
1344     MESSAGEQUEUE *queue;
1345
1346     if (!(queue = QUEUE_Lock( hQueue ))) return;
1347     EnterCriticalSection( &queue->cSection );
1348     queue->wTimerCount++;
1349     LeaveCriticalSection( &queue->cSection );
1350     QUEUE_SetWakeBit( queue, QS_TIMER );
1351     QUEUE_Unlock( queue );
1352 }
1353
1354
1355 /***********************************************************************
1356  *           QUEUE_DecTimerCount
1357  */
1358 void QUEUE_DecTimerCount( HQUEUE16 hQueue )
1359 {
1360     MESSAGEQUEUE *queue;
1361
1362     if (!(queue = QUEUE_Lock( hQueue ))) return;
1363     EnterCriticalSection( &queue->cSection );
1364     queue->wTimerCount--;
1365     if (!queue->wTimerCount) queue->wakeBits &= ~QS_TIMER;
1366     LeaveCriticalSection( &queue->cSection );
1367     QUEUE_Unlock( queue );
1368 }
1369
1370
1371 /***********************************************************************
1372  *              PostQuitMessage (USER.6)
1373  */
1374 void WINAPI PostQuitMessage16( INT16 exitCode )
1375 {
1376     PostQuitMessage( exitCode );
1377 }
1378
1379
1380 /***********************************************************************
1381  *              PostQuitMessage (USER32.@)
1382  *
1383  * PostQuitMessage() posts a message to the system requesting an
1384  * application to terminate execution. As a result of this function,
1385  * the WM_QUIT message is posted to the application, and
1386  * PostQuitMessage() returns immediately.  The exitCode parameter
1387  * specifies an application-defined exit code, which appears in the
1388  * _wParam_ parameter of the WM_QUIT message posted to the application.  
1389  *
1390  * CONFORMANCE
1391  *
1392  *  ECMA-234, Win32
1393  */
1394 void WINAPI PostQuitMessage( INT exitCode )
1395 {
1396     MESSAGEQUEUE *queue;
1397
1398     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return;
1399     EnterCriticalSection( &queue->cSection );
1400     queue->wPostQMsg = TRUE;
1401     queue->wExitCode = (WORD)exitCode;
1402     LeaveCriticalSection( &queue->cSection );
1403     QUEUE_Unlock( queue );
1404 }
1405
1406
1407 /***********************************************************************
1408  *              GetWindowTask (USER.224)
1409  */
1410 HTASK16 WINAPI GetWindowTask16( HWND16 hwnd )
1411 {
1412     HTASK16 retvalue;
1413     WND *wndPtr = WIN_FindWndPtr( hwnd );
1414
1415     if (!wndPtr) return 0;
1416     retvalue = QUEUE_GetQueueTask( wndPtr->hmemTaskQ );
1417     WIN_ReleaseWndPtr(wndPtr);
1418     return retvalue;
1419 }
1420
1421 /***********************************************************************
1422  *              GetWindowThreadProcessId (USER32.@)
1423  */
1424 DWORD WINAPI GetWindowThreadProcessId( HWND hwnd, LPDWORD process )
1425 {
1426     DWORD retvalue;
1427     MESSAGEQUEUE *queue;
1428
1429     WND *wndPtr = WIN_FindWndPtr( hwnd );
1430     if (!wndPtr) return 0;
1431
1432     queue = QUEUE_Lock( wndPtr->hmemTaskQ );
1433     WIN_ReleaseWndPtr(wndPtr);
1434
1435     if (!queue) return 0;
1436
1437     if ( process ) *process = (DWORD)queue->teb->pid;
1438     retvalue = (DWORD)queue->teb->tid;
1439
1440     QUEUE_Unlock( queue );
1441     return retvalue;
1442 }
1443
1444
1445 /***********************************************************************
1446  *              SetMessageQueue (USER.266)
1447  */
1448 BOOL16 WINAPI SetMessageQueue16( INT16 size )
1449 {
1450     return SetMessageQueue( size );
1451 }
1452
1453
1454 /***********************************************************************
1455  *              SetMessageQueue (USER32.@)
1456  */
1457 BOOL WINAPI SetMessageQueue( INT size )
1458 {
1459     /* now obsolete the message queue will be expanded dynamically
1460      as necessary */
1461
1462     /* access the queue to create it if it's not existing */
1463     GetFastQueue16();
1464
1465     return TRUE;
1466 }
1467
1468 /***********************************************************************
1469  *              InitThreadInput (USER.409)
1470  */
1471 HQUEUE16 WINAPI InitThreadInput16( WORD unknown, WORD flags )
1472 {
1473     HQUEUE16 hQueue;
1474     MESSAGEQUEUE *queuePtr;
1475
1476     TEB *teb = NtCurrentTeb();
1477
1478     if (!teb)
1479         return 0;
1480
1481     hQueue = teb->queue;
1482     
1483     if ( !hQueue )
1484     {
1485         /* Create thread message queue */
1486         if( !(hQueue = QUEUE_CreateMsgQueue( TRUE )))
1487         {
1488             ERR_(msg)("failed!\n");
1489             return FALSE;
1490         }
1491         
1492         /* Link new queue into list */
1493         queuePtr = QUEUE_Lock( hQueue );
1494         queuePtr->teb = NtCurrentTeb();
1495
1496         HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
1497         SetThreadQueue16( 0, hQueue );
1498         teb->queue = hQueue;
1499             
1500         queuePtr->next  = hFirstQueue;
1501         hFirstQueue = hQueue;
1502         HeapUnlock( GetProcessHeap() );
1503         
1504         QUEUE_Unlock( queuePtr );
1505     }
1506
1507     return hQueue;
1508 }
1509
1510 /***********************************************************************
1511  *              GetQueueStatus (USER.334)
1512  */
1513 DWORD WINAPI GetQueueStatus16( UINT16 flags )
1514 {
1515     MESSAGEQUEUE *queue;
1516     DWORD ret;
1517
1518     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1519     EnterCriticalSection( &queue->cSection );
1520     ret = MAKELONG( queue->changeBits, queue->wakeBits );
1521     queue->changeBits = 0;
1522     LeaveCriticalSection( &queue->cSection );
1523     QUEUE_Unlock( queue );
1524     
1525     return ret & MAKELONG( flags, flags );
1526 }
1527
1528 /***********************************************************************
1529  *              GetQueueStatus (USER32.@)
1530  */
1531 DWORD WINAPI GetQueueStatus( UINT flags )
1532 {
1533     MESSAGEQUEUE *queue;
1534     DWORD ret;
1535
1536     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1537     EnterCriticalSection( &queue->cSection );
1538     ret = MAKELONG( queue->changeBits, queue->wakeBits );
1539     queue->changeBits = 0;
1540     LeaveCriticalSection( &queue->cSection );
1541     QUEUE_Unlock( queue );
1542     
1543     return ret & MAKELONG( flags, flags );
1544 }
1545
1546
1547 /***********************************************************************
1548  *              GetInputState (USER.335)
1549  */
1550 BOOL16 WINAPI GetInputState16(void)
1551 {
1552     return GetInputState();
1553 }
1554
1555 /***********************************************************************
1556  *              WaitForInputIdle (USER32.@)
1557  */
1558 DWORD WINAPI WaitForInputIdle (HANDLE hProcess, DWORD dwTimeOut)
1559 {
1560     DWORD cur_time, ret;
1561     HANDLE idle_event = -1;
1562
1563     SERVER_START_REQ
1564     {
1565         struct wait_input_idle_request *req = server_alloc_req( sizeof(*req), 0 );
1566         req->handle = hProcess;
1567         req->timeout = dwTimeOut;
1568         if (!(ret = server_call( REQ_WAIT_INPUT_IDLE ))) idle_event = req->event;
1569     }
1570     SERVER_END_REQ;
1571     if (ret) return 0xffffffff;  /* error */
1572     if (!idle_event) return 0;  /* no event to wait on */
1573
1574     cur_time = GetTickCount();
1575
1576     TRACE_(msg)("waiting for %x\n", idle_event );
1577     while ( dwTimeOut > GetTickCount() - cur_time || dwTimeOut == INFINITE ) 
1578     {
1579         ret = MsgWaitForMultipleObjects ( 1, &idle_event, FALSE, dwTimeOut, QS_SENDMESSAGE );
1580         if ( ret == ( WAIT_OBJECT_0 + 1 )) 
1581         {
1582             MESSAGEQUEUE * queue;
1583             if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0xFFFFFFFF;
1584             QUEUE_ReceiveMessage ( queue );
1585             QUEUE_Unlock ( queue );
1586             continue; 
1587         }
1588         if ( ret == WAIT_TIMEOUT || ret == 0xFFFFFFFF ) 
1589         {
1590             TRACE_(msg)("timeout or error\n");
1591             return ret;
1592         }
1593         else 
1594         {
1595             TRACE_(msg)("finished\n");
1596             return 0;
1597         }
1598     }
1599
1600     return WAIT_TIMEOUT;
1601 }
1602
1603 /***********************************************************************
1604  *              GetInputState (USER32.@)
1605  */
1606 BOOL WINAPI GetInputState(void)
1607 {
1608     MESSAGEQUEUE *queue;
1609     BOOL ret;
1610
1611     if (!(queue = QUEUE_Lock( GetFastQueue16() )))
1612         return FALSE;
1613     EnterCriticalSection( &queue->cSection );
1614     ret = queue->wakeBits & (QS_KEY | QS_MOUSEBUTTON);
1615     LeaveCriticalSection( &queue->cSection );
1616     QUEUE_Unlock( queue );
1617
1618     return ret;
1619 }
1620
1621 /***********************************************************************
1622  *              UserYield (USER.332)
1623  *              UserYield16 (USER32.@)
1624  */
1625 void WINAPI UserYield16(void)
1626 {
1627     MESSAGEQUEUE *queue;
1628
1629     /* Handle sent messages */
1630     queue = QUEUE_Lock( GetFastQueue16() );
1631
1632     while ( queue && QUEUE_ReceiveMessage( queue ) )
1633         ;
1634
1635     QUEUE_Unlock( queue );
1636     
1637     /* Yield */
1638     if ( THREAD_IsWin16( NtCurrentTeb() ) )
1639         OldYield16();
1640     else
1641         WIN32_OldYield16();
1642
1643     /* Handle sent messages again */
1644     queue = QUEUE_Lock( GetFastQueue16() );
1645
1646     while ( queue && QUEUE_ReceiveMessage( queue ) )
1647         ;
1648
1649     QUEUE_Unlock( queue );
1650 }
1651
1652 /***********************************************************************
1653  *              GetMessagePos (USER.119) (USER32.@)
1654  * 
1655  * The GetMessagePos() function returns a long value representing a
1656  * cursor position, in screen coordinates, when the last message
1657  * retrieved by the GetMessage() function occurs. The x-coordinate is
1658  * in the low-order word of the return value, the y-coordinate is in
1659  * the high-order word. The application can use the MAKEPOINT()
1660  * macro to obtain a POINT structure from the return value. 
1661  *
1662  * For the current cursor position, use GetCursorPos().
1663  *
1664  * RETURNS
1665  *
1666  * Cursor position of last message on success, zero on failure.
1667  *
1668  * CONFORMANCE
1669  *
1670  * ECMA-234, Win32
1671  *
1672  */
1673 DWORD WINAPI GetMessagePos(void)
1674 {
1675     MESSAGEQUEUE *queue;
1676     DWORD ret;
1677
1678     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1679     ret = queue->GetMessagePosVal;
1680     QUEUE_Unlock( queue );
1681
1682     return ret;
1683 }
1684
1685
1686 /***********************************************************************
1687  *              GetMessageTime (USER.120) (USER32.@)
1688  *
1689  * GetMessageTime() returns the message time for the last message
1690  * retrieved by the function. The time is measured in milliseconds with
1691  * the same offset as GetTickCount().
1692  *
1693  * Since the tick count wraps, this is only useful for moderately short
1694  * relative time comparisons.
1695  *
1696  * RETURNS
1697  *
1698  * Time of last message on success, zero on failure.
1699  *
1700  * CONFORMANCE
1701  *
1702  * ECMA-234, Win32
1703  *  
1704  */
1705 LONG WINAPI GetMessageTime(void)
1706 {
1707     MESSAGEQUEUE *queue;
1708     LONG ret;
1709
1710     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1711     ret = queue->GetMessageTimeVal;
1712     QUEUE_Unlock( queue );
1713     
1714     return ret;
1715 }
1716
1717
1718 /***********************************************************************
1719  *              GetMessageExtraInfo (USER.288) (USER32.@)
1720  */
1721 LONG WINAPI GetMessageExtraInfo(void)
1722 {
1723     MESSAGEQUEUE *queue;
1724     LONG ret;
1725
1726     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1727     ret = queue->GetMessageExtraInfoVal;
1728     QUEUE_Unlock( queue );
1729
1730     return ret;
1731 }
1732
1733
1734 /**********************************************************************
1735  *              AttachThreadInput (USER32.@) Attaches input of 1 thread to other
1736  *
1737  * Attaches the input processing mechanism of one thread to that of
1738  * another thread.
1739  *
1740  * RETURNS
1741  *    Success: TRUE
1742  *    Failure: FALSE
1743  *
1744  * TODO:
1745  *    1. Reset the Key State (currenly per thread key state is not maintained)
1746  */
1747 BOOL WINAPI AttachThreadInput( 
1748     DWORD idAttach,   /* [in] Thread to attach */
1749     DWORD idAttachTo, /* [in] Thread to attach to */
1750     BOOL fAttach)   /* [in] Attach or detach */
1751 {
1752     MESSAGEQUEUE *pSrcMsgQ = 0, *pTgtMsgQ = 0;
1753     BOOL16 bRet = 0;
1754
1755     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1756
1757     /* A thread cannot attach to itself */
1758     if ( idAttach == idAttachTo )
1759         goto CLEANUP;
1760
1761     /* According to the docs this method should fail if a
1762      * "Journal record" hook is installed. (attaches all input queues together)
1763      */
1764     if ( HOOK_IsHooked( WH_JOURNALRECORD ) )
1765         goto CLEANUP;
1766         
1767     /* Retrieve message queues corresponding to the thread id's */
1768     pTgtMsgQ = QUEUE_Lock( GetThreadQueue16( idAttach ) );
1769     pSrcMsgQ = QUEUE_Lock( GetThreadQueue16( idAttachTo ) );
1770
1771     /* Ensure we have message queues and that Src and Tgt threads
1772      * are not system threads.
1773      */
1774     if ( !pSrcMsgQ || !pTgtMsgQ || !pSrcMsgQ->pQData || !pTgtMsgQ->pQData )
1775         goto CLEANUP;
1776
1777     if (fAttach)   /* Attach threads */
1778     {
1779         /* Only attach if currently detached  */
1780         if ( pTgtMsgQ->pQData != pSrcMsgQ->pQData )
1781         {
1782             /* First release the target threads perQData */
1783             PERQDATA_Release( pTgtMsgQ->pQData );
1784         
1785             /* Share a reference to the source threads perQDATA */
1786             PERQDATA_Addref( pSrcMsgQ->pQData );
1787             pTgtMsgQ->pQData = pSrcMsgQ->pQData;
1788         }
1789     }
1790     else    /* Detach threads */
1791     {
1792         /* Only detach if currently attached */
1793         if ( pTgtMsgQ->pQData == pSrcMsgQ->pQData )
1794         {
1795             /* First release the target threads perQData */
1796             PERQDATA_Release( pTgtMsgQ->pQData );
1797         
1798             /* Give the target thread its own private perQDATA once more */
1799             pTgtMsgQ->pQData = PERQDATA_CreateInstance();
1800         }
1801     }
1802
1803     /* TODO: Reset the Key State */
1804
1805     bRet = 1;      /* Success */
1806     
1807 CLEANUP:
1808
1809     /* Unlock the queues before returning */
1810     if ( pSrcMsgQ )
1811         QUEUE_Unlock( pSrcMsgQ );
1812     if ( pTgtMsgQ )
1813         QUEUE_Unlock( pTgtMsgQ );
1814     
1815     return bRet;
1816 }