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