server: Fix a memory leak.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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           error;         /* error code to pass back to sender */
60     lparam_t               result;        /* reply result */
61     struct message        *hardware_msg;  /* hardware message if low-level hook result */
62     struct desktop        *desktop;       /* desktop for hardware message */
63     struct message        *callback_msg;  /* message to queue for callback */
64     void                  *data;          /* message reply data */
65     unsigned int           data_size;     /* size of message reply data */
66     struct timeout_user   *timeout;       /* result timeout */
67 };
68
69 struct message
70 {
71     struct list            entry;     /* entry in message list */
72     enum message_type      type;      /* message type */
73     user_handle_t          win;       /* window handle */
74     unsigned int           msg;       /* message code */
75     lparam_t               wparam;    /* parameters */
76     lparam_t               lparam;    /* parameters */
77     unsigned int           time;      /* message time */
78     void                  *data;      /* message data for sent messages */
79     unsigned int           data_size; /* size of message data */
80     unsigned int           unique_id; /* unique id for nested hw message waits */
81     struct message_result *result;    /* result in sender queue */
82 };
83
84 struct timer
85 {
86     struct list     entry;     /* entry in timer list */
87     timeout_t       when;      /* next expiration */
88     unsigned int    rate;      /* timer rate in ms */
89     user_handle_t   win;       /* window handle */
90     unsigned int    msg;       /* message to post */
91     lparam_t        id;        /* timer id */
92     lparam_t        lparam;    /* lparam for message */
93 };
94
95 struct thread_input
96 {
97     struct object          obj;           /* object header */
98     struct desktop        *desktop;       /* desktop that this thread input belongs to */
99     user_handle_t          focus;         /* focus window */
100     user_handle_t          capture;       /* capture window */
101     user_handle_t          active;        /* active window */
102     user_handle_t          menu_owner;    /* current menu owner window */
103     user_handle_t          move_size;     /* current moving/resizing window */
104     user_handle_t          caret;         /* caret window */
105     rectangle_t            caret_rect;    /* caret rectangle */
106     int                    caret_hide;    /* caret hide count */
107     int                    caret_state;   /* caret on/off state */
108     user_handle_t          cursor;        /* current cursor */
109     int                    cursor_count;  /* cursor show count */
110     struct list            msg_list;      /* list of hardware messages */
111     unsigned char          keystate[256]; /* state of each key */
112 };
113
114 struct msg_queue
115 {
116     struct object          obj;             /* object header */
117     struct fd             *fd;              /* optional file descriptor to poll */
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     int                    cursor_count;    /* per-queue cursor show count */
126     struct list            msg_list[NB_MSG_KINDS];  /* lists of messages */
127     struct list            send_result;     /* stack of sent messages waiting for result */
128     struct list            callback_result; /* list of callback messages waiting for result */
129     struct message_result *recv_result;     /* stack of received messages waiting for result */
130     struct list            pending_timers;  /* list of pending timers */
131     struct list            expired_timers;  /* list of expired timers */
132     lparam_t               next_timer_id;   /* id for the next timer with a 0 window */
133     struct timeout_user   *timeout;         /* timeout for next timer to expire */
134     struct thread_input   *input;           /* thread input descriptor */
135     struct hook_table     *hooks;           /* hook table */
136     timeout_t              last_get_msg;    /* time of last get message call */
137 };
138
139 static void msg_queue_dump( struct object *obj, int verbose );
140 static int msg_queue_add_queue( struct object *obj, struct wait_queue_entry *entry );
141 static void msg_queue_remove_queue( struct object *obj, struct wait_queue_entry *entry );
142 static int msg_queue_signaled( struct object *obj, struct thread *thread );
143 static int msg_queue_satisfied( struct object *obj, struct thread *thread );
144 static void msg_queue_destroy( struct object *obj );
145 static void msg_queue_poll_event( struct fd *fd, int event );
146 static void thread_input_dump( struct object *obj, int verbose );
147 static void thread_input_destroy( struct object *obj );
148 static void timer_callback( void *private );
149
150 static const struct object_ops msg_queue_ops =
151 {
152     sizeof(struct msg_queue),  /* size */
153     msg_queue_dump,            /* dump */
154     no_get_type,               /* get_type */
155     msg_queue_add_queue,       /* add_queue */
156     msg_queue_remove_queue,    /* remove_queue */
157     msg_queue_signaled,        /* signaled */
158     msg_queue_satisfied,       /* satisfied */
159     no_signal,                 /* signal */
160     no_get_fd,                 /* get_fd */
161     no_map_access,             /* map_access */
162     default_get_sd,            /* get_sd */
163     default_set_sd,            /* set_sd */
164     no_lookup_name,            /* lookup_name */
165     no_open_file,              /* open_file */
166     no_close_handle,           /* close_handle */
167     msg_queue_destroy          /* destroy */
168 };
169
170 static const struct fd_ops msg_queue_fd_ops =
171 {
172     NULL,                        /* get_poll_events */
173     msg_queue_poll_event,        /* poll_event */
174     NULL,                        /* flush */
175     NULL,                        /* get_fd_type */
176     NULL,                        /* ioctl */
177     NULL,                        /* queue_async */
178     NULL,                        /* reselect_async */
179     NULL                         /* cancel async */
180 };
181
182
183 static const struct object_ops thread_input_ops =
184 {
185     sizeof(struct thread_input),  /* size */
186     thread_input_dump,            /* dump */
187     no_get_type,                  /* get_type */
188     no_add_queue,                 /* add_queue */
189     NULL,                         /* remove_queue */
190     NULL,                         /* signaled */
191     NULL,                         /* satisfied */
192     no_signal,                    /* signal */
193     no_get_fd,                    /* get_fd */
194     no_map_access,                /* map_access */
195     default_get_sd,               /* get_sd */
196     default_set_sd,               /* set_sd */
197     no_lookup_name,               /* lookup_name */
198     no_open_file,                 /* open_file */
199     no_close_handle,              /* close_handle */
200     thread_input_destroy          /* destroy */
201 };
202
203 /* pointer to input structure of foreground thread */
204 static unsigned int last_input_time;
205
206 static void queue_hardware_message( struct desktop *desktop, struct message *msg );
207 static void free_message( struct message *msg );
208
209 /* set the caret window in a given thread input */
210 static void set_caret_window( struct thread_input *input, user_handle_t win )
211 {
212     if (!win || win != input->caret)
213     {
214         input->caret_rect.left   = 0;
215         input->caret_rect.top    = 0;
216         input->caret_rect.right  = 0;
217         input->caret_rect.bottom = 0;
218     }
219     input->caret             = win;
220     input->caret_hide        = 1;
221     input->caret_state       = 0;
222 }
223
224 /* create a thread input object */
225 static struct thread_input *create_thread_input( struct thread *thread )
226 {
227     struct thread_input *input;
228
229     if ((input = alloc_object( &thread_input_ops )))
230     {
231         input->focus        = 0;
232         input->capture      = 0;
233         input->active       = 0;
234         input->menu_owner   = 0;
235         input->move_size    = 0;
236         input->cursor       = 0;
237         input->cursor_count = 0;
238         list_init( &input->msg_list );
239         set_caret_window( input, 0 );
240         memset( input->keystate, 0, sizeof(input->keystate) );
241
242         if (!(input->desktop = get_thread_desktop( thread, 0 /* FIXME: access rights */ )))
243         {
244             release_object( input );
245             return NULL;
246         }
247     }
248     return input;
249 }
250
251 /* create a message queue object */
252 static struct msg_queue *create_msg_queue( struct thread *thread, struct thread_input *input )
253 {
254     struct thread_input *new_input = NULL;
255     struct msg_queue *queue;
256     int i;
257
258     if (!input)
259     {
260         if (!(new_input = create_thread_input( thread ))) return NULL;
261         input = new_input;
262     }
263
264     if ((queue = alloc_object( &msg_queue_ops )))
265     {
266         queue->fd              = NULL;
267         queue->wake_bits       = 0;
268         queue->wake_mask       = 0;
269         queue->changed_bits    = 0;
270         queue->changed_mask    = 0;
271         queue->paint_count     = 0;
272         queue->quit_message    = 0;
273         queue->cursor_count    = 0;
274         queue->recv_result     = NULL;
275         queue->next_timer_id   = 0x7fff;
276         queue->timeout         = NULL;
277         queue->input           = (struct thread_input *)grab_object( input );
278         queue->hooks           = NULL;
279         queue->last_get_msg    = current_time;
280         list_init( &queue->send_result );
281         list_init( &queue->callback_result );
282         list_init( &queue->pending_timers );
283         list_init( &queue->expired_timers );
284         for (i = 0; i < NB_MSG_KINDS; i++) list_init( &queue->msg_list[i] );
285
286         thread->queue = queue;
287     }
288     if (new_input) release_object( new_input );
289     return queue;
290 }
291
292 /* free the message queue of a thread at thread exit */
293 void free_msg_queue( struct thread *thread )
294 {
295     remove_thread_hooks( thread );
296     if (!thread->queue) return;
297     release_object( thread->queue );
298     thread->queue = NULL;
299 }
300
301 /* change the thread input data of a given thread */
302 static int assign_thread_input( struct thread *thread, struct thread_input *new_input )
303 {
304     struct msg_queue *queue = thread->queue;
305
306     if (!queue)
307     {
308         thread->queue = create_msg_queue( thread, new_input );
309         return thread->queue != NULL;
310     }
311     if (queue->input)
312     {
313         queue->input->cursor_count -= queue->cursor_count;
314         release_object( queue->input );
315     }
316     queue->input = (struct thread_input *)grab_object( new_input );
317     new_input->cursor_count += queue->cursor_count;
318     return 1;
319 }
320
321 /* set the cursor clip rectangle */
322 static void set_clip_rectangle( struct desktop *desktop, const rectangle_t *rect )
323 {
324     rectangle_t top_rect, new_rect;
325
326     get_top_window_rectangle( desktop, &top_rect );
327     if (!rect || !intersect_rect( &new_rect, &top_rect, rect )) new_rect = top_rect;
328     if (!memcmp( &desktop->cursor.clip, &new_rect, sizeof(new_rect) )) return;
329     desktop->cursor.clip = new_rect;
330     if (desktop->cursor.clip_msg) post_desktop_message( desktop, desktop->cursor.clip_msg, 0, 0 );
331 }
332
333 /* change the foreground input and reset the cursor clip rect */
334 static void set_foreground_input( struct desktop *desktop, struct thread_input *input )
335 {
336     if (desktop->foreground_input == input) return;
337     set_clip_rectangle( desktop, NULL );
338     desktop->foreground_input = input;
339 }
340
341 /* get the hook table for a given thread */
342 struct hook_table *get_queue_hooks( struct thread *thread )
343 {
344     if (!thread->queue) return NULL;
345     return thread->queue->hooks;
346 }
347
348 /* set the hook table for a given thread, allocating the queue if needed */
349 void set_queue_hooks( struct thread *thread, struct hook_table *hooks )
350 {
351     struct msg_queue *queue = thread->queue;
352     if (!queue && !(queue = create_msg_queue( thread, NULL ))) return;
353     if (queue->hooks) release_object( queue->hooks );
354     queue->hooks = hooks;
355 }
356
357 /* check the queue status */
358 static inline int is_signaled( struct msg_queue *queue )
359 {
360     return ((queue->wake_bits & queue->wake_mask) || (queue->changed_bits & queue->changed_mask));
361 }
362
363 /* set some queue bits */
364 static inline void set_queue_bits( struct msg_queue *queue, unsigned int bits )
365 {
366     queue->wake_bits |= bits;
367     queue->changed_bits |= bits;
368     if (is_signaled( queue )) wake_up( &queue->obj, 0 );
369 }
370
371 /* clear some queue bits */
372 static inline void clear_queue_bits( struct msg_queue *queue, unsigned int bits )
373 {
374     queue->wake_bits &= ~bits;
375     queue->changed_bits &= ~bits;
376 }
377
378 /* check whether msg is a keyboard message */
379 static inline int is_keyboard_msg( struct message *msg )
380 {
381     return (msg->msg >= WM_KEYFIRST && msg->msg <= WM_KEYLAST);
382 }
383
384 /* check if message is matched by the filter */
385 static inline int check_msg_filter( unsigned int msg, unsigned int first, unsigned int last )
386 {
387     return (msg >= first && msg <= last);
388 }
389
390 /* check whether a message filter contains at least one potential hardware message */
391 static inline int filter_contains_hw_range( unsigned int first, unsigned int last )
392 {
393     /* hardware message ranges are (in numerical order):
394      *   WM_NCMOUSEFIRST .. WM_NCMOUSELAST
395      *   WM_KEYFIRST .. WM_KEYLAST
396      *   WM_MOUSEFIRST .. WM_MOUSELAST
397      */
398     if (last < WM_NCMOUSEFIRST) return 0;
399     if (first > WM_NCMOUSELAST && last < WM_KEYFIRST) return 0;
400     if (first > WM_KEYLAST && last < WM_MOUSEFIRST) return 0;
401     if (first > WM_MOUSELAST) return 0;
402     return 1;
403 }
404
405 /* get the QS_* bit corresponding to a given hardware message */
406 static inline int get_hardware_msg_bit( struct message *msg )
407 {
408     if (msg->msg == WM_MOUSEMOVE || msg->msg == WM_NCMOUSEMOVE) return QS_MOUSEMOVE;
409     if (is_keyboard_msg( msg )) return QS_KEY;
410     return QS_MOUSEBUTTON;
411 }
412
413 /* get the current thread queue, creating it if needed */
414 static inline struct msg_queue *get_current_queue(void)
415 {
416     struct msg_queue *queue = current->queue;
417     if (!queue) queue = create_msg_queue( current, NULL );
418     return queue;
419 }
420
421 /* get a (pseudo-)unique id to tag hardware messages */
422 static inline unsigned int get_unique_id(void)
423 {
424     static unsigned int id;
425     if (!++id) id = 1;  /* avoid an id of 0 */
426     return id;
427 }
428
429 /* try to merge a message with the last in the list; return 1 if successful */
430 static int merge_message( struct thread_input *input, const struct message *msg )
431 {
432     struct message *prev;
433     struct list *ptr = list_tail( &input->msg_list );
434
435     if (!ptr) return 0;
436     prev = LIST_ENTRY( ptr, struct message, entry );
437     if (prev->result) return 0;
438     if (prev->win && msg->win && prev->win != msg->win) return 0;
439     if (prev->msg != msg->msg) return 0;
440     if (prev->type != msg->type) return 0;
441     /* now we can merge it */
442     prev->wparam  = msg->wparam;
443     prev->lparam  = msg->lparam;
444     prev->time    = msg->time;
445     if (msg->type == MSG_HARDWARE && prev->data && msg->data)
446     {
447         struct hardware_msg_data *prev_data = prev->data;
448         struct hardware_msg_data *msg_data = msg->data;
449         prev_data->x     = msg_data->x;
450         prev_data->y     = msg_data->y;
451         prev_data->info  = msg_data->info;
452     }
453     return 1;
454 }
455
456 /* free a result structure */
457 static void free_result( struct message_result *result )
458 {
459     if (result->timeout) remove_timeout_user( result->timeout );
460     free( result->data );
461     if (result->callback_msg) free_message( result->callback_msg );
462     if (result->hardware_msg) free_message( result->hardware_msg );
463     if (result->desktop) release_object( result->desktop );
464     free( result );
465 }
466
467 /* remove the result from the sender list it is on */
468 static inline void remove_result_from_sender( struct message_result *result )
469 {
470     assert( result->sender );
471
472     list_remove( &result->sender_entry );
473     result->sender = NULL;
474     if (!result->receiver) free_result( result );
475 }
476
477 /* store the message result in the appropriate structure */
478 static void store_message_result( struct message_result *res, lparam_t result, unsigned int error )
479 {
480     res->result  = result;
481     res->error   = error;
482     res->replied = 1;
483     if (res->timeout)
484     {
485         remove_timeout_user( res->timeout );
486         res->timeout = NULL;
487     }
488
489     if (res->hardware_msg)
490     {
491         if (!error && result)  /* rejected by the hook */
492             free_message( res->hardware_msg );
493         else
494             queue_hardware_message( res->desktop, res->hardware_msg );
495
496         res->hardware_msg = NULL;
497     }
498
499     if (res->sender)
500     {
501         if (res->callback_msg)
502         {
503             /* queue the callback message in the sender queue */
504             struct callback_msg_data *data = res->callback_msg->data;
505             data->result = result;
506             list_add_tail( &res->sender->msg_list[SEND_MESSAGE], &res->callback_msg->entry );
507             set_queue_bits( res->sender, QS_SENDMESSAGE );
508             res->callback_msg = NULL;
509             remove_result_from_sender( res );
510         }
511         else
512         {
513             /* wake sender queue if waiting on this result */
514             if (list_head(&res->sender->send_result) == &res->sender_entry)
515                 set_queue_bits( res->sender, QS_SMRESULT );
516         }
517     }
518     else if (!res->receiver) free_result( res );
519 }
520
521 /* free a message when deleting a queue or window */
522 static void free_message( struct message *msg )
523 {
524     struct message_result *result = msg->result;
525     if (result)
526     {
527         result->msg = NULL;
528         result->receiver = NULL;
529         store_message_result( result, 0, STATUS_ACCESS_DENIED /*FIXME*/ );
530     }
531     free( msg->data );
532     free( msg );
533 }
534
535 /* remove (and free) a message from a message list */
536 static void remove_queue_message( struct msg_queue *queue, struct message *msg,
537                                   enum message_kind kind )
538 {
539     list_remove( &msg->entry );
540     switch(kind)
541     {
542     case SEND_MESSAGE:
543         if (list_empty( &queue->msg_list[kind] )) clear_queue_bits( queue, QS_SENDMESSAGE );
544         break;
545     case POST_MESSAGE:
546         if (list_empty( &queue->msg_list[kind] ) && !queue->quit_message)
547             clear_queue_bits( queue, QS_POSTMESSAGE|QS_ALLPOSTMESSAGE );
548         break;
549     }
550     free_message( msg );
551 }
552
553 /* message timed out without getting a reply */
554 static void result_timeout( void *private )
555 {
556     struct message_result *result = private;
557
558     assert( !result->replied );
559
560     result->timeout = NULL;
561
562     if (result->msg)  /* not received yet */
563     {
564         struct message *msg = result->msg;
565
566         result->msg = NULL;
567         msg->result = NULL;
568         remove_queue_message( result->receiver, msg, SEND_MESSAGE );
569         result->receiver = NULL;
570     }
571     store_message_result( result, 0, STATUS_TIMEOUT );
572 }
573
574 /* allocate and fill a message result structure */
575 static struct message_result *alloc_message_result( struct msg_queue *send_queue,
576                                                     struct msg_queue *recv_queue,
577                                                     struct message *msg, timeout_t timeout )
578 {
579     struct message_result *result = mem_alloc( sizeof(*result) );
580     if (result)
581     {
582         result->msg          = msg;
583         result->sender       = send_queue;
584         result->receiver     = recv_queue;
585         result->replied      = 0;
586         result->data         = NULL;
587         result->data_size    = 0;
588         result->timeout      = NULL;
589         result->hardware_msg = NULL;
590         result->desktop      = NULL;
591         result->callback_msg = NULL;
592
593         if (msg->type == MSG_CALLBACK)
594         {
595             struct message *callback_msg = mem_alloc( sizeof(*callback_msg) );
596
597             if (!callback_msg)
598             {
599                 free( result );
600                 return NULL;
601             }
602             callback_msg->type      = MSG_CALLBACK_RESULT;
603             callback_msg->win       = msg->win;
604             callback_msg->msg       = msg->msg;
605             callback_msg->wparam    = 0;
606             callback_msg->lparam    = 0;
607             callback_msg->time      = get_tick_count();
608             callback_msg->result    = NULL;
609             /* steal the data from the original message */
610             callback_msg->data      = msg->data;
611             callback_msg->data_size = msg->data_size;
612             msg->data = NULL;
613             msg->data_size = 0;
614
615             result->callback_msg = callback_msg;
616             list_add_head( &send_queue->callback_result, &result->sender_entry );
617         }
618         else if (send_queue) list_add_head( &send_queue->send_result, &result->sender_entry );
619
620         if (timeout != TIMEOUT_INFINITE)
621             result->timeout = add_timeout_user( timeout, result_timeout, result );
622     }
623     return result;
624 }
625
626 /* receive a message, removing it from the sent queue */
627 static void receive_message( struct msg_queue *queue, struct message *msg,
628                              struct get_message_reply *reply )
629 {
630     struct message_result *result = msg->result;
631
632     reply->total = msg->data_size;
633     if (msg->data_size > get_reply_max_size())
634     {
635         set_error( STATUS_BUFFER_OVERFLOW );
636         return;
637     }
638     reply->type   = msg->type;
639     reply->win    = msg->win;
640     reply->msg    = msg->msg;
641     reply->wparam = msg->wparam;
642     reply->lparam = msg->lparam;
643     reply->time   = msg->time;
644
645     if (msg->data) set_reply_data_ptr( msg->data, msg->data_size );
646
647     list_remove( &msg->entry );
648     /* put the result on the receiver result stack */
649     if (result)
650     {
651         result->msg = NULL;
652         result->recv_next  = queue->recv_result;
653         queue->recv_result = result;
654     }
655     free( msg );
656     if (list_empty( &queue->msg_list[SEND_MESSAGE] )) clear_queue_bits( queue, QS_SENDMESSAGE );
657 }
658
659 /* set the result of the current received message */
660 static void reply_message( struct msg_queue *queue, lparam_t result,
661                            unsigned int error, int remove, const void *data, data_size_t len )
662 {
663     struct message_result *res = queue->recv_result;
664
665     if (remove)
666     {
667         queue->recv_result = res->recv_next;
668         res->receiver = NULL;
669         if (!res->sender && !res->hardware_msg)  /* no one waiting for it */
670         {
671             free_result( res );
672             return;
673         }
674     }
675     if (!res->replied)
676     {
677         if (len && (res->data = memdup( data, len ))) res->data_size = len;
678         store_message_result( res, result, error );
679     }
680 }
681
682 static int match_window( user_handle_t win, user_handle_t msg_win )
683 {
684     if (!win) return 1;
685     if (win == -1 || win == 1) return !msg_win;
686     if (msg_win == win) return 1;
687     return is_child_window( win, msg_win );
688 }
689
690 /* retrieve a posted message */
691 static int get_posted_message( struct msg_queue *queue, user_handle_t win,
692                                unsigned int first, unsigned int last, unsigned int flags,
693                                struct get_message_reply *reply )
694 {
695     struct message *msg;
696
697     /* check against the filters */
698     LIST_FOR_EACH_ENTRY( msg, &queue->msg_list[POST_MESSAGE], struct message, entry )
699     {
700         if (!match_window( win, msg->win )) continue;
701         if (!check_msg_filter( msg->msg, first, last )) continue;
702         goto found; /* found one */
703     }
704     return 0;
705
706     /* return it to the app */
707 found:
708     reply->total = msg->data_size;
709     if (msg->data_size > get_reply_max_size())
710     {
711         set_error( STATUS_BUFFER_OVERFLOW );
712         return 1;
713     }
714     reply->type   = msg->type;
715     reply->win    = msg->win;
716     reply->msg    = msg->msg;
717     reply->wparam = msg->wparam;
718     reply->lparam = msg->lparam;
719     reply->time   = msg->time;
720
721     if (flags & PM_REMOVE)
722     {
723         if (msg->data)
724         {
725             set_reply_data_ptr( msg->data, msg->data_size );
726             msg->data = NULL;
727             msg->data_size = 0;
728         }
729         remove_queue_message( queue, msg, POST_MESSAGE );
730     }
731     else if (msg->data) set_reply_data( msg->data, msg->data_size );
732
733     return 1;
734 }
735
736 static int get_quit_message( struct msg_queue *queue, unsigned int flags,
737                              struct get_message_reply *reply )
738 {
739     if (queue->quit_message)
740     {
741         reply->total  = 0;
742         reply->type   = MSG_POSTED;
743         reply->win    = 0;
744         reply->msg    = WM_QUIT;
745         reply->wparam = queue->exit_code;
746         reply->lparam = 0;
747         reply->time   = get_tick_count();
748
749         if (flags & PM_REMOVE)
750         {
751             queue->quit_message = 0;
752             if (list_empty( &queue->msg_list[POST_MESSAGE] ))
753                 clear_queue_bits( queue, QS_POSTMESSAGE|QS_ALLPOSTMESSAGE );
754         }
755         return 1;
756     }
757     else
758         return 0;
759 }
760
761 /* empty a message list and free all the messages */
762 static void empty_msg_list( struct list *list )
763 {
764     struct list *ptr;
765
766     while ((ptr = list_head( list )) != NULL)
767     {
768         struct message *msg = LIST_ENTRY( ptr, struct message, entry );
769         list_remove( &msg->entry );
770         free_message( msg );
771     }
772 }
773
774 /* cleanup all pending results when deleting a queue */
775 static void cleanup_results( struct msg_queue *queue )
776 {
777     struct list *entry;
778
779     while ((entry = list_head( &queue->send_result )) != NULL)
780     {
781         remove_result_from_sender( LIST_ENTRY( entry, struct message_result, sender_entry ) );
782     }
783
784     while ((entry = list_head( &queue->callback_result )) != NULL)
785     {
786         remove_result_from_sender( LIST_ENTRY( entry, struct message_result, sender_entry ) );
787     }
788
789     while (queue->recv_result)
790         reply_message( queue, 0, STATUS_ACCESS_DENIED /*FIXME*/, 1, NULL, 0 );
791 }
792
793 /* check if the thread owning the queue is hung (not checking for messages) */
794 static int is_queue_hung( struct msg_queue *queue )
795 {
796     struct wait_queue_entry *entry;
797
798     if (current_time - queue->last_get_msg <= 5 * TICKS_PER_SEC)
799         return 0;  /* less than 5 seconds since last get message -> not hung */
800
801     LIST_FOR_EACH_ENTRY( entry, &queue->obj.wait_queue, struct wait_queue_entry, entry )
802     {
803         if (entry->thread->queue == queue)
804             return 0;  /* thread is waiting on queue -> not hung */
805     }
806     return 1;
807 }
808
809 static int msg_queue_add_queue( struct object *obj, struct wait_queue_entry *entry )
810 {
811     struct msg_queue *queue = (struct msg_queue *)obj;
812     struct process *process = entry->thread->process;
813
814     /* a thread can only wait on its own queue */
815     if (entry->thread->queue != queue)
816     {
817         set_error( STATUS_ACCESS_DENIED );
818         return 0;
819     }
820     if (process->idle_event && !(queue->wake_mask & QS_SMRESULT)) set_event( process->idle_event );
821
822     if (queue->fd && list_empty( &obj->wait_queue ))  /* first on the queue */
823         set_fd_events( queue->fd, POLLIN );
824     add_queue( obj, entry );
825     return 1;
826 }
827
828 static void msg_queue_remove_queue(struct object *obj, struct wait_queue_entry *entry )
829 {
830     struct msg_queue *queue = (struct msg_queue *)obj;
831
832     remove_queue( obj, entry );
833     if (queue->fd && list_empty( &obj->wait_queue ))  /* last on the queue is gone */
834         set_fd_events( queue->fd, 0 );
835 }
836
837 static void msg_queue_dump( struct object *obj, int verbose )
838 {
839     struct msg_queue *queue = (struct msg_queue *)obj;
840     fprintf( stderr, "Msg queue bits=%x mask=%x\n",
841              queue->wake_bits, queue->wake_mask );
842 }
843
844 static int msg_queue_signaled( struct object *obj, struct thread *thread )
845 {
846     struct msg_queue *queue = (struct msg_queue *)obj;
847     int ret = 0;
848
849     if (queue->fd)
850     {
851         if ((ret = check_fd_events( queue->fd, POLLIN )))
852             /* stop waiting on select() if we are signaled */
853             set_fd_events( queue->fd, 0 );
854         else if (!list_empty( &obj->wait_queue ))
855             /* restart waiting on poll() if we are no longer signaled */
856             set_fd_events( queue->fd, POLLIN );
857     }
858     return ret || is_signaled( queue );
859 }
860
861 static int msg_queue_satisfied( struct object *obj, struct thread *thread )
862 {
863     struct msg_queue *queue = (struct msg_queue *)obj;
864     queue->wake_mask = 0;
865     queue->changed_mask = 0;
866     return 0;  /* Not abandoned */
867 }
868
869 static void msg_queue_destroy( struct object *obj )
870 {
871     struct msg_queue *queue = (struct msg_queue *)obj;
872     struct list *ptr;
873     int i;
874
875     cleanup_results( queue );
876     for (i = 0; i < NB_MSG_KINDS; i++) empty_msg_list( &queue->msg_list[i] );
877
878     while ((ptr = list_head( &queue->pending_timers )))
879     {
880         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
881         list_remove( &timer->entry );
882         free( timer );
883     }
884     while ((ptr = list_head( &queue->expired_timers )))
885     {
886         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
887         list_remove( &timer->entry );
888         free( timer );
889     }
890     if (queue->timeout) remove_timeout_user( queue->timeout );
891     if (queue->input)
892     {
893         queue->input->cursor_count -= queue->cursor_count;
894         release_object( queue->input );
895     }
896     if (queue->hooks) release_object( queue->hooks );
897     if (queue->fd) release_object( queue->fd );
898 }
899
900 static void msg_queue_poll_event( struct fd *fd, int event )
901 {
902     struct msg_queue *queue = get_fd_user( fd );
903     assert( queue->obj.ops == &msg_queue_ops );
904
905     if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
906     else set_fd_events( queue->fd, 0 );
907     wake_up( &queue->obj, 0 );
908 }
909
910 static void thread_input_dump( struct object *obj, int verbose )
911 {
912     struct thread_input *input = (struct thread_input *)obj;
913     fprintf( stderr, "Thread input focus=%08x capture=%08x active=%08x\n",
914              input->focus, input->capture, input->active );
915 }
916
917 static void thread_input_destroy( struct object *obj )
918 {
919     struct thread_input *input = (struct thread_input *)obj;
920
921     empty_msg_list( &input->msg_list );
922     if (input->desktop)
923     {
924         if (input->desktop->foreground_input == input) set_foreground_input( input->desktop, NULL );
925         release_object( input->desktop );
926     }
927 }
928
929 /* fix the thread input data when a window is destroyed */
930 static inline void thread_input_cleanup_window( struct msg_queue *queue, user_handle_t window )
931 {
932     struct thread_input *input = queue->input;
933
934     if (window == input->focus) input->focus = 0;
935     if (window == input->capture) input->capture = 0;
936     if (window == input->active) input->active = 0;
937     if (window == input->menu_owner) input->menu_owner = 0;
938     if (window == input->move_size) input->move_size = 0;
939     if (window == input->caret) set_caret_window( input, 0 );
940 }
941
942 /* check if the specified window can be set in the input data of a given queue */
943 static int check_queue_input_window( struct msg_queue *queue, user_handle_t window )
944 {
945     struct thread *thread;
946     int ret = 0;
947
948     if (!window) return 1;  /* we can always clear the data */
949
950     if ((thread = get_window_thread( window )))
951     {
952         ret = (queue->input == thread->queue->input);
953         if (!ret) set_error( STATUS_ACCESS_DENIED );
954         release_object( thread );
955     }
956     else set_error( STATUS_INVALID_HANDLE );
957
958     return ret;
959 }
960
961 /* make sure the specified thread has a queue */
962 int init_thread_queue( struct thread *thread )
963 {
964     if (thread->queue) return 1;
965     return (create_msg_queue( thread, NULL ) != NULL);
966 }
967
968 /* attach two thread input data structures */
969 int attach_thread_input( struct thread *thread_from, struct thread *thread_to )
970 {
971     struct desktop *desktop;
972     struct thread_input *input;
973     int ret;
974
975     if (!thread_to->queue && !(thread_to->queue = create_msg_queue( thread_to, NULL ))) return 0;
976     if (!(desktop = get_thread_desktop( thread_from, 0 ))) return 0;
977     input = (struct thread_input *)grab_object( thread_to->queue->input );
978     if (input->desktop != desktop)
979     {
980         set_error( STATUS_ACCESS_DENIED );
981         release_object( input );
982         release_object( desktop );
983         return 0;
984     }
985     release_object( desktop );
986
987     ret = assign_thread_input( thread_from, input );
988     if (ret) memset( input->keystate, 0, sizeof(input->keystate) );
989     release_object( input );
990     return ret;
991 }
992
993 /* detach two thread input data structures */
994 void detach_thread_input( struct thread *thread_from )
995 {
996     struct thread_input *input;
997
998     if ((input = create_thread_input( thread_from )))
999     {
1000         assign_thread_input( thread_from, input );
1001         release_object( input );
1002     }
1003 }
1004
1005
1006 /* set the next timer to expire */
1007 static void set_next_timer( struct msg_queue *queue )
1008 {
1009     struct list *ptr;
1010
1011     if (queue->timeout)
1012     {
1013         remove_timeout_user( queue->timeout );
1014         queue->timeout = NULL;
1015     }
1016     if ((ptr = list_head( &queue->pending_timers )))
1017     {
1018         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
1019         queue->timeout = add_timeout_user( timer->when, timer_callback, queue );
1020     }
1021     /* set/clear QS_TIMER bit */
1022     if (list_empty( &queue->expired_timers ))
1023         clear_queue_bits( queue, QS_TIMER );
1024     else
1025         set_queue_bits( queue, QS_TIMER );
1026 }
1027
1028 /* find a timer from its window and id */
1029 static struct timer *find_timer( struct msg_queue *queue, user_handle_t win,
1030                                  unsigned int msg, lparam_t id )
1031 {
1032     struct list *ptr;
1033
1034     /* we need to search both lists */
1035
1036     LIST_FOR_EACH( ptr, &queue->pending_timers )
1037     {
1038         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
1039         if (timer->win == win && timer->msg == msg && timer->id == id) return timer;
1040     }
1041     LIST_FOR_EACH( ptr, &queue->expired_timers )
1042     {
1043         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
1044         if (timer->win == win && timer->msg == msg && timer->id == id) return timer;
1045     }
1046     return NULL;
1047 }
1048
1049 /* callback for the next timer expiration */
1050 static void timer_callback( void *private )
1051 {
1052     struct msg_queue *queue = private;
1053     struct list *ptr;
1054
1055     queue->timeout = NULL;
1056     /* move on to the next timer */
1057     ptr = list_head( &queue->pending_timers );
1058     list_remove( ptr );
1059     list_add_tail( &queue->expired_timers, ptr );
1060     set_next_timer( queue );
1061 }
1062
1063 /* link a timer at its rightful place in the queue list */
1064 static void link_timer( struct msg_queue *queue, struct timer *timer )
1065 {
1066     struct list *ptr;
1067
1068     for (ptr = queue->pending_timers.next; ptr != &queue->pending_timers; ptr = ptr->next)
1069     {
1070         struct timer *t = LIST_ENTRY( ptr, struct timer, entry );
1071         if (t->when >= timer->when) break;
1072     }
1073     list_add_before( ptr, &timer->entry );
1074 }
1075
1076 /* remove a timer from the queue timer list and free it */
1077 static void free_timer( struct msg_queue *queue, struct timer *timer )
1078 {
1079     list_remove( &timer->entry );
1080     free( timer );
1081     set_next_timer( queue );
1082 }
1083
1084 /* restart an expired timer */
1085 static void restart_timer( struct msg_queue *queue, struct timer *timer )
1086 {
1087     list_remove( &timer->entry );
1088     while (timer->when <= current_time) timer->when += (timeout_t)timer->rate * 10000;
1089     link_timer( queue, timer );
1090     set_next_timer( queue );
1091 }
1092
1093 /* find an expired timer matching the filtering parameters */
1094 static struct timer *find_expired_timer( struct msg_queue *queue, user_handle_t win,
1095                                          unsigned int get_first, unsigned int get_last,
1096                                          int remove )
1097 {
1098     struct list *ptr;
1099
1100     LIST_FOR_EACH( ptr, &queue->expired_timers )
1101     {
1102         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
1103         if (win && timer->win != win) continue;
1104         if (check_msg_filter( timer->msg, get_first, get_last ))
1105         {
1106             if (remove) restart_timer( queue, timer );
1107             return timer;
1108         }
1109     }
1110     return NULL;
1111 }
1112
1113 /* add a timer */
1114 static struct timer *set_timer( struct msg_queue *queue, unsigned int rate )
1115 {
1116     struct timer *timer = mem_alloc( sizeof(*timer) );
1117     if (timer)
1118     {
1119         timer->rate = max( rate, 1 );
1120         timer->when = current_time + (timeout_t)timer->rate * 10000;
1121         link_timer( queue, timer );
1122         /* check if we replaced the next timer */
1123         if (list_head( &queue->pending_timers ) == &timer->entry) set_next_timer( queue );
1124     }
1125     return timer;
1126 }
1127
1128 /* change the input key state for a given key */
1129 static void set_input_key_state( unsigned char *keystate, unsigned char key, int down )
1130 {
1131     if (down)
1132     {
1133         if (!(keystate[key] & 0x80)) keystate[key] ^= 0x01;
1134         keystate[key] |= down;
1135     }
1136     else keystate[key] &= ~0x80;
1137 }
1138
1139 /* update the input key state for a keyboard message */
1140 static void update_input_key_state( struct desktop *desktop, unsigned char *keystate,
1141                                     const struct message *msg )
1142 {
1143     unsigned char key;
1144     int down = 0;
1145
1146     switch (msg->msg)
1147     {
1148     case WM_LBUTTONDOWN:
1149         down = (keystate == desktop->keystate) ? 0xc0 : 0x80;
1150         /* fall through */
1151     case WM_LBUTTONUP:
1152         set_input_key_state( keystate, VK_LBUTTON, down );
1153         break;
1154     case WM_MBUTTONDOWN:
1155         down = (keystate == desktop->keystate) ? 0xc0 : 0x80;
1156         /* fall through */
1157     case WM_MBUTTONUP:
1158         set_input_key_state( keystate, VK_MBUTTON, down );
1159         break;
1160     case WM_RBUTTONDOWN:
1161         down = (keystate == desktop->keystate) ? 0xc0 : 0x80;
1162         /* fall through */
1163     case WM_RBUTTONUP:
1164         set_input_key_state( keystate, VK_RBUTTON, down );
1165         break;
1166     case WM_XBUTTONDOWN:
1167         down = (keystate == desktop->keystate) ? 0xc0 : 0x80;
1168         /* fall through */
1169     case WM_XBUTTONUP:
1170         if (msg->wparam >> 16 == XBUTTON1) set_input_key_state( keystate, VK_XBUTTON1, down );
1171         else if (msg->wparam >> 16 == XBUTTON2) set_input_key_state( keystate, VK_XBUTTON2, down );
1172         break;
1173     case WM_KEYDOWN:
1174     case WM_SYSKEYDOWN:
1175         down = (keystate == desktop->keystate) ? 0xc0 : 0x80;
1176         /* fall through */
1177     case WM_KEYUP:
1178     case WM_SYSKEYUP:
1179         key = (unsigned char)msg->wparam;
1180         set_input_key_state( keystate, key, down );
1181         switch(key)
1182         {
1183         case VK_LCONTROL:
1184         case VK_RCONTROL:
1185             down = (keystate[VK_LCONTROL] | keystate[VK_RCONTROL]) & 0x80;
1186             set_input_key_state( keystate, VK_CONTROL, down );
1187             break;
1188         case VK_LMENU:
1189         case VK_RMENU:
1190             down = (keystate[VK_LMENU] | keystate[VK_RMENU]) & 0x80;
1191             set_input_key_state( keystate, VK_MENU, down );
1192             break;
1193         case VK_LSHIFT:
1194         case VK_RSHIFT:
1195             down = (keystate[VK_LSHIFT] | keystate[VK_RSHIFT]) & 0x80;
1196             set_input_key_state( keystate, VK_SHIFT, down );
1197             break;
1198         }
1199         break;
1200     }
1201 }
1202
1203 /* release the hardware message currently being processed by the given thread */
1204 static void release_hardware_message( struct msg_queue *queue, unsigned int hw_id,
1205                                       int remove, user_handle_t new_win )
1206 {
1207     struct thread_input *input = queue->input;
1208     struct message *msg;
1209
1210     LIST_FOR_EACH_ENTRY( msg, &input->msg_list, struct message, entry )
1211     {
1212         if (msg->unique_id == hw_id) break;
1213     }
1214     if (&msg->entry == &input->msg_list) return;  /* not found */
1215
1216     /* clear the queue bit for that message */
1217     if (remove || new_win)
1218     {
1219         struct message *other;
1220         int clr_bit;
1221
1222         clr_bit = get_hardware_msg_bit( msg );
1223         LIST_FOR_EACH_ENTRY( other, &input->msg_list, struct message, entry )
1224         {
1225             if (other != msg && get_hardware_msg_bit( other ) == clr_bit)
1226             {
1227                 clr_bit = 0;
1228                 break;
1229             }
1230         }
1231         if (clr_bit) clear_queue_bits( queue, clr_bit );
1232     }
1233
1234     if (new_win)  /* set the new window */
1235     {
1236         struct thread *owner = get_window_thread( new_win );
1237         if (owner)
1238         {
1239             msg->win = new_win;
1240             if (owner->queue->input != input)
1241             {
1242                 list_remove( &msg->entry );
1243                 if (msg->msg == WM_MOUSEMOVE && merge_message( owner->queue->input, msg ))
1244                 {
1245                     free_message( msg );
1246                     release_object( owner );
1247                     return;
1248                 }
1249                 list_add_tail( &owner->queue->input->msg_list, &msg->entry );
1250             }
1251             set_queue_bits( owner->queue, get_hardware_msg_bit( msg ));
1252             remove = 0;
1253             release_object( owner );
1254         }
1255     }
1256     if (remove)
1257     {
1258         update_input_key_state( input->desktop, input->keystate, msg );
1259         list_remove( &msg->entry );
1260         free_message( msg );
1261     }
1262 }
1263
1264 /* find the window that should receive a given hardware message */
1265 static user_handle_t find_hardware_message_window( struct desktop *desktop, struct thread_input *input,
1266                                                    struct message *msg, unsigned int *msg_code )
1267 {
1268     struct hardware_msg_data *data = msg->data;
1269     user_handle_t win = 0;
1270
1271     *msg_code = msg->msg;
1272     if (is_keyboard_msg( msg ))
1273     {
1274         if (input && !(win = input->focus))
1275         {
1276             win = input->active;
1277             if (*msg_code < WM_SYSKEYDOWN) *msg_code += WM_SYSKEYDOWN - WM_KEYDOWN;
1278         }
1279     }
1280     else  /* mouse message */
1281     {
1282         if (!input || !(win = input->capture))
1283         {
1284             if (!(win = msg->win) || !is_window_visible( win ) || is_window_transparent( win ))
1285                 win = window_from_point( desktop, data->x, data->y );
1286         }
1287     }
1288     return win;
1289 }
1290
1291 /* set the cursor position, clipping to the cursor clip rect */
1292 static void set_cursor_pos( struct desktop *desktop, int x, int y )
1293 {
1294     desktop->cursor.x = min( max( x, desktop->cursor.clip.left ), desktop->cursor.clip.right - 1 );
1295     desktop->cursor.y = min( max( y, desktop->cursor.clip.top ), desktop->cursor.clip.bottom - 1 );
1296     desktop->cursor.last_change = get_tick_count();
1297 }
1298
1299 /* queue a hardware message into a given thread input */
1300 static void queue_hardware_message( struct desktop *desktop, struct message *msg )
1301 {
1302     user_handle_t win;
1303     struct thread *thread;
1304     struct thread_input *input;
1305     unsigned int msg_code;
1306     struct hardware_msg_data *data = msg->data;
1307
1308     update_input_key_state( desktop, desktop->keystate, msg );
1309     last_input_time = get_tick_count();
1310
1311     if (is_keyboard_msg( msg ))
1312     {
1313         if (desktop->keystate[VK_MENU] & 0x80) msg->lparam |= KF_ALTDOWN << 16;
1314         if (msg->wparam == VK_SHIFT || msg->wparam == VK_LSHIFT || msg->wparam == VK_RSHIFT)
1315             msg->lparam &= ~(KF_EXTENDED << 16);
1316     }
1317     else
1318     {
1319         if (msg->msg == WM_MOUSEMOVE) set_cursor_pos( desktop, data->x, data->y );
1320         if (desktop->keystate[VK_LBUTTON] & 0x80)  msg->wparam |= MK_LBUTTON;
1321         if (desktop->keystate[VK_MBUTTON] & 0x80)  msg->wparam |= MK_MBUTTON;
1322         if (desktop->keystate[VK_RBUTTON] & 0x80)  msg->wparam |= MK_RBUTTON;
1323         if (desktop->keystate[VK_SHIFT] & 0x80)    msg->wparam |= MK_SHIFT;
1324         if (desktop->keystate[VK_CONTROL] & 0x80)  msg->wparam |= MK_CONTROL;
1325         if (desktop->keystate[VK_XBUTTON1] & 0x80) msg->wparam |= MK_XBUTTON1;
1326         if (desktop->keystate[VK_XBUTTON2] & 0x80) msg->wparam |= MK_XBUTTON2;
1327     }
1328     data->x = desktop->cursor.x;
1329     data->y = desktop->cursor.y;
1330
1331     if (msg->win && (thread = get_window_thread( msg->win )))
1332     {
1333         input = thread->queue->input;
1334         release_object( thread );
1335     }
1336     else input = desktop->foreground_input;
1337
1338     win = find_hardware_message_window( desktop, input, msg, &msg_code );
1339     if (!win || !(thread = get_window_thread(win)))
1340     {
1341         if (input) update_input_key_state( input->desktop, input->keystate, msg );
1342         free_message( msg );
1343         return;
1344     }
1345     input = thread->queue->input;
1346
1347     if (msg->msg == WM_MOUSEMOVE && merge_message( input, msg )) free_message( msg );
1348     else
1349     {
1350         msg->unique_id = 0;  /* will be set once we return it to the app */
1351         list_add_tail( &input->msg_list, &msg->entry );
1352         set_queue_bits( thread->queue, get_hardware_msg_bit(msg) );
1353     }
1354     release_object( thread );
1355 }
1356
1357 /* send the low-level hook message for a given hardware message */
1358 static int send_hook_ll_message( struct desktop *desktop, struct message *hardware_msg,
1359                                  const hw_input_t *input, struct msg_queue *sender )
1360 {
1361     struct thread *hook_thread;
1362     struct msg_queue *queue;
1363     struct message *msg;
1364     timeout_t timeout = 2000 * -10000;  /* FIXME: load from registry */
1365     int id = (input->type == INPUT_MOUSE) ? WH_MOUSE_LL : WH_KEYBOARD_LL;
1366
1367     if (!(hook_thread = get_first_global_hook( id ))) return 0;
1368     if (!(queue = hook_thread->queue)) return 0;
1369
1370     if (!(msg = mem_alloc( sizeof(*msg) ))) return 0;
1371
1372     msg->type      = MSG_HOOK_LL;
1373     msg->win       = 0;
1374     msg->msg       = id;
1375     msg->wparam    = hardware_msg->msg;
1376     msg->time      = hardware_msg->time;
1377     msg->data_size = hardware_msg->data_size;
1378     msg->result    = NULL;
1379
1380     if (input->type == INPUT_KEYBOARD)
1381     {
1382         unsigned short vkey = input->kbd.vkey;
1383         if (input->kbd.flags & KEYEVENTF_UNICODE) vkey = VK_PACKET;
1384         msg->lparam = (input->kbd.scan << 16) | vkey;
1385     }
1386     else msg->lparam = input->mouse.data << 16;
1387
1388     if (!(msg->data = memdup( hardware_msg->data, hardware_msg->data_size )) ||
1389         !(msg->result = alloc_message_result( sender, queue, msg, timeout )))
1390     {
1391         free_message( msg );
1392         return 0;
1393     }
1394     msg->result->hardware_msg = hardware_msg;
1395     msg->result->desktop = (struct desktop *)grab_object( desktop );
1396     list_add_tail( &queue->msg_list[SEND_MESSAGE], &msg->entry );
1397     set_queue_bits( queue, QS_SENDMESSAGE );
1398     return 1;
1399 }
1400
1401 /* queue a hardware message for a mouse event */
1402 static int queue_mouse_message( struct desktop *desktop, user_handle_t win, const hw_input_t *input,
1403                                 unsigned int hook_flags, struct msg_queue *sender )
1404 {
1405     struct hardware_msg_data *msg_data;
1406     struct message *msg;
1407     unsigned int i, time, flags;
1408     int wait = 0, x, y;
1409
1410     static const unsigned int messages[] =
1411     {
1412         WM_MOUSEMOVE,    /* 0x0001 = MOUSEEVENTF_MOVE */
1413         WM_LBUTTONDOWN,  /* 0x0002 = MOUSEEVENTF_LEFTDOWN */
1414         WM_LBUTTONUP,    /* 0x0004 = MOUSEEVENTF_LEFTUP */
1415         WM_RBUTTONDOWN,  /* 0x0008 = MOUSEEVENTF_RIGHTDOWN */
1416         WM_RBUTTONUP,    /* 0x0010 = MOUSEEVENTF_RIGHTUP */
1417         WM_MBUTTONDOWN,  /* 0x0020 = MOUSEEVENTF_MIDDLEDOWN */
1418         WM_MBUTTONUP,    /* 0x0040 = MOUSEEVENTF_MIDDLEUP */
1419         WM_XBUTTONDOWN,  /* 0x0080 = MOUSEEVENTF_XDOWN */
1420         WM_XBUTTONUP,    /* 0x0100 = MOUSEEVENTF_XUP */
1421         0,               /* 0x0200 = unused */
1422         0,               /* 0x0400 = unused */
1423         WM_MOUSEWHEEL,   /* 0x0800 = MOUSEEVENTF_WHEEL */
1424         WM_MOUSEHWHEEL   /* 0x1000 = MOUSEEVENTF_HWHEEL */
1425     };
1426
1427     desktop->cursor.last_change = get_tick_count();
1428     flags = input->mouse.flags;
1429     time  = input->mouse.time;
1430     if (!time) time = desktop->cursor.last_change;
1431
1432     if (flags & MOUSEEVENTF_MOVE)
1433     {
1434         if (flags & MOUSEEVENTF_ABSOLUTE)
1435         {
1436             x = input->mouse.x;
1437             y = input->mouse.y;
1438             if (flags & ~(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE) &&
1439                 x == desktop->cursor.x && y == desktop->cursor.y)
1440                 flags &= ~MOUSEEVENTF_MOVE;
1441         }
1442         else
1443         {
1444             x = desktop->cursor.x + input->mouse.x;
1445             y = desktop->cursor.y + input->mouse.y;
1446         }
1447     }
1448     else
1449     {
1450         x = desktop->cursor.x;
1451         y = desktop->cursor.y;
1452     }
1453
1454     for (i = 0; i < sizeof(messages)/sizeof(messages[0]); i++)
1455     {
1456         if (!messages[i]) continue;
1457         if (!(flags & (1 << i))) continue;
1458         flags &= ~(1 << i);
1459
1460         if (!(msg = mem_alloc( sizeof(*msg) ))) return 0;
1461         if (!(msg_data = mem_alloc( sizeof(*msg_data) )))
1462         {
1463             free( msg );
1464             return 0;
1465         }
1466         memset( msg_data, 0, sizeof(*msg_data) );
1467
1468         msg->type      = MSG_HARDWARE;
1469         msg->win       = get_user_full_handle( win );
1470         msg->msg       = messages[i];
1471         msg->wparam    = input->mouse.data << 16;
1472         msg->lparam    = 0;
1473         msg->time      = time;
1474         msg->result    = NULL;
1475         msg->data      = msg_data;
1476         msg->data_size = sizeof(*msg_data);
1477         msg_data->x    = x;
1478         msg_data->y    = y;
1479         msg_data->info = input->mouse.info;
1480         if (hook_flags & SEND_HWMSG_INJECTED) msg_data->flags = LLMHF_INJECTED;
1481
1482         /* specify a sender only when sending the last message */
1483         if (!(flags & ((1 << sizeof(messages)/sizeof(messages[0])) - 1)))
1484         {
1485             if (!(wait = send_hook_ll_message( desktop, msg, input, sender )))
1486                 queue_hardware_message( desktop, msg );
1487         }
1488         else if (!send_hook_ll_message( desktop, msg, input, NULL ))
1489             queue_hardware_message( desktop, msg );
1490     }
1491     return wait;
1492 }
1493
1494 /* queue a hardware message for a keyboard event */
1495 static int queue_keyboard_message( struct desktop *desktop, user_handle_t win, const hw_input_t *input,
1496                                    unsigned int hook_flags, struct msg_queue *sender )
1497 {
1498     struct hardware_msg_data *msg_data;
1499     struct message *msg;
1500     unsigned char vkey = input->kbd.vkey;
1501     int wait;
1502
1503     if (!(msg = mem_alloc( sizeof(*msg) ))) return 0;
1504     if (!(msg_data = mem_alloc( sizeof(*msg_data) )))
1505     {
1506         free( msg );
1507         return 0;
1508     }
1509     memset( msg_data, 0, sizeof(*msg_data) );
1510
1511     msg->type      = MSG_HARDWARE;
1512     msg->win       = get_user_full_handle( win );
1513     msg->lparam    = (input->kbd.scan << 16) | 1; /* repeat count */
1514     msg->time      = input->kbd.time;
1515     msg->result    = NULL;
1516     msg->data      = msg_data;
1517     msg->data_size = sizeof(*msg_data);
1518     msg_data->info = input->kbd.info;
1519     if (!msg->time) msg->time = get_tick_count();
1520     if (hook_flags & SEND_HWMSG_INJECTED) msg_data->flags = LLKHF_INJECTED;
1521
1522     if (input->kbd.flags & KEYEVENTF_UNICODE)
1523     {
1524         msg->wparam = VK_PACKET;
1525     }
1526     else
1527     {
1528         unsigned int flags = 0;
1529         switch (vkey)
1530         {
1531         case VK_MENU:
1532         case VK_LMENU:
1533         case VK_RMENU:
1534             vkey = (input->kbd.flags & KEYEVENTF_EXTENDEDKEY) ? VK_RMENU : VK_LMENU;
1535             break;
1536         case VK_CONTROL:
1537         case VK_LCONTROL:
1538         case VK_RCONTROL:
1539             vkey = (input->kbd.flags & KEYEVENTF_EXTENDEDKEY) ? VK_RCONTROL : VK_LCONTROL;
1540             break;
1541         case VK_SHIFT:
1542         case VK_LSHIFT:
1543         case VK_RSHIFT:
1544             vkey = (input->kbd.flags & KEYEVENTF_EXTENDEDKEY) ? VK_RSHIFT : VK_LSHIFT;
1545             break;
1546         }
1547         if (input->kbd.flags & KEYEVENTF_EXTENDEDKEY) flags |= KF_EXTENDED;
1548         /* FIXME: set KF_DLGMODE and KF_MENUMODE when needed */
1549         if (input->kbd.flags & KEYEVENTF_KEYUP) flags |= KF_REPEAT | KF_UP;
1550         else if (desktop->keystate[vkey] & 0x80) flags |= KF_REPEAT;
1551
1552         msg->wparam = vkey;
1553         msg->lparam |= flags << 16;
1554         msg_data->flags |= (flags & (KF_EXTENDED | KF_ALTDOWN | KF_UP)) >> 8;
1555     }
1556
1557     msg->msg = (input->kbd.flags & KEYEVENTF_KEYUP) ? WM_KEYUP : WM_KEYDOWN;
1558
1559     switch (vkey)
1560     {
1561     case VK_LMENU:
1562     case VK_RMENU:
1563         if (input->kbd.flags & KEYEVENTF_KEYUP)
1564         {
1565             /* send WM_SYSKEYUP if Alt still pressed and no other key in between */
1566             /* we use 0x02 as a flag to track if some other SYSKEYUP was sent already */
1567             if ((desktop->keystate[VK_MENU] & 0x82) != 0x82) break;
1568             msg->msg = WM_SYSKEYUP;
1569             desktop->keystate[VK_MENU] &= ~0x02;
1570         }
1571         else
1572         {
1573             /* send WM_SYSKEYDOWN for Alt except with Ctrl */
1574             if (desktop->keystate[VK_CONTROL] & 0x80) break;
1575             msg->msg = WM_SYSKEYDOWN;
1576             desktop->keystate[VK_MENU] |= 0x02;
1577         }
1578         break;
1579
1580     case VK_LCONTROL:
1581     case VK_RCONTROL:
1582         /* send WM_SYSKEYUP on release if Alt still pressed */
1583         if (!(input->kbd.flags & KEYEVENTF_KEYUP)) break;
1584         if (!(desktop->keystate[VK_MENU] & 0x80)) break;
1585         msg->msg = WM_SYSKEYUP;
1586         desktop->keystate[VK_MENU] &= ~0x02;
1587         break;
1588
1589     default:
1590         /* send WM_SYSKEY for Alt-anykey and for F10 */
1591         if (desktop->keystate[VK_CONTROL] & 0x80) break;
1592         if (!(desktop->keystate[VK_MENU] & 0x80)) break;
1593         /* fall through */
1594     case VK_F10:
1595         msg->msg = (input->kbd.flags & KEYEVENTF_KEYUP) ? WM_SYSKEYUP : WM_SYSKEYDOWN;
1596         desktop->keystate[VK_MENU] &= ~0x02;
1597         break;
1598     }
1599     if (!(wait = send_hook_ll_message( desktop, msg, input, sender )))
1600         queue_hardware_message( desktop, msg );
1601
1602     return wait;
1603 }
1604
1605 /* queue a hardware message for a custom type of event */
1606 static void queue_custom_hardware_message( struct desktop *desktop, user_handle_t win,
1607                                            const hw_input_t *input )
1608 {
1609     struct hardware_msg_data *msg_data;
1610     struct message *msg;
1611
1612     if (!(msg = mem_alloc( sizeof(*msg) ))) return;
1613     if (!(msg_data = mem_alloc( sizeof(*msg_data) )))
1614     {
1615         free( msg );
1616         return;
1617     }
1618     memset( msg_data, 0, sizeof(*msg_data) );
1619
1620     msg->type      = MSG_HARDWARE;
1621     msg->win       = get_user_full_handle( win );
1622     msg->msg       = input->hw.msg;
1623     msg->wparam    = 0;
1624     msg->lparam    = input->hw.lparam;
1625     msg->time      = get_tick_count();
1626     msg->result    = NULL;
1627     msg->data      = msg_data;
1628     msg->data_size = sizeof(*msg_data);
1629
1630     queue_hardware_message( desktop, msg );
1631 }
1632
1633 /* check message filter for a hardware message */
1634 static int check_hw_message_filter( user_handle_t win, unsigned int msg_code,
1635                                     user_handle_t filter_win, unsigned int first, unsigned int last )
1636 {
1637     if (msg_code >= WM_KEYFIRST && msg_code <= WM_KEYLAST)
1638     {
1639         /* we can only test the window for a keyboard message since the
1640          * dest window for a mouse message depends on hittest */
1641         if (filter_win && win != filter_win && !is_child_window( filter_win, win ))
1642             return 0;
1643         /* the message code is final for a keyboard message, we can simply check it */
1644         return check_msg_filter( msg_code, first, last );
1645     }
1646     else  /* mouse message */
1647     {
1648         /* we need to check all possible values that the message can have in the end */
1649
1650         if (check_msg_filter( msg_code, first, last )) return 1;
1651         if (msg_code == WM_MOUSEWHEEL) return 0;  /* no other possible value for this one */
1652
1653         /* all other messages can become non-client messages */
1654         if (check_msg_filter( msg_code + (WM_NCMOUSEFIRST - WM_MOUSEFIRST), first, last )) return 1;
1655
1656         /* clicks can become double-clicks or non-client double-clicks */
1657         if (msg_code == WM_LBUTTONDOWN || msg_code == WM_MBUTTONDOWN ||
1658             msg_code == WM_RBUTTONDOWN || msg_code == WM_XBUTTONDOWN)
1659         {
1660             if (check_msg_filter( msg_code + (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN), first, last )) return 1;
1661             if (check_msg_filter( msg_code + (WM_NCLBUTTONDBLCLK - WM_LBUTTONDOWN), first, last )) return 1;
1662         }
1663         return 0;
1664     }
1665 }
1666
1667
1668 /* find a hardware message for the given queue */
1669 static int get_hardware_message( struct thread *thread, unsigned int hw_id, user_handle_t filter_win,
1670                                  unsigned int first, unsigned int last, struct get_message_reply *reply )
1671 {
1672     struct thread_input *input = thread->queue->input;
1673     struct thread *win_thread;
1674     struct list *ptr;
1675     user_handle_t win;
1676     int clear_bits, got_one = 0;
1677     unsigned int msg_code;
1678
1679     ptr = list_head( &input->msg_list );
1680     if (hw_id)
1681     {
1682         while (ptr)
1683         {
1684             struct message *msg = LIST_ENTRY( ptr, struct message, entry );
1685             if (msg->unique_id == hw_id) break;
1686             ptr = list_next( &input->msg_list, ptr );
1687         }
1688         if (!ptr) ptr = list_head( &input->msg_list );
1689         else ptr = list_next( &input->msg_list, ptr );  /* start from the next one */
1690     }
1691
1692     if (ptr == list_head( &input->msg_list ))
1693         clear_bits = QS_KEY | QS_MOUSEMOVE | QS_MOUSEBUTTON;
1694     else
1695         clear_bits = 0;  /* don't clear bits if we don't go through the whole list */
1696
1697     while (ptr)
1698     {
1699         struct message *msg = LIST_ENTRY( ptr, struct message, entry );
1700         struct hardware_msg_data *data = msg->data;
1701
1702         ptr = list_next( &input->msg_list, ptr );
1703         win = find_hardware_message_window( input->desktop, input, msg, &msg_code );
1704         if (!win || !(win_thread = get_window_thread( win )))
1705         {
1706             /* no window at all, remove it */
1707             update_input_key_state( input->desktop, input->keystate, msg );
1708             list_remove( &msg->entry );
1709             free_message( msg );
1710             continue;
1711         }
1712         if (win_thread != thread)
1713         {
1714             if (win_thread->queue->input == input)
1715             {
1716                 /* wake the other thread */
1717                 set_queue_bits( win_thread->queue, get_hardware_msg_bit(msg) );
1718                 got_one = 1;
1719             }
1720             else
1721             {
1722                 /* for another thread input, drop it */
1723                 update_input_key_state( input->desktop, input->keystate, msg );
1724                 list_remove( &msg->entry );
1725                 free_message( msg );
1726             }
1727             release_object( win_thread );
1728             continue;
1729         }
1730         release_object( win_thread );
1731
1732         /* if we already got a message for another thread, or if it doesn't
1733          * match the filter we skip it */
1734         if (got_one || !check_hw_message_filter( win, msg_code, filter_win, first, last ))
1735         {
1736             clear_bits &= ~get_hardware_msg_bit( msg );
1737             continue;
1738         }
1739         /* now we can return it */
1740         if (!msg->unique_id) msg->unique_id = get_unique_id();
1741         reply->type   = MSG_HARDWARE;
1742         reply->win    = win;
1743         reply->msg    = msg_code;
1744         reply->wparam = msg->wparam;
1745         reply->lparam = msg->lparam;
1746         reply->time   = msg->time;
1747
1748         data->hw_id = msg->unique_id;
1749         set_reply_data( msg->data, msg->data_size );
1750         return 1;
1751     }
1752     /* nothing found, clear the hardware queue bits */
1753     clear_queue_bits( thread->queue, clear_bits );
1754     return 0;
1755 }
1756
1757 /* increment (or decrement if 'incr' is negative) the queue paint count */
1758 void inc_queue_paint_count( struct thread *thread, int incr )
1759 {
1760     struct msg_queue *queue = thread->queue;
1761
1762     assert( queue );
1763
1764     if ((queue->paint_count += incr) < 0) queue->paint_count = 0;
1765
1766     if (queue->paint_count)
1767         set_queue_bits( queue, QS_PAINT );
1768     else
1769         clear_queue_bits( queue, QS_PAINT );
1770 }
1771
1772
1773 /* remove all messages and timers belonging to a certain window */
1774 void queue_cleanup_window( struct thread *thread, user_handle_t win )
1775 {
1776     struct msg_queue *queue = thread->queue;
1777     struct list *ptr;
1778     int i;
1779
1780     if (!queue) return;
1781
1782     /* remove timers */
1783
1784     ptr = list_head( &queue->pending_timers );
1785     while (ptr)
1786     {
1787         struct list *next = list_next( &queue->pending_timers, ptr );
1788         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
1789         if (timer->win == win) free_timer( queue, timer );
1790         ptr = next;
1791     }
1792     ptr = list_head( &queue->expired_timers );
1793     while (ptr)
1794     {
1795         struct list *next = list_next( &queue->expired_timers, ptr );
1796         struct timer *timer = LIST_ENTRY( ptr, struct timer, entry );
1797         if (timer->win == win) free_timer( queue, timer );
1798         ptr = next;
1799     }
1800
1801     /* remove messages */
1802     for (i = 0; i < NB_MSG_KINDS; i++)
1803     {
1804         struct list *ptr, *next;
1805
1806         LIST_FOR_EACH_SAFE( ptr, next, &queue->msg_list[i] )
1807         {
1808             struct message *msg = LIST_ENTRY( ptr, struct message, entry );
1809             if (msg->win == win) remove_queue_message( queue, msg, i );
1810         }
1811     }
1812
1813     thread_input_cleanup_window( queue, win );
1814 }
1815
1816 /* post a message to a window; used by socket handling */
1817 void post_message( user_handle_t win, unsigned int message, lparam_t wparam, lparam_t lparam )
1818 {
1819     struct message *msg;
1820     struct thread *thread = get_window_thread( win );
1821
1822     if (!thread) return;
1823
1824     if (thread->queue && (msg = mem_alloc( sizeof(*msg) )))
1825     {
1826         msg->type      = MSG_POSTED;
1827         msg->win       = get_user_full_handle( win );
1828         msg->msg       = message;
1829         msg->wparam    = wparam;
1830         msg->lparam    = lparam;
1831         msg->time      = get_tick_count();
1832         msg->result    = NULL;
1833         msg->data      = NULL;
1834         msg->data_size = 0;
1835
1836         list_add_tail( &thread->queue->msg_list[POST_MESSAGE], &msg->entry );
1837         set_queue_bits( thread->queue, QS_POSTMESSAGE|QS_ALLPOSTMESSAGE );
1838     }
1839     release_object( thread );
1840 }
1841
1842 /* post a win event */
1843 void post_win_event( struct thread *thread, unsigned int event,
1844                      user_handle_t win, unsigned int object_id,
1845                      unsigned int child_id, client_ptr_t hook_proc,
1846                      const WCHAR *module, data_size_t module_size,
1847                      user_handle_t hook)
1848 {
1849     struct message *msg;
1850
1851     if (thread->queue && (msg = mem_alloc( sizeof(*msg) )))
1852     {
1853         struct winevent_msg_data *data;
1854
1855         msg->type      = MSG_WINEVENT;
1856         msg->win       = get_user_full_handle( win );
1857         msg->msg       = event;
1858         msg->wparam    = object_id;
1859         msg->lparam    = child_id;
1860         msg->time      = get_tick_count();
1861         msg->result    = NULL;
1862
1863         if ((data = malloc( sizeof(*data) + module_size )))
1864         {
1865             data->hook = hook;
1866             data->tid  = get_thread_id( current );
1867             data->hook_proc = hook_proc;
1868             memcpy( data + 1, module, module_size );
1869
1870             msg->data = data;
1871             msg->data_size = sizeof(*data) + module_size;
1872
1873             if (debug_level > 1)
1874                 fprintf( stderr, "post_win_event: tid %04x event %04x win %08x object_id %d child_id %d\n",
1875                          get_thread_id(thread), event, win, object_id, child_id );
1876             list_add_tail( &thread->queue->msg_list[SEND_MESSAGE], &msg->entry );
1877             set_queue_bits( thread->queue, QS_SENDMESSAGE );
1878         }
1879         else
1880             free( msg );
1881     }
1882 }
1883
1884
1885 /* check if the thread owning the window is hung */
1886 DECL_HANDLER(is_window_hung)
1887 {
1888     struct thread *thread;
1889
1890     thread = get_window_thread( req->win );
1891     if (thread)
1892     {
1893         reply->is_hung = is_queue_hung( thread->queue );
1894         release_object( thread );
1895     }
1896     else reply->is_hung = 0;
1897 }
1898
1899
1900 /* get the message queue of the current thread */
1901 DECL_HANDLER(get_msg_queue)
1902 {
1903     struct msg_queue *queue = get_current_queue();
1904
1905     reply->handle = 0;
1906     if (queue) reply->handle = alloc_handle( current->process, queue, SYNCHRONIZE, 0 );
1907 }
1908
1909
1910 /* set the file descriptor associated to the current thread queue */
1911 DECL_HANDLER(set_queue_fd)
1912 {
1913     struct msg_queue *queue = get_current_queue();
1914     struct file *file;
1915     int unix_fd;
1916
1917     if (queue->fd)  /* fd can only be set once */
1918     {
1919         set_error( STATUS_ACCESS_DENIED );
1920         return;
1921     }
1922     if (!(file = get_file_obj( current->process, req->handle, SYNCHRONIZE ))) return;
1923
1924     if ((unix_fd = get_file_unix_fd( file )) != -1)
1925     {
1926         if ((unix_fd = dup( unix_fd )) != -1)
1927             queue->fd = create_anonymous_fd( &msg_queue_fd_ops, unix_fd, &queue->obj, 0 );
1928         else
1929             file_set_error();
1930     }
1931     release_object( file );
1932 }
1933
1934
1935 /* set the current message queue wakeup mask */
1936 DECL_HANDLER(set_queue_mask)
1937 {
1938     struct msg_queue *queue = get_current_queue();
1939
1940     if (queue)
1941     {
1942         queue->wake_mask    = req->wake_mask;
1943         queue->changed_mask = req->changed_mask;
1944         reply->wake_bits    = queue->wake_bits;
1945         reply->changed_bits = queue->changed_bits;
1946         if (is_signaled( queue ))
1947         {
1948             /* if skip wait is set, do what would have been done in the subsequent wait */
1949             if (req->skip_wait) msg_queue_satisfied( &queue->obj, current );
1950             else wake_up( &queue->obj, 0 );
1951         }
1952     }
1953 }
1954
1955
1956 /* get the current message queue status */
1957 DECL_HANDLER(get_queue_status)
1958 {
1959     struct msg_queue *queue = current->queue;
1960     if (queue)
1961     {
1962         reply->wake_bits    = queue->wake_bits;
1963         reply->changed_bits = queue->changed_bits;
1964         if (req->clear) queue->changed_bits = 0;
1965     }
1966     else reply->wake_bits = reply->changed_bits = 0;
1967 }
1968
1969
1970 /* send a message to a thread queue */
1971 DECL_HANDLER(send_message)
1972 {
1973     struct message *msg;
1974     struct msg_queue *send_queue = get_current_queue();
1975     struct msg_queue *recv_queue = NULL;
1976     struct thread *thread = NULL;
1977
1978     if (!(thread = get_thread_from_id( req->id ))) return;
1979
1980     if (!(recv_queue = thread->queue))
1981     {
1982         set_error( STATUS_INVALID_PARAMETER );
1983         release_object( thread );
1984         return;
1985     }
1986     if ((req->flags & SEND_MSG_ABORT_IF_HUNG) && is_queue_hung(recv_queue))
1987     {
1988         set_error( STATUS_TIMEOUT );
1989         release_object( thread );
1990         return;
1991     }
1992
1993     if ((msg = mem_alloc( sizeof(*msg) )))
1994     {
1995         msg->type      = req->type;
1996         msg->win       = get_user_full_handle( req->win );
1997         msg->msg       = req->msg;
1998         msg->wparam    = req->wparam;
1999         msg->lparam    = req->lparam;
2000         msg->time      = get_tick_count();
2001         msg->result    = NULL;
2002         msg->data      = NULL;
2003         msg->data_size = get_req_data_size();
2004
2005         if (msg->data_size && !(msg->data = memdup( get_req_data(), msg->data_size )))
2006         {
2007             free( msg );
2008             release_object( thread );
2009             return;
2010         }
2011
2012         switch(msg->type)
2013         {
2014         case MSG_OTHER_PROCESS:
2015         case MSG_ASCII:
2016         case MSG_UNICODE:
2017         case MSG_CALLBACK:
2018             if (!(msg->result = alloc_message_result( send_queue, recv_queue, msg, req->timeout )))
2019             {
2020                 free_message( msg );
2021                 break;
2022             }
2023             /* fall through */
2024         case MSG_NOTIFY:
2025             list_add_tail( &recv_queue->msg_list[SEND_MESSAGE], &msg->entry );
2026             set_queue_bits( recv_queue, QS_SENDMESSAGE );
2027             break;
2028         case MSG_POSTED:
2029             list_add_tail( &recv_queue->msg_list[POST_MESSAGE], &msg->entry );
2030             set_queue_bits( recv_queue, QS_POSTMESSAGE|QS_ALLPOSTMESSAGE );
2031             break;
2032         case MSG_HARDWARE:  /* should use send_hardware_message instead */
2033         case MSG_CALLBACK_RESULT:  /* cannot send this one */
2034         case MSG_HOOK_LL:  /* generated internally */
2035         default:
2036             set_error( STATUS_INVALID_PARAMETER );
2037             free( msg );
2038             break;
2039         }
2040     }
2041     release_object( thread );
2042 }
2043
2044 /* send a hardware message to a thread queue */
2045 DECL_HANDLER(send_hardware_message)
2046 {
2047     struct thread *thread = NULL;
2048     struct desktop *desktop;
2049     struct msg_queue *sender = get_current_queue();
2050
2051     if (req->win)
2052     {
2053         if (!(thread = get_window_thread( req->win ))) return;
2054         desktop = (struct desktop *)grab_object( thread->queue->input->desktop );
2055     }
2056     else if (!(desktop = get_thread_desktop( current, 0 ))) return;
2057
2058     switch (req->input.type)
2059     {
2060     case INPUT_MOUSE:
2061         reply->wait = queue_mouse_message( desktop, req->win, &req->input, req->flags, sender );
2062         break;
2063     case INPUT_KEYBOARD:
2064         reply->wait = queue_keyboard_message( desktop, req->win, &req->input, req->flags, sender );
2065         break;
2066     case INPUT_HARDWARE:
2067         queue_custom_hardware_message( desktop, req->win, &req->input );
2068         break;
2069     default:
2070         set_error( STATUS_INVALID_PARAMETER );
2071     }
2072     if (thread) release_object( thread );
2073     release_object( desktop );
2074 }
2075
2076 /* post a quit message to the current queue */
2077 DECL_HANDLER(post_quit_message)
2078 {
2079     struct msg_queue *queue = get_current_queue();
2080
2081     if (!queue)
2082         return;
2083
2084     queue->quit_message = 1;
2085     queue->exit_code = req->exit_code;
2086     set_queue_bits( queue, QS_POSTMESSAGE|QS_ALLPOSTMESSAGE );
2087 }
2088
2089 /* get a message from the current queue */
2090 DECL_HANDLER(get_message)
2091 {
2092     struct timer *timer;
2093     struct list *ptr;
2094     struct msg_queue *queue = get_current_queue();
2095     user_handle_t get_win = get_user_full_handle( req->get_win );
2096     unsigned int filter = req->flags >> 16;
2097
2098     reply->active_hooks = get_active_hooks();
2099
2100     if (!queue) return;
2101     queue->last_get_msg = current_time;
2102     if (!filter) filter = QS_ALLINPUT;
2103
2104     /* first check for sent messages */
2105     if ((ptr = list_head( &queue->msg_list[SEND_MESSAGE] )))
2106     {
2107         struct message *msg = LIST_ENTRY( ptr, struct message, entry );
2108         receive_message( queue, msg, reply );
2109         return;
2110     }
2111
2112     /* clear changed bits so we can wait on them if we don't find a message */
2113     if (filter & QS_POSTMESSAGE)
2114     {
2115         queue->changed_bits &= ~(QS_POSTMESSAGE | QS_HOTKEY | QS_TIMER);
2116         if (req->get_first == 0 && req->get_last == ~0U) queue->changed_bits &= ~QS_ALLPOSTMESSAGE;
2117     }
2118     if (filter & QS_INPUT) queue->changed_bits &= ~QS_INPUT;
2119     if (filter & QS_PAINT) queue->changed_bits &= ~QS_PAINT;
2120
2121     /* then check for posted messages */
2122     if ((filter & QS_POSTMESSAGE) &&
2123         get_posted_message( queue, get_win, req->get_first, req->get_last, req->flags, reply ))
2124         return;
2125
2126     /* only check for quit messages if not posted messages pending.
2127      * note: the quit message isn't filtered */
2128     if (get_quit_message( queue, req->flags, reply ))
2129         return;
2130
2131     /* then check for any raw hardware message */
2132     if ((filter & QS_INPUT) &&
2133         filter_contains_hw_range( req->get_first, req->get_last ) &&
2134         get_hardware_message( current, req->hw_id, get_win, req->get_first, req->get_last, reply ))
2135         return;
2136
2137     /* now check for WM_PAINT */
2138     if ((filter & QS_PAINT) &&
2139         queue->paint_count &&
2140         check_msg_filter( WM_PAINT, req->get_first, req->get_last ) &&
2141         (reply->win = find_window_to_repaint( get_win, current )))
2142     {
2143         reply->type   = MSG_POSTED;
2144         reply->msg    = WM_PAINT;
2145         reply->wparam = 0;
2146         reply->lparam = 0;
2147         reply->time   = get_tick_count();
2148         return;
2149     }
2150
2151     /* now check for timer */
2152     if ((filter & QS_TIMER) &&
2153         (timer = find_expired_timer( queue, get_win, req->get_first,
2154                                      req->get_last, (req->flags & PM_REMOVE) )))
2155     {
2156         reply->type   = MSG_POSTED;
2157         reply->win    = timer->win;
2158         reply->msg    = timer->msg;
2159         reply->wparam = timer->id;
2160         reply->lparam = timer->lparam;
2161         reply->time   = get_tick_count();
2162         if (!(req->flags & PM_NOYIELD) && current->process->idle_event)
2163             set_event( current->process->idle_event );
2164         return;
2165     }
2166
2167     if (get_win == -1 && current->process->idle_event) set_event( current->process->idle_event );
2168     queue->wake_mask = req->wake_mask;
2169     queue->changed_mask = req->changed_mask;
2170     set_error( STATUS_PENDING );  /* FIXME */
2171 }
2172
2173
2174 /* reply to a sent message */
2175 DECL_HANDLER(reply_message)
2176 {
2177     if (!current->queue) set_error( STATUS_ACCESS_DENIED );
2178     else if (current->queue->recv_result)
2179         reply_message( current->queue, req->result, 0, req->remove,
2180                        get_req_data(), get_req_data_size() );
2181 }
2182
2183
2184 /* accept the current hardware message */
2185 DECL_HANDLER(accept_hardware_message)
2186 {
2187     if (current->queue)
2188         release_hardware_message( current->queue, req->hw_id, req->remove, req->new_win );
2189     else
2190         set_error( STATUS_ACCESS_DENIED );
2191 }
2192
2193
2194 /* retrieve the reply for the last message sent */
2195 DECL_HANDLER(get_message_reply)
2196 {
2197     struct message_result *result;
2198     struct list *entry;
2199     struct msg_queue *queue = current->queue;
2200
2201     if (queue)
2202     {
2203         set_error( STATUS_PENDING );
2204         reply->result = 0;
2205
2206         if (!(entry = list_head( &queue->send_result ))) return;  /* no reply ready */
2207
2208         result = LIST_ENTRY( entry, struct message_result, sender_entry );
2209         if (result->replied || req->cancel)
2210         {
2211             if (result->replied)
2212             {
2213                 reply->result = result->result;
2214                 set_error( result->error );
2215                 if (result->data)
2216                 {
2217                     data_size_t data_len = min( result->data_size, get_reply_max_size() );
2218                     set_reply_data_ptr( result->data, data_len );
2219                     result->data = NULL;
2220                     result->data_size = 0;
2221                 }
2222             }
2223             remove_result_from_sender( result );
2224
2225             entry = list_head( &queue->send_result );
2226             if (!entry) clear_queue_bits( queue, QS_SMRESULT );
2227             else
2228             {
2229                 result = LIST_ENTRY( entry, struct message_result, sender_entry );
2230                 if (!result->replied) clear_queue_bits( queue, QS_SMRESULT );
2231             }
2232         }
2233     }
2234     else set_error( STATUS_ACCESS_DENIED );
2235 }
2236
2237
2238 /* set a window timer */
2239 DECL_HANDLER(set_win_timer)
2240 {
2241     struct timer *timer;
2242     struct msg_queue *queue;
2243     struct thread *thread = NULL;
2244     user_handle_t win = 0;
2245     lparam_t id = req->id;
2246
2247     if (req->win)
2248     {
2249         if (!(win = get_user_full_handle( req->win )) || !(thread = get_window_thread( win )))
2250         {
2251             set_error( STATUS_INVALID_HANDLE );
2252             return;
2253         }
2254         if (thread->process != current->process)
2255         {
2256             release_object( thread );
2257             set_error( STATUS_ACCESS_DENIED );
2258             return;
2259         }
2260         queue = thread->queue;
2261         /* remove it if it existed already */
2262         if ((timer = find_timer( queue, win, req->msg, id ))) free_timer( queue, timer );
2263     }
2264     else
2265     {
2266         queue = get_current_queue();
2267         /* look for a timer with this id */
2268         if (id && (timer = find_timer( queue, 0, req->msg, id )))
2269         {
2270             /* free and reuse id */
2271             free_timer( queue, timer );
2272         }
2273         else
2274         {
2275             /* find a free id for it */
2276             do
2277             {
2278                 id = queue->next_timer_id;
2279                 if (--queue->next_timer_id <= 0x100) queue->next_timer_id = 0x7fff;
2280             }
2281             while (find_timer( queue, 0, req->msg, id ));
2282         }
2283     }
2284
2285     if ((timer = set_timer( queue, req->rate )))
2286     {
2287         timer->win    = win;
2288         timer->msg    = req->msg;
2289         timer->id     = id;
2290         timer->lparam = req->lparam;
2291         reply->id     = id;
2292     }
2293     if (thread) release_object( thread );
2294 }
2295
2296 /* kill a window timer */
2297 DECL_HANDLER(kill_win_timer)
2298 {
2299     struct timer *timer;
2300     struct thread *thread;
2301     user_handle_t win = 0;
2302
2303     if (req->win)
2304     {
2305         if (!(win = get_user_full_handle( req->win )) || !(thread = get_window_thread( win )))
2306         {
2307             set_error( STATUS_INVALID_HANDLE );
2308             return;
2309         }
2310         if (thread->process != current->process)
2311         {
2312             release_object( thread );
2313             set_error( STATUS_ACCESS_DENIED );
2314             return;
2315         }
2316     }
2317     else thread = (struct thread *)grab_object( current );
2318
2319     if (thread->queue && (timer = find_timer( thread->queue, win, req->msg, req->id )))
2320         free_timer( thread->queue, timer );
2321     else
2322         set_error( STATUS_INVALID_PARAMETER );
2323
2324     release_object( thread );
2325 }
2326
2327
2328 /* attach (or detach) thread inputs */
2329 DECL_HANDLER(attach_thread_input)
2330 {
2331     struct thread *thread_from = get_thread_from_id( req->tid_from );
2332     struct thread *thread_to = get_thread_from_id( req->tid_to );
2333
2334     if (!thread_from || !thread_to)
2335     {
2336         if (thread_from) release_object( thread_from );
2337         if (thread_to) release_object( thread_to );
2338         return;
2339     }
2340     if (thread_from != thread_to)
2341     {
2342         if (req->attach) attach_thread_input( thread_from, thread_to );
2343         else
2344         {
2345             if (thread_from->queue && thread_to->queue &&
2346                 thread_from->queue->input == thread_to->queue->input)
2347                 detach_thread_input( thread_from );
2348             else
2349                 set_error( STATUS_ACCESS_DENIED );
2350         }
2351     }
2352     else set_error( STATUS_ACCESS_DENIED );
2353     release_object( thread_from );
2354     release_object( thread_to );
2355 }
2356
2357
2358 /* get thread input data */
2359 DECL_HANDLER(get_thread_input)
2360 {
2361     struct thread *thread = NULL;
2362     struct desktop *desktop;
2363     struct thread_input *input;
2364
2365     if (req->tid)
2366     {
2367         if (!(thread = get_thread_from_id( req->tid ))) return;
2368         if (!(desktop = get_thread_desktop( thread, 0 )))
2369         {
2370             release_object( thread );
2371             return;
2372         }
2373         input = thread->queue ? thread->queue->input : NULL;
2374     }
2375     else
2376     {
2377         if (!(desktop = get_thread_desktop( current, 0 ))) return;
2378         input = desktop->foreground_input;  /* get the foreground thread info */
2379     }
2380
2381     if (input)
2382     {
2383         reply->focus      = input->focus;
2384         reply->capture    = input->capture;
2385         reply->active     = input->active;
2386         reply->menu_owner = input->menu_owner;
2387         reply->move_size  = input->move_size;
2388         reply->caret      = input->caret;
2389         reply->cursor     = input->cursor;
2390         reply->show_count = input->cursor_count;
2391         reply->rect       = input->caret_rect;
2392     }
2393
2394     /* foreground window is active window of foreground thread */
2395     reply->foreground = desktop->foreground_input ? desktop->foreground_input->active : 0;
2396     if (thread) release_object( thread );
2397     release_object( desktop );
2398 }
2399
2400
2401 /* retrieve queue keyboard state for a given thread */
2402 DECL_HANDLER(get_key_state)
2403 {
2404     struct thread *thread;
2405     struct desktop *desktop;
2406     data_size_t size = min( 256, get_reply_max_size() );
2407
2408     if (!req->tid)  /* get global async key state */
2409     {
2410         if (!(desktop = get_thread_desktop( current, 0 ))) return;
2411         if (req->key >= 0)
2412         {
2413             reply->state = desktop->keystate[req->key & 0xff];
2414             desktop->keystate[req->key & 0xff] &= ~0x40;
2415         }
2416         set_reply_data( desktop->keystate, size );
2417         release_object( desktop );
2418     }
2419     else
2420     {
2421         if (!(thread = get_thread_from_id( req->tid ))) return;
2422         if (thread->queue)
2423         {
2424             if (req->key >= 0) reply->state = thread->queue->input->keystate[req->key & 0xff];
2425             set_reply_data( thread->queue->input->keystate, size );
2426         }
2427         release_object( thread );
2428     }
2429 }
2430
2431
2432 /* set queue keyboard state for a given thread */
2433 DECL_HANDLER(set_key_state)
2434 {
2435     struct thread *thread;
2436     struct desktop *desktop;
2437     data_size_t size = min( 256, get_req_data_size() );
2438
2439     if (!req->tid)  /* set global async key state */
2440     {
2441         if (!(desktop = get_thread_desktop( current, 0 ))) return;
2442         memcpy( desktop->keystate, get_req_data(), size );
2443         release_object( desktop );
2444     }
2445     else
2446     {
2447         if (!(thread = get_thread_from_id( req->tid ))) return;
2448         if (thread->queue) memcpy( thread->queue->input->keystate, get_req_data(), size );
2449         release_object( thread );
2450     }
2451 }
2452
2453
2454 /* set the system foreground window */
2455 DECL_HANDLER(set_foreground_window)
2456 {
2457     struct thread *thread = NULL;
2458     struct desktop *desktop;
2459     struct msg_queue *queue = get_current_queue();
2460
2461     if (!(desktop = get_thread_desktop( current, 0 ))) return;
2462     reply->previous = desktop->foreground_input ? desktop->foreground_input->active : 0;
2463     reply->send_msg_old = (reply->previous && desktop->foreground_input != queue->input);
2464     reply->send_msg_new = FALSE;
2465
2466     if (is_top_level_window( req->handle ) &&
2467         ((thread = get_window_thread( req->handle ))) &&
2468         (thread->queue->input->desktop == desktop))
2469     {
2470         set_foreground_input( desktop, thread->queue->input );
2471         reply->send_msg_new = (desktop->foreground_input != queue->input);
2472     }
2473     else set_win32_error( ERROR_INVALID_WINDOW_HANDLE );
2474
2475     if (thread) release_object( thread );
2476     release_object( desktop );
2477 }
2478
2479
2480 /* set the current thread focus window */
2481 DECL_HANDLER(set_focus_window)
2482 {
2483     struct msg_queue *queue = get_current_queue();
2484
2485     reply->previous = 0;
2486     if (queue && check_queue_input_window( queue, req->handle ))
2487     {
2488         reply->previous = queue->input->focus;
2489         queue->input->focus = get_user_full_handle( req->handle );
2490     }
2491 }
2492
2493
2494 /* set the current thread active window */
2495 DECL_HANDLER(set_active_window)
2496 {
2497     struct msg_queue *queue = get_current_queue();
2498
2499     reply->previous = 0;
2500     if (queue && check_queue_input_window( queue, req->handle ))
2501     {
2502         if (!req->handle || make_window_active( req->handle ))
2503         {
2504             reply->previous = queue->input->active;
2505             queue->input->active = get_user_full_handle( req->handle );
2506         }
2507         else set_error( STATUS_INVALID_HANDLE );
2508     }
2509 }
2510
2511
2512 /* set the current thread capture window */
2513 DECL_HANDLER(set_capture_window)
2514 {
2515     struct msg_queue *queue = get_current_queue();
2516
2517     reply->previous = reply->full_handle = 0;
2518     if (queue && check_queue_input_window( queue, req->handle ))
2519     {
2520         struct thread_input *input = queue->input;
2521
2522         /* if in menu mode, reject all requests to change focus, except if the menu bit is set */
2523         if (input->menu_owner && !(req->flags & CAPTURE_MENU))
2524         {
2525             set_error(STATUS_ACCESS_DENIED);
2526             return;
2527         }
2528         reply->previous = input->capture;
2529         input->capture = get_user_full_handle( req->handle );
2530         input->menu_owner = (req->flags & CAPTURE_MENU) ? input->capture : 0;
2531         input->move_size = (req->flags & CAPTURE_MOVESIZE) ? input->capture : 0;
2532         reply->full_handle = input->capture;
2533     }
2534 }
2535
2536
2537 /* Set the current thread caret window */
2538 DECL_HANDLER(set_caret_window)
2539 {
2540     struct msg_queue *queue = get_current_queue();
2541
2542     reply->previous = 0;
2543     if (queue && check_queue_input_window( queue, req->handle ))
2544     {
2545         struct thread_input *input = queue->input;
2546
2547         reply->previous  = input->caret;
2548         reply->old_rect  = input->caret_rect;
2549         reply->old_hide  = input->caret_hide;
2550         reply->old_state = input->caret_state;
2551
2552         set_caret_window( input, get_user_full_handle(req->handle) );
2553         input->caret_rect.right  = input->caret_rect.left + req->width;
2554         input->caret_rect.bottom = input->caret_rect.top + req->height;
2555     }
2556 }
2557
2558
2559 /* Set the current thread caret information */
2560 DECL_HANDLER(set_caret_info)
2561 {
2562     struct msg_queue *queue = get_current_queue();
2563     struct thread_input *input;
2564
2565     if (!queue) return;
2566     input = queue->input;
2567     reply->full_handle = input->caret;
2568     reply->old_rect    = input->caret_rect;
2569     reply->old_hide    = input->caret_hide;
2570     reply->old_state   = input->caret_state;
2571
2572     if (req->handle && get_user_full_handle(req->handle) != input->caret)
2573     {
2574         set_error( STATUS_ACCESS_DENIED );
2575         return;
2576     }
2577     if (req->flags & SET_CARET_POS)
2578     {
2579         input->caret_rect.right  += req->x - input->caret_rect.left;
2580         input->caret_rect.bottom += req->y - input->caret_rect.top;
2581         input->caret_rect.left = req->x;
2582         input->caret_rect.top  = req->y;
2583     }
2584     if (req->flags & SET_CARET_HIDE)
2585     {
2586         input->caret_hide += req->hide;
2587         if (input->caret_hide < 0) input->caret_hide = 0;
2588     }
2589     if (req->flags & SET_CARET_STATE)
2590     {
2591         if (req->state == -1) input->caret_state = !input->caret_state;
2592         else input->caret_state = !!req->state;
2593     }
2594 }
2595
2596
2597 /* get the time of the last input event */
2598 DECL_HANDLER(get_last_input_time)
2599 {
2600     reply->time = last_input_time;
2601 }
2602
2603 /* set/get the current cursor */
2604 DECL_HANDLER(set_cursor)
2605 {
2606     struct msg_queue *queue = get_current_queue();
2607     struct thread_input *input;
2608
2609     if (!queue) return;
2610     input = queue->input;
2611
2612     reply->prev_handle = input->cursor;
2613     reply->prev_count  = input->cursor_count;
2614
2615     if (req->flags & SET_CURSOR_HANDLE)
2616     {
2617         if (req->handle && !get_user_object( req->handle, USER_CLIENT ))
2618         {
2619             set_win32_error( ERROR_INVALID_CURSOR_HANDLE );
2620             return;
2621         }
2622         input->cursor = req->handle;
2623     }
2624     if (req->flags & SET_CURSOR_COUNT)
2625     {
2626         queue->cursor_count += req->show_count;
2627         input->cursor_count += req->show_count;
2628     }
2629     if (req->flags & SET_CURSOR_POS)
2630     {
2631         set_cursor_pos( input->desktop, req->x, req->y );
2632     }
2633     if (req->flags & SET_CURSOR_CLIP)
2634     {
2635         struct desktop *desktop = input->desktop;
2636
2637         /* only the desktop owner can set the message */
2638         if (req->clip_msg && get_top_window_owner(desktop) == current->process)
2639             desktop->cursor.clip_msg = req->clip_msg;
2640
2641         set_clip_rectangle( desktop, &req->clip );
2642     }
2643
2644     reply->new_x       = input->desktop->cursor.x;
2645     reply->new_y       = input->desktop->cursor.y;
2646     reply->new_clip    = input->desktop->cursor.clip;
2647     reply->last_change = input->desktop->cursor.last_change;
2648 }