Added an unknown VxD error code.
[wine] / windows / queue.c
1 /*
2  * Message queues related functions
3  *
4  * Copyright 1993, 1994 Alexandre Julliard
5  */
6
7 #include <string.h>
8 #include <signal.h>
9 #include <assert.h>
10 #include "windef.h"
11 #include "wingdi.h"
12 #include "winerror.h"
13 #include "wine/winbase16.h"
14 #include "wine/winuser16.h"
15 #include "queue.h"
16 #include "win.h"
17 #include "user.h"
18 #include "hook.h"
19 #include "thread.h"
20 #include "debugtools.h"
21 #include "server.h"
22 #include "spy.h"
23
24 DECLARE_DEBUG_CHANNEL(sendmsg);
25 DEFAULT_DEBUG_CHANNEL(msg);
26
27 #define MAX_QUEUE_SIZE   120  /* Max. size of a message queue */
28
29 static HQUEUE16 hExitingQueue = 0;
30 static HQUEUE16 hmemSysMsgQueue = 0;
31 static MESSAGEQUEUE *sysMsgQueue = NULL;
32 static PERQUEUEDATA *pQDataWin16 = NULL;  /* Global perQData for Win16 tasks */
33
34 static MESSAGEQUEUE *pMouseQueue = NULL;  /* Queue for last mouse message */
35 static MESSAGEQUEUE *pKbdQueue = NULL;    /* Queue for last kbd message */
36
37 HQUEUE16 hCursorQueue = 0;
38 HQUEUE16 hActiveQueue = 0;
39
40
41 /***********************************************************************
42  *           PERQDATA_CreateInstance
43  *
44  * Creates an instance of a reference counted PERQUEUEDATA element
45  * for the message queue. perQData is stored globally for 16 bit tasks.
46  *
47  * Note: We don't implement perQdata exactly the same way Windows does.
48  * Each perQData element is reference counted since it may be potentially
49  * shared by multiple message Queues (via AttachThreadInput).
50  * We only store the current values for Active, Capture and focus windows
51  * currently.
52  */
53 PERQUEUEDATA * PERQDATA_CreateInstance( )
54 {
55     PERQUEUEDATA *pQData;
56     
57     BOOL16 bIsWin16 = 0;
58     
59     TRACE_(msg)("()\n");
60
61     /* Share a single instance of perQData for all 16 bit tasks */
62     if ( ( bIsWin16 = !(NtCurrentTeb()->tibflags & TEBF_WIN32) ) )
63     {
64         /* If previously allocated, just bump up ref count */
65         if ( pQDataWin16 )
66         {
67             PERQDATA_Addref( pQDataWin16 );
68             return pQDataWin16;
69         }
70     }
71
72     /* Allocate PERQUEUEDATA from the system heap */
73     if (!( pQData = (PERQUEUEDATA *) HeapAlloc( GetProcessHeap(), 0,
74                                                     sizeof(PERQUEUEDATA) ) ))
75         return 0;
76
77     /* Initialize */
78     pQData->hWndCapture = pQData->hWndFocus = pQData->hWndActive = 0;
79     pQData->ulRefCount = 1;
80     pQData->nCaptureHT = HTCLIENT;
81
82     /* Note: We have an independent critical section for the per queue data
83      * since this may be shared by different threads. see AttachThreadInput()
84      */
85     InitializeCriticalSection( &pQData->cSection );
86     /* FIXME: not all per queue data critical sections should be global */
87     MakeCriticalSectionGlobal( &pQData->cSection );
88
89     /* Save perQData globally for 16 bit tasks */
90     if ( bIsWin16 )
91         pQDataWin16 = pQData;
92         
93     return pQData;
94 }
95
96
97 /***********************************************************************
98  *           PERQDATA_Addref
99  *
100  * Increment reference count for the PERQUEUEDATA instance
101  * Returns reference count for debugging purposes
102  */
103 ULONG PERQDATA_Addref( PERQUEUEDATA *pQData )
104 {
105     assert(pQData != 0 );
106     TRACE_(msg)("(): current refcount %lu ...\n", pQData->ulRefCount);
107
108     EnterCriticalSection( &pQData->cSection );
109     ++pQData->ulRefCount;
110     LeaveCriticalSection( &pQData->cSection );
111
112     return pQData->ulRefCount;
113 }
114
115
116 /***********************************************************************
117  *           PERQDATA_Release
118  *
119  * Release a reference to a PERQUEUEDATA instance.
120  * Destroy the instance if no more references exist
121  * Returns reference count for debugging purposes
122  */
123 ULONG PERQDATA_Release( PERQUEUEDATA *pQData )
124 {
125     assert(pQData != 0 );
126     TRACE_(msg)("(): current refcount %lu ...\n",
127           (LONG)pQData->ulRefCount );
128
129     EnterCriticalSection( &pQData->cSection );
130     if ( --pQData->ulRefCount == 0 )
131     {
132         LeaveCriticalSection( &pQData->cSection );
133         DeleteCriticalSection( &pQData->cSection );
134
135         TRACE_(msg)("(): deleting PERQUEUEDATA instance ...\n" );
136
137         /* Deleting our global 16 bit perQData? */
138         if ( pQData == pQDataWin16 )
139             pQDataWin16 = 0;
140             
141         /* Free the PERQUEUEDATA instance */
142         HeapFree( GetProcessHeap(), 0, pQData );
143
144         return 0;
145     }
146     LeaveCriticalSection( &pQData->cSection );
147
148     return pQData->ulRefCount;
149 }
150
151
152 /***********************************************************************
153  *           PERQDATA_GetFocusWnd
154  *
155  * Get the focus hwnd member in a threadsafe manner
156  */
157 HWND PERQDATA_GetFocusWnd( PERQUEUEDATA *pQData )
158 {
159     HWND hWndFocus;
160     assert(pQData != 0 );
161
162     EnterCriticalSection( &pQData->cSection );
163     hWndFocus = pQData->hWndFocus;
164     LeaveCriticalSection( &pQData->cSection );
165
166     return hWndFocus;
167 }
168
169
170 /***********************************************************************
171  *           PERQDATA_SetFocusWnd
172  *
173  * Set the focus hwnd member in a threadsafe manner
174  */
175 HWND PERQDATA_SetFocusWnd( PERQUEUEDATA *pQData, HWND hWndFocus )
176 {
177     HWND hWndFocusPrv;
178     assert(pQData != 0 );
179
180     EnterCriticalSection( &pQData->cSection );
181     hWndFocusPrv = pQData->hWndFocus;
182     pQData->hWndFocus = hWndFocus;
183     LeaveCriticalSection( &pQData->cSection );
184
185     return hWndFocusPrv;
186 }
187
188
189 /***********************************************************************
190  *           PERQDATA_GetActiveWnd
191  *
192  * Get the active hwnd member in a threadsafe manner
193  */
194 HWND PERQDATA_GetActiveWnd( PERQUEUEDATA *pQData )
195 {
196     HWND hWndActive;
197     assert(pQData != 0 );
198
199     EnterCriticalSection( &pQData->cSection );
200     hWndActive = pQData->hWndActive;
201     LeaveCriticalSection( &pQData->cSection );
202
203     return hWndActive;
204 }
205
206
207 /***********************************************************************
208  *           PERQDATA_SetActiveWnd
209  *
210  * Set the active focus hwnd member in a threadsafe manner
211  */
212 HWND PERQDATA_SetActiveWnd( PERQUEUEDATA *pQData, HWND hWndActive )
213 {
214     HWND hWndActivePrv;
215     assert(pQData != 0 );
216
217     EnterCriticalSection( &pQData->cSection );
218     hWndActivePrv = pQData->hWndActive;
219     pQData->hWndActive = hWndActive;
220     LeaveCriticalSection( &pQData->cSection );
221
222     return hWndActivePrv;
223 }
224
225
226 /***********************************************************************
227  *           PERQDATA_GetCaptureWnd
228  *
229  * Get the capture hwnd member in a threadsafe manner
230  */
231 HWND PERQDATA_GetCaptureWnd( PERQUEUEDATA *pQData )
232 {
233     HWND hWndCapture;
234     assert(pQData != 0 );
235
236     EnterCriticalSection( &pQData->cSection );
237     hWndCapture = pQData->hWndCapture;
238     LeaveCriticalSection( &pQData->cSection );
239
240     return hWndCapture;
241 }
242
243
244 /***********************************************************************
245  *           PERQDATA_SetCaptureWnd
246  *
247  * Set the capture hwnd member in a threadsafe manner
248  */
249 HWND PERQDATA_SetCaptureWnd( PERQUEUEDATA *pQData, HWND hWndCapture )
250 {
251     HWND hWndCapturePrv;
252     assert(pQData != 0 );
253
254     EnterCriticalSection( &pQData->cSection );
255     hWndCapturePrv = pQData->hWndCapture;
256     pQData->hWndCapture = hWndCapture;
257     LeaveCriticalSection( &pQData->cSection );
258
259     return hWndCapturePrv;
260 }
261
262
263 /***********************************************************************
264  *           PERQDATA_GetCaptureInfo
265  *
266  * Get the capture info member in a threadsafe manner
267  */
268 INT16 PERQDATA_GetCaptureInfo( PERQUEUEDATA *pQData )
269 {
270     INT16 nCaptureHT;
271     assert(pQData != 0 );
272
273     EnterCriticalSection( &pQData->cSection );
274     nCaptureHT = pQData->nCaptureHT;
275     LeaveCriticalSection( &pQData->cSection );
276
277     return nCaptureHT;
278 }
279
280
281 /***********************************************************************
282  *           PERQDATA_SetCaptureInfo
283  *
284  * Set the capture info member in a threadsafe manner
285  */
286 INT16 PERQDATA_SetCaptureInfo( PERQUEUEDATA *pQData, INT16 nCaptureHT )
287 {
288     INT16 nCaptureHTPrv;
289     assert(pQData != 0 );
290
291     EnterCriticalSection( &pQData->cSection );
292     nCaptureHTPrv = pQData->nCaptureHT;
293     pQData->nCaptureHT = nCaptureHT;
294     LeaveCriticalSection( &pQData->cSection );
295
296     return nCaptureHTPrv;
297 }
298
299
300 /***********************************************************************
301  *           QUEUE_Lock
302  *
303  * Function for getting a 32 bit pointer on queue structure. For thread
304  * safeness programmers should use this function instead of GlobalLock to
305  * retrieve a pointer on the structure. QUEUE_Unlock should also be called
306  * when access to the queue structure is not required anymore.
307  */
308 MESSAGEQUEUE *QUEUE_Lock( HQUEUE16 hQueue )
309 {
310     MESSAGEQUEUE *queue;
311
312     HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
313     queue = GlobalLock16( hQueue );
314     if ( !queue || (queue->magic != QUEUE_MAGIC) )
315     {
316         HeapUnlock( GetProcessHeap() );
317         return NULL;
318     }
319
320     queue->lockCount++;
321     HeapUnlock( GetProcessHeap() );
322     return queue;
323 }
324
325
326 /***********************************************************************
327  *           QUEUE_Unlock
328  *
329  * Use with QUEUE_Lock to get a thread safe access to message queue
330  * structure
331  */
332 void QUEUE_Unlock( MESSAGEQUEUE *queue )
333 {
334     if (queue)
335     {
336         HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
337
338         if ( --queue->lockCount == 0 )
339         {
340             DeleteCriticalSection ( &queue->cSection );
341             if (queue->server_queue)
342                 CloseHandle( queue->server_queue );
343             GlobalFree16( queue->self );
344         }
345     
346         HeapUnlock( GetProcessHeap() );
347     }
348 }
349
350
351 /***********************************************************************
352  *           QUEUE_DumpQueue
353  */
354 void QUEUE_DumpQueue( HQUEUE16 hQueue )
355 {
356     MESSAGEQUEUE *pq; 
357
358     if (!(pq = QUEUE_Lock( hQueue )) )
359     {
360         WARN_(msg)("%04x is not a queue handle\n", hQueue );
361         return;
362     }
363
364     EnterCriticalSection( &pq->cSection );
365
366     DPRINTF( "thread: %10p  Intertask SendMessage:\n"
367              "firstMsg: %8p   lastMsg:  %8p\n"
368              "lockCount: %7.4x\n"
369              "paints: %10.4x\n"
370              "hCurHook: %8.4x\n",
371              pq->teb, pq->firstMsg, pq->lastMsg,
372              (unsigned)pq->lockCount, pq->wPaintCount,
373              pq->hCurHook);
374
375     LeaveCriticalSection( &pq->cSection );
376
377     QUEUE_Unlock( pq );
378 }
379
380
381 /***********************************************************************
382  *           QUEUE_IsExitingQueue
383  */
384 BOOL QUEUE_IsExitingQueue( HQUEUE16 hQueue )
385 {
386     return (hExitingQueue && (hQueue == hExitingQueue));
387 }
388
389
390 /***********************************************************************
391  *           QUEUE_SetExitingQueue
392  */
393 void QUEUE_SetExitingQueue( HQUEUE16 hQueue )
394 {
395     hExitingQueue = hQueue;
396 }
397
398
399 /***********************************************************************
400  *           QUEUE_CreateMsgQueue
401  *
402  * Creates a message queue. Doesn't link it into queue list!
403  */
404 static HQUEUE16 QUEUE_CreateMsgQueue( BOOL16 bCreatePerQData )
405 {
406     HQUEUE16 hQueue;
407     HANDLE handle;
408     MESSAGEQUEUE * msgQueue;
409
410     TRACE_(msg)("(): Creating message queue...\n");
411
412     if (!(hQueue = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT,
413                                   sizeof(MESSAGEQUEUE) )))
414         return 0;
415
416     msgQueue = (MESSAGEQUEUE *) GlobalLock16( hQueue );
417     if ( !msgQueue )
418         return 0;
419
420     if (bCreatePerQData)
421     {
422         SERVER_START_REQ( get_msg_queue )
423         {
424             SERVER_CALL_ERR();
425             handle = req->handle;
426         }
427         SERVER_END_REQ;
428         if (!handle)
429         {
430             ERR_(msg)("Cannot get thread queue");
431             GlobalFree16( hQueue );
432             return 0;
433         }
434         msgQueue->server_queue = handle;
435     }
436
437     msgQueue->self = hQueue;
438
439     InitializeCriticalSection( &msgQueue->cSection );
440     MakeCriticalSectionGlobal( &msgQueue->cSection );
441
442     msgQueue->lockCount = 1;
443     msgQueue->magic = QUEUE_MAGIC;
444     
445     /* Create and initialize our per queue data */
446     msgQueue->pQData = bCreatePerQData ? PERQDATA_CreateInstance() : NULL;
447     
448     return hQueue;
449 }
450
451
452 /***********************************************************************
453  *           QUEUE_DeleteMsgQueue
454  *
455  * Unlinks and deletes a message queue.
456  *
457  * Note: We need to mask asynchronous events to make sure PostMessage works
458  * even in the signal handler.
459  */
460 BOOL QUEUE_DeleteMsgQueue( HQUEUE16 hQueue )
461 {
462     MESSAGEQUEUE * msgQueue = QUEUE_Lock(hQueue);
463
464     TRACE_(msg)("(): Deleting message queue %04x\n", hQueue);
465
466     if (!hQueue || !msgQueue)
467     {
468         ERR_(msg)("invalid argument.\n");
469         return 0;
470     }
471
472     msgQueue->magic = 0;
473     
474     if( hCursorQueue == hQueue ) hCursorQueue = 0;
475     if( hActiveQueue == hQueue ) hActiveQueue = 0;
476
477     HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
478
479     /* Release per queue data if present */
480     if ( msgQueue->pQData )
481     {
482         PERQDATA_Release( msgQueue->pQData );
483         msgQueue->pQData = 0;
484     }
485
486     msgQueue->self = 0;
487
488     HeapUnlock( GetProcessHeap() );
489
490     /* free up resource used by MESSAGEQUEUE structure */
491     msgQueue->lockCount--;
492     QUEUE_Unlock( msgQueue );
493     
494     return 1;
495 }
496
497
498 /***********************************************************************
499  *           QUEUE_CreateSysMsgQueue
500  *
501  * Create the system message queue, and set the double-click speed.
502  * Must be called only once.
503  */
504 BOOL QUEUE_CreateSysMsgQueue( int size )
505 {
506     /* Note: We dont need perQ data for the system message queue */
507     if (!(hmemSysMsgQueue = QUEUE_CreateMsgQueue( FALSE )))
508         return FALSE;
509     FarSetOwner16( hmemSysMsgQueue, 0 );
510     sysMsgQueue = (MESSAGEQUEUE *) GlobalLock16( hmemSysMsgQueue );
511     return TRUE;
512 }
513
514
515 /***********************************************************************
516  *           QUEUE_GetSysQueue
517  */
518 MESSAGEQUEUE *QUEUE_GetSysQueue(void)
519 {
520     return sysMsgQueue;
521 }
522
523
524 /***********************************************************************
525  *           QUEUE_SetWakeBit
526  *
527  * See "Windows Internals", p.449
528  */
529 static BOOL QUEUE_TrySetWakeBit( MESSAGEQUEUE *queue, WORD set, WORD clear, BOOL always )
530 {
531     BOOL wake = FALSE;
532
533     TRACE_(msg)("queue = %04x, set = %04x, clear = %04x, always = %d\n",
534                 queue->self, set, clear, always );
535     if (!queue->server_queue) return FALSE;
536
537     SERVER_START_REQ( set_queue_bits )
538     {
539         req->handle    = queue->server_queue;
540         req->set       = set;
541         req->clear     = clear;
542         req->mask_cond = always ? 0 : set;
543         if (!SERVER_CALL()) wake = (req->changed_mask & set) != 0;
544     }
545     SERVER_END_REQ;
546
547     if (wake || always)
548     {
549         if (set & QS_MOUSE) pMouseQueue = queue;
550         if (set & QS_KEY) pKbdQueue = queue;
551     }
552     return wake;
553 }
554 void QUEUE_SetWakeBit( MESSAGEQUEUE *queue, WORD set, WORD clear )
555 {
556     QUEUE_TrySetWakeBit( queue, set, clear, TRUE );
557 }
558
559
560 /***********************************************************************
561  *           QUEUE_ClearWakeBit
562  */
563 void QUEUE_ClearWakeBit( MESSAGEQUEUE *queue, WORD bit )
564 {
565     QUEUE_SetWakeBit( queue, 0, bit );
566 }
567
568 /***********************************************************************
569  *           QUEUE_WaitBits
570  *
571  * See "Windows Internals", p.447
572  *
573  * return values:
574  *    0 if exit with timeout
575  *    1 otherwise
576  */
577 int QUEUE_WaitBits( WORD bits, DWORD timeout )
578 {
579     MESSAGEQUEUE *queue;
580     HQUEUE16 hQueue;
581
582     TRACE_(msg)("q %04x waiting for %04x\n", GetFastQueue16(), bits);
583
584     hQueue = GetFastQueue16();
585     if (!(queue = QUEUE_Lock( hQueue ))) return 0;
586     
587     for (;;)
588     {
589         unsigned int wake_bits = 0, changed_bits = 0;
590         DWORD dwlc;
591
592         SERVER_START_REQ( set_queue_mask )
593         {
594             req->wake_mask    = QS_SENDMESSAGE;
595             req->changed_mask = bits | QS_SENDMESSAGE;
596             req->skip_wait    = 1;
597             if (!SERVER_CALL())
598             {
599                 wake_bits    = req->wake_bits;
600                 changed_bits = req->changed_bits;
601             }
602         }
603         SERVER_END_REQ;
604
605         if (changed_bits & bits)
606         {
607             /* One of the bits is set; we can return */
608             QUEUE_Unlock( queue );
609             return 1;
610         }
611         if (wake_bits & QS_SENDMESSAGE)
612         {
613             /* Process the sent message immediately */
614             QMSG msg;
615             QUEUE_FindMsg( 0, 0, 0, TRUE, TRUE, &msg );
616             continue;  /* nested sm crux */
617         }
618
619         TRACE_(msg)("(%04x) mask=%08x, bits=%08x, changed=%08x, waiting\n",
620                     queue->self, bits, wake_bits, changed_bits );
621
622         ReleaseThunkLock( &dwlc );
623         if (dwlc) TRACE_(msg)("had win16 lock\n");
624
625         if (USER_Driver.pMsgWaitForMultipleObjectsEx)
626             USER_Driver.pMsgWaitForMultipleObjectsEx( 1, &queue->server_queue, timeout, 0, 0 );
627         else
628             WaitForSingleObject( queue->server_queue, timeout );
629         if (dwlc) RestoreThunkLock( dwlc );
630     }
631 }
632
633
634 /* handle the reception of a sent message by calling the corresponding window proc */
635 static void handle_sent_message( QMSG *msg )
636 {
637     LRESULT result = 0;
638     MESSAGEQUEUE *queue = QUEUE_Lock( GetFastQueue16() );
639     DWORD extraInfo = queue->GetMessageExtraInfoVal; /* save ExtraInfo */
640     WND *wndPtr = WIN_FindWndPtr( msg->msg.hwnd );
641
642     TRACE( "got hwnd %x msg %x (%s) wp %x lp %lx\n",
643            msg->msg.hwnd, msg->msg.message, SPY_GetMsgName(msg->msg.message),
644            msg->msg.wParam, msg->msg.lParam );
645
646     queue->GetMessageExtraInfoVal = msg->extraInfo;
647
648     /* call the right version of CallWindowProcXX */
649     switch(msg->type)
650     {
651     case QMSG_WIN16:
652         result = CallWindowProc16( (WNDPROC16)wndPtr->winproc,
653                                    (HWND16) msg->msg.hwnd,
654                                    (UINT16) msg->msg.message,
655                                    LOWORD(msg->msg.wParam),
656                                    msg->msg.lParam );
657         break;
658     case QMSG_WIN32A:
659         result = CallWindowProcA( wndPtr->winproc, msg->msg.hwnd, msg->msg.message,
660                                   msg->msg.wParam, msg->msg.lParam );
661         break;
662     case QMSG_WIN32W:
663         result = CallWindowProcW( wndPtr->winproc, msg->msg.hwnd, msg->msg.message,
664                                   msg->msg.wParam, msg->msg.lParam );
665         break;
666     }
667
668     queue->GetMessageExtraInfoVal = extraInfo;  /* Restore extra info */
669     WIN_ReleaseWndPtr(wndPtr);
670     QUEUE_Unlock( queue );
671
672     SERVER_START_REQ( reply_message )
673     {
674         req->result = result;
675         req->remove = 1;
676         SERVER_CALL();
677     }
678     SERVER_END_REQ;
679 }
680
681
682 /***********************************************************************
683  *           QUEUE_FindMsg
684  *
685  * Find a message matching the given parameters. Return -1 if none available.
686  */
687 BOOL QUEUE_FindMsg( HWND hwnd, UINT first, UINT last, BOOL remove, BOOL sent_only, QMSG *msg )
688 {
689     BOOL ret = FALSE, sent = FALSE;
690
691     if (!first && !last) last = ~0;
692
693     for (;;)
694     {
695         SERVER_START_REQ( get_message )
696         {
697             req->remove    = remove;
698             req->posted    = !sent_only;
699             req->get_win   = hwnd;
700             req->get_first = first;
701             req->get_last  = last;
702             if ((ret = !SERVER_CALL()))
703             {
704                 sent             = req->sent;
705                 msg->type        = req->type;
706                 msg->msg.hwnd    = req->win;
707                 msg->msg.message = req->msg;
708                 msg->msg.wParam  = req->wparam;
709                 msg->msg.lParam  = req->lparam;
710                 msg->msg.time    = 0;  /* FIXME */
711                 msg->msg.pt.x    = 0;  /* FIXME */
712                 msg->msg.pt.y    = 0;  /* FIXME */
713                 msg->extraInfo   = req->info;
714             }
715         }
716         SERVER_END_REQ;
717
718         if (!ret || !sent) break;
719         handle_sent_message( msg );
720     }
721
722     if (ret) TRACE( "got hwnd %x msg %x (%s) wp %x lp %lx\n",
723                     msg->msg.hwnd, msg->msg.message, SPY_GetMsgName(msg->msg.message),
724                     msg->msg.wParam, msg->msg.lParam );
725     return ret;
726 }
727
728
729
730 /***********************************************************************
731  *           QUEUE_RemoveMsg
732  *
733  * Remove a message from the queue (pos must be a valid position).
734  */
735 void QUEUE_RemoveMsg( MESSAGEQUEUE * msgQueue, QMSG *qmsg )
736 {
737     EnterCriticalSection( &msgQueue->cSection );
738
739     /* set the linked list */
740     if (qmsg->prevMsg)
741         qmsg->prevMsg->nextMsg = qmsg->nextMsg;
742
743     if (qmsg->nextMsg)
744         qmsg->nextMsg->prevMsg = qmsg->prevMsg;
745
746     if (msgQueue->firstMsg == qmsg)
747         msgQueue->firstMsg = qmsg->nextMsg;
748
749     if (msgQueue->lastMsg == qmsg)
750         msgQueue->lastMsg = qmsg->prevMsg;
751
752     /* deallocate the memory for the message */
753     HeapFree( GetProcessHeap(), 0, qmsg );
754
755     LeaveCriticalSection( &msgQueue->cSection );
756 }
757
758
759 /***********************************************************************
760  *           QUEUE_CleanupWindow
761  *
762  * Cleanup the queue to account for a window being deleted.
763  */
764 void QUEUE_CleanupWindow( HWND hwnd )
765 {
766     SERVER_START_REQ( cleanup_window_queue )
767     {
768         req->win = hwnd;
769         SERVER_CALL();
770     }
771     SERVER_END_REQ;
772 }
773
774
775 /***********************************************************************
776  *           hardware_event
777  *
778  * Add an event to the system message queue.
779  * Note: the position is relative to the desktop window.
780  */
781 void hardware_event( UINT message, WPARAM wParam, LPARAM lParam,
782                      int xPos, int yPos, DWORD time, DWORD extraInfo )
783 {
784     MSG *msg;
785     QMSG  *qmsg;
786     MESSAGEQUEUE *queue;
787     int  mergeMsg = 0;
788
789     if (!sysMsgQueue) return;
790
791     EnterCriticalSection( &sysMsgQueue->cSection );
792
793     /* Merge with previous event if possible */
794     qmsg = sysMsgQueue->lastMsg;
795
796     if ((message == WM_MOUSEMOVE) && sysMsgQueue->lastMsg)
797     {
798         msg = &(sysMsgQueue->lastMsg->msg);
799         
800         if ((msg->message == message) && (msg->wParam == wParam))
801         {
802             /* Merge events */
803             qmsg = sysMsgQueue->lastMsg;
804             mergeMsg = 1;
805         }
806     }
807
808     if (!mergeMsg)
809     {
810         /* Should I limit the number of messages in
811           the system message queue??? */
812
813         /* Don't merge allocate a new msg in the global heap */
814         
815         if (!(qmsg = (QMSG *) HeapAlloc( GetProcessHeap(), 0, sizeof(QMSG) ) ))
816         {
817             LeaveCriticalSection( &sysMsgQueue->cSection );
818             return;
819         }
820         
821         /* put message at the end of the linked list */
822         qmsg->nextMsg = 0;
823         qmsg->prevMsg = sysMsgQueue->lastMsg;
824
825         if (sysMsgQueue->lastMsg)
826             sysMsgQueue->lastMsg->nextMsg = qmsg;
827
828         /* set last and first anchor index in system message queue */
829         sysMsgQueue->lastMsg = qmsg;
830         if (!sysMsgQueue->firstMsg)
831             sysMsgQueue->firstMsg = qmsg;
832     }
833
834       /* Store message */
835     msg = &(qmsg->msg);
836     msg->hwnd    = 0;
837     msg->message = message;
838     msg->wParam  = wParam;
839     msg->lParam  = lParam;
840     msg->time    = time;
841     msg->pt.x    = xPos;
842     msg->pt.y    = yPos;
843     qmsg->extraInfo = extraInfo;
844     qmsg->type      = QMSG_HARDWARE;
845
846     LeaveCriticalSection( &sysMsgQueue->cSection );
847
848     if ((queue = QUEUE_Lock( GetFastQueue16() )))
849     {
850         WORD wakeBit;
851
852         if ((message >= WM_KEYFIRST) && (message <= WM_KEYLAST)) wakeBit = QS_KEY;
853         else wakeBit = (message == WM_MOUSEMOVE) ? QS_MOUSEMOVE : QS_MOUSEBUTTON;
854
855         QUEUE_SetWakeBit( queue, wakeBit, 0 );
856         QUEUE_Unlock( queue );
857     }
858 }
859
860
861 /***********************************************************************
862  *           QUEUE_GetQueueTask
863  */
864 HTASK16 QUEUE_GetQueueTask( HQUEUE16 hQueue )
865 {
866     HTASK16 hTask = 0;
867     
868     MESSAGEQUEUE *queue = QUEUE_Lock( hQueue );
869
870     if (queue)
871     {
872         hTask = queue->teb->htask16;
873         QUEUE_Unlock( queue );
874     }
875
876     return hTask;
877 }
878
879
880
881 /***********************************************************************
882  *           QUEUE_IncPaintCount
883  */
884 void QUEUE_IncPaintCount( HQUEUE16 hQueue )
885 {
886     MESSAGEQUEUE *queue;
887
888     if (!(queue = QUEUE_Lock( hQueue ))) return;
889     EnterCriticalSection( &queue->cSection );
890     queue->wPaintCount++;
891     LeaveCriticalSection( &queue->cSection );
892     QUEUE_SetWakeBit( queue, QS_PAINT, 0 );
893     QUEUE_Unlock( queue );
894 }
895
896
897 /***********************************************************************
898  *           QUEUE_DecPaintCount
899  */
900 void QUEUE_DecPaintCount( HQUEUE16 hQueue )
901 {
902     MESSAGEQUEUE *queue;
903
904     if (!(queue = QUEUE_Lock( hQueue ))) return;
905     EnterCriticalSection( &queue->cSection );
906     queue->wPaintCount--;
907     if (!queue->wPaintCount) QUEUE_ClearWakeBit( queue, QS_PAINT );
908     LeaveCriticalSection( &queue->cSection );
909     QUEUE_Unlock( queue );
910 }
911
912
913 /***********************************************************************
914  *              PostQuitMessage (USER.6)
915  */
916 void WINAPI PostQuitMessage16( INT16 exitCode )
917 {
918     PostQuitMessage( exitCode );
919 }
920
921
922 /***********************************************************************
923  *              PostQuitMessage (USER32.@)
924  *
925  * PostQuitMessage() posts a message to the system requesting an
926  * application to terminate execution. As a result of this function,
927  * the WM_QUIT message is posted to the application, and
928  * PostQuitMessage() returns immediately.  The exitCode parameter
929  * specifies an application-defined exit code, which appears in the
930  * _wParam_ parameter of the WM_QUIT message posted to the application.  
931  *
932  * CONFORMANCE
933  *
934  *  ECMA-234, Win32
935  */
936 void WINAPI PostQuitMessage( INT exitCode )
937 {
938     PostThreadMessageW( GetCurrentThreadId(), WM_QUIT, exitCode, 0 );
939 }
940
941
942 /***********************************************************************
943  *              GetWindowTask (USER.224)
944  */
945 HTASK16 WINAPI GetWindowTask16( HWND16 hwnd )
946 {
947     HTASK16 retvalue;
948     WND *wndPtr = WIN_FindWndPtr( hwnd );
949
950     if (!wndPtr) return 0;
951     retvalue = QUEUE_GetQueueTask( wndPtr->hmemTaskQ );
952     WIN_ReleaseWndPtr(wndPtr);
953     return retvalue;
954 }
955
956 /***********************************************************************
957  *              GetWindowThreadProcessId (USER32.@)
958  */
959 DWORD WINAPI GetWindowThreadProcessId( HWND hwnd, LPDWORD process )
960 {
961     DWORD retvalue;
962     MESSAGEQUEUE *queue;
963
964     WND *wndPtr = WIN_FindWndPtr( hwnd );
965     if (!wndPtr) return 0;
966
967     queue = QUEUE_Lock( wndPtr->hmemTaskQ );
968     WIN_ReleaseWndPtr(wndPtr);
969
970     if (!queue) return 0;
971
972     if ( process ) *process = (DWORD)queue->teb->pid;
973     retvalue = (DWORD)queue->teb->tid;
974
975     QUEUE_Unlock( queue );
976     return retvalue;
977 }
978
979
980 /***********************************************************************
981  *              SetMessageQueue (USER.266)
982  */
983 BOOL16 WINAPI SetMessageQueue16( INT16 size )
984 {
985     return SetMessageQueue( size );
986 }
987
988
989 /***********************************************************************
990  *              SetMessageQueue (USER32.@)
991  */
992 BOOL WINAPI SetMessageQueue( INT size )
993 {
994     /* now obsolete the message queue will be expanded dynamically
995      as necessary */
996
997     /* access the queue to create it if it's not existing */
998     GetFastQueue16();
999
1000     return TRUE;
1001 }
1002
1003 /***********************************************************************
1004  *              InitThreadInput (USER.409)
1005  */
1006 HQUEUE16 WINAPI InitThreadInput16( WORD unknown, WORD flags )
1007 {
1008     HQUEUE16 hQueue;
1009     MESSAGEQUEUE *queuePtr;
1010
1011     TEB *teb = NtCurrentTeb();
1012
1013     if (!teb)
1014         return 0;
1015
1016     hQueue = teb->queue;
1017     
1018     if ( !hQueue )
1019     {
1020         /* Create thread message queue */
1021         if( !(hQueue = QUEUE_CreateMsgQueue( TRUE )))
1022         {
1023             ERR_(msg)("failed!\n");
1024             return FALSE;
1025         }
1026         
1027         /* Link new queue into list */
1028         queuePtr = QUEUE_Lock( hQueue );
1029         queuePtr->teb = NtCurrentTeb();
1030
1031         HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
1032         SetThreadQueue16( 0, hQueue );
1033         teb->queue = hQueue;
1034         HeapUnlock( GetProcessHeap() );
1035         
1036         QUEUE_Unlock( queuePtr );
1037     }
1038
1039     return hQueue;
1040 }
1041
1042 /***********************************************************************
1043  *              GetQueueStatus (USER.334)
1044  */
1045 DWORD WINAPI GetQueueStatus16( UINT16 flags )
1046 {
1047     return GetQueueStatus( flags );
1048 }
1049
1050 /***********************************************************************
1051  *              GetQueueStatus (USER32.@)
1052  */
1053 DWORD WINAPI GetQueueStatus( UINT flags )
1054 {
1055     DWORD ret = 0;
1056
1057     SERVER_START_REQ( get_queue_status )
1058     {
1059         req->clear = 1;
1060         SERVER_CALL();
1061         ret = MAKELONG( req->changed_bits & flags, req->wake_bits & flags );
1062     }
1063     SERVER_END_REQ;
1064     return ret;
1065 }
1066
1067
1068 /***********************************************************************
1069  *              GetInputState (USER.335)
1070  */
1071 BOOL16 WINAPI GetInputState16(void)
1072 {
1073     return GetInputState();
1074 }
1075
1076 /***********************************************************************
1077  *              GetInputState   (USER32.@)
1078  */
1079 BOOL WINAPI GetInputState(void)
1080 {
1081     DWORD ret = 0;
1082
1083     SERVER_START_REQ( get_queue_status )
1084     {
1085         req->clear = 0;
1086         SERVER_CALL();
1087         ret = req->wake_bits & (QS_KEY | QS_MOUSEBUTTON);
1088     }
1089     SERVER_END_REQ;
1090     return ret;
1091 }
1092
1093 /***********************************************************************
1094  *              WaitForInputIdle (USER32.@)
1095  */
1096 DWORD WINAPI WaitForInputIdle (HANDLE hProcess, DWORD dwTimeOut)
1097 {
1098     DWORD cur_time, ret;
1099     HANDLE idle_event = -1;
1100
1101     SERVER_START_REQ( wait_input_idle )
1102     {
1103         req->handle = hProcess;
1104         req->timeout = dwTimeOut;
1105         if (!(ret = SERVER_CALL_ERR())) idle_event = req->event;
1106     }
1107     SERVER_END_REQ;
1108     if (ret) return 0xffffffff;  /* error */
1109     if (!idle_event) return 0;  /* no event to wait on */
1110
1111     cur_time = GetTickCount();
1112
1113     TRACE_(msg)("waiting for %x\n", idle_event );
1114     while ( dwTimeOut > GetTickCount() - cur_time || dwTimeOut == INFINITE ) 
1115     {
1116         ret = MsgWaitForMultipleObjects ( 1, &idle_event, FALSE, dwTimeOut, QS_SENDMESSAGE );
1117         if ( ret == ( WAIT_OBJECT_0 + 1 )) 
1118         {
1119             QMSG msg;
1120             QUEUE_FindMsg( 0, 0, 0, TRUE, TRUE, &msg );
1121             continue; 
1122         }
1123         if ( ret == WAIT_TIMEOUT || ret == 0xFFFFFFFF ) 
1124         {
1125             TRACE_(msg)("timeout or error\n");
1126             return ret;
1127         }
1128         else 
1129         {
1130             TRACE_(msg)("finished\n");
1131             return 0;
1132         }
1133     }
1134
1135     return WAIT_TIMEOUT;
1136 }
1137
1138 /***********************************************************************
1139  *              UserYield (USER.332)
1140  *              UserYield16 (USER32.@)
1141  */
1142 void WINAPI UserYield16(void)
1143 {
1144     QMSG msg;
1145
1146     /* Handle sent messages */
1147     while (QUEUE_FindMsg( 0, 0, 0, TRUE, TRUE, &msg ))
1148         ;
1149
1150     /* Yield */
1151     OldYield16();
1152
1153     /* Handle sent messages again */
1154     while (QUEUE_FindMsg( 0, 0, 0, TRUE, TRUE, &msg ))
1155         ;
1156 }
1157
1158 /***********************************************************************
1159  *              GetMessagePos (USER.119) (USER32.@)
1160  * 
1161  * The GetMessagePos() function returns a long value representing a
1162  * cursor position, in screen coordinates, when the last message
1163  * retrieved by the GetMessage() function occurs. The x-coordinate is
1164  * in the low-order word of the return value, the y-coordinate is in
1165  * the high-order word. The application can use the MAKEPOINT()
1166  * macro to obtain a POINT structure from the return value. 
1167  *
1168  * For the current cursor position, use GetCursorPos().
1169  *
1170  * RETURNS
1171  *
1172  * Cursor position of last message on success, zero on failure.
1173  *
1174  * CONFORMANCE
1175  *
1176  * ECMA-234, Win32
1177  *
1178  */
1179 DWORD WINAPI GetMessagePos(void)
1180 {
1181     MESSAGEQUEUE *queue;
1182     DWORD ret;
1183
1184     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1185     ret = queue->GetMessagePosVal;
1186     QUEUE_Unlock( queue );
1187
1188     return ret;
1189 }
1190
1191
1192 /***********************************************************************
1193  *              GetMessageTime (USER.120) (USER32.@)
1194  *
1195  * GetMessageTime() returns the message time for the last message
1196  * retrieved by the function. The time is measured in milliseconds with
1197  * the same offset as GetTickCount().
1198  *
1199  * Since the tick count wraps, this is only useful for moderately short
1200  * relative time comparisons.
1201  *
1202  * RETURNS
1203  *
1204  * Time of last message on success, zero on failure.
1205  *
1206  * CONFORMANCE
1207  *
1208  * ECMA-234, Win32
1209  *  
1210  */
1211 LONG WINAPI GetMessageTime(void)
1212 {
1213     MESSAGEQUEUE *queue;
1214     LONG ret;
1215
1216     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1217     ret = queue->GetMessageTimeVal;
1218     QUEUE_Unlock( queue );
1219     
1220     return ret;
1221 }
1222
1223
1224 /***********************************************************************
1225  *              GetMessageExtraInfo (USER.288) (USER32.@)
1226  */
1227 LONG WINAPI GetMessageExtraInfo(void)
1228 {
1229     MESSAGEQUEUE *queue;
1230     LONG ret;
1231
1232     if (!(queue = QUEUE_Lock( GetFastQueue16() ))) return 0;
1233     ret = queue->GetMessageExtraInfoVal;
1234     QUEUE_Unlock( queue );
1235
1236     return ret;
1237 }
1238
1239
1240 /**********************************************************************
1241  *              AttachThreadInput (USER32.@) Attaches input of 1 thread to other
1242  *
1243  * Attaches the input processing mechanism of one thread to that of
1244  * another thread.
1245  *
1246  * RETURNS
1247  *    Success: TRUE
1248  *    Failure: FALSE
1249  *
1250  * TODO:
1251  *    1. Reset the Key State (currenly per thread key state is not maintained)
1252  */
1253 BOOL WINAPI AttachThreadInput( 
1254     DWORD idAttach,   /* [in] Thread to attach */
1255     DWORD idAttachTo, /* [in] Thread to attach to */
1256     BOOL fAttach)   /* [in] Attach or detach */
1257 {
1258     MESSAGEQUEUE *pSrcMsgQ = 0, *pTgtMsgQ = 0;
1259     BOOL16 bRet = 0;
1260
1261     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1262
1263     /* A thread cannot attach to itself */
1264     if ( idAttach == idAttachTo )
1265         goto CLEANUP;
1266
1267     /* According to the docs this method should fail if a
1268      * "Journal record" hook is installed. (attaches all input queues together)
1269      */
1270     if ( HOOK_IsHooked( WH_JOURNALRECORD ) )
1271         goto CLEANUP;
1272         
1273     /* Retrieve message queues corresponding to the thread id's */
1274     pTgtMsgQ = QUEUE_Lock( GetThreadQueue16( idAttach ) );
1275     pSrcMsgQ = QUEUE_Lock( GetThreadQueue16( idAttachTo ) );
1276
1277     /* Ensure we have message queues and that Src and Tgt threads
1278      * are not system threads.
1279      */
1280     if ( !pSrcMsgQ || !pTgtMsgQ || !pSrcMsgQ->pQData || !pTgtMsgQ->pQData )
1281         goto CLEANUP;
1282
1283     if (fAttach)   /* Attach threads */
1284     {
1285         /* Only attach if currently detached  */
1286         if ( pTgtMsgQ->pQData != pSrcMsgQ->pQData )
1287         {
1288             /* First release the target threads perQData */
1289             PERQDATA_Release( pTgtMsgQ->pQData );
1290         
1291             /* Share a reference to the source threads perQDATA */
1292             PERQDATA_Addref( pSrcMsgQ->pQData );
1293             pTgtMsgQ->pQData = pSrcMsgQ->pQData;
1294         }
1295     }
1296     else    /* Detach threads */
1297     {
1298         /* Only detach if currently attached */
1299         if ( pTgtMsgQ->pQData == pSrcMsgQ->pQData )
1300         {
1301             /* First release the target threads perQData */
1302             PERQDATA_Release( pTgtMsgQ->pQData );
1303         
1304             /* Give the target thread its own private perQDATA once more */
1305             pTgtMsgQ->pQData = PERQDATA_CreateInstance();
1306         }
1307     }
1308
1309     /* TODO: Reset the Key State */
1310
1311     bRet = 1;      /* Success */
1312     
1313 CLEANUP:
1314
1315     /* Unlock the queues before returning */
1316     if ( pSrcMsgQ )
1317         QUEUE_Unlock( pSrcMsgQ );
1318     if ( pTgtMsgQ )
1319         QUEUE_Unlock( pTgtMsgQ );
1320     
1321     return bRet;
1322 }