]> Pileus Git - ~andy/gtk/blob - gdk/win32/gdkevents-win32.c
Make win32 backend build and minimally work
[~andy/gtk] / gdk / win32 / gdkevents-win32.c
1 /* GDK - The GIMP Drawing Kit
2  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3  * Copyright (C) 1998-2002 Tor Lillqvist
4  * Copyright (C) 2007-2009 Cody Russell
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 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
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /*
23  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
24  * file for a list of people on the GTK+ Team.  See the ChangeLog
25  * files for a list of changes.  These files are distributed with
26  * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
27  */
28
29 /* Cannot use TrackMouseEvent, as the stupid WM_MOUSELEAVE message
30  * doesn't tell us where the mouse has gone. Thus we cannot use it to
31  * generate a correct GdkNotifyType. Pity, as using TrackMouseEvent
32  * otherwise would make it possible to reliably generate
33  * GDK_LEAVE_NOTIFY events, which would help get rid of those pesky
34  * tooltips sometimes popping up in the wrong place.
35  *
36  * Update: a combination of TrackMouseEvent, GetCursorPos and 
37  * GetWindowPos can and is actually used to get rid of those
38  * pesky tooltips. It should be possible to use this for the
39  * whole ENTER/LEAVE NOTIFY handling but some platforms may
40  * not have TrackMouseEvent at all (?) --hb
41  */
42
43 #include "config.h"
44
45 #include <glib/gprintf.h>
46
47 #include "gdk.h"
48 #include "gdkprivate-win32.h"
49 #include "gdkinput-win32.h"
50 #include "gdkkeysyms.h"
51
52 #include <windowsx.h>
53
54 #ifdef G_WITH_CYGWIN
55 #include <fcntl.h>
56 #include <errno.h>
57 #endif
58
59 #include <objbase.h>
60
61 #include <imm.h>
62
63 #ifndef XBUTTON1
64 #define XBUTTON1 1
65 #define XBUTTON2 2
66 #endif
67
68 #ifndef VK_XBUTTON1
69 #define VK_XBUTTON1 5
70 #define VK_XBUTTON2 6
71 #endif
72
73 #ifndef MK_XBUTTON1
74 #define MK_XBUTTON1 32
75 #define MK_XBUTTON2 64
76 #endif
77
78 /* 
79  * Private function declarations
80  */
81
82 static gboolean gdk_event_translate (MSG        *msg,
83                                      gint       *ret_valp);
84 static void     handle_wm_paint     (MSG        *msg,
85                                      GdkWindow  *window,
86                                      gboolean    return_exposes,
87                                      GdkEvent  **event);
88
89 static gboolean gdk_event_prepare  (GSource     *source,
90                                     gint        *timeout);
91 static gboolean gdk_event_check    (GSource     *source);
92 static gboolean gdk_event_dispatch (GSource     *source,
93                                     GSourceFunc  callback,
94                                     gpointer     user_data);
95
96 static void append_event (GdkEvent *event);
97 static gboolean is_modally_blocked (GdkWindow   *window);
98
99 /* Private variable declarations
100  */
101
102 #if 0
103 static GdkWindow *p_grab_window = NULL; /* Window that currently holds
104                                          * the pointer grab
105                                          */
106
107 static GdkWindow *p_grab_confine_to = NULL;
108
109 static GdkWindow *k_grab_window = NULL; /* Window the holds the
110                                          * keyboard grab
111                                          */
112 #endif
113
114 static GList *client_filters;   /* Filters for client messages */
115
116 static gboolean p_grab_automatic;
117 static GdkEventMask p_grab_mask;
118 static gboolean p_grab_owner_events, k_grab_owner_events;
119 static HCURSOR p_grab_cursor;
120
121 static GSourceFuncs event_funcs = {
122   gdk_event_prepare,
123   gdk_event_check,
124   gdk_event_dispatch,
125   NULL
126 };
127
128 GPollFD event_poll_fd;
129
130 static GdkWindow *current_toplevel = NULL;
131 static gint current_x, current_y;
132 static gint current_root_x, current_root_y;
133 static UINT client_message;
134
135 static UINT got_gdk_events_message;
136 static HWND modal_win32_dialog = NULL;
137
138 #if 0
139 static HKL latin_locale = NULL;
140 #endif
141
142 static gboolean in_ime_composition = FALSE;
143 static UINT     modal_timer;
144 static UINT     sync_timer = 0;
145
146 static int debug_indent = 0;
147
148 static void
149 assign_object (gpointer lhsp,
150                gpointer rhs)
151 {
152   if (*(gpointer *)lhsp != rhs)
153     {
154       if (*(gpointer *)lhsp != NULL)
155         g_object_unref (*(gpointer *)lhsp);
156       *(gpointer *)lhsp = rhs;
157       if (rhs != NULL)
158         g_object_ref (rhs);
159     }
160 }
161
162 static void
163 track_mouse_event (DWORD dwFlags,
164                    HWND  hwnd)
165 {
166   typedef BOOL (WINAPI *PFN_TrackMouseEvent) (LPTRACKMOUSEEVENT);
167   static PFN_TrackMouseEvent p_TrackMouseEvent = NULL;
168   static gboolean once = FALSE;
169
170   if (!once)
171     {
172       HMODULE user32;
173       HINSTANCE commctrl32;
174
175       user32 = GetModuleHandle ("user32.dll");
176       if ((p_TrackMouseEvent = (PFN_TrackMouseEvent)GetProcAddress (user32, "TrackMouseEvent")) == NULL)
177         {
178           if ((commctrl32 = LoadLibrary ("commctrl32.dll")) != NULL)
179             p_TrackMouseEvent = (PFN_TrackMouseEvent)
180               GetProcAddress (commctrl32, "_TrackMouseEvent");
181         }
182       once = TRUE;
183     }
184
185   if (p_TrackMouseEvent)
186     {
187       TRACKMOUSEEVENT tme;
188       tme.cbSize = sizeof(TRACKMOUSEEVENT);
189       tme.dwFlags = dwFlags;
190       tme.hwndTrack = hwnd;
191       tme.dwHoverTime = HOVER_DEFAULT; /* not used */
192
193       if (!p_TrackMouseEvent (&tme))
194         WIN32_API_FAILED ("TrackMouseEvent");
195       else if (dwFlags == TME_LEAVE)
196         GDK_NOTE (EVENTS, g_print(" (TrackMouseEvent %p)", hwnd));
197       else if (dwFlags == TME_CANCEL)
198         GDK_NOTE (EVENTS, g_print(" (cancel TrackMouseEvent %p)", hwnd));
199     }
200 }
201
202 gulong
203 _gdk_win32_get_next_tick (gulong suggested_tick)
204 {
205   static gulong cur_tick = 0;
206
207   if (suggested_tick == 0)
208     suggested_tick = GetTickCount ();
209   if (suggested_tick <= cur_tick)
210     return cur_tick;
211   else
212     return cur_tick = suggested_tick;
213 }
214
215 static void
216 generate_focus_event (GdkWindow *window,
217                       gboolean   in)
218 {
219   GdkEvent *event;
220
221   event = gdk_event_new (GDK_FOCUS_CHANGE);
222   event->focus_change.window = window;
223   event->focus_change.in = in;
224
225   append_event (event);
226 }
227
228 static void
229 generate_grab_broken_event (GdkWindow *window,
230                             gboolean   keyboard,
231                             GdkWindow *grab_window)
232 {
233   GdkEvent *event = gdk_event_new (GDK_GRAB_BROKEN);
234
235   event->grab_broken.window = window;
236   event->grab_broken.send_event = 0;
237   event->grab_broken.keyboard = keyboard;
238   event->grab_broken.implicit = FALSE;
239   event->grab_broken.grab_window = grab_window;
240           
241   append_event (event);
242 }
243
244 static LRESULT 
245 inner_window_procedure (HWND   hwnd,
246                         UINT   message,
247                         WPARAM wparam,
248                         LPARAM lparam)
249 {
250   MSG msg;
251   DWORD pos;
252   gint ret_val = 0;
253
254   msg.hwnd = hwnd;
255   msg.message = message;
256   msg.wParam = wparam;
257   msg.lParam = lparam;
258   msg.time = _gdk_win32_get_next_tick (0);
259   pos = GetMessagePos ();
260   msg.pt.x = GET_X_LPARAM (pos);
261   msg.pt.y = GET_Y_LPARAM (pos);
262
263   if (gdk_event_translate (&msg, &ret_val))
264     {
265       /* If gdk_event_translate() returns TRUE, we return ret_val from
266        * the window procedure.
267        */
268       if (modal_win32_dialog)
269         PostMessageW (modal_win32_dialog, got_gdk_events_message,
270                       (WPARAM) 1, 0);
271       return ret_val;
272     }
273   else
274     {
275       /* Otherwise call DefWindowProcW(). */
276       GDK_NOTE (EVENTS, g_print (" DefWindowProcW"));
277       return DefWindowProcW (hwnd, message, wparam, lparam);
278     }
279 }
280
281 LRESULT CALLBACK
282 _gdk_win32_window_procedure (HWND   hwnd,
283                              UINT   message,
284                              WPARAM wparam,
285                              LPARAM lparam)
286 {
287   LRESULT retval;
288
289   GDK_NOTE (EVENTS, g_print ("%s%*s%s %p",
290                              (debug_indent > 0 ? "\n" : ""),
291                              debug_indent, "", 
292                              _gdk_win32_message_to_string (message), hwnd));
293   debug_indent += 2;
294   retval = inner_window_procedure (hwnd, message, wparam, lparam);
295   debug_indent -= 2;
296
297   GDK_NOTE (EVENTS, g_print (" => %I64d%s", (gint64) retval, (debug_indent == 0 ? "\n" : "")));
298
299   return retval;
300 }
301
302 void 
303 _gdk_events_init (void)
304 {
305   GSource *source;
306
307 #if 0
308   int i, j, n;
309
310   /* List of languages that use a latin keyboard. Somewhat sorted in
311    * "order of least surprise", in case we have to load one of them if
312    * the user only has arabic loaded, for instance.
313    */
314   static int latin_languages[] = {
315     LANG_ENGLISH,
316     LANG_SPANISH,
317     LANG_PORTUGUESE,
318     LANG_FRENCH,
319     LANG_GERMAN,
320     /* Rest in numeric order */
321     LANG_CZECH,
322     LANG_DANISH,
323     LANG_FINNISH,
324     LANG_HUNGARIAN,
325     LANG_ICELANDIC,
326     LANG_ITALIAN,
327     LANG_DUTCH,
328     LANG_NORWEGIAN,
329     LANG_POLISH,
330     LANG_ROMANIAN,
331     LANG_SLOVAK,
332     LANG_ALBANIAN,
333     LANG_SWEDISH,
334     LANG_TURKISH,
335     LANG_INDONESIAN,
336     LANG_SLOVENIAN,
337     LANG_ESTONIAN,
338     LANG_LATVIAN,
339     LANG_LITHUANIAN,
340     LANG_VIETNAMESE,
341     LANG_AFRIKAANS,
342     LANG_FAEROESE
343 #ifdef LANG_SWAHILI
344    ,LANG_SWAHILI
345 #endif
346   };
347 #endif
348
349   client_message = RegisterWindowMessage ("GDK_WIN32_CLIENT_MESSAGE");
350   got_gdk_events_message = RegisterWindowMessage ("GDK_WIN32_GOT_EVENTS");
351
352 #if 0
353   /* Check if we have some input locale identifier loaded that uses a
354    * latin keyboard, to be able to get the virtual-key code for the
355    * latin characters corresponding to ASCII control characters.
356    */
357   if ((n = GetKeyboardLayoutList (0, NULL)) == 0)
358     WIN32_API_FAILED ("GetKeyboardLayoutList");
359   else
360     {
361       HKL *hkl_list = g_new (HKL, n);
362       if (GetKeyboardLayoutList (n, hkl_list) == 0)
363         WIN32_API_FAILED ("GetKeyboardLayoutList");
364       else
365         {
366           for (i = 0; latin_locale == NULL && i < n; i++)
367             for (j = 0; j < G_N_ELEMENTS (latin_languages); j++)
368               if (PRIMARYLANGID (LOWORD (hkl_list[i])) == latin_languages[j])
369                 {
370                   latin_locale = hkl_list [i];
371                   break;
372                 }
373         }
374       g_free (hkl_list);
375     }
376
377   if (latin_locale == NULL)
378     {
379       /* Try to load a keyboard layout with latin characters then.
380        */
381       i = 0;
382       while (latin_locale == NULL && i < G_N_ELEMENTS (latin_languages))
383         {
384           char id[9];
385           g_sprintf (id, "%08x", MAKELANGID (latin_languages[i++], SUBLANG_DEFAULT));
386           latin_locale = LoadKeyboardLayout (id, KLF_NOTELLSHELL|KLF_SUBSTITUTE_OK);
387         }
388     }
389
390   GDK_NOTE (EVENTS, g_print ("latin_locale = %08x\n", (guint) latin_locale));
391 #endif
392
393   source = g_source_new (&event_funcs, sizeof (GSource));
394   g_source_set_priority (source, GDK_PRIORITY_EVENTS);
395
396 #ifdef G_WITH_CYGWIN
397   event_poll_fd.fd = open ("/dev/windows", O_RDONLY);
398   if (event_poll_fd.fd == -1)
399     g_error ("can't open \"/dev/windows\": %s", g_strerror (errno));
400 #else
401   event_poll_fd.fd = G_WIN32_MSG_HANDLE;
402 #endif
403   event_poll_fd.events = G_IO_IN;
404   
405   g_source_add_poll (source, &event_poll_fd);
406   g_source_set_can_recurse (source, TRUE);
407   g_source_attach (source, NULL);
408 }
409
410 gboolean
411 gdk_events_pending (void)
412 {
413   MSG msg;
414   return (_gdk_event_queue_find_first (_gdk_display) ||
415           (modal_win32_dialog == NULL &&
416            PeekMessageW (&msg, NULL, 0, 0, PM_NOREMOVE)));
417 }
418
419 GdkEvent*
420 gdk_event_get_graphics_expose (GdkWindow *window)
421 {
422   MSG msg;
423   GdkEvent *event = NULL;
424
425   g_return_val_if_fail (window != NULL, NULL);
426   
427   GDK_NOTE (EVENTS, g_print ("gdk_event_get_graphics_expose\n"));
428
429   if (PeekMessageW (&msg, GDK_WINDOW_HWND (window), WM_PAINT, WM_PAINT, PM_REMOVE))
430     {
431       handle_wm_paint (&msg, window, TRUE, &event);
432       if (event != NULL)
433         {
434           GDK_NOTE (EVENTS, g_print ("gdk_event_get_graphics_expose: got it!\n"));
435           return event;
436         }
437     }
438   
439   GDK_NOTE (EVENTS, g_print ("gdk_event_get_graphics_expose: nope\n"));
440   return NULL;  
441 }
442
443 static char *
444 event_mask_string (GdkEventMask mask)
445 {
446   static char bfr[500];
447   char *p = bfr;
448
449   *p = '\0';
450 #define BIT(x) \
451   if (mask & GDK_##x##_MASK) \
452     p += g_sprintf (p, "%s" #x, (p > bfr ? " " : ""))
453   BIT (EXPOSURE);
454   BIT (POINTER_MOTION);
455   BIT (POINTER_MOTION_HINT);
456   BIT (BUTTON_MOTION);
457   BIT (BUTTON1_MOTION);
458   BIT (BUTTON2_MOTION);
459   BIT (BUTTON3_MOTION);
460   BIT (BUTTON_PRESS);
461   BIT (BUTTON_RELEASE);
462   BIT (KEY_PRESS);
463   BIT (KEY_RELEASE);
464   BIT (ENTER_NOTIFY);
465   BIT (LEAVE_NOTIFY);
466   BIT (FOCUS_CHANGE);
467   BIT (STRUCTURE);
468   BIT (PROPERTY_CHANGE);
469   BIT (VISIBILITY_NOTIFY);
470   BIT (PROXIMITY_IN);
471   BIT (PROXIMITY_OUT);
472   BIT (SUBSTRUCTURE);
473   BIT (SCROLL);
474 #undef BIT
475
476   return bfr;
477 }
478
479 GdkGrabStatus
480 _gdk_windowing_pointer_grab (GdkWindow    *window,
481                              GdkWindow    *native_window,
482                              gboolean   owner_events,
483                              GdkEventMask       event_mask,
484                              GdkWindow    *confine_to,
485                              GdkCursor    *cursor,
486                              guint32    time)
487 {
488   SetCapture (GDK_WINDOW_HWND (native_window));
489   /* TODO_CSW: grab brokens, confine window, cursor, input_grab */
490   return GDK_GRAB_SUCCESS;
491 }
492
493 void
494 gdk_display_pointer_ungrab (GdkDisplay *display,
495                             guint32     time)
496 {
497   GdkPointerGrabInfo *info;
498
499   info = _gdk_display_get_last_pointer_grab (display);
500   if (info)
501     {
502       info->serial_end = 0;
503       ReleaseCapture ();
504     }
505   /* TODO_CSW: cursor, confines, etc */
506
507   _gdk_display_pointer_grab_update (display, 0);
508 }
509
510 GdkGrabStatus
511 gdk_keyboard_grab (GdkWindow *window,
512                    gboolean   owner_events,
513                    guint32    time)
514 {
515   GdkDisplay *display;
516   GdkWindow  *toplevel;
517
518   g_return_val_if_fail (window != NULL, 0);
519   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
520   
521   GDK_NOTE (EVENTS, g_print ("gdk_keyboard_grab %p%s\n",
522                              GDK_WINDOW_HWND (window), owner_events ? " OWNER_EVENTS" : ""));
523
524   display = gdk_drawable_get_display (window);
525   toplevel = gdk_window_get_toplevel (window);
526
527   _gdk_display_set_has_keyboard_grab (display,
528                                       window,
529                                       toplevel,
530                                       owner_events,
531                                       0,
532                                       time);
533
534   return GDK_GRAB_SUCCESS;
535 }
536
537 void
538 gdk_display_keyboard_ungrab (GdkDisplay *display,
539                              guint32 time)
540 {
541   GDK_NOTE (EVENTS, g_print ("gdk_display_keyboard_ungrab\n"));
542   _gdk_display_unset_has_keyboard_grab (display, FALSE);
543 }
544
545 void 
546 gdk_display_add_client_message_filter (GdkDisplay   *display,
547                                        GdkAtom       message_type,
548                                        GdkFilterFunc func,
549                                        gpointer      data)
550 {
551   /* XXX */
552   gdk_add_client_message_filter (message_type, func, data);
553 }
554
555 void
556 gdk_add_client_message_filter (GdkAtom       message_type,
557                                GdkFilterFunc func,
558                                gpointer      data)
559 {
560   GdkClientFilter *filter = g_new (GdkClientFilter, 1);
561
562   filter->type = message_type;
563   filter->function = func;
564   filter->data = data;
565   
566   client_filters = g_list_append (client_filters, filter);
567 }
568
569 static void
570 build_key_event_state (GdkEvent *event,
571                        BYTE     *key_state)
572 {
573   event->key.state = 0;
574
575   if (key_state[VK_SHIFT] & 0x80)
576     event->key.state |= GDK_SHIFT_MASK;
577
578   if (key_state[VK_CAPITAL] & 0x01)
579     event->key.state |= GDK_LOCK_MASK;
580
581   if (key_state[VK_LBUTTON] & 0x80)
582     event->key.state |= GDK_BUTTON1_MASK;
583   if (key_state[VK_MBUTTON] & 0x80)
584     event->key.state |= GDK_BUTTON2_MASK;
585   if (key_state[VK_RBUTTON] & 0x80)
586     event->key.state |= GDK_BUTTON3_MASK;
587   if (key_state[VK_XBUTTON1] & 0x80)
588     event->key.state |= GDK_BUTTON4_MASK;
589   if (key_state[VK_XBUTTON2] & 0x80)
590     event->key.state |= GDK_BUTTON5_MASK;
591
592   if (_gdk_keyboard_has_altgr &&
593       (key_state[VK_LCONTROL] & 0x80) &&
594       (key_state[VK_RMENU] & 0x80))
595     {
596       event->key.group = 1;
597       event->key.state |= GDK_MOD2_MASK;
598       if (key_state[VK_RCONTROL] & 0x80)
599         event->key.state |= GDK_CONTROL_MASK;
600       if (key_state[VK_LMENU] & 0x80)
601         event->key.state |= GDK_MOD1_MASK;
602     }
603   else
604     {
605       event->key.group = 0;
606       if (key_state[VK_CONTROL] & 0x80)
607         event->key.state |= GDK_CONTROL_MASK;
608       if (key_state[VK_MENU] & 0x80)
609         event->key.state |= GDK_MOD1_MASK;
610     }
611 }
612
613 static gint
614 build_pointer_event_state (MSG *msg)
615 {
616   gint state;
617   
618   state = 0;
619
620   if (msg->wParam & MK_CONTROL)
621     state |= GDK_CONTROL_MASK;
622
623   if ((msg->message != WM_LBUTTONDOWN &&
624        (msg->wParam & MK_LBUTTON)) ||
625       msg->message == WM_LBUTTONUP)
626     state |= GDK_BUTTON1_MASK;
627
628   if ((msg->message != WM_MBUTTONDOWN &&
629        (msg->wParam & MK_MBUTTON)) ||
630       msg->message == WM_MBUTTONUP)
631     state |= GDK_BUTTON2_MASK;
632
633   if ((msg->message != WM_RBUTTONDOWN &&
634        (msg->wParam & MK_RBUTTON)) ||
635       msg->message == WM_RBUTTONUP)
636     state |= GDK_BUTTON3_MASK;
637
638   if (((msg->message != WM_XBUTTONDOWN || HIWORD (msg->wParam) != XBUTTON1) &&
639        (msg->wParam & MK_XBUTTON1)) ||
640       (msg->message == WM_XBUTTONUP && HIWORD (msg->wParam) == XBUTTON1))
641     state |= GDK_BUTTON4_MASK;
642
643   if (((msg->message != WM_XBUTTONDOWN || HIWORD (msg->wParam) != XBUTTON2) &&
644        (msg->wParam & MK_XBUTTON2)) ||
645       (msg->message == WM_XBUTTONUP && HIWORD (msg->wParam) == XBUTTON2))
646     state |= GDK_BUTTON5_MASK;
647
648   if (msg->wParam & MK_SHIFT)
649     state |= GDK_SHIFT_MASK;
650
651   if (GetKeyState (VK_MENU) < 0)
652     state |= GDK_MOD1_MASK;
653
654   if (GetKeyState (VK_CAPITAL) & 0x1)
655     state |= GDK_LOCK_MASK;
656
657   return state;
658 }
659
660 static void
661 build_wm_ime_composition_event (GdkEvent *event,
662                                 MSG      *msg,
663                                 wchar_t   wc,
664                                 BYTE     *key_state)
665 {
666   event->key.time = _gdk_win32_get_next_tick (msg->time);
667   
668   build_key_event_state (event, key_state);
669
670   event->key.hardware_keycode = 0; /* FIXME: What should it be? */
671   event->key.string = NULL;
672   event->key.length = 0;
673   event->key.keyval = gdk_unicode_to_keyval (wc);
674 }
675
676 #ifdef G_ENABLE_DEBUG
677
678 static void
679 print_event_state (guint state)
680 {
681 #define CASE(bit) if (state & GDK_ ## bit ## _MASK) g_print (#bit " ");
682   CASE (SHIFT);
683   CASE (LOCK);
684   CASE (CONTROL);
685   CASE (MOD1);
686   CASE (MOD2);
687   CASE (MOD3);
688   CASE (MOD4);
689   CASE (MOD5);
690   CASE (BUTTON1);
691   CASE (BUTTON2);
692   CASE (BUTTON3);
693   CASE (BUTTON4);
694   CASE (BUTTON5);
695 #undef CASE
696 }
697
698 static void
699 print_event (GdkEvent *event)
700 {
701   gchar *escaped, *kvname;
702   gchar *selection_name, *target_name, *property_name;
703
704   g_print ("%s%*s===> ", (debug_indent > 0 ? "\n" : ""), debug_indent, "");
705   switch (event->any.type)
706     {
707 #define CASE(x) case x: g_print (#x); break;
708     CASE (GDK_NOTHING);
709     CASE (GDK_DELETE);
710     CASE (GDK_DESTROY);
711     CASE (GDK_EXPOSE);
712     CASE (GDK_MOTION_NOTIFY);
713     CASE (GDK_BUTTON_PRESS);
714     CASE (GDK_2BUTTON_PRESS);
715     CASE (GDK_3BUTTON_PRESS);
716     CASE (GDK_BUTTON_RELEASE);
717     CASE (GDK_KEY_PRESS);
718     CASE (GDK_KEY_RELEASE);
719     CASE (GDK_ENTER_NOTIFY);
720     CASE (GDK_LEAVE_NOTIFY);
721     CASE (GDK_FOCUS_CHANGE);
722     CASE (GDK_CONFIGURE);
723     CASE (GDK_MAP);
724     CASE (GDK_UNMAP);
725     CASE (GDK_PROPERTY_NOTIFY);
726     CASE (GDK_SELECTION_CLEAR);
727     CASE (GDK_SELECTION_REQUEST);
728     CASE (GDK_SELECTION_NOTIFY);
729     CASE (GDK_PROXIMITY_IN);
730     CASE (GDK_PROXIMITY_OUT);
731     CASE (GDK_DRAG_ENTER);
732     CASE (GDK_DRAG_LEAVE);
733     CASE (GDK_DRAG_MOTION);
734     CASE (GDK_DRAG_STATUS);
735     CASE (GDK_DROP_START);
736     CASE (GDK_DROP_FINISHED);
737     CASE (GDK_CLIENT_EVENT);
738     CASE (GDK_VISIBILITY_NOTIFY);
739     CASE (GDK_NO_EXPOSE);
740     CASE (GDK_SCROLL);
741     CASE (GDK_WINDOW_STATE);
742     CASE (GDK_SETTING);
743     CASE (GDK_OWNER_CHANGE);
744     CASE (GDK_GRAB_BROKEN);
745 #undef CASE
746     default: g_assert_not_reached ();
747     }
748
749   g_print (" %p ", GDK_WINDOW_HWND (event->any.window));
750
751   switch (event->any.type)
752     {
753     case GDK_EXPOSE:
754       g_print ("%s %d",
755                _gdk_win32_gdkrectangle_to_string (&event->expose.area),
756                event->expose.count);
757       break;
758     case GDK_MOTION_NOTIFY:
759       g_print ("(%.4g,%.4g) (%.4g,%.4g) %s",
760                event->motion.x, event->motion.y,
761                event->motion.x_root, event->motion.y_root,
762                event->motion.is_hint ? "HINT " : "");
763       print_event_state (event->motion.state);
764       break;
765     case GDK_BUTTON_PRESS:
766     case GDK_2BUTTON_PRESS:
767     case GDK_3BUTTON_PRESS:
768     case GDK_BUTTON_RELEASE:
769       g_print ("%d (%.4g,%.4g) (%.4g,%.4g) ",
770                event->button.button,
771                event->button.x, event->button.y,
772                event->button.x_root, event->button.y_root);
773       print_event_state (event->button.state);
774       break;
775     case GDK_KEY_PRESS: 
776     case GDK_KEY_RELEASE:
777       if (event->key.length == 0)
778         escaped = g_strdup ("");
779       else
780         escaped = g_strescape (event->key.string, NULL);
781       kvname = gdk_keyval_name (event->key.keyval);
782       g_print ("%#.02x group:%d %s %d:\"%s\" ",
783                event->key.hardware_keycode, event->key.group,
784                (kvname ? kvname : "??"),
785                event->key.length,
786                escaped);
787       g_free (escaped);
788       print_event_state (event->key.state);
789       break;
790     case GDK_ENTER_NOTIFY:
791     case GDK_LEAVE_NOTIFY:
792       g_print ("%p (%.4g,%.4g) (%.4g,%.4g) %s %s%s",
793                event->crossing.subwindow == NULL ? NULL : GDK_WINDOW_HWND (event->crossing.subwindow),
794                event->crossing.x, event->crossing.y,
795                event->crossing.x_root, event->crossing.y_root,
796                (event->crossing.mode == GDK_CROSSING_NORMAL ? "NORMAL" :
797                 (event->crossing.mode == GDK_CROSSING_GRAB ? "GRAB" :
798                  (event->crossing.mode == GDK_CROSSING_UNGRAB ? "UNGRAB" :
799                   "???"))),
800                (event->crossing.detail == GDK_NOTIFY_ANCESTOR ? "ANCESTOR" :
801                 (event->crossing.detail == GDK_NOTIFY_VIRTUAL ? "VIRTUAL" :
802                  (event->crossing.detail == GDK_NOTIFY_INFERIOR ? "INFERIOR" :
803                   (event->crossing.detail == GDK_NOTIFY_NONLINEAR ? "NONLINEAR" :
804                    (event->crossing.detail == GDK_NOTIFY_NONLINEAR_VIRTUAL ? "NONLINEAR_VIRTUAL" :
805                     (event->crossing.detail == GDK_NOTIFY_UNKNOWN ? "UNKNOWN" :
806                      "???")))))),
807                event->crossing.focus ? " FOCUS" : "");
808       print_event_state (event->crossing.state);
809       break;
810     case GDK_FOCUS_CHANGE:
811       g_print ("%s", (event->focus_change.in ? "IN" : "OUT"));
812       break;
813     case GDK_SELECTION_REQUEST:
814     case GDK_SELECTION_NOTIFY:
815     case GDK_SELECTION_CLEAR:
816       selection_name = gdk_atom_name (event->selection.selection);
817       target_name = gdk_atom_name (event->selection.target);
818       property_name = gdk_atom_name (event->selection.property);
819       g_print ("sel:%s tgt:%s prop:%s",
820                selection_name, target_name, property_name);
821       g_free (selection_name);
822       g_free (target_name);
823       g_free (property_name);
824       break;
825     case GDK_CONFIGURE:
826       g_print ("x:%d y:%d w:%d h:%d",
827                event->configure.x, event->configure.y,
828                event->configure.width, event->configure.height);
829       break;
830     case GDK_CLIENT_EVENT:
831       g_print ("%s %d %ld %ld %ld %ld %ld",
832                gdk_atom_name (event->client.message_type),
833                event->client.data_format,
834                event->client.data.l[0],
835                event->client.data.l[1],
836                event->client.data.l[2],
837                event->client.data.l[3],
838                event->client.data.l[4]);
839       break;
840     case GDK_SCROLL:
841       g_print ("(%.4g,%.4g) (%.4g,%.4g) %s ",
842                event->scroll.x, event->scroll.y,
843                event->scroll.x_root, event->scroll.y_root,
844                (event->scroll.direction == GDK_SCROLL_UP ? "UP" :
845                 (event->scroll.direction == GDK_SCROLL_DOWN ? "DOWN" :
846                  (event->scroll.direction == GDK_SCROLL_LEFT ? "LEFT" :
847                   (event->scroll.direction == GDK_SCROLL_RIGHT ? "RIGHT" :
848                    "???")))));
849       print_event_state (event->scroll.state);
850       break;
851     case GDK_WINDOW_STATE:
852       g_print ("%s: %s",
853                _gdk_win32_window_state_to_string (event->window_state.changed_mask),
854                _gdk_win32_window_state_to_string (event->window_state.new_window_state));
855     case GDK_SETTING:
856       g_print ("%s: %s",
857                (event->setting.action == GDK_SETTING_ACTION_NEW ? "NEW" :
858                 (event->setting.action == GDK_SETTING_ACTION_CHANGED ? "CHANGED" :
859                  (event->setting.action == GDK_SETTING_ACTION_DELETED ? "DELETED" :
860                   "???"))),
861                (event->setting.name ? event->setting.name : "NULL"));
862     case GDK_GRAB_BROKEN:
863       g_print ("%s %s %p",
864                (event->grab_broken.keyboard ? "KEYBOARD" : "POINTER"),
865                (event->grab_broken.implicit ? "IMPLICIT" : "EXPLICIT"),
866                (event->grab_broken.grab_window ? GDK_WINDOW_HWND (event->grab_broken.grab_window) : 0));
867     default:
868       /* Nothing */
869       break;
870     }  
871   g_print ("%s", (debug_indent == 0 ? "\n" : "")); 
872 }
873
874 static char *
875 decode_key_lparam (LPARAM lParam)
876 {
877   static char buf[100];
878   char *p = buf;
879
880   if (HIWORD (lParam) & KF_UP)
881     p += g_sprintf (p, "KF_UP ");
882   if (HIWORD (lParam) & KF_REPEAT)
883     p += g_sprintf (p, "KF_REPEAT ");
884   if (HIWORD (lParam) & KF_ALTDOWN)
885     p += g_sprintf (p, "KF_ALTDOWN ");
886   if (HIWORD (lParam) & KF_EXTENDED)
887     p += g_sprintf (p, "KF_EXTENDED ");
888   p += g_sprintf (p, "sc:%d rep:%d", LOBYTE (HIWORD (lParam)), LOWORD (lParam));
889
890   return buf;
891 }
892
893 #endif
894
895 static void
896 fixup_event (GdkEvent *event)
897 {
898   if (event->any.window)
899     g_object_ref (event->any.window);
900   if (((event->any.type == GDK_ENTER_NOTIFY) ||
901        (event->any.type == GDK_LEAVE_NOTIFY)) &&
902       (event->crossing.subwindow != NULL))
903     g_object_ref (event->crossing.subwindow);
904   event->any.send_event = InSendMessage (); 
905 }
906
907 static void
908 append_event (GdkEvent *event)
909 {
910   GList *link;
911   
912   fixup_event (event);
913   link = _gdk_event_queue_append (_gdk_display, event);
914   _gdk_windowing_got_event (_gdk_display, link, event, 0);
915   GDK_NOTE (EVENTS, print_event (event));
916 }
917
918 static void
919 fill_key_event_string (GdkEvent *event)
920 {
921   gunichar c;
922   gchar buf[256];
923
924   /* Fill in event->string crudely, since various programs
925    * depend on it.
926    */
927   
928   c = 0;
929   if (event->key.keyval != GDK_VoidSymbol)
930     c = gdk_keyval_to_unicode (event->key.keyval);
931
932   if (c)
933     {
934       gsize bytes_written;
935       gint len;
936       
937       /* Apply the control key - Taken from Xlib
938        */
939       if (event->key.state & GDK_CONTROL_MASK)
940         {
941           if ((c >= '@' && c < '\177') || c == ' ')
942             c &= 0x1F;
943           else if (c == '2')
944             {
945               event->key.string = g_memdup ("\0\0", 2);
946               event->key.length = 1;
947               return;
948             }
949           else if (c >= '3' && c <= '7')
950             c -= ('3' - '\033');
951           else if (c == '8')
952             c = '\177';
953           else if (c == '/')
954             c = '_' & 0x1F;
955         }
956       
957       len = g_unichar_to_utf8 (c, buf);
958       buf[len] = '\0';
959           
960       event->key.string = g_locale_from_utf8 (buf, len,
961                                               NULL, &bytes_written,
962                                               NULL);
963       if (event->key.string)
964         event->key.length = bytes_written;
965     }
966   else if (event->key.keyval == GDK_Escape)
967     {
968       event->key.length = 1;
969       event->key.string = g_strdup ("\033");
970     }
971   else if (event->key.keyval == GDK_Return ||
972            event->key.keyval == GDK_KP_Enter)
973     {
974       event->key.length = 1;
975       event->key.string = g_strdup ("\r");
976     }
977   
978   if (!event->key.string)
979     {
980       event->key.length = 0;
981       event->key.string = g_strdup ("");
982     }
983 }
984
985 static GdkFilterReturn
986 apply_event_filters (GdkWindow  *window,
987                      MSG        *msg,
988                      GList      *filters)
989 {
990   GdkFilterReturn result = GDK_FILTER_CONTINUE;
991   GdkEvent *event;
992   GList *node;
993   GList *tmp_list;
994
995   event = gdk_event_new (GDK_NOTHING);
996   if (window != NULL)
997     event->any.window = g_object_ref (window);
998   ((GdkEventPrivate *)event)->flags |= GDK_EVENT_PENDING;
999
1000   /* I think GdkFilterFunc semantics require the passed-in event
1001    * to already be in the queue. The filter func can generate
1002    * more events and append them after it if it likes.
1003    */
1004   node = _gdk_event_queue_append (_gdk_display, event);
1005   
1006   tmp_list = filters;
1007   while (tmp_list)
1008     {
1009       GdkEventFilter *filter = (GdkEventFilter *) tmp_list->data;
1010       
1011       tmp_list = tmp_list->next;
1012       result = filter->function (msg, event, filter->data);
1013       if (result !=  GDK_FILTER_CONTINUE)
1014         break;
1015     }
1016
1017   if (result == GDK_FILTER_CONTINUE || result == GDK_FILTER_REMOVE)
1018     {
1019       _gdk_event_queue_remove_link (_gdk_display, node);
1020       g_list_free_1 (node);
1021       gdk_event_free (event);
1022     }
1023   else /* GDK_FILTER_TRANSLATE */
1024     {
1025       ((GdkEventPrivate *)event)->flags &= ~GDK_EVENT_PENDING;
1026       fixup_event (event);
1027       GDK_NOTE (EVENTS, print_event (event));
1028     }
1029   return result;
1030 }
1031
1032 /*
1033  * On Windows, transient windows will not have their own taskbar entries.
1034  * Because of this, we must hide and restore groups of transients in both
1035  * directions.  That is, all transient children must be hidden or restored
1036  * with this window, but if this window's transient owner also has a
1037  * transient owner then this window's transient owner must be hidden/restored
1038  * with this one.  And etc, up the chain until we hit an ancestor that has no
1039  * transient owner.
1040  *
1041  * It would be a good idea if applications don't chain transient windows
1042  * together.  There's a limit to how much evil GTK can try to shield you
1043  * from.
1044  */
1045 static void
1046 show_window_recurse (GdkWindow *window, gboolean hide_window)
1047 {
1048   GdkWindowImplWin32 *impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (window)->impl);
1049   GSList *children = impl->transient_children;
1050   GdkWindow *child = NULL;
1051
1052   if (!impl->changing_state)
1053     {
1054       impl->changing_state = TRUE;
1055
1056       if (children != NULL)
1057         {
1058           while (children != NULL)
1059             {
1060               child = children->data;
1061               show_window_recurse (child, hide_window);
1062
1063               children = g_slist_next (children);
1064             }
1065         }
1066
1067       if (GDK_WINDOW_IS_MAPPED (window))
1068         {
1069           if (!hide_window)
1070             {
1071               if (GDK_WINDOW_OBJECT (window)->state & GDK_WINDOW_STATE_ICONIFIED)
1072                 {
1073                   if (GDK_WINDOW_OBJECT (window)->state & GDK_WINDOW_STATE_MAXIMIZED)
1074                     {
1075                       ShowWindow (GDK_WINDOW_HWND (window), SW_SHOWMAXIMIZED);
1076                     }
1077                   else
1078                     {
1079                       ShowWindow (GDK_WINDOW_HWND (window), SW_RESTORE);
1080                     }
1081                 }
1082             }
1083           else
1084             {
1085               ShowWindow (GDK_WINDOW_HWND (window), SW_MINIMIZE);
1086             }
1087         }
1088
1089       impl->changing_state = FALSE;
1090     }
1091 }
1092
1093 static void
1094 do_show_window (GdkWindow *window, gboolean hide_window)
1095 {
1096   GdkWindow *tmp_window = NULL;
1097   GdkWindowImplWin32 *tmp_impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (window)->impl);
1098
1099   if (!tmp_impl->changing_state)
1100     {
1101       /* Find the top-level window in our transient chain. */
1102       while (tmp_impl->transient_owner != NULL)
1103         {
1104           tmp_window = tmp_impl->transient_owner;
1105           tmp_impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (tmp_window)->impl);
1106         }
1107
1108       /* If we couldn't find one, use the window provided. */
1109       if (tmp_window == NULL)
1110         {
1111           tmp_window = window;
1112         }
1113
1114       /* Recursively show/hide every window in the chain. */
1115       if (tmp_window != window)
1116         {
1117           show_window_recurse (tmp_window, hide_window);
1118         }
1119     }
1120 }
1121
1122 static gboolean
1123 gdk_window_is_ancestor (GdkWindow *ancestor,
1124                         GdkWindow *window)
1125 {
1126   if (ancestor == NULL || window == NULL)
1127     return FALSE;
1128
1129   return (gdk_window_get_parent (window) == ancestor ||
1130           gdk_window_is_ancestor (ancestor, gdk_window_get_parent (window)));
1131 }
1132
1133 static void
1134 synthesize_enter_or_leave_event (GdkWindow      *window,
1135                                  MSG            *msg,
1136                                  GdkEventType    type,
1137                                  GdkCrossingMode mode,
1138                                  GdkNotifyType detail)
1139 {
1140   GdkEvent *event;
1141   POINT pt;
1142
1143   pt = msg->pt;
1144   ScreenToClient (GDK_WINDOW_HWND (window), &pt);
1145   
1146   event = gdk_event_new (type);
1147   event->crossing.window = window;
1148   event->crossing.subwindow = NULL;
1149   event->crossing.time = _gdk_win32_get_next_tick (msg->time);
1150   event->crossing.x = pt.x;
1151   event->crossing.y = pt.y;
1152   event->crossing.x_root = msg->pt.x + _gdk_offset_x;
1153   event->crossing.y_root = msg->pt.y + _gdk_offset_y;
1154   event->crossing.mode = mode;
1155   event->crossing.detail = detail;
1156   event->crossing.focus = TRUE; /* FIXME: Set correctly */
1157   event->crossing.state = 0;    /* FIXME: Set correctly */
1158
1159   append_event (event);
1160   
1161   if (type == GDK_ENTER_NOTIFY &&
1162       ((GdkWindowObject *) window)->extension_events != 0)
1163     _gdk_input_enter_event (window);
1164 }
1165                          
1166 static void
1167 synthesize_expose_events (GdkWindow *window)
1168 {
1169   RECT r;
1170   HDC hdc;
1171   GdkDrawableImplWin32 *impl = GDK_DRAWABLE_IMPL_WIN32 (((GdkWindowObject *) window)->impl);
1172   GList *list = gdk_window_get_children (window);
1173   GList *head = list;
1174   GdkEvent *event;
1175   int k;
1176   
1177   while (list)
1178     {
1179       synthesize_expose_events ((GdkWindow *) list->data);
1180       list = list->next;
1181     }
1182
1183   g_list_free (head);
1184
1185   if (((GdkWindowObject *) window)->input_only)
1186     ;
1187   else if (!(hdc = GetDC (impl->handle)))
1188     WIN32_GDI_FAILED ("GetDC");
1189   else
1190     {
1191       if ((k = GetClipBox (hdc, &r)) == ERROR)
1192         WIN32_GDI_FAILED ("GetClipBox");
1193       else if (k != NULLREGION)
1194         {
1195           event = gdk_event_new (GDK_EXPOSE);
1196           event->expose.window = window;
1197           event->expose.area.x = r.left;
1198           event->expose.area.y = r.top;
1199           event->expose.area.width = r.right - r.left;
1200           event->expose.area.height = r.bottom - r.top;
1201           event->expose.region = gdk_region_rectangle (&(event->expose.area));
1202           event->expose.count = 0;
1203   
1204           append_event (event);
1205         }
1206       GDI_CALL (ReleaseDC, (impl->handle, hdc));
1207     }
1208 }
1209
1210 static void
1211 update_colors (GdkWindow *window,
1212                gboolean   top)
1213 {
1214   HDC hdc;
1215   GdkDrawableImplWin32 *impl = GDK_DRAWABLE_IMPL_WIN32 (((GdkWindowObject *) window)->impl);
1216   GList *list = gdk_window_get_children (window);
1217   GList *head = list;
1218
1219   GDK_NOTE (COLORMAP, (top ? g_print ("update_colors:") : (void) 0));
1220
1221   while (list)
1222     {
1223       update_colors ((GdkWindow *) list->data, FALSE);
1224       list = list->next;
1225     }
1226   g_list_free (head);
1227
1228   if (((GdkWindowObject *) window)->input_only ||
1229       impl->colormap == NULL)
1230     return;
1231
1232   if (!(hdc = GetDC (impl->handle)))
1233     WIN32_GDI_FAILED ("GetDC");
1234   else
1235     {
1236       GdkColormapPrivateWin32 *cmapp = GDK_WIN32_COLORMAP_DATA (impl->colormap);
1237       HPALETTE holdpal;
1238       gint k;
1239       
1240       if ((holdpal = SelectPalette (hdc, cmapp->hpal, TRUE)) == NULL)
1241         WIN32_GDI_FAILED ("SelectPalette");
1242       else if ((k = RealizePalette (hdc)) == GDI_ERROR)
1243         WIN32_GDI_FAILED ("RealizePalette");
1244       else
1245         {
1246           GDK_NOTE (COLORMAP,
1247                     (k > 0 ?
1248                      g_print (" %p pal=%p: realized %d colors\n"
1249                               "update_colors:",
1250                               impl->handle, cmapp->hpal, k) :
1251                      (void) 0,
1252                      g_print (" %p", impl->handle)));
1253           GDI_CALL (UpdateColors, (hdc));
1254           SelectPalette (hdc, holdpal, TRUE);
1255           RealizePalette (hdc);
1256         }
1257       GDI_CALL (ReleaseDC, (impl->handle, hdc));
1258     }
1259   GDK_NOTE (COLORMAP, (top ? g_print ("\n") : (void) 0));
1260 }
1261
1262 static void
1263 translate_mouse_coords (GdkWindow *window1,
1264                         GdkWindow *window2,
1265                         MSG       *msg)
1266 {
1267   POINT pt;
1268
1269   pt.x = GET_X_LPARAM (msg->lParam);
1270   pt.y = GET_Y_LPARAM (msg->lParam);
1271   ClientToScreen (GDK_WINDOW_HWND (window1), &pt);
1272   ScreenToClient (GDK_WINDOW_HWND (window2), &pt);
1273   msg->lParam = MAKELPARAM (pt.x, pt.y);
1274 }
1275
1276 /* The check_extended flag controls whether to check if the windows want
1277  * events from extended input devices and if the message should be skipped
1278  * because an extended input device is active
1279  */
1280 static gboolean
1281 propagate (GdkWindow  **window,
1282            MSG         *msg,
1283            GdkWindow   *grab_window,
1284            gboolean     grab_owner_events,
1285            gint         grab_mask,
1286            gboolean   (*doesnt_want_it) (gint mask,
1287                                          MSG *msg),
1288            gboolean     check_extended)
1289 {
1290   if (grab_window != NULL && !grab_owner_events)
1291     {
1292       /* Event source is grabbed with owner_events FALSE */
1293
1294       /* See if the event should be ignored because an extended input
1295        * device is used
1296        */
1297       if (check_extended &&
1298           ((GdkWindowObject *) grab_window)->extension_events != 0 &&
1299           _gdk_input_ignore_core)
1300         {
1301           GDK_NOTE (EVENTS, g_print (" (ignored for grabber)"));
1302           return FALSE;
1303         }
1304       if ((*doesnt_want_it) (grab_mask, msg))
1305         {
1306           GDK_NOTE (EVENTS, g_print (" (grabber doesn't want it)"));
1307           return FALSE;
1308         }
1309       else
1310         {
1311           GDK_NOTE (EVENTS, g_print (" (to grabber)"));
1312           assign_object (window, grab_window);
1313           return TRUE;
1314         }
1315     }
1316
1317   /* If we come here, we know that if grab_window != NULL then
1318    * grab_owner_events is TRUE
1319    */
1320   while (TRUE)
1321     {
1322       if (check_extended &&
1323           ((GdkWindowObject *) *window)->extension_events != 0 &&
1324           _gdk_input_ignore_core)
1325         {
1326           GDK_NOTE (EVENTS, g_print (" (ignored)"));
1327           return FALSE;
1328         }
1329       if ((*doesnt_want_it) (((GdkWindowObject *) *window)->event_mask, msg))
1330         {
1331           /* Owner doesn't want it, propagate to parent. */
1332           GdkWindow *parent = gdk_window_get_parent (*window);
1333           if (parent == _gdk_root || parent == NULL)
1334             {
1335               /* No parent; check if grabbed */
1336               if (grab_window != NULL)
1337                 {
1338                   /* Event source is grabbed with owner_events TRUE */
1339
1340                   if (check_extended &&
1341                       ((GdkWindowObject *) grab_window)->extension_events != 0 &&
1342                       _gdk_input_ignore_core)
1343                     {
1344                       GDK_NOTE (EVENTS, g_print (" (ignored for grabber)"));
1345                       return FALSE;
1346                     }
1347                   if ((*doesnt_want_it) (grab_mask, msg))
1348                     {
1349                       /* Grabber doesn't want it either */
1350                       GDK_NOTE (EVENTS, g_print (" (grabber doesn't want it)"));
1351                       return FALSE;
1352                     }
1353                   else
1354                     {
1355                       /* Grabbed! */
1356                       GDK_NOTE (EVENTS, g_print (" (to grabber)"));
1357                       assign_object (window, grab_window);
1358                       return TRUE;
1359                     }
1360                 }
1361               else
1362                 {
1363                   GDK_NOTE (EVENTS, g_print (" (undelivered)"));
1364                   return FALSE;
1365                 }
1366             }
1367           else
1368             {
1369               assign_object (window, parent);
1370               /* The only branch where we actually continue the loop */
1371             }
1372         }
1373       else
1374         return TRUE;
1375     }
1376 }
1377
1378 static gboolean
1379 doesnt_want_key (gint mask,
1380                  MSG *msg)
1381 {
1382   return (((msg->message == WM_KEYUP || msg->message == WM_SYSKEYUP) &&
1383            !(mask & GDK_KEY_RELEASE_MASK)) ||
1384           ((msg->message == WM_KEYDOWN || msg->message == WM_SYSKEYDOWN) &&
1385            !(mask & GDK_KEY_PRESS_MASK)));
1386 }
1387
1388 static gboolean
1389 doesnt_want_char (gint mask,
1390                   MSG *msg)
1391 {
1392   return !(mask & (GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK));
1393 }
1394
1395 static gboolean
1396 doesnt_want_button_press (gint mask,
1397                           MSG *msg)
1398 {
1399   return !(mask & GDK_BUTTON_PRESS_MASK);
1400 }
1401
1402 static gboolean
1403 doesnt_want_button_release (gint mask,
1404                             MSG *msg)
1405 {
1406   return !(mask & GDK_BUTTON_RELEASE_MASK);
1407 }
1408
1409 static gboolean
1410 doesnt_want_button_motion (gint mask,
1411                            MSG *msg)
1412 {
1413   return !((mask & GDK_POINTER_MOTION_MASK) ||
1414            ((msg->wParam & (MK_LBUTTON|MK_MBUTTON|MK_RBUTTON)) && (mask & GDK_BUTTON_MOTION_MASK)) ||
1415            ((msg->wParam & MK_LBUTTON) && (mask & GDK_BUTTON1_MOTION_MASK)) ||
1416            ((msg->wParam & MK_MBUTTON) && (mask & GDK_BUTTON2_MOTION_MASK)) ||
1417            ((msg->wParam & MK_RBUTTON) && (mask & GDK_BUTTON3_MOTION_MASK)));
1418 }
1419
1420 static gboolean
1421 doesnt_want_scroll (gint mask,
1422                     MSG *msg)
1423 {
1424   /* As there are no separate scroll events in X11, button press
1425    * events are used, so higher level code might be selecting for
1426    * either GDK_BUTTON_PRESS_MASK or GDK_SCROLL_MASK when it wants GDK
1427    * scroll events. Make sure this works in the Win32 backend, too.
1428    */
1429   return !(mask & (GDK_SCROLL_MASK|GDK_BUTTON_PRESS_MASK));
1430 }
1431
1432 static void
1433 handle_configure_event (MSG       *msg,
1434                         GdkWindow *window)
1435 {
1436   RECT client_rect;
1437   POINT point;
1438   GdkWindowObject *window_object;
1439
1440   GetClientRect (msg->hwnd, &client_rect);
1441   point.x = client_rect.left; /* always 0 */
1442   point.y = client_rect.top;
1443
1444   /* top level windows need screen coords */
1445   if (gdk_window_get_parent (window) == _gdk_root)
1446     {
1447       ClientToScreen (msg->hwnd, &point);
1448       point.x += _gdk_offset_x;
1449       point.y += _gdk_offset_y;
1450     }
1451
1452   window_object = GDK_WINDOW_OBJECT (window);
1453
1454   window_object->width = client_rect.right - client_rect.left;
1455   window_object->height = client_rect.bottom - client_rect.top;
1456   
1457   window_object->x = point.x;
1458   window_object->y = point.y;
1459
1460   _gdk_window_update_size (window);
1461   
1462   if (window_object->event_mask & GDK_STRUCTURE_MASK)
1463     {
1464       GdkEvent *event = gdk_event_new (GDK_CONFIGURE);
1465
1466       event->configure.window = window;
1467
1468       event->configure.width = client_rect.right - client_rect.left;
1469       event->configure.height = client_rect.bottom - client_rect.top;
1470       
1471       event->configure.x = point.x;
1472       event->configure.y = point.y;
1473
1474       append_event (event);
1475     }
1476 }
1477
1478 GdkRegion *
1479 _gdk_win32_hrgn_to_region (HRGN hrgn)
1480 {
1481   RGNDATA *rgndata;
1482   RECT *rects;
1483   GdkRegion *result;
1484   gint nbytes;
1485   guint i;
1486
1487   if ((nbytes = GetRegionData (hrgn, 0, NULL)) == 0)
1488     {
1489       WIN32_GDI_FAILED ("GetRegionData");
1490       return NULL;
1491     }
1492
1493   rgndata = (RGNDATA *) g_malloc (nbytes);
1494
1495   if (GetRegionData (hrgn, nbytes, rgndata) == 0)
1496     {
1497       WIN32_GDI_FAILED ("GetRegionData");
1498       g_free (rgndata);
1499       return NULL;
1500     }
1501
1502   result = gdk_region_new ();
1503   rects = (RECT *) rgndata->Buffer;
1504   for (i = 0; i < rgndata->rdh.nCount; i++)
1505     {
1506       GdkRectangle r;
1507
1508       r.x = rects[i].left;
1509       r.y = rects[i].top;
1510       r.width = rects[i].right - r.x;
1511       r.height = rects[i].bottom - r.y;
1512
1513       gdk_region_union_with_rect (result, &r);
1514     }
1515
1516   g_free (rgndata);
1517
1518   return result;
1519 }
1520
1521 static void
1522 adjust_drag (LONG *drag,
1523              LONG  curr,
1524              gint  inc)
1525 {
1526   if (*drag > curr)
1527     *drag = curr + ((*drag + inc/2 - curr) / inc) * inc;
1528   else
1529     *drag = curr - ((curr - *drag + inc/2) / inc) * inc;
1530 }
1531
1532 static void
1533 handle_wm_paint (MSG        *msg,
1534                  GdkWindow  *window,
1535                  gboolean    return_exposes,
1536                  GdkEvent  **event)
1537 {
1538   HRGN hrgn = CreateRectRgn (0, 0, 0, 0);
1539   HDC hdc;
1540   PAINTSTRUCT paintstruct;
1541   GdkRegion *update_region;
1542
1543   if (GetUpdateRgn (msg->hwnd, hrgn, FALSE) == ERROR)
1544     {
1545       WIN32_GDI_FAILED ("GetUpdateRgn");
1546       DeleteObject (hrgn);
1547       return;
1548     }
1549
1550   hdc = BeginPaint (msg->hwnd, &paintstruct);
1551
1552   GDK_NOTE (EVENTS, g_print (" %s %s dc %p%s",
1553                              _gdk_win32_rect_to_string (&paintstruct.rcPaint),
1554                              (paintstruct.fErase ? "erase" : ""),
1555                              hdc,
1556                              (return_exposes ? " return_exposes" : "")));
1557
1558   EndPaint (msg->hwnd, &paintstruct);
1559
1560   /* HB: don't generate GDK_EXPOSE events for InputOnly
1561    * windows -> backing store now works!
1562    */
1563   if (((GdkWindowObject *) window)->input_only)
1564     {
1565       DeleteObject (hrgn);
1566       return;
1567     }
1568
1569   if (!(((GdkWindowObject *) window)->event_mask & GDK_EXPOSURE_MASK))
1570     {
1571       GDK_NOTE (EVENTS, g_print (" (ignored)"));
1572       DeleteObject (hrgn);
1573       return;
1574     }
1575
1576 #if 0 /* we need to process exposes even with GDK_NO_BG
1577    * Otherwise The GIMP canvas update is broken ....
1578    */
1579   if (((GdkWindowObject *) window)->bg_pixmap == GDK_NO_BG)
1580     break;
1581 #endif
1582
1583   if ((paintstruct.rcPaint.right == paintstruct.rcPaint.left) ||
1584       (paintstruct.rcPaint.bottom == paintstruct.rcPaint.top))
1585     {
1586       GDK_NOTE (EVENTS, g_print (" (empty paintstruct, ignored)"));
1587       DeleteObject (hrgn);
1588       return;
1589     }
1590
1591   if (return_exposes)
1592     {
1593       if (!GDK_WINDOW_DESTROYED (window))
1594         {
1595           GList *list = _gdk_display->queued_events;
1596
1597           *event = gdk_event_new (GDK_EXPOSE);
1598           (*event)->expose.window = window;
1599           (*event)->expose.area.x = paintstruct.rcPaint.left;
1600           (*event)->expose.area.y = paintstruct.rcPaint.top;
1601           (*event)->expose.area.width = paintstruct.rcPaint.right - paintstruct.rcPaint.left;
1602           (*event)->expose.area.height = paintstruct.rcPaint.bottom - paintstruct.rcPaint.top;
1603           (*event)->expose.region = _gdk_win32_hrgn_to_region (hrgn);
1604           (*event)->expose.count = 0;
1605
1606           while (list != NULL)
1607             {
1608               GdkEventPrivate *evp = list->data;
1609
1610               if (evp->event.any.type == GDK_EXPOSE &&
1611                   evp->event.any.window == window &&
1612                   !(evp->flags & GDK_EVENT_PENDING))
1613                 evp->event.expose.count++;
1614
1615               list = list->next;
1616             }
1617         }
1618
1619       DeleteObject (hrgn);
1620       return;
1621     }
1622
1623   update_region = _gdk_win32_hrgn_to_region (hrgn);
1624
1625
1626   //_gdk_win32_windowing_window_get_offsets (window, &xoffset, &yoffset);
1627   //gdk_region_offset (update_region, xoffset, yoffset);
1628
1629   _gdk_window_process_expose (window, update_region);
1630   gdk_region_destroy (update_region);
1631
1632   DeleteObject (hrgn);
1633 }
1634
1635 static void
1636 handle_stuff_while_moving_or_resizing (void)
1637 {
1638   int arbitrary_limit = 1;
1639   while (g_main_context_pending (NULL) && arbitrary_limit--)
1640     g_main_context_iteration (NULL, FALSE);
1641 }
1642
1643 static VOID CALLBACK
1644 modal_timer_proc (HWND     hwnd,
1645                   UINT     msg,
1646                   UINT_PTR id,
1647                   DWORD    time)
1648 {
1649   if (_sizemove_in_progress)
1650     handle_stuff_while_moving_or_resizing ();
1651 }
1652
1653 static VOID CALLBACK
1654 sync_timer_proc (HWND     hwnd,
1655                  UINT     msg,
1656                  UINT_PTR id,
1657                  DWORD    time)
1658 {
1659   MSG message;
1660   if (PeekMessageW (&message, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
1661     {
1662       return;
1663     }
1664
1665   RedrawWindow (hwnd, NULL, NULL, RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
1666
1667   KillTimer (hwnd, sync_timer);
1668 }
1669
1670 static void
1671 handle_display_change (void)
1672 {
1673   _gdk_monitor_init ();
1674   _gdk_root_window_size_init ();
1675   g_signal_emit_by_name (_gdk_screen, "size_changed");
1676 }
1677
1678 static void
1679 generate_button_event (GdkEventType type,
1680                        gint         button,
1681                        GdkWindow   *window,
1682                        MSG         *msg)
1683 {
1684   GdkEvent *event = gdk_event_new (type);
1685
1686   event->button.window = window;
1687   event->button.time = _gdk_win32_get_next_tick (msg->time);
1688   event->button.x = current_x = (gint16) GET_X_LPARAM (msg->lParam);
1689   event->button.y = current_y = (gint16) GET_Y_LPARAM (msg->lParam);
1690   event->button.x_root = msg->pt.x + _gdk_offset_x;
1691   event->button.y_root = msg->pt.y + _gdk_offset_y;
1692   event->button.axes = NULL;
1693   event->button.state = build_pointer_event_state (msg);
1694   event->button.button = button;
1695   event->button.device = _gdk_display->core_pointer;
1696
1697   append_event (event);
1698 }
1699
1700 static void
1701 ensure_stacking_on_unminimize (MSG *msg)
1702 {
1703   HWND rover;
1704   HWND lowest_transient = NULL;
1705
1706   rover = msg->hwnd;
1707   while ((rover = GetNextWindow (rover, GW_HWNDNEXT)))
1708     {
1709       GdkWindow *rover_gdkw = gdk_win32_handle_table_lookup (rover);
1710
1711       /* Checking window group not implemented yet */
1712       if (rover_gdkw)
1713         {
1714           GdkWindowImplWin32 *rover_impl =
1715             (GdkWindowImplWin32 *)((GdkWindowObject *)rover_gdkw)->impl;
1716
1717           if (GDK_WINDOW_IS_MAPPED (rover_gdkw) &&
1718               (rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_UTILITY ||
1719                rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_DIALOG ||
1720                rover_impl->transient_owner != NULL))
1721             {
1722               lowest_transient = rover;
1723             }
1724         }
1725     }
1726   if (lowest_transient != NULL)
1727     {
1728       GDK_NOTE (EVENTS, g_print (" restacking: %p", lowest_transient));
1729       SetWindowPos (msg->hwnd, lowest_transient, 0, 0, 0, 0,
1730                     SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1731     }
1732 }
1733
1734 static gboolean
1735 ensure_stacking_on_window_pos_changing (MSG       *msg,
1736                                         GdkWindow *window)
1737 {
1738   GdkWindowImplWin32 *impl = (GdkWindowImplWin32 *)((GdkWindowObject *) window)->impl;
1739   WINDOWPOS *windowpos = (WINDOWPOS *) msg->lParam;
1740
1741   if (GetActiveWindow () == msg->hwnd &&
1742       impl->type_hint != GDK_WINDOW_TYPE_HINT_UTILITY &&
1743       impl->type_hint != GDK_WINDOW_TYPE_HINT_DIALOG &&
1744       impl->transient_owner == NULL)
1745     {
1746       /* Make sure the window stays behind any transient-type windows
1747        * of the same window group.
1748        *
1749        * If the window is not active and being activated, we let
1750        * Windows bring it to the top and rely on the WM_ACTIVATEAPP
1751        * handling to bring any utility windows on top of it.
1752        */
1753       HWND rover;
1754       gboolean restacking;
1755
1756       rover = windowpos->hwndInsertAfter;
1757       restacking = FALSE;
1758       while (rover)
1759         {
1760           GdkWindow *rover_gdkw = gdk_win32_handle_table_lookup (rover);
1761
1762           /* Checking window group not implemented yet */
1763           if (rover_gdkw)
1764             {
1765               GdkWindowImplWin32 *rover_impl =
1766                 (GdkWindowImplWin32 *)((GdkWindowObject *)rover_gdkw)->impl;
1767
1768               if (GDK_WINDOW_IS_MAPPED (rover_gdkw) &&
1769                   (rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_UTILITY ||
1770                    rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_DIALOG ||
1771                    rover_impl->transient_owner != NULL))
1772                 {
1773                   restacking = TRUE;
1774                   windowpos->hwndInsertAfter = rover;
1775                 }
1776             }
1777           rover = GetNextWindow (rover, GW_HWNDNEXT);
1778         }
1779
1780       if (restacking)
1781         {
1782           GDK_NOTE (EVENTS, g_print (" restacking: %p", windowpos->hwndInsertAfter));
1783           return TRUE;
1784         }
1785     }
1786   return FALSE;
1787 }
1788
1789 static void
1790 ensure_stacking_on_activate_app (MSG       *msg,
1791                                  GdkWindow *window)
1792 {
1793   GdkWindowImplWin32 *impl = (GdkWindowImplWin32 *)((GdkWindowObject *) window)->impl;
1794
1795   if (impl->type_hint == GDK_WINDOW_TYPE_HINT_UTILITY ||
1796       impl->type_hint == GDK_WINDOW_TYPE_HINT_DIALOG ||
1797       impl->transient_owner != NULL)
1798     {
1799       SetWindowPos (msg->hwnd, HWND_TOP, 0, 0, 0, 0,
1800                     SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1801       return;
1802     }
1803
1804   if (IsWindowVisible (msg->hwnd) &&
1805       msg->hwnd == GetActiveWindow ())
1806     {
1807       /* This window is not a transient-type window and it is the
1808        * activated window. Make sure this window is as visible as
1809        * possible, just below the lowest transient-type window of this
1810        * app.
1811        */
1812       HWND rover;
1813
1814       rover = msg->hwnd;
1815       while ((rover = GetNextWindow (rover, GW_HWNDPREV)))
1816         {
1817           GdkWindow *rover_gdkw = gdk_win32_handle_table_lookup (rover);
1818
1819           /* Checking window group not implemented yet */
1820           if (rover_gdkw)
1821             {
1822               GdkWindowImplWin32 *rover_impl =
1823                 (GdkWindowImplWin32 *)((GdkWindowObject *)rover_gdkw)->impl;
1824
1825               if (GDK_WINDOW_IS_MAPPED (rover_gdkw) &&
1826                   (rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_UTILITY ||
1827                    rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_DIALOG ||
1828                    rover_impl->transient_owner != NULL))
1829                 {
1830                   GDK_NOTE (EVENTS, g_print (" restacking: %p", rover));
1831                   SetWindowPos (msg->hwnd, rover, 0, 0, 0, 0,
1832                                 SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1833                   break;
1834                 }
1835             }
1836         }
1837     }
1838 }
1839
1840 static gboolean
1841 gdk_event_translate (MSG  *msg,
1842                      gint *ret_valp)
1843 {
1844   RECT rect, *drag, orig_drag;
1845   POINT point;
1846   MINMAXINFO *mmi;
1847   HWND hwnd;
1848   HCURSOR hcursor;
1849   BYTE key_state[256];
1850   HIMC himc;
1851   WINDOWPOS *windowpos;
1852
1853   GdkEvent *event;
1854
1855   wchar_t wbuf[100];
1856   gint ccount;
1857
1858   GdkWindow *window = NULL;
1859   GdkWindowImplWin32 *impl;
1860
1861   GdkWindow *orig_window, *new_window, *toplevel;
1862
1863   GdkPointerGrabInfo *grab = NULL;
1864   GdkWindow *grab_window = NULL;
1865   guint grab_mask = 0;
1866   gboolean grab_owner_events = FALSE;
1867
1868   static gint update_colors_counter = 0;
1869   gint button;
1870   GdkAtom target;
1871
1872   gchar buf[256];
1873   gboolean return_val = FALSE;
1874
1875   int i;
1876
1877   if (_gdk_default_filters)
1878     {
1879       /* Apply global filters */
1880
1881       GdkFilterReturn result = apply_event_filters (NULL, msg, _gdk_default_filters);
1882       
1883       /* If result is GDK_FILTER_CONTINUE, we continue as if nothing
1884        * happened. If it is GDK_FILTER_REMOVE or GDK_FILTER_TRANSLATE,
1885        * we return TRUE, and DefWindowProcW() will not be called.
1886        */
1887       if (result == GDK_FILTER_REMOVE || result == GDK_FILTER_TRANSLATE)
1888         return TRUE;
1889     }
1890
1891   window = gdk_win32_handle_table_lookup ((GdkNativeWindow) msg->hwnd);
1892   orig_window = window;
1893
1894   if (window == NULL)
1895     {
1896       /* XXX Handle WM_QUIT here ? */
1897       if (msg->message == WM_QUIT)
1898         {
1899           GDK_NOTE (EVENTS, g_print (" %d", (int) msg->wParam));
1900           exit (msg->wParam);
1901         }
1902       else if (msg->message == WM_MOVE ||
1903                msg->message == WM_SIZE)
1904         {
1905           /* It's quite normal to get these messages before we have
1906            * had time to register the window in our lookup table, or
1907            * when the window is being destroyed and we already have
1908            * removed it. Repost the same message to our queue so that
1909            * we will get it later when we are prepared.
1910            */
1911           GDK_NOTE (EVENTS, g_print (" (posted)"));
1912         
1913           PostMessageW (msg->hwnd, msg->message, msg->wParam, msg->lParam);
1914         }
1915       else if (msg->message == WM_CREATE)
1916         {
1917           window = (UNALIGNED GdkWindow*) (((LPCREATESTRUCTW) msg->lParam)->lpCreateParams);
1918           GDK_WINDOW_HWND (window) = msg->hwnd;
1919         }
1920       else
1921         {
1922           GDK_NOTE (EVENTS, g_print (" (no GdkWindow)"));
1923         }
1924       return FALSE;
1925     }
1926   
1927   g_object_ref (window);
1928
1929   /* window's refcount has now been increased, so code below should
1930    * not just return from this function, but instead goto done (or
1931    * break out of the big switch). To protect against forgetting this,
1932    * #define return to a syntax error...
1933    */
1934 #define return GOTO_DONE_INSTEAD
1935   
1936   if (!GDK_WINDOW_DESTROYED (window) && ((GdkWindowObject *) window)->filters)
1937     {
1938       /* Apply per-window filters */
1939
1940       GdkFilterReturn result = apply_event_filters (window, msg, ((GdkWindowObject *) window)->filters);
1941
1942       if (result == GDK_FILTER_REMOVE || result == GDK_FILTER_TRANSLATE)
1943         {
1944           return_val = TRUE;
1945           goto done;
1946         }
1947     }
1948
1949   if (msg->message == client_message)
1950     {
1951       GList *tmp_list;
1952       GdkFilterReturn result = GDK_FILTER_CONTINUE;
1953       GList *node;
1954
1955       GDK_NOTE (EVENTS, g_print (" client_message"));
1956
1957       event = gdk_event_new (GDK_NOTHING);
1958       ((GdkEventPrivate *)event)->flags |= GDK_EVENT_PENDING;
1959
1960       node = _gdk_event_queue_append (_gdk_display, event);
1961
1962       tmp_list = client_filters;
1963       while (tmp_list)
1964         {
1965           GdkClientFilter *filter = tmp_list->data;
1966
1967           tmp_list = tmp_list->next;
1968
1969           if (filter->type == GDK_POINTER_TO_ATOM (msg->wParam))
1970             {
1971               GDK_NOTE (EVENTS, g_print (" (match)"));
1972
1973               result = (*filter->function) (msg, event, filter->data);
1974
1975               if (result != GDK_FILTER_CONTINUE)
1976                 break;
1977             }
1978         }
1979
1980       switch (result)
1981         {
1982         case GDK_FILTER_REMOVE:
1983           _gdk_event_queue_remove_link (_gdk_display, node);
1984           g_list_free_1 (node);
1985           gdk_event_free (event);
1986           return_val = TRUE;
1987           goto done;
1988
1989         case GDK_FILTER_TRANSLATE:
1990           ((GdkEventPrivate *)event)->flags &= ~GDK_EVENT_PENDING;
1991           GDK_NOTE (EVENTS, print_event (event));
1992           return_val = TRUE;
1993           goto done;
1994
1995         case GDK_FILTER_CONTINUE:
1996           /* Send unknown client messages on to Gtk for it to use */
1997
1998           event->client.type = GDK_CLIENT_EVENT;
1999           event->client.window = window;
2000           event->client.message_type = GDK_POINTER_TO_ATOM (msg->wParam);
2001           event->client.data_format = 32;
2002           event->client.data.l[0] = msg->lParam;
2003           for (i = 1; i < 5; i++)
2004             event->client.data.l[i] = 0;
2005           GDK_NOTE (EVENTS, print_event (event));
2006           return_val = TRUE;
2007           goto done;
2008         }
2009     }
2010
2011   switch (msg->message)
2012     {
2013     case WM_INPUTLANGCHANGE:
2014       _gdk_input_locale = (HKL) msg->lParam;
2015       _gdk_input_locale_is_ime = ImmIsIME (_gdk_input_locale);
2016       GetLocaleInfo (MAKELCID (LOWORD (_gdk_input_locale), SORT_DEFAULT),
2017                      LOCALE_IDEFAULTANSICODEPAGE,
2018                      buf, sizeof (buf));
2019       _gdk_input_codepage = atoi (buf);
2020       _gdk_keymap_serial++;
2021       GDK_NOTE (EVENTS,
2022                 g_print (" cs:%lu hkl:%p%s cp:%d",
2023                          (gulong) msg->wParam,
2024                          (gpointer) msg->lParam, _gdk_input_locale_is_ime ? " (IME)" : "",
2025                          _gdk_input_codepage));
2026       break;
2027
2028     case WM_SYSKEYUP:
2029     case WM_SYSKEYDOWN:
2030       GDK_NOTE (EVENTS,
2031                 g_print (" %s ch:%.02x %s",
2032                          _gdk_win32_key_to_string (msg->lParam),
2033                          (int) msg->wParam,
2034                          decode_key_lparam (msg->lParam)));
2035
2036       /* If posted without us having keyboard focus, ignore */
2037       if ((msg->wParam != VK_F10 && msg->wParam != VK_MENU) &&
2038           !(HIWORD (msg->lParam) & KF_ALTDOWN))
2039         break;
2040
2041       /* Let the system handle Alt-Tab, Alt-Space and Alt-F4 unless
2042        * the keyboard is grabbed.
2043        */
2044       if (_gdk_display->keyboard_grab.window == NULL &&
2045           (msg->wParam == VK_TAB ||
2046            msg->wParam == VK_SPACE ||
2047            msg->wParam == VK_F4))
2048         break;
2049
2050       /* Jump to code in common with WM_KEYUP and WM_KEYDOWN */
2051       goto keyup_or_down;
2052
2053     case WM_KEYUP:
2054     case WM_KEYDOWN:
2055       GDK_NOTE (EVENTS, 
2056                 g_print (" %s ch:%.02x %s",
2057                          _gdk_win32_key_to_string (msg->lParam),
2058                          (int) msg->wParam,
2059                          decode_key_lparam (msg->lParam)));
2060
2061     keyup_or_down:
2062
2063       /* Ignore key messages intended for the IME */
2064       if (msg->wParam == VK_PROCESSKEY ||
2065           in_ime_composition)
2066         break;
2067
2068       if (!propagate (&window, msg,
2069                       _gdk_display->keyboard_grab.window,
2070                       _gdk_display->keyboard_grab.owner_events,
2071                       GDK_ALL_EVENTS_MASK,
2072                       doesnt_want_key, FALSE))
2073         break;
2074
2075       if (GDK_WINDOW_DESTROYED (window))
2076         break;
2077
2078       event = gdk_event_new ((msg->message == WM_KEYDOWN ||
2079                               msg->message == WM_SYSKEYDOWN) ?
2080                              GDK_KEY_PRESS : GDK_KEY_RELEASE);
2081       event->key.window = window;
2082       event->key.time = _gdk_win32_get_next_tick (msg->time);
2083       event->key.keyval = GDK_VoidSymbol;
2084       event->key.string = NULL;
2085       event->key.length = 0;
2086       event->key.hardware_keycode = msg->wParam;
2087       if (HIWORD (msg->lParam) & KF_EXTENDED)
2088         {
2089           switch (msg->wParam)
2090             {
2091             case VK_CONTROL:
2092               event->key.hardware_keycode = VK_RCONTROL;
2093               break;
2094             case VK_SHIFT:      /* Actually, KF_EXTENDED is not set
2095                                  * for the right shift key.
2096                                  */
2097               event->key.hardware_keycode = VK_RSHIFT;
2098               break;
2099             case VK_MENU:
2100               event->key.hardware_keycode = VK_RMENU;
2101               break;
2102             }
2103         }
2104       else if (msg->wParam == VK_SHIFT &&
2105                LOBYTE (HIWORD (msg->lParam)) == _scancode_rshift)
2106         event->key.hardware_keycode = VK_RSHIFT;
2107
2108       API_CALL (GetKeyboardState, (key_state));
2109
2110       /* g_print ("ctrl:%02x lctrl:%02x rctrl:%02x alt:%02x lalt:%02x ralt:%02x\n", key_state[VK_CONTROL], key_state[VK_LCONTROL], key_state[VK_RCONTROL], key_state[VK_MENU], key_state[VK_LMENU], key_state[VK_RMENU]); */
2111       
2112       build_key_event_state (event, key_state);
2113
2114       gdk_keymap_translate_keyboard_state (NULL,
2115                                            event->key.hardware_keycode,
2116                                            event->key.state,
2117                                            event->key.group,
2118                                            &event->key.keyval,
2119                                            NULL, NULL, NULL);
2120
2121       fill_key_event_string (event);
2122
2123       /* Reset MOD1_MASK if it is the Alt key itself */
2124       if (msg->wParam == VK_MENU)
2125         event->key.state &= ~GDK_MOD1_MASK;
2126
2127       append_event (event);
2128
2129       return_val = TRUE;
2130       break;
2131
2132     case WM_SYSCHAR:
2133       if (msg->wParam != VK_SPACE)
2134         {
2135           /* To prevent beeps, don't let DefWindowProcW() be called */
2136           return_val = TRUE;
2137           goto done;
2138         }
2139       break;
2140
2141     case WM_IME_STARTCOMPOSITION:
2142       in_ime_composition = TRUE;
2143       break;
2144
2145     case WM_IME_ENDCOMPOSITION:
2146       in_ime_composition = FALSE;
2147       break;
2148
2149     case WM_IME_COMPOSITION:
2150       /* On Win2k WM_IME_CHAR doesn't work correctly for non-Unicode
2151        * applications. Thus, handle WM_IME_COMPOSITION with
2152        * GCS_RESULTSTR instead, fetch the Unicode chars from the IME
2153        * with ImmGetCompositionStringW().
2154        *
2155        * See for instance
2156        * http://groups.google.com/groups?selm=natX5.57%24g77.19788%40nntp2.onemain.com
2157        * and
2158        * http://groups.google.com/groups?selm=u2XfrXw5BHA.1628%40tkmsftngp02
2159        * for comments by other people that seems to have the same
2160        * experience. WM_IME_CHAR just gives question marks, apparently
2161        * because of going through some conversion to the current code
2162        * page.
2163        *
2164        * WM_IME_CHAR might work on NT4 or Win9x with ActiveIMM, but
2165        * use WM_IME_COMPOSITION there, too, to simplify the code.
2166        */
2167       GDK_NOTE (EVENTS, g_print (" %#lx", (long) msg->lParam));
2168
2169       if (!(msg->lParam & GCS_RESULTSTR))
2170         break;
2171
2172       if (!propagate (&window, msg,
2173                       _gdk_display->keyboard_grab.window,
2174                       _gdk_display->keyboard_grab.owner_events,
2175                       GDK_ALL_EVENTS_MASK,
2176                       doesnt_want_char, FALSE))
2177         break;
2178
2179       if (GDK_WINDOW_DESTROYED (window))
2180         break;
2181
2182       himc = ImmGetContext (msg->hwnd);
2183       ccount = ImmGetCompositionStringW (himc, GCS_RESULTSTR,
2184                                          wbuf, sizeof (wbuf));
2185       ImmReleaseContext (msg->hwnd, himc);
2186
2187       ccount /= 2;
2188
2189       API_CALL (GetKeyboardState, (key_state));
2190
2191       for (i = 0; i < ccount; i++)
2192         {
2193           if (((GdkWindowObject *) window)->event_mask & GDK_KEY_PRESS_MASK)
2194             {
2195               /* Build a key press event */
2196               event = gdk_event_new (GDK_KEY_PRESS);
2197               event->key.window = window;
2198               build_wm_ime_composition_event (event, msg, wbuf[i], key_state);
2199
2200               append_event (event);
2201             }
2202           
2203           if (((GdkWindowObject *) window)->event_mask & GDK_KEY_RELEASE_MASK)
2204             {
2205               /* Build a key release event.  */
2206               event = gdk_event_new (GDK_KEY_RELEASE);
2207               event->key.window = window;
2208               build_wm_ime_composition_event (event, msg, wbuf[i], key_state);
2209
2210               append_event (event);
2211             }
2212         }
2213       return_val = TRUE;
2214       break;
2215
2216     case WM_LBUTTONDOWN:
2217       button = 1;
2218       goto buttondown0;
2219
2220     case WM_MBUTTONDOWN:
2221       button = 2;
2222       goto buttondown0;
2223
2224     case WM_RBUTTONDOWN:
2225       button = 3;
2226       goto buttondown0;
2227
2228     case WM_XBUTTONDOWN:
2229       if (HIWORD (msg->wParam) == XBUTTON1)
2230         button = 4;
2231       else
2232         button = 5;
2233
2234     buttondown0:
2235       GDK_NOTE (EVENTS, 
2236                 g_print (" (%d,%d)",
2237                          GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
2238
2239       if (GDK_WINDOW_DESTROYED (window))
2240         break;
2241
2242       generate_button_event (GDK_BUTTON_PRESS, button,
2243                              window, msg);
2244
2245       return_val = TRUE;
2246       break;
2247
2248     case WM_LBUTTONUP:
2249       button = 1;
2250       goto buttonup0;
2251
2252     case WM_MBUTTONUP:
2253       button = 2;
2254       goto buttonup0;
2255
2256     case WM_RBUTTONUP:
2257       button = 3;
2258       goto buttonup0;
2259
2260     case WM_XBUTTONUP:
2261       if (HIWORD (msg->wParam) == XBUTTON1)
2262         button = 4;
2263       else
2264         button = 5;
2265
2266     buttonup0:
2267       GDK_NOTE (EVENTS, 
2268                 g_print (" (%d,%d)",
2269                          GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
2270
2271 #if 0
2272       if (((GdkWindowObject *) window)->extension_events != 0 &&
2273           _gdk_input_ignore_core)
2274         {
2275           GDK_NOTE (EVENTS, g_print (" (ignored)"));
2276           break;
2277         }
2278 #endif
2279
2280       generate_button_event (GDK_BUTTON_RELEASE, button,
2281                              window, msg);
2282
2283       return_val = TRUE;
2284       break;
2285
2286     case WM_MOUSEMOVE:
2287       GDK_NOTE (EVENTS,
2288                 g_print (" %p (%d,%d)",
2289                          (gpointer) msg->wParam,
2290                          GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
2291
2292       toplevel = gdk_window_get_toplevel (window);
2293       if (current_toplevel != toplevel)
2294         {
2295           if (current_toplevel)
2296             synthesize_enter_or_leave_event (current_toplevel, msg, 
2297                                              GDK_LEAVE_NOTIFY, GDK_CROSSING_NORMAL, GDK_NOTIFY_ANCESTOR);
2298           synthesize_enter_or_leave_event (toplevel, msg, 
2299                                            GDK_ENTER_NOTIFY, GDK_CROSSING_NORMAL, GDK_NOTIFY_ANCESTOR);
2300           assign_object (&current_toplevel, toplevel);
2301           track_mouse_event (TME_LEAVE, GDK_WINDOW_HWND (toplevel));
2302         }
2303       
2304       /* If we haven't moved, don't create any GDK event. Windows
2305        * sends WM_MOUSEMOVE messages after a new window is shows under
2306        * the mouse, even if the mouse hasn't moved. This disturbs gtk.
2307        */
2308       if (msg->pt.x + _gdk_offset_x == current_root_x &&
2309           msg->pt.y + _gdk_offset_y == current_root_y)
2310         break;
2311
2312       current_root_x = msg->pt.x + _gdk_offset_x;
2313       current_root_y = msg->pt.y + _gdk_offset_y;
2314
2315       event = gdk_event_new (GDK_MOTION_NOTIFY);
2316       event->motion.window = window;
2317       event->motion.time = _gdk_win32_get_next_tick (msg->time);
2318       event->motion.x = current_x = (gint16) GET_X_LPARAM (msg->lParam);
2319       event->motion.y = current_y = (gint16) GET_Y_LPARAM (msg->lParam);
2320       event->motion.x_root = current_root_x;
2321       event->motion.y_root = current_root_y;
2322       event->motion.axes = NULL;
2323       event->motion.state = build_pointer_event_state (msg);
2324       event->motion.is_hint = FALSE;
2325       event->motion.device = _gdk_display->core_pointer;
2326
2327       append_event (event);
2328
2329       return_val = TRUE;
2330       break;
2331
2332     case WM_NCMOUSEMOVE:
2333       GDK_NOTE (EVENTS,
2334                 g_print (" (%d,%d)",
2335                          GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
2336
2337       break;
2338
2339     case WM_MOUSELEAVE:
2340       GDK_NOTE (EVENTS, g_print (" %d (%ld,%ld)",
2341                                  HIWORD (msg->wParam), msg->pt.x, msg->pt.y));
2342
2343       if (!gdk_win32_handle_table_lookup ((GdkNativeWindow) WindowFromPoint (msg->pt)))
2344         {
2345           /* we are only interested if we don't know the new window */
2346           if (current_toplevel)
2347             synthesize_enter_or_leave_event (current_toplevel, msg, 
2348                                              GDK_LEAVE_NOTIFY, GDK_CROSSING_NORMAL, GDK_NOTIFY_ANCESTOR);
2349           assign_object (&current_toplevel, NULL);
2350         }
2351       else
2352         {
2353           GDK_NOTE (EVENTS, g_print (" (ignored)"));
2354         }
2355       
2356       return_val = TRUE;
2357       break;
2358
2359     case WM_MOUSEWHEEL:
2360       GDK_NOTE (EVENTS, g_print (" %d", (short) HIWORD (msg->wParam)));
2361
2362       /* WM_MOUSEWHEEL is delivered to the focus window. Work around
2363        * that. Also, the position is in screen coordinates, not client
2364        * coordinates as with the button messages. I love the
2365        * consistency of Windows.
2366        */
2367       point.x = GET_X_LPARAM (msg->lParam);
2368       point.y = GET_Y_LPARAM (msg->lParam);
2369
2370       if ((hwnd = WindowFromPoint (point)) == NULL)
2371         break;
2372
2373       msg->hwnd = hwnd;
2374       if ((new_window = gdk_win32_handle_table_lookup ((GdkNativeWindow) msg->hwnd)) == NULL)
2375         break;
2376
2377       if (new_window != window)
2378         {
2379           assign_object (&window, new_window);
2380         }
2381
2382       ScreenToClient (msg->hwnd, &point);
2383
2384       event = gdk_event_new (GDK_SCROLL);
2385       event->scroll.window = window;
2386       event->scroll.direction = (((short) HIWORD (msg->wParam)) > 0) ?
2387         GDK_SCROLL_UP : GDK_SCROLL_DOWN;
2388       event->scroll.time = _gdk_win32_get_next_tick (msg->time);
2389       event->scroll.x = (gint16) point.x;
2390       event->scroll.y = (gint16) point.y;
2391       event->scroll.x_root = (gint16) GET_X_LPARAM (msg->lParam) + _gdk_offset_x;
2392       event->scroll.y_root = (gint16) GET_Y_LPARAM (msg->lParam) + _gdk_offset_y;
2393       event->scroll.state = build_pointer_event_state (msg);
2394       event->scroll.device = _gdk_display->core_pointer;
2395
2396       append_event (event);
2397       
2398       return_val = TRUE;
2399       break;
2400
2401     case WM_HSCROLL:
2402       /* Just print more debugging information, don't actually handle it. */
2403       GDK_NOTE (EVENTS,
2404                 (g_print (" %s",
2405                           (LOWORD (msg->wParam) == SB_ENDSCROLL ? "ENDSCROLL" :
2406                            (LOWORD (msg->wParam) == SB_LEFT ? "LEFT" :
2407                             (LOWORD (msg->wParam) == SB_RIGHT ? "RIGHT" :
2408                              (LOWORD (msg->wParam) == SB_LINELEFT ? "LINELEFT" :
2409                               (LOWORD (msg->wParam) == SB_LINERIGHT ? "LINERIGHT" :
2410                                (LOWORD (msg->wParam) == SB_PAGELEFT ? "PAGELEFT" :
2411                                 (LOWORD (msg->wParam) == SB_PAGERIGHT ? "PAGERIGHT" :
2412                                  (LOWORD (msg->wParam) == SB_THUMBPOSITION ? "THUMBPOSITION" :
2413                                   (LOWORD (msg->wParam) == SB_THUMBTRACK ? "THUMBTRACK" :
2414                                    "???")))))))))),
2415                  (LOWORD (msg->wParam) == SB_THUMBPOSITION ||
2416                   LOWORD (msg->wParam) == SB_THUMBTRACK) ?
2417                  (g_print (" %d", HIWORD (msg->wParam)), 0) : 0));
2418       break;
2419
2420     case WM_VSCROLL:
2421       /* Just print more debugging information, don't actually handle it. */
2422       GDK_NOTE (EVENTS,
2423                 (g_print (" %s",
2424                           (LOWORD (msg->wParam) == SB_ENDSCROLL ? "ENDSCROLL" :
2425                            (LOWORD (msg->wParam) == SB_BOTTOM ? "BOTTOM" :
2426                             (LOWORD (msg->wParam) == SB_TOP ? "TOP" :
2427                              (LOWORD (msg->wParam) == SB_LINEDOWN ? "LINDOWN" :
2428                               (LOWORD (msg->wParam) == SB_LINEUP ? "LINEUP" :
2429                                (LOWORD (msg->wParam) == SB_PAGEDOWN ? "PAGEDOWN" :
2430                                 (LOWORD (msg->wParam) == SB_PAGEUP ? "PAGEUP" :
2431                                  (LOWORD (msg->wParam) == SB_THUMBPOSITION ? "THUMBPOSITION" :
2432                                   (LOWORD (msg->wParam) == SB_THUMBTRACK ? "THUMBTRACK" :
2433                                    "???")))))))))),
2434                  (LOWORD (msg->wParam) == SB_THUMBPOSITION ||
2435                   LOWORD (msg->wParam) == SB_THUMBTRACK) ?
2436                  (g_print (" %d", HIWORD (msg->wParam)), 0) : 0));
2437       break;
2438
2439     case WM_QUERYNEWPALETTE:
2440       if (gdk_visual_get_system ()->type == GDK_VISUAL_PSEUDO_COLOR)
2441         {
2442           synthesize_expose_events (window);
2443           update_colors_counter = 0;
2444         }
2445       return_val = TRUE;
2446       break;
2447
2448     case WM_PALETTECHANGED:
2449       GDK_NOTE (EVENTS_OR_COLORMAP, g_print (" %p", (HWND) msg->wParam));
2450       if (gdk_visual_get_system ()->type != GDK_VISUAL_PSEUDO_COLOR)
2451         break;
2452
2453       return_val = TRUE;
2454
2455       if (msg->hwnd == (HWND) msg->wParam)
2456         break;
2457
2458       if (++update_colors_counter == 5)
2459         {
2460           synthesize_expose_events (window);
2461           update_colors_counter = 0;
2462           break;
2463         }
2464       
2465       update_colors (window, TRUE);
2466       break;
2467
2468      case WM_MOUSEACTIVATE:
2469        {
2470          GdkWindow *tmp;
2471
2472          if (gdk_window_get_window_type (window) == GDK_WINDOW_TEMP 
2473              || !((GdkWindowObject *)window)->accept_focus)
2474            {
2475              *ret_valp = MA_NOACTIVATE;
2476              return_val = TRUE;
2477            }
2478
2479          tmp = _gdk_modal_current ();
2480
2481          if (tmp != NULL)
2482            {
2483              if (gdk_window_get_toplevel (window) != tmp)
2484                {
2485                  *ret_valp = MA_NOACTIVATEANDEAT;
2486                  return_val = TRUE;
2487                }
2488            }
2489        }
2490
2491        break;
2492
2493     case WM_KILLFOCUS:
2494       if (_gdk_display->keyboard_grab.window != NULL &&
2495           !GDK_WINDOW_DESTROYED (_gdk_display->keyboard_grab.window))
2496         {
2497           generate_grab_broken_event (_gdk_display->keyboard_grab.window, FALSE, NULL);
2498         }
2499
2500       /* fallthrough */
2501     case WM_SETFOCUS:
2502       if (_gdk_display->keyboard_grab.window != NULL &&
2503           !_gdk_display->keyboard_grab.owner_events)
2504         break;
2505
2506       if (!(((GdkWindowObject *) window)->event_mask & GDK_FOCUS_CHANGE_MASK))
2507         break;
2508
2509       if (GDK_WINDOW_DESTROYED (window))
2510         break;
2511
2512       generate_focus_event (window, (msg->message == WM_SETFOCUS));
2513       return_val = TRUE;
2514       break;
2515
2516     case WM_ERASEBKGND:
2517       GDK_NOTE (EVENTS, g_print (" %p", (HANDLE) msg->wParam));
2518       
2519       if (GDK_WINDOW_DESTROYED (window))
2520         break;
2521
2522       return_val = TRUE;
2523       *ret_valp = 1;
2524       break;
2525
2526     case WM_SYNCPAINT:
2527       sync_timer = SetTimer (GDK_WINDOW_HWND (window),
2528                              1,
2529                              200, sync_timer_proc);
2530       break;
2531
2532     case WM_PAINT:
2533       handle_wm_paint (msg, window, FALSE, NULL);
2534       break;
2535
2536     case WM_SETCURSOR:
2537       GDK_NOTE (EVENTS, g_print (" %#x %#x",
2538                                  LOWORD (msg->lParam), HIWORD (msg->lParam)));
2539
2540 #ifdef TODO_CSW
2541       grab = _gdk_display_get_last_pointer_grab (_gdk_display);
2542       if (grab != NULL)
2543         {
2544           grab_window = grab->window;
2545         }
2546
2547       if (grab_window == NULL && LOWORD (msg->lParam) != HTCLIENT)
2548         break;
2549
2550       if (grab_window != NULL && p_grab_cursor != NULL)
2551         hcursor = p_grab_cursor;
2552       else if (!GDK_WINDOW_DESTROYED (window))
2553         hcursor = GDK_WINDOW_IMPL_WIN32 (((GdkWindowObject *) window)->impl)->hcursor;
2554       else
2555         hcursor = NULL;
2556
2557       if (hcursor != NULL)
2558         {
2559           GDK_NOTE (EVENTS, g_print (" (SetCursor(%p)", hcursor));
2560           SetCursor (hcursor);
2561           return_val = TRUE;
2562           *ret_valp = TRUE;
2563         }
2564 #endif
2565       
2566       break;
2567
2568     case WM_SHOWWINDOW:
2569       GDK_NOTE (EVENTS, g_print (" %s %s",
2570                                  (msg->wParam ? "YES" : "NO"),
2571                                  (msg->lParam == 0 ? "ShowWindow" :
2572                                   (msg->lParam == SW_OTHERUNZOOM ? "OTHERUNZOOM" :
2573                                    (msg->lParam == SW_OTHERZOOM ? "OTHERZOOM" :
2574                                     (msg->lParam == SW_PARENTCLOSING ? "PARENTCLOSING" :
2575                                      (msg->lParam == SW_PARENTOPENING ? "PARENTOPENING" :
2576                                       "???")))))));
2577
2578       if (!(((GdkWindowObject *) window)->event_mask & GDK_STRUCTURE_MASK))
2579         break;
2580
2581       if (msg->lParam == SW_OTHERUNZOOM ||
2582           msg->lParam == SW_OTHERZOOM)
2583         break;
2584
2585       if (GDK_WINDOW_DESTROYED (window))
2586         break;
2587
2588       event = gdk_event_new (msg->wParam ? GDK_MAP : GDK_UNMAP);
2589       event->any.window = window;
2590
2591       append_event (event);
2592
2593       if (event->any.type == GDK_UNMAP)
2594         {
2595           impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (window)->impl);
2596
2597           if (impl->transient_owner && GetForegroundWindow () == GDK_WINDOW_HWND (window))
2598             {
2599               SetForegroundWindow (GDK_WINDOW_HWND (impl->transient_owner));
2600             }
2601
2602           grab = _gdk_display_get_last_pointer_grab (_gdk_display);
2603           if (grab != NULL)
2604             {
2605               if (grab->window == window)
2606                 gdk_pointer_ungrab (msg->time);
2607             }
2608
2609           if (_gdk_display->keyboard_grab.window == window)
2610             gdk_keyboard_ungrab (msg->time);
2611         }
2612
2613       return_val = TRUE;
2614       break;
2615
2616     case WM_SYSCOMMAND:
2617       switch (msg->wParam)
2618         {
2619         case SC_MINIMIZE:
2620         case SC_RESTORE:
2621           do_show_window (window, msg->wParam == SC_MINIMIZE ? TRUE : FALSE);
2622           break;
2623         }
2624
2625       break;
2626
2627     case WM_SIZE:
2628       GDK_NOTE (EVENTS,
2629                 g_print (" %s %dx%d",
2630                          (msg->wParam == SIZE_MAXHIDE ? "MAXHIDE" :
2631                           (msg->wParam == SIZE_MAXIMIZED ? "MAXIMIZED" :
2632                            (msg->wParam == SIZE_MAXSHOW ? "MAXSHOW" :
2633                             (msg->wParam == SIZE_MINIMIZED ? "MINIMIZED" :
2634                              (msg->wParam == SIZE_RESTORED ? "RESTORED" : "?"))))),
2635                          LOWORD (msg->lParam), HIWORD (msg->lParam)));
2636
2637       if (msg->wParam == SIZE_MINIMIZED)
2638         {
2639           /* Don't generate any GDK event. This is *not* an UNMAP. */
2640           grab = _gdk_display_get_last_pointer_grab (_gdk_display);
2641           if (grab != NULL)
2642             {
2643               if (grab->window == window)
2644                 gdk_pointer_ungrab (msg->time);
2645             }
2646           if (_gdk_display->keyboard_grab.window == window)
2647             gdk_keyboard_ungrab (msg->time);
2648
2649           gdk_synthesize_window_state (window,
2650                                        GDK_WINDOW_STATE_WITHDRAWN,
2651                                        GDK_WINDOW_STATE_ICONIFIED);
2652           do_show_window (window, TRUE);
2653         }
2654       else if ((msg->wParam == SIZE_RESTORED ||
2655                 msg->wParam == SIZE_MAXIMIZED) &&
2656                GDK_WINDOW_TYPE (window) != GDK_WINDOW_CHILD)
2657         {
2658           GdkWindowState withdrawn_bit =
2659             IsWindowVisible (msg->hwnd) ? GDK_WINDOW_STATE_WITHDRAWN : 0;
2660
2661           if (((GdkWindowObject *) window)->state & GDK_WINDOW_STATE_ICONIFIED)
2662             ensure_stacking_on_unminimize (msg);
2663
2664           if (!GDK_WINDOW_DESTROYED (window))
2665             handle_configure_event (msg, window);
2666           
2667           if (msg->wParam == SIZE_RESTORED)
2668             {
2669               gdk_synthesize_window_state (window,
2670                                            GDK_WINDOW_STATE_ICONIFIED |
2671                                            GDK_WINDOW_STATE_MAXIMIZED |
2672                                            withdrawn_bit,
2673                                            0);
2674
2675               if (GDK_WINDOW_TYPE (window) != GDK_WINDOW_TEMP && !GDK_WINDOW_IS_MAPPED (window))
2676                 {
2677                   do_show_window (window, FALSE);
2678                 }
2679             }
2680           else if (msg->wParam == SIZE_MAXIMIZED)
2681             {
2682               gdk_synthesize_window_state (window,
2683                                            GDK_WINDOW_STATE_ICONIFIED |
2684                                            withdrawn_bit,
2685                                            GDK_WINDOW_STATE_MAXIMIZED);
2686             }
2687
2688           if (((GdkWindowObject *) window)->resize_count > 1)
2689             ((GdkWindowObject *) window)->resize_count -= 1;
2690           
2691           if (((GdkWindowObject *) window)->extension_events != 0)
2692             _gdk_input_configure_event (window);
2693
2694           return_val = TRUE;
2695         }
2696       break;
2697
2698     case WM_ENTERSIZEMOVE:
2699       _sizemove_in_progress = TRUE;
2700       modal_timer = SetTimer (NULL, 0, 20, modal_timer_proc);
2701       break;
2702
2703     case WM_EXITSIZEMOVE:
2704       _sizemove_in_progress = FALSE;
2705       KillTimer (NULL, modal_timer);
2706       break;
2707
2708     case WM_ENTERMENULOOP:
2709       _sizemove_in_progress = TRUE;
2710       modal_timer = SetTimer (NULL, 0, 20, modal_timer_proc);
2711       break;
2712
2713     case WM_EXITMENULOOP:
2714       _sizemove_in_progress = FALSE;
2715       KillTimer (NULL, modal_timer);
2716       break;
2717
2718     case WM_WINDOWPOSCHANGING:
2719       GDK_NOTE (EVENTS, (windowpos = (WINDOWPOS *) msg->lParam,
2720                          g_print (" %s %s %dx%d@%+d%+d now below %p",
2721                                   _gdk_win32_window_pos_bits_to_string (windowpos->flags),
2722                                   (windowpos->hwndInsertAfter == HWND_BOTTOM ? "BOTTOM" :
2723                                    (windowpos->hwndInsertAfter == HWND_NOTOPMOST ? "NOTOPMOST" :
2724                                     (windowpos->hwndInsertAfter == HWND_TOP ? "TOP" :
2725                                      (windowpos->hwndInsertAfter == HWND_TOPMOST ? "TOPMOST" :
2726                                       (sprintf (buf, "%p", windowpos->hwndInsertAfter),
2727                                        buf))))),
2728                                   windowpos->cx, windowpos->cy, windowpos->x, windowpos->y,
2729                                   GetNextWindow (msg->hwnd, GW_HWNDPREV))));
2730
2731       if (GDK_WINDOW_IS_MAPPED (window))
2732         return_val = ensure_stacking_on_window_pos_changing (msg, window);
2733       break;
2734
2735     case WM_WINDOWPOSCHANGED:
2736       windowpos = (WINDOWPOS *) msg->lParam;
2737       GDK_NOTE (EVENTS, g_print (" %s %s %dx%d@%+d%+d",
2738                                  _gdk_win32_window_pos_bits_to_string (windowpos->flags),
2739                                  (windowpos->hwndInsertAfter == HWND_BOTTOM ? "BOTTOM" :
2740                                   (windowpos->hwndInsertAfter == HWND_NOTOPMOST ? "NOTOPMOST" :
2741                                    (windowpos->hwndInsertAfter == HWND_TOP ? "TOP" :
2742                                     (windowpos->hwndInsertAfter == HWND_TOPMOST ? "TOPMOST" :
2743                                      (sprintf (buf, "%p", windowpos->hwndInsertAfter),
2744                                       buf))))),
2745                                  windowpos->cx, windowpos->cy, windowpos->x, windowpos->y));
2746
2747       /* If position and size haven't changed, don't do anything */
2748       if (_sizemove_in_progress &&
2749           (windowpos->flags & SWP_NOMOVE) &&
2750           (windowpos->flags & SWP_NOSIZE))
2751         break;
2752
2753       /* Once we've entered the moving or sizing modal loop, we won't
2754        * return to the main loop until we're done sizing or moving.
2755        */
2756       if (_sizemove_in_progress &&
2757          GDK_WINDOW_TYPE (window) != GDK_WINDOW_CHILD &&
2758          !GDK_WINDOW_DESTROYED (window))
2759         {
2760           if (((GdkWindowObject *) window)->event_mask & GDK_STRUCTURE_MASK)
2761             {
2762               GDK_NOTE (EVENTS, g_print (" do magic"));
2763               if (((GdkWindowObject *) window)->resize_count > 1)
2764                 ((GdkWindowObject *) window)->resize_count -= 1;
2765               
2766               handle_configure_event (msg, window);
2767               g_main_context_iteration (NULL, FALSE);
2768
2769               /* Dispatch main loop - to realize resizes... */
2770               handle_stuff_while_moving_or_resizing ();
2771               
2772               /* Claim as handled, so that WM_SIZE and WM_MOVE are avoided */
2773               return_val = TRUE;
2774               *ret_valp = 1;
2775             }
2776         }
2777       break;
2778
2779     case WM_SIZING:
2780       GetWindowRect (GDK_WINDOW_HWND (window), &rect);
2781       drag = (RECT *) msg->lParam;
2782       GDK_NOTE (EVENTS, g_print (" %s curr:%s drag:%s",
2783                                  (msg->wParam == WMSZ_BOTTOM ? "BOTTOM" :
2784                                   (msg->wParam == WMSZ_BOTTOMLEFT ? "BOTTOMLEFT" :
2785                                    (msg->wParam == WMSZ_LEFT ? "LEFT" :
2786                                     (msg->wParam == WMSZ_TOPLEFT ? "TOPLEFT" :
2787                                      (msg->wParam == WMSZ_TOP ? "TOP" :
2788                                       (msg->wParam == WMSZ_TOPRIGHT ? "TOPRIGHT" :
2789                                        (msg->wParam == WMSZ_RIGHT ? "RIGHT" :
2790                                         
2791                                         (msg->wParam == WMSZ_BOTTOMRIGHT ? "BOTTOMRIGHT" :
2792                                          "???")))))))),
2793                                  _gdk_win32_rect_to_string (&rect),
2794                                  _gdk_win32_rect_to_string (drag)));
2795
2796       impl = GDK_WINDOW_IMPL_WIN32 (((GdkWindowObject *) window)->impl);
2797       orig_drag = *drag;
2798       if (impl->hint_flags & GDK_HINT_RESIZE_INC)
2799         {
2800           GDK_NOTE (EVENTS, g_print (" (RESIZE_INC)"));
2801           if (impl->hint_flags & GDK_HINT_BASE_SIZE)
2802             {
2803               /* Resize in increments relative to the base size */
2804               rect.left = rect.top = 0;
2805               rect.right = impl->hints.base_width;
2806               rect.bottom = impl->hints.base_height;
2807               _gdk_win32_adjust_client_rect (window, &rect);
2808               point.x = rect.left;
2809               point.y = rect.top;
2810               ClientToScreen (GDK_WINDOW_HWND (window), &point);
2811               rect.left = point.x;
2812               rect.top = point.y;
2813               point.x = rect.right;
2814               point.y = rect.bottom;
2815               ClientToScreen (GDK_WINDOW_HWND (window), &point);
2816               rect.right = point.x;
2817               rect.bottom = point.y;
2818               
2819               GDK_NOTE (EVENTS, g_print (" (also BASE_SIZE, using %s)",
2820                                          _gdk_win32_rect_to_string (&rect)));
2821             }
2822
2823           switch (msg->wParam)
2824             {
2825             case WMSZ_BOTTOM:
2826               if (drag->bottom == rect.bottom)
2827                 break;
2828               adjust_drag (&drag->bottom, rect.bottom, impl->hints.height_inc);
2829               break;
2830
2831             case WMSZ_BOTTOMLEFT:
2832               if (drag->bottom == rect.bottom && drag->left == rect.left)
2833                 break;
2834               adjust_drag (&drag->bottom, rect.bottom, impl->hints.height_inc);
2835               adjust_drag (&drag->left, rect.left, impl->hints.width_inc);
2836               break;
2837
2838             case WMSZ_LEFT:
2839               if (drag->left == rect.left)
2840                 break;
2841               adjust_drag (&drag->left, rect.left, impl->hints.width_inc);
2842               break;
2843
2844             case WMSZ_TOPLEFT:
2845               if (drag->top == rect.top && drag->left == rect.left)
2846                 break;
2847               adjust_drag (&drag->top, rect.top, impl->hints.height_inc);
2848               adjust_drag (&drag->left, rect.left, impl->hints.width_inc);
2849               break;
2850
2851             case WMSZ_TOP:
2852               if (drag->top == rect.top)
2853                 break;
2854               adjust_drag (&drag->top, rect.top, impl->hints.height_inc);
2855               break;
2856
2857             case WMSZ_TOPRIGHT:
2858               if (drag->top == rect.top && drag->right == rect.right)
2859                 break;
2860               adjust_drag (&drag->top, rect.top, impl->hints.height_inc);
2861               adjust_drag (&drag->right, rect.right, impl->hints.width_inc);
2862               break;
2863
2864             case WMSZ_RIGHT:
2865               if (drag->right == rect.right)
2866                 break;
2867               adjust_drag (&drag->right, rect.right, impl->hints.width_inc);
2868               break;
2869
2870             case WMSZ_BOTTOMRIGHT:
2871               if (drag->bottom == rect.bottom && drag->right == rect.right)
2872                 break;
2873               adjust_drag (&drag->bottom, rect.bottom, impl->hints.height_inc);
2874               adjust_drag (&drag->right, rect.right, impl->hints.width_inc);
2875               break;
2876             }
2877
2878           if (drag->bottom != orig_drag.bottom || drag->left != orig_drag.left ||
2879               drag->top != orig_drag.top || drag->right != orig_drag.right)
2880             {
2881               *ret_valp = TRUE;
2882               return_val = TRUE;
2883               GDK_NOTE (EVENTS, g_print (" (handled RESIZE_INC: %s)",
2884                                          _gdk_win32_rect_to_string (drag)));
2885             }
2886         }
2887
2888       /* WM_GETMINMAXINFO handles min_size and max_size hints? */
2889
2890       if (impl->hint_flags & GDK_HINT_ASPECT)
2891         {
2892           RECT decorated_rect;
2893           RECT undecorated_drag;
2894           int decoration_width, decoration_height;
2895           gdouble drag_aspect;
2896           int drag_width, drag_height, new_width, new_height;
2897
2898           GetClientRect (GDK_WINDOW_HWND (window), &rect);
2899           decorated_rect = rect;
2900           _gdk_win32_adjust_client_rect (window, &decorated_rect);
2901
2902           /* Set undecorated_drag to the client area being dragged
2903            * out, in screen coordinates.
2904            */
2905           undecorated_drag = *drag;
2906           undecorated_drag.left -= decorated_rect.left - rect.left;
2907           undecorated_drag.right -= decorated_rect.right - rect.right;
2908           undecorated_drag.top -= decorated_rect.top - rect.top;
2909           undecorated_drag.bottom -= decorated_rect.bottom - rect.bottom;
2910
2911           decoration_width = (decorated_rect.right - decorated_rect.left) - (rect.right - rect.left);
2912           decoration_height = (decorated_rect.bottom - decorated_rect.top) - (rect.bottom - rect.top);
2913
2914           drag_width = undecorated_drag.right - undecorated_drag.left;
2915           drag_height = undecorated_drag.bottom - undecorated_drag.top;
2916
2917           drag_aspect = (gdouble) drag_width / drag_height;
2918
2919           GDK_NOTE (EVENTS, g_print (" (ASPECT:%g--%g curr: %g)",
2920                                      impl->hints.min_aspect, impl->hints.max_aspect, drag_aspect));
2921
2922           if (drag_aspect < impl->hints.min_aspect)
2923             {
2924               /* Aspect is getting too narrow */
2925               switch (msg->wParam)
2926                 {
2927                 case WMSZ_BOTTOM:
2928                 case WMSZ_TOP:
2929                   /* User drags top or bottom edge outward. Keep height, increase width. */
2930                   new_width = impl->hints.min_aspect * drag_height;
2931                   drag->left -= (new_width - drag_width) / 2;
2932                   drag->right = drag->left + new_width + decoration_width;
2933                   break;
2934                 case WMSZ_BOTTOMLEFT:
2935                 case WMSZ_BOTTOMRIGHT:
2936                   /* User drags bottom-left or bottom-right corner down. Adjust height. */
2937                   new_height = drag_width / impl->hints.min_aspect;
2938                   drag->bottom = drag->top + new_height + decoration_height;
2939                   break;
2940                 case WMSZ_LEFT:
2941                 case WMSZ_RIGHT:
2942                   /* User drags left or right edge inward. Decrease height */
2943                   new_height = drag_width / impl->hints.min_aspect;
2944                   drag->top += (drag_height - new_height) / 2;
2945                   drag->bottom = drag->top + new_height + decoration_height;
2946                   break;
2947                 case WMSZ_TOPLEFT:
2948                 case WMSZ_TOPRIGHT:
2949                   /* User drags top-left or top-right corner up. Adjust height. */
2950                   new_height = drag_width / impl->hints.min_aspect;
2951                   drag->top = drag->bottom - new_height - decoration_height;
2952                 }
2953             }
2954           else if (drag_aspect > impl->hints.max_aspect)
2955             {
2956               /* Aspect is getting too wide */
2957               switch (msg->wParam)
2958                 {
2959                 case WMSZ_BOTTOM:
2960                 case WMSZ_TOP:
2961                   /* User drags top or bottom edge inward. Decrease width. */
2962                   new_width = impl->hints.max_aspect * drag_height;
2963                   drag->left += (drag_width - new_width) / 2;
2964                   drag->right = drag->left + new_width + decoration_width;
2965                   break;
2966                 case WMSZ_BOTTOMLEFT:
2967                 case WMSZ_TOPLEFT:
2968                   /* User drags bottom-left or top-left corner left. Adjust width. */
2969                   new_width = impl->hints.max_aspect * drag_height;
2970                   drag->left = drag->right - new_width - decoration_width;
2971                   break;
2972                 case WMSZ_BOTTOMRIGHT:
2973                 case WMSZ_TOPRIGHT:
2974                   /* User drags bottom-right or top-right corner right. Adjust width. */
2975                   new_width = impl->hints.max_aspect * drag_height;
2976                   drag->right = drag->left + new_width + decoration_width;
2977                   break;
2978                 case WMSZ_LEFT:
2979                 case WMSZ_RIGHT:
2980                   /* User drags left or right edge outward. Increase height. */
2981                   new_height = drag_width / impl->hints.max_aspect;
2982                   drag->top -= (new_height - drag_height) / 2;
2983                   drag->bottom = drag->top + new_height + decoration_height;
2984                   break;
2985                 }
2986             }
2987
2988           *ret_valp = TRUE;
2989           return_val = TRUE;
2990           GDK_NOTE (EVENTS, g_print (" (handled ASPECT: %s)",
2991                                      _gdk_win32_rect_to_string (drag)));
2992         }
2993       break;
2994
2995     case WM_GETMINMAXINFO:
2996       if (GDK_WINDOW_DESTROYED (window))
2997         break;
2998
2999       impl = GDK_WINDOW_IMPL_WIN32 (((GdkWindowObject *) window)->impl);
3000       mmi = (MINMAXINFO*) msg->lParam;
3001       GDK_NOTE (EVENTS, g_print (" (mintrack:%ldx%ld maxtrack:%ldx%ld "
3002                                  "maxpos:%+ld%+ld maxsize:%ldx%ld)",
3003                                  mmi->ptMinTrackSize.x, mmi->ptMinTrackSize.y,
3004                                  mmi->ptMaxTrackSize.x, mmi->ptMaxTrackSize.y,
3005                                  mmi->ptMaxPosition.x, mmi->ptMaxPosition.y,
3006                                  mmi->ptMaxSize.x, mmi->ptMaxSize.y));
3007
3008       if (impl->hint_flags & GDK_HINT_MIN_SIZE)
3009         {
3010           rect.left = rect.top = 0;
3011           rect.right = impl->hints.min_width;
3012           rect.bottom = impl->hints.min_height;
3013
3014           _gdk_win32_adjust_client_rect (window, &rect);
3015
3016           mmi->ptMinTrackSize.x = rect.right - rect.left;
3017           mmi->ptMinTrackSize.y = rect.bottom - rect.top;
3018         }
3019
3020       if (impl->hint_flags & GDK_HINT_MAX_SIZE)
3021         {
3022           int maxw, maxh;
3023
3024           rect.left = rect.top = 0;
3025           rect.right = impl->hints.max_width;
3026           rect.bottom = impl->hints.max_height;
3027
3028           _gdk_win32_adjust_client_rect (window, &rect);
3029
3030           /* at least on win9x we have the 16 bit trouble */
3031           maxw = rect.right - rect.left;
3032           maxh = rect.bottom - rect.top;
3033           mmi->ptMaxTrackSize.x = maxw > 0 && maxw < G_MAXSHORT ? maxw : G_MAXSHORT;
3034           mmi->ptMaxTrackSize.y = maxh > 0 && maxh < G_MAXSHORT ? maxh : G_MAXSHORT;
3035         }
3036
3037       if (impl->hint_flags & (GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE))
3038         {
3039           /* Don't call DefWindowProcW() */
3040           GDK_NOTE (EVENTS, g_print (" (handled, mintrack:%ldx%ld maxtrack:%ldx%ld "
3041                                      "maxpos:%+ld%+ld maxsize:%ldx%ld)",
3042                                      mmi->ptMinTrackSize.x, mmi->ptMinTrackSize.y,
3043                                      mmi->ptMaxTrackSize.x, mmi->ptMaxTrackSize.y,
3044                                      mmi->ptMaxPosition.x, mmi->ptMaxPosition.y,
3045                                      mmi->ptMaxSize.x, mmi->ptMaxSize.y));
3046           return_val = TRUE;
3047         }
3048       break;
3049
3050     case WM_MOVE:
3051       GDK_NOTE (EVENTS, g_print (" (%d,%d)",
3052                                  GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
3053
3054       if (GDK_WINDOW_TYPE (window) != GDK_WINDOW_CHILD &&
3055           !IsIconic (msg->hwnd))
3056         {
3057           if (!GDK_WINDOW_DESTROYED (window))
3058             handle_configure_event (msg, window);
3059
3060           return_val = TRUE;
3061         }
3062       break;
3063
3064     case WM_CLOSE:
3065       if (GDK_WINDOW_DESTROYED (window))
3066         break;
3067
3068       event = gdk_event_new (GDK_DELETE);
3069       event->any.window = window;
3070
3071       append_event (event);
3072
3073       impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (window)->impl);
3074
3075       if (impl->transient_owner && GetForegroundWindow() == GDK_WINDOW_HWND (window))
3076         {
3077           SetForegroundWindow (GDK_WINDOW_HWND (impl->transient_owner));
3078         }
3079
3080       return_val = TRUE;
3081       break;
3082
3083     case WM_DESTROY:
3084       grab = _gdk_display_get_last_pointer_grab (_gdk_display);
3085       if (grab != NULL)
3086         {
3087           if (grab->window == window)
3088             gdk_pointer_ungrab (msg->time);
3089         }
3090
3091       if (_gdk_display->keyboard_grab.window == window)
3092         gdk_keyboard_ungrab (msg->time);
3093
3094       if ((window != NULL) && (msg->hwnd != GetDesktopWindow ()))
3095         gdk_window_destroy_notify (window);
3096
3097       if (window == NULL || GDK_WINDOW_DESTROYED (window))
3098         break;
3099
3100       event = gdk_event_new (GDK_DESTROY);
3101       event->any.window = window;
3102
3103       append_event (event);
3104
3105       return_val = TRUE;
3106       break;
3107
3108     case WM_DISPLAYCHANGE:
3109       handle_display_change ();
3110       break;
3111       
3112     case WM_DESTROYCLIPBOARD:
3113       if (!_ignore_destroy_clipboard)
3114         {
3115           event = gdk_event_new (GDK_SELECTION_CLEAR);
3116           event->selection.window = window;
3117           event->selection.selection = GDK_SELECTION_CLIPBOARD;
3118           event->selection.time = _gdk_win32_get_next_tick (msg->time);
3119           append_event (event);
3120         }
3121       else
3122         {
3123           return_val = TRUE;
3124         }
3125
3126       break;
3127
3128     case WM_RENDERFORMAT:
3129       GDK_NOTE (EVENTS, g_print (" %s", _gdk_win32_cf_to_string (msg->wParam)));
3130
3131       if (!(target = g_hash_table_lookup (_format_atom_table, GINT_TO_POINTER (msg->wParam))))
3132         {
3133           GDK_NOTE (EVENTS, g_print (" (target not found)"));
3134           return_val = TRUE;
3135           break;
3136         }
3137
3138       /* We need to render to clipboard immediately, don't call
3139        * append_event()
3140        */
3141       if (_gdk_event_func)
3142         {
3143           event = gdk_event_new (GDK_SELECTION_REQUEST);
3144           event->selection.window = window;
3145           event->selection.send_event = FALSE;
3146           event->selection.selection = GDK_SELECTION_CLIPBOARD;
3147           event->selection.target = target;
3148           event->selection.property = _gdk_selection;
3149           event->selection.requestor = msg->hwnd;
3150           event->selection.time = msg->time;
3151
3152           fixup_event (event);
3153           GDK_NOTE (EVENTS, g_print (" (calling gdk_event_func)"));
3154           GDK_NOTE (EVENTS, print_event (event));
3155           (*_gdk_event_func) (event, _gdk_event_data);
3156           gdk_event_free (event);
3157
3158           /* Now the clipboard owner should have rendered */
3159           if (!_delayed_rendering_data)
3160             {
3161               GDK_NOTE (EVENTS, g_print (" (no _delayed_rendering_data?)"));
3162             }
3163           else
3164             {
3165               if (msg->wParam == CF_DIB)
3166                 {
3167                   _delayed_rendering_data =
3168                     _gdk_win32_selection_convert_to_dib (_delayed_rendering_data,
3169                                                          target);
3170                   if (!_delayed_rendering_data)
3171                     {
3172                       g_warning ("Cannot convert to DIB from delayed rendered image");
3173                       break;
3174                     }
3175                 }
3176
3177               /* The requestor is holding the clipboard, no
3178                * OpenClipboard() is required/possible
3179                */
3180               GDK_NOTE (DND,
3181                         g_print (" SetClipboardData(%s,%p)",
3182                                  _gdk_win32_cf_to_string (msg->wParam),
3183                                  _delayed_rendering_data));
3184
3185               API_CALL (SetClipboardData, (msg->wParam, _delayed_rendering_data));
3186               _delayed_rendering_data = NULL;
3187             }
3188         }
3189       break;
3190
3191     case WM_ACTIVATE:
3192       GDK_NOTE (EVENTS, g_print (" %s%s %p",
3193                                  (LOWORD (msg->wParam) == WA_ACTIVE ? "ACTIVE" :
3194                                   (LOWORD (msg->wParam) == WA_CLICKACTIVE ? "CLICKACTIVE" :
3195                                    (LOWORD (msg->wParam) == WA_INACTIVE ? "INACTIVE" : "???"))),
3196                                  HIWORD (msg->wParam) ? " minimized" : "",
3197                                  (HWND) msg->lParam));
3198       /* We handle mouse clicks for modally-blocked windows under WM_MOUSEACTIVATE,
3199        * but we still need to deal with alt-tab, or with SetActiveWindow() type
3200        * situations.
3201        */
3202       if (is_modally_blocked (window) && LOWORD (msg->wParam) == WA_ACTIVE)
3203         {
3204           GdkWindow *modal_current = _gdk_modal_current ();
3205           SetActiveWindow (GDK_WINDOW_HWND (modal_current));
3206           *ret_valp = 0;
3207           return_val = TRUE;
3208           break;
3209         }
3210
3211       /* Bring any tablet contexts to the top of the overlap order when
3212        * one of our windows is activated.
3213        * NOTE: It doesn't seem to work well if it is done in WM_ACTIVATEAPP
3214        * instead
3215        */
3216       if (LOWORD(msg->wParam) != WA_INACTIVE)
3217         _gdk_input_set_tablet_active ();
3218       break;
3219
3220     case WM_ACTIVATEAPP:
3221       GDK_NOTE (EVENTS, g_print (" %s thread: %I64d",
3222                                  msg->wParam ? "YES" : "NO",
3223                                  (gint64) msg->lParam));
3224       if (msg->wParam && GDK_WINDOW_IS_MAPPED (window))
3225         ensure_stacking_on_activate_app (msg, window);
3226       break;
3227
3228       /* Handle WINTAB events here, as we know that gdkinput.c will
3229        * use the fixed WT_DEFBASE as lcMsgBase, and we thus can use the
3230        * constants as case labels.
3231        */
3232     case WT_PACKET:
3233       GDK_NOTE (EVENTS, g_print (" %d %p",
3234                                  (int) msg->wParam, (gpointer) msg->lParam));
3235       goto wintab;
3236       
3237     case WT_CSRCHANGE:
3238       GDK_NOTE (EVENTS, g_print (" %d %p",
3239                                  (int) msg->wParam, (gpointer) msg->lParam));
3240       goto wintab;
3241       
3242     case WT_PROXIMITY:
3243       GDK_NOTE (EVENTS, g_print (" %p %d %d",
3244                                  (gpointer) msg->wParam,
3245                                  LOWORD (msg->lParam),
3246                                  HIWORD (msg->lParam)));
3247       /* Fall through */
3248     wintab:
3249
3250       event = gdk_event_new (GDK_NOTHING);
3251       event->any.window = window;
3252       g_object_ref (window);
3253
3254       if (_gdk_input_other_event (event, msg, window))
3255         append_event (event);
3256       else
3257         gdk_event_free (event);
3258
3259       break;
3260     }
3261
3262 done:
3263
3264   if (window)
3265     g_object_unref (window);
3266   
3267 #undef return
3268   return return_val;
3269 }
3270
3271 void
3272 _gdk_events_queue (GdkDisplay *display)
3273 {
3274   MSG msg;
3275
3276   if (modal_win32_dialog != NULL)
3277     return;
3278   
3279   while (!_gdk_event_queue_find_first (display) &&
3280          PeekMessageW (&msg, NULL, 0, 0, PM_REMOVE))
3281     {
3282       TranslateMessage (&msg);
3283       DispatchMessageW (&msg);
3284     }
3285 }
3286
3287 static gboolean
3288 gdk_event_prepare (GSource *source,
3289                    gint    *timeout)
3290 {
3291   MSG msg;
3292   gboolean retval;
3293
3294   GDK_THREADS_ENTER ();
3295
3296   *timeout = -1;
3297
3298   retval = (_gdk_event_queue_find_first (_gdk_display) != NULL ||
3299             (modal_win32_dialog == NULL &&
3300              PeekMessageW (&msg, NULL, 0, 0, PM_NOREMOVE)));
3301
3302   GDK_THREADS_LEAVE ();
3303
3304   return retval;
3305 }
3306
3307 static gboolean
3308 gdk_event_check (GSource *source)
3309 {
3310   MSG msg;
3311   gboolean retval;
3312   
3313   GDK_THREADS_ENTER ();
3314
3315   if (event_poll_fd.revents & G_IO_IN)
3316     {
3317       retval = (_gdk_event_queue_find_first (_gdk_display) != NULL ||
3318                 (modal_win32_dialog == NULL &&
3319                  PeekMessageW (&msg, NULL, 0, 0, PM_NOREMOVE)));
3320     }
3321   else
3322     {
3323       retval = FALSE;
3324     }
3325
3326   GDK_THREADS_LEAVE ();
3327
3328   return retval;
3329 }
3330
3331 static gboolean
3332 gdk_event_dispatch (GSource     *source,
3333                     GSourceFunc  callback,
3334                     gpointer     user_data)
3335 {
3336   GdkEvent *event;
3337  
3338   GDK_THREADS_ENTER ();
3339
3340   _gdk_events_queue (_gdk_display);
3341   event = _gdk_event_unqueue (_gdk_display);
3342
3343   if (event)
3344     {
3345       if (_gdk_event_func)
3346         (*_gdk_event_func) (event, _gdk_event_data);
3347       
3348       gdk_event_free (event);
3349     }
3350   
3351   GDK_THREADS_LEAVE ();
3352
3353   return TRUE;
3354 }
3355
3356 void
3357 gdk_win32_set_modal_dialog_libgtk_only (HWND window)
3358 {
3359   modal_win32_dialog = window;
3360 }
3361
3362 static gboolean
3363 is_modally_blocked (GdkWindow *window)
3364 {
3365   GdkWindow *modal_current = _gdk_modal_current ();
3366   return modal_current != NULL ? gdk_window_get_toplevel (window) != modal_current : FALSE;
3367 }
3368
3369 static void
3370 check_for_too_much_data (GdkEvent *event)
3371 {
3372   if (event->client.data.l[1] ||
3373       event->client.data.l[2] ||
3374       event->client.data.l[3] ||
3375       event->client.data.l[4])
3376     {
3377       g_warning ("Only four bytes of data are passed in client messages on Win32\n");
3378     }
3379 }
3380
3381 gboolean
3382 gdk_event_send_client_message_for_display (GdkDisplay     *display,
3383                                            GdkEvent       *event, 
3384                                            GdkNativeWindow winid)
3385 {
3386   check_for_too_much_data (event);
3387
3388   return PostMessageW ((HWND) winid, client_message,
3389                        (WPARAM) event->client.message_type,
3390                        event->client.data.l[0]);
3391 }
3392
3393 void
3394 gdk_screen_broadcast_client_message (GdkScreen *screen, 
3395                                      GdkEvent  *event)
3396 {
3397   check_for_too_much_data (event);
3398
3399   PostMessageW (HWND_BROADCAST, client_message,
3400                (WPARAM) event->client.message_type,
3401                 event->client.data.l[0]);
3402 }
3403
3404 void
3405 gdk_flush (void)
3406 {
3407 #if 0
3408   MSG msg;
3409
3410   /* Process all messages currently available */
3411   while (PeekMessageW (&msg, NULL, 0, 0, PM_REMOVE))
3412     {
3413       TranslateMessage (&msg);
3414       DispatchMessageW (&msg);
3415     }
3416 #endif
3417
3418   GdiFlush ();
3419 }
3420
3421 void
3422 gdk_display_sync (GdkDisplay * display)
3423 {
3424   MSG msg;
3425
3426   g_return_if_fail (display == _gdk_display);
3427
3428   /* Process all messages currently available */
3429   while (PeekMessageW (&msg, NULL, 0, 0, PM_REMOVE))
3430     DispatchMessageW (&msg);
3431 }
3432
3433 void
3434 gdk_display_flush (GdkDisplay * display)
3435 {
3436   g_return_if_fail (display == _gdk_display);
3437
3438   /* Nothing */
3439 }
3440
3441 gboolean
3442 gdk_net_wm_supports (GdkAtom property)
3443 {
3444   return FALSE;
3445 }
3446
3447 void
3448 _gdk_windowing_event_data_copy (const GdkEvent *src,
3449                                 GdkEvent       *dst)
3450 {
3451 }
3452
3453 void
3454 _gdk_windowing_event_data_free (GdkEvent *event)
3455 {
3456 }