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