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