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