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