server: Handle failure of mem_alloc in duplicate_token.
[wine] / server / queue.c
1 /*
2  * Server-side message queues
3  *
4  * Copyright (C) 2000 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 "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28
29 #include "ntstatus.h"
30 #define WIN32_NO_STATUS
31 #include "windef.h"
32 #include "winbase.h"
33 #include "wingdi.h"
34 #include "winuser.h"
35 #include "winternl.h"
36
37 #include "handle.h"
38 #include "file.h"
39 #include "thread.h"
40 #include "process.h"
41 #include "request.h"
42 #include "user.h"
43
44 #define WM_NCMOUSEFIRST WM_NCMOUSEMOVE
45 #define WM_NCMOUSELAST  (WM_NCMOUSEFIRST+(WM_MOUSELAST-WM_MOUSEFIRST))
46
47 enum message_kind { SEND_MESSAGE, POST_MESSAGE };
48 #define NB_MSG_KINDS (POST_MESSAGE+1)
49
50
51 struct message_result
52 {
53     struct list            sender_entry;  /* entry in sender list */
54     struct message        *msg;           /* message the result is for */
55     struct message_result *recv_next;     /* next in receiver list */
56     struct msg_queue      *sender;        /* sender queue */
57     struct msg_queue      *receiver;      /* receiver queue */
58     int                    replied;       /* has it been replied to? */
59     unsigned int           result;        /* reply result */
60     unsigned int           error;         /* error code to pass back to sender */
61     struct message        *callback_msg;  /* message to queue for callback */
62     void                  *data;          /* message reply data */
63     unsigned int           data_size;     /* size of message reply data */
64     struct timeout_user   *timeout;       /* result timeout */
65 };
66
67 struct message
68 {
69     struct list            entry;     /* entry in message list */
70     enum message_type      type;      /* message type */
71     user_handle_t          win;       /* window handle */
72     unsigned int           msg;       /* message code */
73     unsigned int           wparam;    /* parameters */
74     unsigned int           lparam;    /* parameters */
75     int                    x;         /* x position */
76     int                    y;         /* y position */
77     unsigned int           time;      /* message time */
78     unsigned int           info;      /* extra info */
79     user_handle_t          hook;      /* winevent hook handle */
80     void                  *hook_proc; /* winevent hook proc address */
81     void                  *data;      /* message data for sent messages */
82     unsigned int           data_size; /* size of message data */
83     unsigned int           unique_id; /* unique id for nested hw message waits */
84     struct message_result *result;    /* result in sender queue */
85 };
86
87 struct timer
88 {
89     struct list     entry;     /* entry in timer list */
90     struct timeval  when;      /* next expiration */
91     unsigned int    rate;      /* timer rate in ms */
92     user_handle_t   win;       /* window handle */
93     unsigned int    msg;       /* message to post */
94     unsigned int    id;        /* timer id */
95     unsigned int    lparam;    /* lparam for message */
96 };
97
98 struct thread_input
99 {
100     struct object          obj;           /* object header */
101     struct desktop        *desktop;       /* desktop that this thread input belongs to */
102     user_handle_t          focus;         /* focus window */
103     user_handle_t          capture;       /* capture window */
104     user_handle_t          active;        /* active window */
105     user_handle_t          menu_owner;    /* current menu owner window */
106     user_handle_t          move_size;     /* current moving/resizing window */
107     user_handle_t          caret;         /* caret window */
108     rectangle_t            caret_rect;    /* caret rectangle */
109     int                    caret_hide;    /* caret hide count */
110     int                    caret_state;   /* caret on/off state */
111     struct list            msg_list;      /* list of hardware messages */
112     unsigned char          keystate[256]; /* state of each key */
113 };
114
115 struct msg_queue
116 {
117     struct object          obj;             /* object header */
118     unsigned int           wake_bits;       /* wakeup bits */
119     unsigned int           wake_mask;       /* wakeup mask */
120     unsigned int           changed_bits;    /* changed wakeup bits */
121     unsigned int           changed_mask;    /* changed wakeup mask */
122     int                    paint_count;     /* pending paint messages count */
123     int                    quit_message;    /* is there a pending quit message? */
124     int                    exit_code;       /* exit code of pending quit message */
125     struct list            msg_list[NB_MSG_KINDS];  /* lists of messages */
126     struct list            send_result;     /* stack of sent messages waiting for result */
127     struct list            callback_result; /* list of callback messages waiting for result */
128     struct message_result *recv_result;     /* stack of received messages waiting for result */
129     struct list            pending_timers;  /* list of pending timers */
130     struct list            expired_timers;  /* list of expired timers */
131     unsigned int           next_timer_id;   /* id for the next timer with a 0 window */
132     struct timeout_user   *timeout;         /* timeout for next timer to expire */
133     struct thread_input   *input;           /* thread input descriptor */
134     struct hook_table     *hooks;           /* hook table */
135     struct timeval         last_get_msg;    /* time of last get message call */
136 };
137
138 static void msg_queue_dump( struct object *obj, int verbose );
139 static int msg_queue_add_queue( struct object *obj, struct wait_queue_entry *entry );
140 static void msg_queue_remove_queue( struct object *obj, struct wait_queue_entry *entry );
141 static int msg_queue_signaled( struct object *obj, struct thread *thread );
142 static int msg_queue_satisfied( struct object *obj, struct thread *thread );
143 static void msg_queue_destroy( struct object *obj );
144 static void thread_input_dump( struct object *obj, int verbose );
145 static void thread_input_destroy( struct object *obj );
146 static void timer_callback( void *private );
147
148 static const struct object_ops msg_queue_ops =
149 {
150     sizeof(struct msg_queue),  /* size */
151     msg_queue_dump,            /* dump */
152     msg_queue_add_queue,       /* add_queue */
153     msg_queue_remove_queue,    /* remove_queue */
154     msg_queue_signaled,        /* signaled */
155     msg_queue_satisfied,       /* satisfied */
156     no_signal,                 /* signal */
157     no_get_fd,                 /* get_fd */
158     no_map_access,             /* map_access */
159     no_lookup_name,            /* lookup_name */
160     no_close_handle,           /* close_handle */
161     msg_queue_destroy          /* destroy */
162 };
163
164
165 static const struct object_ops thread_input_ops =
166 {
167     sizeof(struct thread_input),  /* size */
168     thread_input_dump,            /* dump */
169     no_add_queue,                 /* add_queue */
170     NULL,                         /* remove_queue */
171     NULL,                         /* signaled */
172     NULL,                         /* satisfied */
173     no_signal,                    /* signal */
174     no_get_fd,                    /* get_fd */
175     no_map_access,                /* map_access */
176     no_lookup_name,               /* lookup_name */
177     no_close_handle,              /* close_handle */
178     thread_input_destroy          /* destroy */
179 };
180
181 /* pointer to input structure of foreground thread */
182 static struct thread_input *foreground_input;
183 static unsigned int last_input_time;
184
185
186 /* set the caret window in a given thread input */
187 static void set_caret_window( struct thread_input *input, user_handle_t win )
188 {
189     if (!win || win != input->caret)
190     {
191         input->caret_rect.left   = 0;
192         input->caret_rect.top    = 0;
193         input->caret_rect.right  = 0;
194         input->caret_rect.bottom = 0;
195     }
196     input->caret             = win;
197     input->caret_hide        = 1;
198     input->caret_state       = 0;
199 }
200
201 /* create a thread input object */
202 static struct thread_input *create_thread_input( struct thread *thread )
203 {
204     struct thread_input *input;
205
206     if ((input = alloc_object( &thread_input_ops )))
207     {
208         input->focus       = 0;
209         input->capture     = 0;
210         input->active      = 0;
211         input->menu_owner  = 0;
212         input->move_size   = 0;
213         list_init( &input->msg_list );
214         set_caret_window( input, 0 );
215         memset( input->keystate, 0, sizeof(input->keystate) );
216
217         if (!(input->desktop = get_thread_desktop( thread, 0 /* FIXME: access rights */ )))
218         {
219             release_object( input );
220             return NULL;
221         }
222     }
223     return input;
224 }
225
226 /* release the thread input data of a given thread */
227 static inline void release_thread_input( struct thread *thread )
228 {
229     struct thread_input *input = thread->queue->input;
230
231     if (!input) return;
232     release_object( input );
233     thread->queue->input = NULL;
234 }
235
236 /* create a message queue object */
237 static struct msg_queue *create_msg_queue( struct thread *thread, struct thread_input *input )
238 {
239     struct msg_queue *queue;
240     int i;
241
242     if (!input && !(input = create_thread_input( thread ))) return NULL;
243     if ((queue = alloc_object( &msg_queue_ops )))
244     {
245         queue->wake_bits       = 0;
246         queue->wake_mask       = 0;
247         queue->changed_bits    = 0;
248         queue->changed_mask    = 0;
249         queue->paint_count     = 0;
250         queue->quit_message    = 0;
251         queue->recv_result     = NULL;
252         queue->next_timer_id   = 1;
253         queue->timeout         = NULL;
254         queue->input           = (struct thread_input *)grab_object( input );
255         queue->hooks           = NULL;
256         gettimeofday( &queue->last_get_msg, NULL );
257         list_init( &queue->send_result );
258         list_init( &queue->callback_result );
259         list_init( &queue->pending_timers );
260         list_init( &queue->expired_timers );
261         for (i = 0; i < NB_MSG_KINDS; i++) list_init( &queue->msg_list[i] );
262
263         thread->queue = queue;
264         if (!thread->process->queue)
265             thread->process->queue = (struct msg_queue *)grab_object( queue );
266     }
267     release_object( input );
268     return queue;
269 }
270
271 /* free the message queue of a thread at thread exit */
272 void free_msg_queue( struct thread *thread )
273 {
274     struct process *process = thread->process;
275
276     remove_thread_hooks( thread );
277     if (!thread->queue) return;
278     if (process->queue == thread->queue)  /* is it the process main queue? */
279     {
280         release_object( process->queue );
281         process->queue = NULL;
282         if (process->idle_event)
283         {
284             set_event( process->idle_event );
285             release_object( process->idle_event );
286             process->idle_event = NULL;
287         }
288     }
289     release_object( thread->queue );
290     thread->queue = NULL;
291 }
292
293 /* get the hook table for a given thread */
294 struct hook_table *get_queue_hooks( struct thread *thread )
295 {
296     if (!thread->queue) return NULL;
297     return thread->queue->hooks;
298 }
299
300 /* set the hook table for a given thread, allocating the queue if needed */
301 void set_queue_hooks( struct thread *thread, struct hook_table *hooks )
302 {
303     struct msg_queue *queue = thread->queue;
304     if (!queue && !(queue = create_msg_queue( thread, NULL ))) return;
305     if (queue->hooks) release_object( queue->hooks );
306     queue->hooks = hooks;
307 }
308
309 /* check the queue status */
310 inline static int is_signaled( struct msg_queue *queue )
311 {
312     return ((queue->wake_bits & queue->wake_mask) || (queue->changed_bits & queue->changed_mask));
313 }
314
315 /* set some queue bits */
316 inline static void set_queue_bits( struct msg_queue *queue, unsigned int bits )
317 {
318     queue->wake_bits |= bits;
319     queue->changed_bits |= bits;
320     if (is_signaled( queue )) wake_up( &queue->obj, 0 );
321 }
322
323 /* clear some queue bits */
324 inline static void clear_queue_bits( struct msg_queue *queue, unsigned int bits )
325 {
326     queue->wake_bits &= ~bits;
327     queue->changed_bits &= ~bits;
328 }
329
330 /* check whether msg is a keyboard message */
331 inline static int is_keyboard_msg( struct message *msg )
332 {
333     return (msg->msg >= WM_KEYFIRST && msg->msg <= WM_KEYLAST);
334 }
335
336 /* check if message is matched by the filter */
337 inline static int check_msg_filter( unsigned int msg, unsigned int first, unsigned int last )
338 {
339     return (msg >= first && msg <= last);
340 }
341
342 /* check whether a message filter contains at least one potential hardware message */
343 inline static int filter_contains_hw_range( unsigned int first, unsigned int last )
344 {
345     /* hardware message ranges are (in numerical order):
346      *   WM_NCMOUSEFIRST .. WM_NCMOUSELAST
347      *   WM_KEYFIRST .. WM_KEYLAST
348      *   WM_MOUSEFIRST .. WM_MOUSELAST
349      */
350     if (last < WM_NCMOUSEFIRST) return 0;
351     if (first > WM_NCMOUSELAST && last < WM_KEYFIRST) return 0;
352     if (first > WM_KEYLAST && last < WM_MOUSEFIRST) return 0;
353     if (first > WM_MOUSELAST) return 0;
354     return 1;
355 }
356
357 /* get the QS_* bit corresponding to a given hardware message */
358 inline static int get_hardware_msg_bit( struct message *msg )
359 {
360     if (msg->msg == WM_MOUSEMOVE || msg->msg == WM_NCMOUSEMOVE) return QS_MOUSEMOVE;
361     if (is_keyboard_msg( msg )) return QS_KEY;
362     return QS_MOUSEBUTTON;
363 }
364
365 /* get the current thread queue, creating it if needed */
366 inline static struct msg_queue *get_current_queue(void)
367 {
368     struct msg_queue *queue = current->queue;
369     if (!queue) queue = create_msg_queue( current, NULL );
370     return queue;
371 }
372
373 /* get a (pseudo-)unique id to tag hardware messages */
374 inline static unsigned int get_unique_id(void)
375 {
376     static unsigned int id;
377     if (!++id) id = 1;  /* avoid an id of 0 */
378     return id;
379 }
380
381 /* try to merge a message with the last in the list; return 1 if successful */
382 static int merge_message( struct thread_input *input, const struct message *msg )
383 {
384     struct message *prev;
385     struct list *ptr = list_tail( &input->msg_list );
386
387     if (!ptr) return 0;
388     prev = LIST_ENTRY( ptr, struct message, entry );
389     if (prev->unique_id) return 0;
390     if (prev->result) return 0;
391     if (prev->win != msg->win) return 0;
392     if (prev->msg != msg->msg) return 0;
393     if (prev->type != msg->type) return 0;
394     /* now we can merge it */
395     prev->wparam  = msg->wparam;
396     prev->lparam  = msg->lparam;
397     prev->x       = msg->x;
398     prev->y       = msg->y;
399     prev->time    = msg->time;
400     prev->info    = msg->info;
401     return 1;
402 }
403
404 /* free a result structure */
405 static void free_result( struct message_result *result )
406 {
407     if (result->timeout) remove_timeout_user( result->timeout );
408     if (result->data) free( result->data );
409     if (result->callback_msg) free( result->callback_msg );
410     free( result );
411 }
412
413 /* remove the result from the sender list it is on */
414 static inline void remove_result_from_sender( struct message_result *result )
415 {
416     assert( result->sender );
417
418     list_remove( &result->sender_entry );
419     result->sender = NULL;
420     if (!result->receiver) free_result( result );
421 }
422
423 /* store the message result in the appropriate structure */
424 static void store_message_result( struct message_result *res, unsigned int result,
425                                   unsigned int error )
426 {
427     res->result  = result;
428     res->error   = error;
429     res->replied = 1;
430     if (res->timeout)
431     {
432         remove_timeout_user( res->timeout );
433         res->timeout = NULL;
434     }
435     if (res->sender)
436     {
437         if (res->callback_msg)
438         {
439             /* queue the callback message in the sender queue */
440             res->callback_msg->lparam = result;
441             list_add_tail( &res->sender->msg_list[SEND_MESSAGE], &res->callback_msg->entry );
442             set_queue_bits( res->sender, QS_SENDMESSAGE );
443             res->callback_msg = NULL;
444             remove_result_from_sender( res );
445         }
446         else
447         {
448             /* wake sender queue if waiting on this result */
449             if (list_head(&res->sender->send_result) == &res->sender_entry)
450                 set_queue_bits( res->sender, QS_SMRESULT );
451         }
452     }
453
454 }
455
456 /* free a message when deleting a queue or window */
457 static void free_message( struct message *msg )
458 {
459     struct message_result *result = msg->result;
460     if (result)
461     {
462         result->msg = NULL;
463         if (result->sender)
464         {
465             result->receiver = NULL;
466             store_message_result( result, 0, STATUS_ACCESS_DENIED /*FIXME*/ );
467         }
468         else free_result( result );
469     }
470     if (msg->data) free( msg->data );
471     free( msg );
472 }
473
474 /* remove (and free) a message from a message list */
475 static void remove_queue_message( struct msg_queue *queue, struct message *msg,
476                                   enum message_kind kind )
477 {
478     list_remove( &msg->entry );
479     switch(kind)
480     {
481     case SEND_MESSAGE:
482         if (list_empty( &queue->msg_list[kind] )) clear_queue_bits( queue, QS_SENDMESSAGE );
483         break;
484     case POST_MESSAGE:
485         if (list_empty( &queue->msg_list[kind] )) clear_queue_bits( queue, QS_POSTMESSAGE|QS_ALLPOSTMESSAGE );
486         break;
487     }
488     free_message( msg );
489 }
490
491 /* message timed out without getting a reply */
492 static void result_timeout( void *private )
493 {
494     struct message_result *result = private;
495
496     assert( !result->replied );
497
498     result->timeout = NULL;
499
500     if (result->msg)  /* not received yet */
501     {
502         struct message *msg = result->msg;
503
504         result->msg = NULL;
505         msg->result = NULL;
506         remove_queue_message( result->receiver, msg, SEND_MESSAGE );
507         result->receiver = NULL;
508         if (!result->sender)
509         {
510             free_result( result );
511             return;
512         }
513     }
514
515     store_message_result( result, 0, STATUS_TIMEOUT );
516 }
517
518 /* allocate and fill a message result structure */
519 static struct message_result *alloc_message_result( struct msg_queue *send_queue,
520                                                     struct msg_queue *recv_queue,
521                                                     struct message *msg, int timeout,
522                                                     void *callback, unsigned int callback_data )
523 {
524     struct message_result *result = mem_alloc( sizeof(*result) );
525     if (result)
526     {
527         result->msg       = msg;
528         result->sender    = send_queue;
529         result->receiver  = recv_queue;
530         result->replied   = 0;
531         result->data      = NULL;
532         result->data_size = 0;
533         result->timeout   = NULL;
534
535         if (msg->type == MSG_CALLBACK)
536         {
537             struct message *callback_msg = mem_alloc( sizeof(*callback_msg) );
538             if (!callback_msg)
539             {
540                 free( result );
541                 return NULL;
542             }
543             callback_msg->type      = MSG_CALLBACK_RESULT;
544             callback_msg->win       = msg->win;
545             callback_msg->msg       = msg->msg;
546             callback_msg->wparam    = (unsigned int)callback;
547             callback_msg->lparam    = 0;
548             callback_msg->time      = get_tick_count();
549             callback_msg->x         = 0;
550             callback_msg->y         = 0;
551             callback_msg->info      = callback_data;
552             callback_msg->hook      = 0;
553             callback_msg->hook_proc = NULL;
554             callback_msg->result    = NULL;
555             callback_msg->data      = NULL;
556             callback_msg->data_size = 0;
557
558             result->callback_msg = callback_msg;
559             list_add_head( &send_queue->callback_result, &result->sender_entry );
560         }
561         else
562         {
563             result->callback_msg = NULL;
564             list_add_head( &send_queue->send_result, &result->sender_entry );
565         }
566
567         if (timeout)
568         {
569             struct timeval when;
570             gettimeofday( &when, NULL );
571             add_timeout( &when, timeout );
572             result->timeout = add_timeout_user( &when, result_timeout, result );
573         }
574     }
575     return result;
576 }
577
578 /* receive a message, removing it from the sent queue */
579 static void receive_message( struct msg_queue *queue, struct message *msg,
580                              struct get_message_reply *reply )
581 {
582     struct message_result *result = msg->result;
583
584     reply->total = msg->data_size;
585     if (msg->data_size > get_reply_max_size())
586     {
587         set_error( STATUS_BUFFER_OVERFLOW );
588         return;
589     }
590     reply->type   = msg->type;
591     reply->win    = msg->win;
592     reply->msg    = msg->msg;
593     reply->wparam = msg->wparam;
594     reply->lparam = msg->lparam;
595     reply->x      = msg->x;
596     reply->y      = msg->y;
597     reply->time   = msg->time;
598     reply->info   = msg->info;
599     reply->hook   = msg->hook;
600     reply->hook_proc = msg->hook_proc;
601
602     if (msg->data) set_reply_data_ptr( msg->data, msg->data_size );
603
604     list_remove( &msg->entry );
605     /* put the result on the receiver result stack */
606     if (result)
607     {
608         result->msg = NULL;
609         result->recv_next  = queue->recv_result;
610         queue->recv_result = result;
611     }
612     free( msg );
613     if (list_empty( &queue->msg_list[SEND_MESSAGE] )) clear_queue_bits( queue, QS_SENDMESSAGE );
614 }
615
616 /* set the result of the current received message */
617 static void reply_message( struct msg_queue *queue, unsigned int result,
618                            unsigned int error, int remove, const void *data, size_t len )
619 {
620     struct message_result *res = queue->recv_result;
621
622     if (remove)
623     {
624         queue->recv_result = res->recv_next;
625         res->receiver = NULL;
626         if (!res->sender)  /* no one waiting for it */
627         {
628             free_result( res );
629             return;
630         }
631     }
632     if (!res->replied)
633     {
634         if (len && (res->data = memdup( data, len ))) res->data_size = len;
635         store_message_result( res, result, error );
636     }
637 }
638
639 /* retrieve a posted message */
640 static int get_posted_message( struct msg_queue *queue, user_handle_t win,
641                                unsigned int first, unsigned int last, unsigned int flags,
642                                struct get_message_reply *reply )
643 {
644     struct message *msg;
645
646     /* check against the filters */
647     LIST_FOR_EACH_ENTRY( msg, &queue->msg_list[POST_MESSAGE], struct message, entry )
648     {
649         if (win && msg->win && msg->win != win && !is_child_window( win, msg->win )) continue;
650         if (!check_msg_filter( msg->msg, first, last )) continue;
651         goto found; /* found one */
652     }
653     return 0;
654
655     /* return it to the app */
656 found:
657     reply->total = msg->data_size;
658     if (msg->data_size > get_reply_max_size())
659     {
660         set_error( STATUS_BUFFER_OVERFLOW );
661         return 1;
662     }
663     reply->type   = msg->type;
664     reply->win    = msg->win;
665     reply->msg    = msg->msg;
666     reply->wparam = msg->wparam;
667     reply->lparam = msg->lparam;
668     reply->x      = msg->x;
669     reply->y      = msg->y;
670     reply->time   = msg->time;
671     reply->info   = msg->info;
672
673     if (flags & GET_MSG_REMOVE)
674     {
675         if (msg->data)
676         {
677             set_reply_data_ptr( msg->data, msg->data_size );
678             msg->data = NULL;
679             msg->data_size = 0;
680         }
681         remove_queue_message( queue, msg, POST_MESSAGE );
682     }
683     else if (msg->data) set_reply_data( msg->data, msg->data_size );
684
685     return 1;
686 }
687
688 static int get_quit_message( struct msg_queue *queue, unsigned int flags,
689                              struct get_message_reply *reply )
690 {
691     if (queue->quit_message)
692     {
693         reply->total  = 0;
694         reply->type   = MSG_POSTED;
695         reply->win    = NULL;
696         reply->msg    = WM_QUIT;
697         reply->wparam = queue->exit_code;
698         reply->lparam = 0;
699         reply->x      = 0;
700         reply->y      = 0;
701         reply->time   = get_tick_count();
702         reply->info   = 0;
703
704         if (flags & GET_MSG_REMOVE)
705             queue->quit_message = 0;
706
707         return 1;
708     }
709     else
710         return 0;
711 }
712
713 /* empty a message list and free all the messages */
714 static void empty_msg_list( struct list *list )
715 {
716     struct list *ptr;
717
718     while ((ptr = list_head( list )) != NULL)
719     {
720         struct message *msg = LIST_ENTRY( ptr, struct message, entry );
721         list_remove( &msg->entry );
722         free_message( msg );
723     }
724 }
725
726 /* cleanup all pending results when deleting a queue */
727 static void cleanup_results( struct msg_queue *queue )
728 {
729     struct list *entry;
730
731     while ((entry = list_head( &queue->send_result )) != NULL)
732     {
733         remove_result_from_sender( LIST_ENTRY( entry, struct message_result, sender_entry ) );
734     }
735
736     while ((entry = list_head( &queue->callback_result )) != NULL)
737     {
738         remove_result_from_sender( LIST_ENTRY( entry, struct message_result, sender_entry ) );
739     }
740
741     while (queue->recv_result)
742         reply_message( queue, 0, STATUS_ACCESS_DENIED /*FIXME*/, 1, NULL, 0 );
743 }
744
745 /* check if the thread owning the queue is hung (not checking for messages) */
746 static int is_queue_hung( struct msg_queue *queue )
747 {
748     struct timeval now;
749     struct wait_queue_entry *entry;
750
751     gettimeofday( &now, NULL );
752     if (now.tv_sec - queue->last_get_msg.tv_sec <= 5)
753         return 0;  /* less than 5 seconds since last get message -> not hung */
754
755     LIST_FOR_EACH_ENTRY( entry, &queue->obj.wait_queue, struct wait_queue_entry, entry )
756     {
757         if (entry->thread->queue == queue)
758             return 0;  /* thread is waiting on queue -> not hung */
759     }
760     return 1;
761 }
762
763 static int msg_queue_add_queue( struct object *obj, struct wait_queue_entry *entry )
764 {
765     struct msg_queue *queue = (struct msg_queue *)obj;
766     struct process *process = entry->thread->process;
767
768     /* a thread can only wait on its own queue */
769     if (entry->thread->queue != queue)
770     {
771         set_error( STATUS_ACCESS_DENIED );
772         return 0;
773     }
774     /* if waiting on the main process queue, set the idle event */
775     if (process->queue == queue)
776     {
777         if (process->idle_event) set_event( process->idle_event );
778     }
779     add_queue( obj, entry );
780     return 1;
781 }
782
783 static void msg_queue_remove_queue(struct object *obj, struct wait_queue_entry *entry )
784 {
785     struct msg_queue *queue = (struct msg_queue *)obj;
786     struct process *process = entry->thread->process;
787
788     remove_queue( obj, entry );
789
790     assert( entry->thread->queue == queue );
791
792     /* if waiting on the main process queue, reset the idle event */
793     if (process->queue == queue)
794     {
795         if (process->idle_event) reset_event( process->idle_event );
796     }
797 }
798
799 static void msg_queue_dump( struct object *obj, int verbose )
800 {
801     struct msg_queue *queue = (struct msg_queue *)obj;
802     fprintf( stderr, "Msg queue bits=%x mask=%x\n",
803              queue->wake_bits, queue->wake_mask );
804 }
805
806 static int msg_queue_signaled( struct object *obj, struct thread *thread )
807 {
808     struct msg_queue *queue = (struct msg_queue *)obj;
809     return is_signaled( queue );
810 }
811
812 static int msg_queue_satisfied( struct object *obj, struct thread *thread )
813 {
814     struct msg_queue *queue = (struct msg_queue *)obj;
815     queue->wake_mask = 0;
816     queue->changed_mask = 0;
817     return 0;  /* Not abandoned */
818 }
819
820 static void msg_queue_destroy( struct object *obj )
821 {
822     struct msg_queue *queue = (struct msg_queue *)obj;
823     struct list *ptr;
824     int i;
825
826     cleanup_results( queue );
827     for (i = 0; i < NB_MSG_KINDS; i++) empty_msg_list( &queue->msg_list[i] );
828
829     while ((ptr = list_head( &queue->pending_timers )))
830     {
831         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
832         list_remove( &timer->entry );
833         free( timer );
834     }
835     while ((ptr = list_head( &queue->expired_timers )))
836     {
837         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
838         list_remove( &timer->entry );
839         free( timer );
840     }
841     if (queue->timeout) remove_timeout_user( queue->timeout );
842     if (queue->input) release_object( queue->input );
843     if (queue->hooks) release_object( queue->hooks );
844 }
845
846 static void thread_input_dump( struct object *obj, int verbose )
847 {
848     struct thread_input *input = (struct thread_input *)obj;
849     fprintf( stderr, "Thread input focus=%p capture=%p active=%p\n",
850              input->focus, input->capture, input->active );
851 }
852
853 static void thread_input_destroy( struct object *obj )
854 {
855     struct thread_input *input = (struct thread_input *)obj;
856
857     if (foreground_input == input) foreground_input = NULL;
858     empty_msg_list( &input->msg_list );
859     if (input->desktop) release_object( input->desktop );
860 }
861
862 /* fix the thread input data when a window is destroyed */
863 inline static void thread_input_cleanup_window( struct msg_queue *queue, user_handle_t window )
864 {
865     struct thread_input *input = queue->input;
866
867     if (window == input->focus) input->focus = 0;
868     if (window == input->capture) input->capture = 0;
869     if (window == input->active) input->active = 0;
870     if (window == input->menu_owner) input->menu_owner = 0;
871     if (window == input->move_size) input->move_size = 0;
872     if (window == input->caret) set_caret_window( input, 0 );
873 }
874
875 /* check if the specified window can be set in the input data of a given queue */
876 static int check_queue_input_window( struct msg_queue *queue, user_handle_t window )
877 {
878     struct thread *thread;
879     int ret = 0;
880
881     if (!window) return 1;  /* we can always clear the data */
882
883     if ((thread = get_window_thread( window )))
884     {
885         ret = (queue->input == thread->queue->input);
886         if (!ret) set_error( STATUS_ACCESS_DENIED );
887         release_object( thread );
888     }
889     else set_error( STATUS_INVALID_HANDLE );
890
891     return ret;
892 }
893
894 /* make sure the specified thread has a queue */
895 int init_thread_queue( struct thread *thread )
896 {
897     if (thread->queue) return 1;
898     return (create_msg_queue( thread, NULL ) != NULL);
899 }
900
901 /* attach two thread input data structures */
902 int attach_thread_input( struct thread *thread_from, struct thread *thread_to )
903 {
904     struct desktop *desktop;
905     struct thread_input *input;
906
907     if (!thread_to->queue && !(thread_to->queue = create_msg_queue( thread_to, NULL ))) return 0;
908     if (!(desktop = get_thread_desktop( thread_from, 0 ))) return 0;
909     input = (struct thread_input *)grab_object( thread_to->queue->input );
910     if (input->desktop != desktop)
911     {
912         set_error( STATUS_ACCESS_DENIED );
913         release_object( input );
914         release_object( desktop );
915         return 0;
916     }
917     release_object( desktop );
918
919     if (thread_from->queue)
920     {
921         release_thread_input( thread_from );
922         thread_from->queue->input = input;
923     }
924     else
925     {
926         if (!(thread_from->queue = create_msg_queue( thread_from, input ))) return 0;
927     }
928     memset( input->keystate, 0, sizeof(input->keystate) );
929     return 1;
930 }
931
932 /* detach two thread input data structures */
933 void detach_thread_input( struct thread *thread_from )
934 {
935     struct thread_input *input;
936
937     if ((input = create_thread_input( thread_from )))
938     {
939         release_thread_input( thread_from );
940         thread_from->queue->input = input;
941     }
942 }
943
944
945 /* set the next timer to expire */
946 static void set_next_timer( struct msg_queue *queue )
947 {
948     struct list *ptr;
949
950     if (queue->timeout)
951     {
952         remove_timeout_user( queue->timeout );
953         queue->timeout = NULL;
954     }
955     if ((ptr = list_head( &queue->pending_timers )))
956     {
957         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
958         queue->timeout = add_timeout_user( &timer->when, timer_callback, queue );
959     }
960     /* set/clear QS_TIMER bit */
961     if (list_empty( &queue->expired_timers ))
962         clear_queue_bits( queue, QS_TIMER );
963     else
964         set_queue_bits( queue, QS_TIMER );
965 }
966
967 /* find a timer from its window and id */
968 static struct timer *find_timer( struct msg_queue *queue, user_handle_t win,
969                                  unsigned int msg, unsigned int id )
970 {
971     struct list *ptr;
972
973     /* we need to search both lists */
974
975     LIST_FOR_EACH( ptr, &queue->pending_timers )
976     {
977         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
978         if (timer->win == win && timer->msg == msg && timer->id == id) return timer;
979     }
980     LIST_FOR_EACH( ptr, &queue->expired_timers )
981     {
982         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
983         if (timer->win == win && timer->msg == msg && timer->id == id) return timer;
984     }
985     return NULL;
986 }
987
988 /* callback for the next timer expiration */
989 static void timer_callback( void *private )
990 {
991     struct msg_queue *queue = private;
992     struct list *ptr;
993
994     queue->timeout = NULL;
995     /* move on to the next timer */
996     ptr = list_head( &queue->pending_timers );
997     list_remove( ptr );
998     list_add_tail( &queue->expired_timers, ptr );
999     set_next_timer( queue );
1000 }
1001
1002 /* link a timer at its rightful place in the queue list */
1003 static void link_timer( struct msg_queue *queue, struct timer *timer )
1004 {
1005     struct list *ptr;
1006
1007     for (ptr = queue->pending_timers.next; ptr != &queue->pending_timers; ptr = ptr->next)
1008     {
1009         struct timer *t = LIST_ENTRY( ptr, struct timer, entry );
1010         if (!time_before( &t->when, &timer->when )) break;
1011     }
1012     list_add_before( ptr, &timer->entry );
1013 }
1014
1015 /* remove a timer from the queue timer list and free it */
1016 static void free_timer( struct msg_queue *queue, struct timer *timer )
1017 {
1018     list_remove( &timer->entry );
1019     free( timer );
1020     set_next_timer( queue );
1021 }
1022
1023 /* restart an expired timer */
1024 static void restart_timer( struct msg_queue *queue, struct timer *timer )
1025 {
1026     struct timeval now;
1027
1028     list_remove( &timer->entry );
1029     gettimeofday( &now, NULL );
1030     while (!time_before( &now, &timer->when )) add_timeout( &timer->when, timer->rate );
1031     link_timer( queue, timer );
1032     set_next_timer( queue );
1033 }
1034
1035 /* find an expired timer matching the filtering parameters */
1036 static struct timer *find_expired_timer( struct msg_queue *queue, user_handle_t win,
1037                                          unsigned int get_first, unsigned int get_last,
1038                                          int remove )
1039 {
1040     struct list *ptr;
1041
1042     LIST_FOR_EACH( ptr, &queue->expired_timers )
1043     {
1044         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
1045         if (win && timer->win != win) continue;
1046         if (check_msg_filter( timer->msg, get_first, get_last ))
1047         {
1048             if (remove) restart_timer( queue, timer );
1049             return timer;
1050         }
1051     }
1052     return NULL;
1053 }
1054
1055 /* add a timer */
1056 static struct timer *set_timer( struct msg_queue *queue, unsigned int rate )
1057 {
1058     struct timer *timer = mem_alloc( sizeof(*timer) );
1059     if (timer)
1060     {
1061         timer->rate  = max( rate, 1 );
1062         gettimeofday( &timer->when, NULL );
1063         add_timeout( &timer->when, rate );
1064         link_timer( queue, timer );
1065         /* check if we replaced the next timer */
1066         if (list_head( &queue->pending_timers ) == &timer->entry) set_next_timer( queue );
1067     }
1068     return timer;
1069 }
1070
1071 /* change the input key state for a given key */
1072 static void set_input_key_state( struct thread_input *input, unsigned char key, int down )
1073 {
1074     if (down)
1075     {
1076         if (!(input->keystate[key] & 0x80)) input->keystate[key] ^= 0x01;
1077         input->keystate[key] |= 0x80;
1078     }
1079     else input->keystate[key] &= ~0x80;
1080 }
1081
1082 /* update the input key state for a keyboard message */
1083 static void update_input_key_state( struct thread_input *input, const struct message *msg )
1084 {
1085     unsigned char key;
1086     int down = 0, extended;
1087
1088     switch (msg->msg)
1089     {
1090     case WM_LBUTTONDOWN:
1091         down = 1;
1092         /* fall through */
1093     case WM_LBUTTONUP:
1094         set_input_key_state( input, VK_LBUTTON, down );
1095         break;
1096     case WM_MBUTTONDOWN:
1097         down = 1;
1098         /* fall through */
1099     case WM_MBUTTONUP:
1100         set_input_key_state( input, VK_MBUTTON, down );
1101         break;
1102     case WM_RBUTTONDOWN:
1103         down = 1;
1104         /* fall through */
1105     case WM_RBUTTONUP:
1106         set_input_key_state( input, VK_RBUTTON, down );
1107         break;
1108     case WM_XBUTTONDOWN:
1109         down = 1;
1110         /* fall through */
1111     case WM_XBUTTONUP:
1112         if (msg->wparam == XBUTTON1) set_input_key_state( input, VK_XBUTTON1, down );
1113         else if (msg->wparam == XBUTTON2) set_input_key_state( input, VK_XBUTTON2, down );
1114         break;
1115     case WM_KEYDOWN:
1116     case WM_SYSKEYDOWN:
1117         down = 1;
1118         /* fall through */
1119     case WM_KEYUP:
1120     case WM_SYSKEYUP:
1121         key = (unsigned char)msg->wparam;
1122         extended = ((msg->lparam >> 16) & KF_EXTENDED) != 0;
1123         set_input_key_state( input, key, down );
1124         switch(key)
1125         {
1126         case VK_SHIFT:
1127             set_input_key_state( input, extended ? VK_RSHIFT : VK_LSHIFT, down );
1128             break;
1129         case VK_CONTROL:
1130             set_input_key_state( input, extended ? VK_RCONTROL : VK_LCONTROL, down );
1131             break;
1132         case VK_MENU:
1133             set_input_key_state( input, extended ? VK_RMENU : VK_LMENU, down );
1134             break;
1135         }
1136         break;
1137     }
1138 }
1139
1140 /* release the hardware message currently being processed by the given thread */
1141 static void release_hardware_message( struct msg_queue *queue, unsigned int hw_id,
1142                                       int remove, user_handle_t new_win )
1143 {
1144     struct thread_input *input = queue->input;
1145     struct message *msg;
1146
1147     LIST_FOR_EACH_ENTRY( msg, &input->msg_list, struct message, entry )
1148     {
1149         if (msg->unique_id == hw_id) break;
1150     }
1151     if (&msg->entry == &input->msg_list) return;  /* not found */
1152
1153     /* clear the queue bit for that message */
1154     if (remove || new_win)
1155     {
1156         struct message *other;
1157         int clr_bit;
1158
1159         clr_bit = get_hardware_msg_bit( msg );
1160         LIST_FOR_EACH_ENTRY( other, &input->msg_list, struct message, entry )
1161         {
1162             if (other != msg && get_hardware_msg_bit( other ) == clr_bit)
1163             {
1164                 clr_bit = 0;
1165                 break;
1166             }
1167         }
1168         if (clr_bit) clear_queue_bits( queue, clr_bit );
1169     }
1170
1171     if (new_win)  /* set the new window */
1172     {
1173         struct thread *owner = get_window_thread( new_win );
1174         if (owner)
1175         {
1176             if (owner->queue->input == input)
1177             {
1178                 msg->win = new_win;
1179                 set_queue_bits( owner->queue, get_hardware_msg_bit( msg ));
1180                 remove = 0;
1181             }
1182             release_object( owner );
1183         }
1184     }
1185     if (remove)
1186     {
1187         update_input_key_state( input, msg );
1188         list_remove( &msg->entry );
1189         free_message( msg );
1190     }
1191 }
1192
1193 /* find the window that should receive a given hardware message */
1194 static user_handle_t find_hardware_message_window( struct thread_input *input, struct message *msg,
1195                                                    unsigned int *msg_code )
1196 {
1197     user_handle_t win = 0;
1198
1199     *msg_code = msg->msg;
1200     if (is_keyboard_msg( msg ))
1201     {
1202         if (input && !(win = input->focus))
1203         {
1204             win = input->active;
1205             if (*msg_code < WM_SYSKEYDOWN) *msg_code += WM_SYSKEYDOWN - WM_KEYDOWN;
1206         }
1207     }
1208     else  /* mouse message */
1209     {
1210         if (!input || !(win = input->capture))
1211         {
1212             if (!(win = msg->win) || !is_window_visible( win ))
1213             {
1214                 if (input) win = window_from_point( input->desktop, msg->x, msg->y );
1215             }
1216         }
1217     }
1218     return win;
1219 }
1220
1221 /* queue a hardware message into a given thread input */
1222 static void queue_hardware_message( struct msg_queue *queue, struct message *msg )
1223 {
1224     user_handle_t win;
1225     struct thread *thread;
1226     struct thread_input *input = queue ? queue->input : foreground_input;
1227     unsigned int msg_code;
1228
1229     last_input_time = get_tick_count();
1230     win = find_hardware_message_window( input, msg, &msg_code );
1231     if (!win || !(thread = get_window_thread(win)))
1232     {
1233         if (input) update_input_key_state( input, msg );
1234         free( msg );
1235         return;
1236     }
1237     input = thread->queue->input;
1238
1239     if (msg->msg == WM_MOUSEMOVE && merge_message( input, msg )) free( msg );
1240     else
1241     {
1242         msg->unique_id = 0;  /* will be set once we return it to the app */
1243         list_add_tail( &input->msg_list, &msg->entry );
1244         set_queue_bits( thread->queue, get_hardware_msg_bit(msg) );
1245     }
1246     release_object( thread );
1247 }
1248
1249 /* check message filter for a hardware message */
1250 static int check_hw_message_filter( user_handle_t win, unsigned int msg_code,
1251                                     user_handle_t filter_win, unsigned int first, unsigned int last )
1252 {
1253     if (msg_code >= WM_KEYFIRST && msg_code <= WM_KEYLAST)
1254     {
1255         /* we can only test the window for a keyboard message since the
1256          * dest window for a mouse message depends on hittest */
1257         if (filter_win && win != filter_win && !is_child_window( filter_win, win ))
1258             return 0;
1259         /* the message code is final for a keyboard message, we can simply check it */
1260         return check_msg_filter( msg_code, first, last );
1261     }
1262     else  /* mouse message */
1263     {
1264         /* we need to check all possible values that the message can have in the end */
1265
1266         if (check_msg_filter( msg_code, first, last )) return 1;
1267         if (msg_code == WM_MOUSEWHEEL) return 0;  /* no other possible value for this one */
1268
1269         /* all other messages can become non-client messages */
1270         if (check_msg_filter( msg_code + (WM_NCMOUSEFIRST - WM_MOUSEFIRST), first, last )) return 1;
1271
1272         /* clicks can become double-clicks or non-client double-clicks */
1273         if (msg_code == WM_LBUTTONDOWN || msg_code == WM_MBUTTONDOWN ||
1274             msg_code == WM_RBUTTONDOWN || msg_code == WM_XBUTTONDOWN)
1275         {
1276             if (check_msg_filter( msg_code + (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN), first, last )) return 1;
1277             if (check_msg_filter( msg_code + (WM_NCLBUTTONDBLCLK - WM_LBUTTONDOWN), first, last )) return 1;
1278         }
1279         return 0;
1280     }
1281 }
1282
1283
1284 /* find a hardware message for the given queue */
1285 static int get_hardware_message( struct thread *thread, int hw_id, user_handle_t filter_win,
1286                                  unsigned int first, unsigned int last, struct get_message_reply *reply )
1287 {
1288     struct thread_input *input = thread->queue->input;
1289     struct thread *win_thread;
1290     struct list *ptr;
1291     user_handle_t win;
1292     int clear_bits, got_one = 0;
1293     unsigned int msg_code;
1294
1295     ptr = list_head( &input->msg_list );
1296     if (hw_id)
1297     {
1298         while (ptr)
1299         {
1300             struct message *msg = LIST_ENTRY( ptr, struct message, entry );
1301             if (msg->unique_id == hw_id) break;
1302             ptr = list_next( &input->msg_list, ptr );
1303         }
1304         if (!ptr) ptr = list_head( &input->msg_list );
1305         else ptr = list_next( &input->msg_list, ptr );  /* start from the next one */
1306     }
1307
1308     if (ptr == list_head( &input->msg_list ))
1309         clear_bits = QS_KEY | QS_MOUSEMOVE | QS_MOUSEBUTTON;
1310     else
1311         clear_bits = 0;  /* don't clear bits if we don't go through the whole list */
1312
1313     while (ptr)
1314     {
1315         struct message *msg = LIST_ENTRY( ptr, struct message, entry );
1316         ptr = list_next( &input->msg_list, ptr );
1317         win = find_hardware_message_window( input, msg, &msg_code );
1318         if (!win || !(win_thread = get_window_thread( win )))
1319         {
1320             /* no window at all, remove it */
1321             update_input_key_state( input, msg );
1322             list_remove( &msg->entry );
1323             free_message( msg );
1324             continue;
1325         }
1326         if (win_thread != thread)
1327         {
1328             if (win_thread->queue->input == input)
1329             {
1330                 /* wake the other thread */
1331                 set_queue_bits( win_thread->queue, get_hardware_msg_bit(msg) );
1332                 got_one = 1;
1333             }
1334             else
1335             {
1336                 /* for another thread input, drop it */
1337                 update_input_key_state( input, msg );
1338                 list_remove( &msg->entry );
1339                 free_message( msg );
1340             }
1341             release_object( win_thread );
1342             continue;
1343         }
1344         release_object( win_thread );
1345
1346         /* if we already got a message for another thread, or if it doesn't
1347          * match the filter we skip it */
1348         if (got_one || !check_hw_message_filter( win, msg_code, filter_win, first, last ))
1349         {
1350             clear_bits &= ~get_hardware_msg_bit( msg );
1351             continue;
1352         }
1353         /* now we can return it */
1354         if (!msg->unique_id) msg->unique_id = get_unique_id();
1355         reply->type   = MSG_HARDWARE;
1356         reply->win    = win;
1357         reply->msg    = msg_code;
1358         reply->wparam = msg->wparam;
1359         reply->lparam = msg->lparam;
1360         reply->x      = msg->x;
1361         reply->y      = msg->y;
1362         reply->time   = msg->time;
1363         reply->info   = msg->info;
1364         reply->hw_id  = msg->unique_id;
1365         return 1;
1366     }
1367     /* nothing found, clear the hardware queue bits */
1368     clear_queue_bits( thread->queue, clear_bits );
1369     return 0;
1370 }
1371
1372 /* increment (or decrement if 'incr' is negative) the queue paint count */
1373 void inc_queue_paint_count( struct thread *thread, int incr )
1374 {
1375     struct msg_queue *queue = thread->queue;
1376
1377     assert( queue );
1378
1379     if ((queue->paint_count += incr) < 0) queue->paint_count = 0;
1380
1381     if (queue->paint_count)
1382         set_queue_bits( queue, QS_PAINT );
1383     else
1384         clear_queue_bits( queue, QS_PAINT );
1385 }
1386
1387
1388 /* remove all messages and timers belonging to a certain window */
1389 void queue_cleanup_window( struct thread *thread, user_handle_t win )
1390 {
1391     struct msg_queue *queue = thread->queue;
1392     struct list *ptr;
1393     int i;
1394
1395     if (!queue) return;
1396
1397     /* remove timers */
1398
1399     ptr = list_head( &queue->pending_timers );
1400     while (ptr)
1401     {
1402         struct list *next = list_next( &queue->pending_timers, ptr );
1403         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
1404         if (timer->win == win) free_timer( queue, timer );
1405         ptr = next;
1406     }
1407     ptr = list_head( &queue->expired_timers );
1408     while (ptr)
1409     {
1410         struct list *next = list_next( &queue->expired_timers, ptr );
1411         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
1412         if (timer->win == win) free_timer( queue, timer );
1413         ptr = next;
1414     }
1415
1416     /* remove messages */
1417     for (i = 0; i < NB_MSG_KINDS; i++)
1418     {
1419         struct list *ptr, *next;
1420
1421         LIST_FOR_EACH_SAFE( ptr, next, &queue->msg_list[i] )
1422         {
1423             struct message *msg = LIST_ENTRY( ptr, struct message, entry );
1424             if (msg->win == win) remove_queue_message( queue, msg, i );
1425         }
1426     }
1427
1428     thread_input_cleanup_window( queue, win );
1429 }
1430
1431 /* post a message to a window; used by socket handling */
1432 void post_message( user_handle_t win, unsigned int message,
1433                    unsigned int wparam, unsigned int lparam )
1434 {
1435     struct message *msg;
1436     struct thread *thread = get_window_thread( win );
1437
1438     if (!thread) return;
1439
1440     if (thread->queue && (msg = mem_alloc( sizeof(*msg) )))
1441     {
1442         msg->type      = MSG_POSTED;
1443         msg->win       = get_user_full_handle( win );
1444         msg->msg       = message;
1445         msg->wparam    = wparam;
1446         msg->lparam    = lparam;
1447         msg->time      = get_tick_count();
1448         msg->x         = 0;
1449         msg->y         = 0;
1450         msg->info      = 0;
1451         msg->hook      = 0;
1452         msg->hook_proc = NULL;
1453         msg->result    = NULL;
1454         msg->data      = NULL;
1455         msg->data_size = 0;
1456
1457         list_add_tail( &thread->queue->msg_list[POST_MESSAGE], &msg->entry );
1458         set_queue_bits( thread->queue, QS_POSTMESSAGE|QS_ALLPOSTMESSAGE );
1459     }
1460     release_object( thread );
1461 }
1462
1463 /* post a win event */
1464 void post_win_event( struct thread *thread, unsigned int event,
1465                      user_handle_t win, unsigned int object_id,
1466                      unsigned int child_id, void *hook_proc,
1467                      const WCHAR *module, size_t module_size,
1468                      user_handle_t hook)
1469 {
1470     struct message *msg;
1471
1472     if (thread->queue && (msg = mem_alloc( sizeof(*msg) )))
1473     {
1474         msg->type      = MSG_WINEVENT;
1475         msg->win       = get_user_full_handle( win );
1476         msg->msg       = event;
1477         msg->wparam    = object_id;
1478         msg->lparam    = child_id;
1479         msg->time      = get_tick_count();
1480         msg->x         = 0;
1481         msg->y         = 0;
1482         msg->info      = get_thread_id( current );
1483         msg->result    = NULL;
1484         msg->hook      = hook;
1485         msg->hook_proc = hook_proc;
1486
1487         if ((msg->data = malloc( module_size )))
1488         {
1489             msg->data_size = module_size;
1490             memcpy( msg->data, module, module_size );
1491
1492             if (debug_level > 1)
1493                 fprintf( stderr, "post_win_event: tid %04x event %04x win %p object_id %d child_id %d\n",
1494                          get_thread_id(thread), event, win, object_id, child_id );
1495             list_add_tail( &thread->queue->msg_list[SEND_MESSAGE], &msg->entry );
1496             set_queue_bits( thread->queue, QS_SENDMESSAGE );
1497         }
1498         else
1499             free( msg );
1500     }
1501 }
1502
1503 /* get the message queue of the current thread */
1504 DECL_HANDLER(get_msg_queue)
1505 {
1506     struct msg_queue *queue = get_current_queue();
1507
1508     reply->handle = 0;
1509     if (queue) reply->handle = alloc_handle( current->process, queue, SYNCHRONIZE, 0 );
1510 }
1511
1512
1513 /* set the current message queue wakeup mask */
1514 DECL_HANDLER(set_queue_mask)
1515 {
1516     struct msg_queue *queue = get_current_queue();
1517
1518     if (queue)
1519     {
1520         queue->wake_mask    = req->wake_mask;
1521         queue->changed_mask = req->changed_mask;
1522         reply->wake_bits    = queue->wake_bits;
1523         reply->changed_bits = queue->changed_bits;
1524         if (is_signaled( queue ))
1525         {
1526             /* if skip wait is set, do what would have been done in the subsequent wait */
1527             if (req->skip_wait) msg_queue_satisfied( &queue->obj, current );
1528             else wake_up( &queue->obj, 0 );
1529         }
1530     }
1531 }
1532
1533
1534 /* get the current message queue status */
1535 DECL_HANDLER(get_queue_status)
1536 {
1537     struct msg_queue *queue = current->queue;
1538     if (queue)
1539     {
1540         reply->wake_bits    = queue->wake_bits;
1541         reply->changed_bits = queue->changed_bits;
1542         if (req->clear) queue->changed_bits = 0;
1543     }
1544     else reply->wake_bits = reply->changed_bits = 0;
1545 }
1546
1547
1548 /* send a message to a thread queue */
1549 DECL_HANDLER(send_message)
1550 {
1551     struct message *msg;
1552     struct msg_queue *send_queue = get_current_queue();
1553     struct msg_queue *recv_queue = NULL;
1554     struct thread *thread = NULL;
1555
1556     if (req->id)
1557     {
1558         if (!(thread = get_thread_from_id( req->id ))) return;
1559     }
1560     else if (req->type != MSG_HARDWARE)
1561     {
1562         /* only hardware messages are allowed without destination thread */
1563         set_error( STATUS_INVALID_PARAMETER );
1564         return;
1565     }
1566
1567     if (thread && !(recv_queue = thread->queue))
1568     {
1569         set_error( STATUS_INVALID_PARAMETER );
1570         release_object( thread );
1571         return;
1572     }
1573     if (recv_queue && (req->flags & SEND_MSG_ABORT_IF_HUNG) && is_queue_hung(recv_queue))
1574     {
1575         set_error( STATUS_TIMEOUT );
1576         release_object( thread );
1577         return;
1578     }
1579
1580     if ((msg = mem_alloc( sizeof(*msg) )))
1581     {
1582         msg->type      = req->type;
1583         msg->win       = get_user_full_handle( req->win );
1584         msg->msg       = req->msg;
1585         msg->wparam    = req->wparam;
1586         msg->lparam    = req->lparam;
1587         msg->time      = req->time;
1588         msg->x         = req->x;
1589         msg->y         = req->y;
1590         msg->info      = req->info;
1591         msg->hook      = 0;
1592         msg->hook_proc = NULL;
1593         msg->result    = NULL;
1594         msg->data      = NULL;
1595         msg->data_size = 0;
1596
1597         switch(msg->type)
1598         {
1599         case MSG_OTHER_PROCESS:
1600             msg->data_size = get_req_data_size();
1601             if (msg->data_size && !(msg->data = memdup( get_req_data(), msg->data_size )))
1602             {
1603                 free( msg );
1604                 break;
1605             }
1606             /* fall through */
1607         case MSG_ASCII:
1608         case MSG_UNICODE:
1609         case MSG_CALLBACK:
1610             if (!(msg->result = alloc_message_result( send_queue, recv_queue, msg,
1611                                                       req->timeout, req->callback, req->info )))
1612             {
1613                 free_message( msg );
1614                 break;
1615             }
1616             /* fall through */
1617         case MSG_NOTIFY:
1618             list_add_tail( &recv_queue->msg_list[SEND_MESSAGE], &msg->entry );
1619             set_queue_bits( recv_queue, QS_SENDMESSAGE );
1620             break;
1621         case MSG_POSTED:
1622             /* needed for posted DDE messages */
1623             msg->data_size = get_req_data_size();
1624             if (msg->data_size && !(msg->data = memdup( get_req_data(), msg->data_size )))
1625             {
1626                 free( msg );
1627                 break;
1628             }
1629             list_add_tail( &recv_queue->msg_list[POST_MESSAGE], &msg->entry );
1630             set_queue_bits( recv_queue, QS_POSTMESSAGE|QS_ALLPOSTMESSAGE );
1631             break;
1632         case MSG_HARDWARE:
1633             queue_hardware_message( recv_queue, msg );
1634             break;
1635         case MSG_CALLBACK_RESULT:  /* cannot send this one */
1636         default:
1637             set_error( STATUS_INVALID_PARAMETER );
1638             free( msg );
1639             break;
1640         }
1641     }
1642     if (thread) release_object( thread );
1643 }
1644
1645 /* post a quit message to the current queue */
1646 DECL_HANDLER(post_quit_message)
1647 {
1648     struct msg_queue *queue = get_current_queue();
1649
1650     if (!queue)
1651         return;
1652
1653     queue->quit_message = 1;
1654     queue->exit_code = req->exit_code;
1655     set_queue_bits( queue, QS_POSTMESSAGE|QS_ALLPOSTMESSAGE );
1656 }
1657
1658 /* get a message from the current queue */
1659 DECL_HANDLER(get_message)
1660 {
1661     struct timer *timer;
1662     struct list *ptr;
1663     struct msg_queue *queue = get_current_queue();
1664     user_handle_t get_win = get_user_full_handle( req->get_win );
1665
1666     reply->active_hooks = get_active_hooks();
1667
1668     if (!queue) return;
1669     gettimeofday( &queue->last_get_msg, NULL );
1670
1671     /* first check for sent messages */
1672     if ((ptr = list_head( &queue->msg_list[SEND_MESSAGE] )))
1673     {
1674         struct message *msg = LIST_ENTRY( ptr, struct message, entry );
1675         receive_message( queue, msg, reply );
1676         return;
1677     }
1678     if (req->flags & GET_MSG_SENT_ONLY) goto done;  /* nothing else to check */
1679
1680     /* clear changed bits so we can wait on them if we don't find a message */
1681     if (req->get_first == 0 && req->get_last == ~0U) queue->changed_bits = 0;
1682     else queue->changed_bits &= QS_ALLPOSTMESSAGE;
1683
1684     /* then check for posted messages */
1685     if (get_posted_message( queue, get_win, req->get_first, req->get_last, req->flags, reply ))
1686         return;
1687
1688     /* only check for quit messages if not posted messages pending.
1689      * note: the quit message isn't filtered */
1690     if (get_quit_message( queue, req->flags, reply ))
1691         return;
1692
1693     /* then check for any raw hardware message */
1694     if (filter_contains_hw_range( req->get_first, req->get_last ) &&
1695         get_hardware_message( current, req->hw_id, get_win, req->get_first, req->get_last, reply ))
1696         return;
1697
1698     /* now check for WM_PAINT */
1699     if (queue->paint_count &&
1700         check_msg_filter( WM_PAINT, req->get_first, req->get_last ) &&
1701         (reply->win = find_window_to_repaint( get_win, current )))
1702     {
1703         reply->type   = MSG_POSTED;
1704         reply->msg    = WM_PAINT;
1705         reply->wparam = 0;
1706         reply->lparam = 0;
1707         reply->x      = 0;
1708         reply->y      = 0;
1709         reply->time   = get_tick_count();
1710         reply->info   = 0;
1711         return;
1712     }
1713
1714     /* now check for timer */
1715     if ((timer = find_expired_timer( queue, get_win, req->get_first,
1716                                      req->get_last, (req->flags & GET_MSG_REMOVE) )))
1717     {
1718         reply->type   = MSG_POSTED;
1719         reply->win    = timer->win;
1720         reply->msg    = timer->msg;
1721         reply->wparam = timer->id;
1722         reply->lparam = timer->lparam;
1723         reply->x      = 0;
1724         reply->y      = 0;
1725         reply->time   = get_tick_count();
1726         reply->info   = 0;
1727         return;
1728     }
1729
1730  done:
1731     set_error( STATUS_PENDING );  /* FIXME */
1732 }
1733
1734
1735 /* reply to a sent message */
1736 DECL_HANDLER(reply_message)
1737 {
1738     if (!current->queue) set_error( STATUS_ACCESS_DENIED );
1739     else if (current->queue->recv_result)
1740         reply_message( current->queue, req->result, 0, req->remove,
1741                        get_req_data(), get_req_data_size() );
1742 }
1743
1744
1745 /* accept the current hardware message */
1746 DECL_HANDLER(accept_hardware_message)
1747 {
1748     if (current->queue)
1749         release_hardware_message( current->queue, req->hw_id, req->remove, req->new_win );
1750     else
1751         set_error( STATUS_ACCESS_DENIED );
1752 }
1753
1754
1755 /* retrieve the reply for the last message sent */
1756 DECL_HANDLER(get_message_reply)
1757 {
1758     struct message_result *result;
1759     struct list *entry;
1760     struct msg_queue *queue = current->queue;
1761
1762     if (queue)
1763     {
1764         set_error( STATUS_PENDING );
1765         reply->result = 0;
1766
1767         if (!(entry = list_head( &queue->send_result ))) return;  /* no reply ready */
1768
1769         result = LIST_ENTRY( entry, struct message_result, sender_entry );
1770         if (result->replied || req->cancel)
1771         {
1772             if (result->replied)
1773             {
1774                 reply->result = result->result;
1775                 set_error( result->error );
1776                 if (result->data)
1777                 {
1778                     size_t data_len = min( result->data_size, get_reply_max_size() );
1779                     set_reply_data_ptr( result->data, data_len );
1780                     result->data = NULL;
1781                     result->data_size = 0;
1782                 }
1783             }
1784             remove_result_from_sender( result );
1785
1786             entry = list_head( &queue->send_result );
1787             if (!entry) clear_queue_bits( queue, QS_SMRESULT );
1788             else
1789             {
1790                 result = LIST_ENTRY( entry, struct message_result, sender_entry );
1791                 if (!result->replied) clear_queue_bits( queue, QS_SMRESULT );
1792             }
1793         }
1794     }
1795     else set_error( STATUS_ACCESS_DENIED );
1796 }
1797
1798
1799 /* set a window timer */
1800 DECL_HANDLER(set_win_timer)
1801 {
1802     struct timer *timer;
1803     struct msg_queue *queue;
1804     struct thread *thread = NULL;
1805     user_handle_t win = 0;
1806     unsigned int id = req->id;
1807
1808     if (req->win)
1809     {
1810         if (!(win = get_user_full_handle( req->win )) || !(thread = get_window_thread( win )))
1811         {
1812             set_error( STATUS_INVALID_HANDLE );
1813             return;
1814         }
1815         if (thread->process != current->process)
1816         {
1817             release_object( thread );
1818             set_error( STATUS_ACCESS_DENIED );
1819             return;
1820         }
1821         queue = thread->queue;
1822         /* remove it if it existed already */
1823         if ((timer = find_timer( queue, win, req->msg, id ))) free_timer( queue, timer );
1824     }
1825     else
1826     {
1827         queue = get_current_queue();
1828         /* find a free id for it */
1829         do
1830         {
1831             id = queue->next_timer_id;
1832             if (++queue->next_timer_id >= 0x10000) queue->next_timer_id = 1;
1833         }
1834         while (find_timer( queue, 0, req->msg, id ));
1835     }
1836
1837     if ((timer = set_timer( queue, req->rate )))
1838     {
1839         timer->win    = win;
1840         timer->msg    = req->msg;
1841         timer->id     = id;
1842         timer->lparam = req->lparam;
1843         reply->id     = id;
1844     }
1845     if (thread) release_object( thread );
1846 }
1847
1848 /* kill a window timer */
1849 DECL_HANDLER(kill_win_timer)
1850 {
1851     struct timer *timer;
1852     struct thread *thread;
1853     user_handle_t win = 0;
1854
1855     if (req->win)
1856     {
1857         if (!(win = get_user_full_handle( req->win )) || !(thread = get_window_thread( win )))
1858         {
1859             set_error( STATUS_INVALID_HANDLE );
1860             return;
1861         }
1862         if (thread->process != current->process)
1863         {
1864             release_object( thread );
1865             set_error( STATUS_ACCESS_DENIED );
1866             return;
1867         }
1868     }
1869     else thread = (struct thread *)grab_object( current );
1870
1871     if (thread->queue && (timer = find_timer( thread->queue, win, req->msg, req->id )))
1872         free_timer( thread->queue, timer );
1873     else
1874         set_error( STATUS_INVALID_PARAMETER );
1875
1876     release_object( thread );
1877 }
1878
1879
1880 /* attach (or detach) thread inputs */
1881 DECL_HANDLER(attach_thread_input)
1882 {
1883     struct thread *thread_from = get_thread_from_id( req->tid_from );
1884     struct thread *thread_to = get_thread_from_id( req->tid_to );
1885
1886     if (!thread_from || !thread_to)
1887     {
1888         if (thread_from) release_object( thread_from );
1889         if (thread_to) release_object( thread_to );
1890         return;
1891     }
1892     if (thread_from != thread_to)
1893     {
1894         if (req->attach) attach_thread_input( thread_from, thread_to );
1895         else
1896         {
1897             if (thread_from->queue && thread_to->queue &&
1898                 thread_from->queue->input == thread_to->queue->input)
1899                 detach_thread_input( thread_from );
1900             else
1901                 set_error( STATUS_ACCESS_DENIED );
1902         }
1903     }
1904     else set_error( STATUS_ACCESS_DENIED );
1905     release_object( thread_from );
1906     release_object( thread_to );
1907 }
1908
1909
1910 /* get thread input data */
1911 DECL_HANDLER(get_thread_input)
1912 {
1913     struct thread *thread = NULL;
1914     struct thread_input *input;
1915
1916     if (req->tid)
1917     {
1918         if (!(thread = get_thread_from_id( req->tid ))) return;
1919         input = thread->queue ? thread->queue->input : NULL;
1920     }
1921     else input = foreground_input;  /* get the foreground thread info */
1922
1923     if (input)
1924     {
1925         reply->focus      = input->focus;
1926         reply->capture    = input->capture;
1927         reply->active     = input->active;
1928         reply->menu_owner = input->menu_owner;
1929         reply->move_size  = input->move_size;
1930         reply->caret      = input->caret;
1931         reply->rect       = input->caret_rect;
1932     }
1933     else
1934     {
1935         reply->focus      = 0;
1936         reply->capture    = 0;
1937         reply->active     = 0;
1938         reply->menu_owner = 0;
1939         reply->move_size  = 0;
1940         reply->caret      = 0;
1941         reply->rect.left = reply->rect.top = reply->rect.right = reply->rect.bottom = 0;
1942     }
1943     /* foreground window is active window of foreground thread */
1944     reply->foreground = foreground_input ? foreground_input->active : 0;
1945     if (thread) release_object( thread );
1946 }
1947
1948
1949 /* retrieve queue keyboard state for a given thread */
1950 DECL_HANDLER(get_key_state)
1951 {
1952     struct thread *thread;
1953     struct thread_input *input;
1954
1955     if (!(thread = get_thread_from_id( req->tid ))) return;
1956     input = thread->queue ? thread->queue->input : NULL;
1957     if (input)
1958     {
1959         if (req->key >= 0) reply->state = input->keystate[req->key & 0xff];
1960         set_reply_data( input->keystate, min( get_reply_max_size(), sizeof(input->keystate) ));
1961     }
1962     release_object( thread );
1963 }
1964
1965
1966 /* set queue keyboard state for a given thread */
1967 DECL_HANDLER(set_key_state)
1968 {
1969     struct thread *thread = NULL;
1970     struct thread_input *input;
1971
1972     if (!(thread = get_thread_from_id( req->tid ))) return;
1973     input = thread->queue ? thread->queue->input : NULL;
1974     if (input)
1975     {
1976         size_t size = min( sizeof(input->keystate), get_req_data_size() );
1977         if (size) memcpy( input->keystate, get_req_data(), size );
1978     }
1979     release_object( thread );
1980 }
1981
1982
1983 /* set the system foreground window */
1984 DECL_HANDLER(set_foreground_window)
1985 {
1986     struct msg_queue *queue = get_current_queue();
1987
1988     reply->previous = foreground_input ? foreground_input->active : 0;
1989     reply->send_msg_old = (reply->previous && foreground_input != queue->input);
1990     reply->send_msg_new = FALSE;
1991
1992     if (req->handle)
1993     {
1994         struct thread *thread;
1995
1996         if (is_top_level_window( req->handle ) &&
1997             ((thread = get_window_thread( req->handle ))))
1998         {
1999             foreground_input = thread->queue->input;
2000             reply->send_msg_new = (foreground_input != queue->input);
2001             release_object( thread );
2002         }
2003         else set_error( STATUS_INVALID_HANDLE );
2004     }
2005     else foreground_input = NULL;
2006 }
2007
2008
2009 /* set the current thread focus window */
2010 DECL_HANDLER(set_focus_window)
2011 {
2012     struct msg_queue *queue = get_current_queue();
2013
2014     reply->previous = 0;
2015     if (queue && check_queue_input_window( queue, req->handle ))
2016     {
2017         reply->previous = queue->input->focus;
2018         queue->input->focus = get_user_full_handle( req->handle );
2019     }
2020 }
2021
2022
2023 /* set the current thread active window */
2024 DECL_HANDLER(set_active_window)
2025 {
2026     struct msg_queue *queue = get_current_queue();
2027
2028     reply->previous = 0;
2029     if (queue && check_queue_input_window( queue, req->handle ))
2030     {
2031         if (!req->handle || make_window_active( req->handle ))
2032         {
2033             reply->previous = queue->input->active;
2034             queue->input->active = get_user_full_handle( req->handle );
2035         }
2036         else set_error( STATUS_INVALID_HANDLE );
2037     }
2038 }
2039
2040
2041 /* set the current thread capture window */
2042 DECL_HANDLER(set_capture_window)
2043 {
2044     struct msg_queue *queue = get_current_queue();
2045
2046     reply->previous = reply->full_handle = 0;
2047     if (queue && check_queue_input_window( queue, req->handle ))
2048     {
2049         struct thread_input *input = queue->input;
2050
2051         reply->previous = input->capture;
2052         input->capture = get_user_full_handle( req->handle );
2053         input->menu_owner = (req->flags & CAPTURE_MENU) ? input->capture : 0;
2054         input->move_size = (req->flags & CAPTURE_MOVESIZE) ? input->capture : 0;
2055         reply->full_handle = input->capture;
2056     }
2057 }
2058
2059
2060 /* Set the current thread caret window */
2061 DECL_HANDLER(set_caret_window)
2062 {
2063     struct msg_queue *queue = get_current_queue();
2064
2065     reply->previous = 0;
2066     if (queue && check_queue_input_window( queue, req->handle ))
2067     {
2068         struct thread_input *input = queue->input;
2069
2070         reply->previous  = input->caret;
2071         reply->old_rect  = input->caret_rect;
2072         reply->old_hide  = input->caret_hide;
2073         reply->old_state = input->caret_state;
2074
2075         set_caret_window( input, get_user_full_handle(req->handle) );
2076         input->caret_rect.right  = input->caret_rect.left + req->width;
2077         input->caret_rect.bottom = input->caret_rect.top + req->height;
2078     }
2079 }
2080
2081
2082 /* Set the current thread caret information */
2083 DECL_HANDLER(set_caret_info)
2084 {
2085     struct msg_queue *queue = get_current_queue();
2086     struct thread_input *input;
2087
2088     if (!queue) return;
2089     input = queue->input;
2090     reply->full_handle = input->caret;
2091     reply->old_rect    = input->caret_rect;
2092     reply->old_hide    = input->caret_hide;
2093     reply->old_state   = input->caret_state;
2094
2095     if (req->handle && get_user_full_handle(req->handle) != input->caret)
2096     {
2097         set_error( STATUS_ACCESS_DENIED );
2098         return;
2099     }
2100     if (req->flags & SET_CARET_POS)
2101     {
2102         input->caret_rect.right  += req->x - input->caret_rect.left;
2103         input->caret_rect.bottom += req->y - input->caret_rect.top;
2104         input->caret_rect.left = req->x;
2105         input->caret_rect.top  = req->y;
2106     }
2107     if (req->flags & SET_CARET_HIDE)
2108     {
2109         input->caret_hide += req->hide;
2110         if (input->caret_hide < 0) input->caret_hide = 0;
2111     }
2112     if (req->flags & SET_CARET_STATE)
2113     {
2114         if (req->state == -1) input->caret_state = !input->caret_state;
2115         else input->caret_state = !!req->state;
2116     }
2117 }
2118
2119
2120 /* get the time of the last input event */
2121 DECL_HANDLER(get_last_input_time)
2122 {
2123     reply->time = last_input_time;
2124 }