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