Fixed some issues found by winapi_check.
[wine] / windows / queue.c
1 /*
2  * Message queues related functions
3  *
4  * Copyright 1993, 1994 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <string.h>
22 #include <signal.h>
23 #include <assert.h>
24 #include "windef.h"
25 #include "wingdi.h"
26 #include "winerror.h"
27 #include "wine/winbase16.h"
28 #include "wine/winuser16.h"
29 #include "queue.h"
30 #include "win.h"
31 #include "user.h"
32 #include "hook.h"
33 #include "thread.h"
34 #include "wine/debug.h"
35 #include "wine/server.h"
36 #include "spy.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(msg);
39
40
41 static PERQUEUEDATA *pQDataWin16 = NULL;  /* Global perQData for Win16 tasks */
42
43 HQUEUE16 hActiveQueue = 0;
44
45
46 /***********************************************************************
47  *           PERQDATA_Addref
48  *
49  * Increment reference count for the PERQUEUEDATA instance
50  * Returns reference count for debugging purposes
51  */
52 static void PERQDATA_Addref( PERQUEUEDATA *pQData )
53 {
54     assert(pQData != 0 );
55     TRACE_(msg)("(): current refcount %lu ...\n", pQData->ulRefCount);
56
57     InterlockedIncrement( &pQData->ulRefCount );
58 }
59
60
61 /***********************************************************************
62  *           PERQDATA_Release
63  *
64  * Release a reference to a PERQUEUEDATA instance.
65  * Destroy the instance if no more references exist
66  * Returns reference count for debugging purposes
67  */
68 static void PERQDATA_Release( PERQUEUEDATA *pQData )
69 {
70     assert(pQData != 0 );
71     TRACE_(msg)("(): current refcount %lu ...\n",
72           (LONG)pQData->ulRefCount );
73
74     if (!InterlockedDecrement( &pQData->ulRefCount ))
75     {
76         DeleteCriticalSection( &pQData->cSection );
77
78         TRACE_(msg)("(): deleting PERQUEUEDATA instance ...\n" );
79
80         /* Deleting our global 16 bit perQData? */
81         if ( pQData == pQDataWin16 ) pQDataWin16 = 0;
82
83         /* Free the PERQUEUEDATA instance */
84         HeapFree( GetProcessHeap(), 0, pQData );
85     }
86 }
87
88
89 /***********************************************************************
90  *           PERQDATA_CreateInstance
91  *
92  * Creates an instance of a reference counted PERQUEUEDATA element
93  * for the message queue. perQData is stored globally for 16 bit tasks.
94  *
95  * Note: We don't implement perQdata exactly the same way Windows does.
96  * Each perQData element is reference counted since it may be potentially
97  * shared by multiple message Queues (via AttachThreadInput).
98  * We only store the current values for Active, Capture and focus windows
99  * currently.
100  */
101 static PERQUEUEDATA * PERQDATA_CreateInstance(void)
102 {
103     PERQUEUEDATA *pQData;
104
105     BOOL16 bIsWin16 = 0;
106
107     TRACE_(msg)("()\n");
108
109     /* Share a single instance of perQData for all 16 bit tasks */
110     if ( ( bIsWin16 = !(NtCurrentTeb()->tibflags & TEBF_WIN32) ) )
111     {
112         /* If previously allocated, just bump up ref count */
113         if ( pQDataWin16 )
114         {
115             PERQDATA_Addref( pQDataWin16 );
116             return pQDataWin16;
117         }
118     }
119
120     /* Allocate PERQUEUEDATA from the system heap */
121     if (!( pQData = (PERQUEUEDATA *) HeapAlloc( GetProcessHeap(), 0,
122                                                     sizeof(PERQUEUEDATA) ) ))
123         return 0;
124
125     /* Initialize */
126     pQData->hWndCapture = pQData->hWndFocus = pQData->hWndActive = 0;
127     pQData->ulRefCount = 1;
128     pQData->nCaptureHT = HTCLIENT;
129
130     /* Note: We have an independent critical section for the per queue data
131      * since this may be shared by different threads. see AttachThreadInput()
132      */
133     InitializeCriticalSection( &pQData->cSection );
134     /* FIXME: not all per queue data critical sections should be global */
135     MakeCriticalSectionGlobal( &pQData->cSection );
136
137     /* Save perQData globally for 16 bit tasks */
138     if ( bIsWin16 )
139         pQDataWin16 = pQData;
140
141     return pQData;
142 }
143
144
145 /***********************************************************************
146  *           PERQDATA_GetFocusWnd
147  *
148  * Get the focus hwnd member in a threadsafe manner
149  */
150 HWND PERQDATA_GetFocusWnd( PERQUEUEDATA *pQData )
151 {
152     HWND hWndFocus;
153     assert(pQData != 0 );
154
155     EnterCriticalSection( &pQData->cSection );
156     hWndFocus = pQData->hWndFocus;
157     LeaveCriticalSection( &pQData->cSection );
158
159     return hWndFocus;
160 }
161
162
163 /***********************************************************************
164  *           PERQDATA_SetFocusWnd
165  *
166  * Set the focus hwnd member in a threadsafe manner
167  */
168 HWND PERQDATA_SetFocusWnd( PERQUEUEDATA *pQData, HWND hWndFocus )
169 {
170     HWND hWndFocusPrv;
171     assert(pQData != 0 );
172
173     EnterCriticalSection( &pQData->cSection );
174     hWndFocusPrv = pQData->hWndFocus;
175     pQData->hWndFocus = hWndFocus;
176     LeaveCriticalSection( &pQData->cSection );
177
178     return hWndFocusPrv;
179 }
180
181
182 /***********************************************************************
183  *           PERQDATA_GetActiveWnd
184  *
185  * Get the active hwnd member in a threadsafe manner
186  */
187 HWND PERQDATA_GetActiveWnd( PERQUEUEDATA *pQData )
188 {
189     HWND hWndActive;
190     assert(pQData != 0 );
191
192     EnterCriticalSection( &pQData->cSection );
193     hWndActive = pQData->hWndActive;
194     LeaveCriticalSection( &pQData->cSection );
195
196     return hWndActive;
197 }
198
199
200 /***********************************************************************
201  *           PERQDATA_SetActiveWnd
202  *
203  * Set the active focus hwnd member in a threadsafe manner
204  */
205 HWND PERQDATA_SetActiveWnd( PERQUEUEDATA *pQData, HWND hWndActive )
206 {
207     HWND hWndActivePrv;
208     assert(pQData != 0 );
209
210     EnterCriticalSection( &pQData->cSection );
211     hWndActivePrv = pQData->hWndActive;
212     pQData->hWndActive = hWndActive;
213     LeaveCriticalSection( &pQData->cSection );
214
215     return hWndActivePrv;
216 }
217
218
219 /***********************************************************************
220  *           PERQDATA_GetCaptureWnd
221  *
222  * Get the capture hwnd member in a threadsafe manner
223  */
224 HWND PERQDATA_GetCaptureWnd( INT *hittest )
225 {
226     MESSAGEQUEUE *queue;
227     PERQUEUEDATA *pQData;
228     HWND hWndCapture;
229
230     if (!(queue = QUEUE_Current())) return 0;
231     pQData = queue->pQData;
232
233     EnterCriticalSection( &pQData->cSection );
234     hWndCapture = pQData->hWndCapture;
235     *hittest = pQData->nCaptureHT;
236     LeaveCriticalSection( &pQData->cSection );
237     return hWndCapture;
238 }
239
240
241 /***********************************************************************
242  *           PERQDATA_SetCaptureWnd
243  *
244  * Set the capture hwnd member in a threadsafe manner
245  */
246 HWND PERQDATA_SetCaptureWnd( HWND hWndCapture, INT hittest )
247 {
248     MESSAGEQUEUE *queue;
249     PERQUEUEDATA *pQData;
250     HWND hWndCapturePrv;
251
252     if (!(queue = QUEUE_Current())) return 0;
253     pQData = queue->pQData;
254
255     EnterCriticalSection( &pQData->cSection );
256     hWndCapturePrv = pQData->hWndCapture;
257     pQData->hWndCapture = hWndCapture;
258     pQData->nCaptureHT = hittest;
259     LeaveCriticalSection( &pQData->cSection );
260     return hWndCapturePrv;
261 }
262
263
264
265 /***********************************************************************
266  *           QUEUE_Lock
267  *
268  * Function for getting a 32 bit pointer on queue structure. For thread
269  * safeness programmers should use this function instead of GlobalLock to
270  * retrieve a pointer on the structure. QUEUE_Unlock should also be called
271  * when access to the queue structure is not required anymore.
272  */
273 MESSAGEQUEUE *QUEUE_Lock( HQUEUE16 hQueue )
274 {
275     MESSAGEQUEUE *queue;
276
277     HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
278     queue = GlobalLock16( hQueue );
279     if ( !queue || (queue->magic != QUEUE_MAGIC) )
280     {
281         HeapUnlock( GetProcessHeap() );
282         return NULL;
283     }
284
285     queue->lockCount++;
286     HeapUnlock( GetProcessHeap() );
287     return queue;
288 }
289
290
291 /***********************************************************************
292  *           QUEUE_Current
293  *
294  * Get the current thread queue, creating it if required.
295  * QUEUE_Unlock is not needed since the queue can only be deleted by
296  * the current thread anyway.
297  */
298 MESSAGEQUEUE *QUEUE_Current(void)
299 {
300     MESSAGEQUEUE *queue;
301     HQUEUE16 hQueue;
302
303     if (!(hQueue = GetThreadQueue16(0)))
304     {
305         if (!(hQueue = InitThreadInput16( 0, 0 ))) return NULL;
306     }
307
308     if ((queue = GlobalLock16( hQueue )))
309     {
310         if (queue->magic != QUEUE_MAGIC) queue = NULL;
311     }
312     return queue;
313 }
314
315
316 /***********************************************************************
317  *           QUEUE_Unlock
318  *
319  * Use with QUEUE_Lock to get a thread safe access to message queue
320  * structure
321  */
322 void QUEUE_Unlock( MESSAGEQUEUE *queue )
323 {
324     if (queue)
325     {
326         HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
327
328         if ( --queue->lockCount == 0 )
329         {
330             if (queue->server_queue)
331                 CloseHandle( queue->server_queue );
332             GlobalFree16( queue->self );
333         }
334
335         HeapUnlock( GetProcessHeap() );
336     }
337 }
338
339
340 /***********************************************************************
341  *           QUEUE_CreateMsgQueue
342  *
343  * Creates a message queue. Doesn't link it into queue list!
344  */
345 static HQUEUE16 QUEUE_CreateMsgQueue( BOOL16 bCreatePerQData )
346 {
347     HQUEUE16 hQueue;
348     HANDLE handle;
349     MESSAGEQUEUE * msgQueue;
350
351     TRACE_(msg)("(): Creating message queue...\n");
352
353     if (!(hQueue = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT,
354                                   sizeof(MESSAGEQUEUE) )))
355         return 0;
356
357     msgQueue = (MESSAGEQUEUE *) GlobalLock16( hQueue );
358     if ( !msgQueue )
359         return 0;
360
361     if (bCreatePerQData)
362     {
363         SERVER_START_REQ( get_msg_queue )
364         {
365             wine_server_call_err( req );
366             handle = reply->handle;
367         }
368         SERVER_END_REQ;
369         if (!handle)
370         {
371             ERR_(msg)("Cannot get thread queue");
372             GlobalFree16( hQueue );
373             return 0;
374         }
375         msgQueue->server_queue = handle;
376     }
377
378     msgQueue->self = hQueue;
379     msgQueue->lockCount = 1;
380     msgQueue->magic = QUEUE_MAGIC;
381
382     /* Create and initialize our per queue data */
383     msgQueue->pQData = bCreatePerQData ? PERQDATA_CreateInstance() : NULL;
384
385     return hQueue;
386 }
387
388
389 /***********************************************************************
390  *           QUEUE_DeleteMsgQueue
391  *
392  * Unlinks and deletes a message queue.
393  *
394  * Note: We need to mask asynchronous events to make sure PostMessage works
395  * even in the signal handler.
396  */
397 void QUEUE_DeleteMsgQueue(void)
398 {
399     HQUEUE16 hQueue = GetThreadQueue16(0);
400     MESSAGEQUEUE * msgQueue;
401
402     if (!hQueue) return;  /* thread doesn't have a queue */
403
404     TRACE("(): Deleting message queue %04x\n", hQueue);
405
406     if (!(msgQueue = QUEUE_Lock(hQueue)))
407     {
408         ERR("invalid thread queue\n");
409         return;
410     }
411
412     msgQueue->magic = 0;
413
414     if( hActiveQueue == hQueue ) hActiveQueue = 0;
415
416     HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
417
418     /* Release per queue data if present */
419     if ( msgQueue->pQData )
420     {
421         PERQDATA_Release( msgQueue->pQData );
422         msgQueue->pQData = 0;
423     }
424
425     msgQueue->self = 0;
426
427     HeapUnlock( GetProcessHeap() );
428     SetThreadQueue16( 0, 0 );
429
430     /* free up resource used by MESSAGEQUEUE structure */
431     msgQueue->lockCount--;
432     QUEUE_Unlock( msgQueue );
433 }
434
435
436 /***********************************************************************
437  *              GetWindowTask (USER.224)
438  */
439 HTASK16 WINAPI GetWindowTask16( HWND16 hwnd )
440 {
441     HTASK16 retvalue;
442     MESSAGEQUEUE *queue;
443
444     WND *wndPtr = WIN_FindWndPtr16( hwnd );
445     if (!wndPtr) return 0;
446
447     queue = QUEUE_Lock( wndPtr->hmemTaskQ );
448     WIN_ReleaseWndPtr(wndPtr);
449
450     if (!queue) return 0;
451
452     retvalue = queue->teb->htask16;
453     QUEUE_Unlock( queue );
454
455     return retvalue;
456 }
457
458 /***********************************************************************
459  *              InitThreadInput   (USER.409)
460  *              InitThreadInput16 (USER32.@)
461  */
462 HQUEUE16 WINAPI InitThreadInput16( WORD unknown, WORD flags )
463 {
464     MESSAGEQUEUE *queuePtr;
465     HQUEUE16 hQueue = NtCurrentTeb()->queue;
466
467     if ( !hQueue )
468     {
469         /* Create thread message queue */
470         if( !(hQueue = QUEUE_CreateMsgQueue( TRUE )))
471         {
472             ERR_(msg)("failed!\n");
473             return FALSE;
474         }
475
476         /* Link new queue into list */
477         queuePtr = QUEUE_Lock( hQueue );
478         queuePtr->teb = NtCurrentTeb();
479
480         HeapLock( GetProcessHeap() );  /* FIXME: a bit overkill */
481         SetThreadQueue16( 0, hQueue );
482         NtCurrentTeb()->queue = hQueue;
483         HeapUnlock( GetProcessHeap() );
484
485         QUEUE_Unlock( queuePtr );
486     }
487
488     return hQueue;
489 }
490
491 /***********************************************************************
492  *              GetQueueStatus (USER32.@)
493  */
494 DWORD WINAPI GetQueueStatus( UINT flags )
495 {
496     DWORD ret = 0;
497
498     SERVER_START_REQ( get_queue_status )
499     {
500         req->clear = 1;
501         wine_server_call( req );
502         ret = MAKELONG( reply->changed_bits & flags, reply->wake_bits & flags );
503     }
504     SERVER_END_REQ;
505     return ret;
506 }
507
508
509 /***********************************************************************
510  *              GetInputState   (USER32.@)
511  */
512 BOOL WINAPI GetInputState(void)
513 {
514     DWORD ret = 0;
515
516     SERVER_START_REQ( get_queue_status )
517     {
518         req->clear = 0;
519         wine_server_call( req );
520         ret = reply->wake_bits & (QS_KEY | QS_MOUSEBUTTON);
521     }
522     SERVER_END_REQ;
523     return ret;
524 }
525
526 /***********************************************************************
527  *              GetMessagePos (USER.119)
528  *              GetMessagePos (USER32.@)
529  *
530  * The GetMessagePos() function returns a long value representing a
531  * cursor position, in screen coordinates, when the last message
532  * retrieved by the GetMessage() function occurs. The x-coordinate is
533  * in the low-order word of the return value, the y-coordinate is in
534  * the high-order word. The application can use the MAKEPOINT()
535  * macro to obtain a POINT structure from the return value.
536  *
537  * For the current cursor position, use GetCursorPos().
538  *
539  * RETURNS
540  *
541  * Cursor position of last message on success, zero on failure.
542  *
543  * CONFORMANCE
544  *
545  * ECMA-234, Win32
546  *
547  */
548 DWORD WINAPI GetMessagePos(void)
549 {
550     MESSAGEQUEUE *queue;
551
552     if (!(queue = QUEUE_Current())) return 0;
553     return queue->GetMessagePosVal;
554 }
555
556
557 /***********************************************************************
558  *              GetMessageTime (USER.120)
559  *              GetMessageTime (USER32.@)
560  *
561  * GetMessageTime() returns the message time for the last message
562  * retrieved by the function. The time is measured in milliseconds with
563  * the same offset as GetTickCount().
564  *
565  * Since the tick count wraps, this is only useful for moderately short
566  * relative time comparisons.
567  *
568  * RETURNS
569  *
570  * Time of last message on success, zero on failure.
571  *
572  * CONFORMANCE
573  *
574  * ECMA-234, Win32
575  *
576  */
577 LONG WINAPI GetMessageTime(void)
578 {
579     MESSAGEQUEUE *queue;
580
581     if (!(queue = QUEUE_Current())) return 0;
582     return queue->GetMessageTimeVal;
583 }
584
585
586 /***********************************************************************
587  *              GetMessageExtraInfo (USER.288)
588  *              GetMessageExtraInfo (USER32.@)
589  */
590 LONG WINAPI GetMessageExtraInfo(void)
591 {
592     MESSAGEQUEUE *queue;
593
594     if (!(queue = QUEUE_Current())) return 0;
595     return queue->GetMessageExtraInfoVal;
596 }
597
598
599 /**********************************************************************
600  *              AttachThreadInput (USER32.@) Attaches input of 1 thread to other
601  *
602  * Attaches the input processing mechanism of one thread to that of
603  * another thread.
604  *
605  * RETURNS
606  *    Success: TRUE
607  *    Failure: FALSE
608  *
609  * TODO:
610  *    1. Reset the Key State (currenly per thread key state is not maintained)
611  */
612 BOOL WINAPI AttachThreadInput(
613     DWORD idAttach,   /* [in] Thread to attach */
614     DWORD idAttachTo, /* [in] Thread to attach to */
615     BOOL fAttach)   /* [in] Attach or detach */
616 {
617     MESSAGEQUEUE *pSrcMsgQ = 0, *pTgtMsgQ = 0;
618     BOOL16 bRet = 0;
619
620     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
621
622     /* A thread cannot attach to itself */
623     if ( idAttach == idAttachTo )
624         goto CLEANUP;
625
626     /* According to the docs this method should fail if a
627      * "Journal record" hook is installed. (attaches all input queues together)
628      */
629     if ( HOOK_IsHooked( WH_JOURNALRECORD ) )
630         goto CLEANUP;
631
632     /* Retrieve message queues corresponding to the thread id's */
633     pTgtMsgQ = QUEUE_Lock( GetThreadQueue16( idAttach ) );
634     pSrcMsgQ = QUEUE_Lock( GetThreadQueue16( idAttachTo ) );
635
636     /* Ensure we have message queues and that Src and Tgt threads
637      * are not system threads.
638      */
639     if ( !pSrcMsgQ || !pTgtMsgQ || !pSrcMsgQ->pQData || !pTgtMsgQ->pQData )
640         goto CLEANUP;
641
642     if (fAttach)   /* Attach threads */
643     {
644         /* Only attach if currently detached  */
645         if ( pTgtMsgQ->pQData != pSrcMsgQ->pQData )
646         {
647             /* First release the target threads perQData */
648             PERQDATA_Release( pTgtMsgQ->pQData );
649
650             /* Share a reference to the source threads perQDATA */
651             PERQDATA_Addref( pSrcMsgQ->pQData );
652             pTgtMsgQ->pQData = pSrcMsgQ->pQData;
653         }
654     }
655     else    /* Detach threads */
656     {
657         /* Only detach if currently attached */
658         if ( pTgtMsgQ->pQData == pSrcMsgQ->pQData )
659         {
660             /* First release the target threads perQData */
661             PERQDATA_Release( pTgtMsgQ->pQData );
662
663             /* Give the target thread its own private perQDATA once more */
664             pTgtMsgQ->pQData = PERQDATA_CreateInstance();
665         }
666     }
667
668     /* TODO: Reset the Key State */
669
670     bRet = 1;      /* Success */
671
672 CLEANUP:
673
674     /* Unlock the queues before returning */
675     if ( pSrcMsgQ )
676         QUEUE_Unlock( pSrcMsgQ );
677     if ( pTgtMsgQ )
678         QUEUE_Unlock( pTgtMsgQ );
679
680     return bRet;
681 }