]> Pileus Git - ~andy/gtk/blob - gdk/win32/gdkevents-win32.c
Just use TrackMouseEvent directly
[~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_NO_EXPOSE);
760     CASE (GDK_SCROLL);
761     CASE (GDK_WINDOW_STATE);
762     CASE (GDK_SETTING);
763     CASE (GDK_OWNER_CHANGE);
764     CASE (GDK_GRAB_BROKEN);
765 #undef CASE
766     default: g_assert_not_reached ();
767     }
768
769   g_print (" %p ", event->any.window ? GDK_WINDOW_HWND (event->any.window) : NULL);
770
771   switch (event->any.type)
772     {
773     case GDK_EXPOSE:
774       g_print ("%s %d",
775                _gdk_win32_gdkrectangle_to_string (&event->expose.area),
776                event->expose.count);
777       break;
778     case GDK_MOTION_NOTIFY:
779       g_print ("(%.4g,%.4g) (%.4g,%.4g) %s",
780                event->motion.x, event->motion.y,
781                event->motion.x_root, event->motion.y_root,
782                event->motion.is_hint ? "HINT " : "");
783       print_event_state (event->motion.state);
784       break;
785     case GDK_BUTTON_PRESS:
786     case GDK_2BUTTON_PRESS:
787     case GDK_3BUTTON_PRESS:
788     case GDK_BUTTON_RELEASE:
789       g_print ("%d (%.4g,%.4g) (%.4g,%.4g) ",
790                event->button.button,
791                event->button.x, event->button.y,
792                event->button.x_root, event->button.y_root);
793       print_event_state (event->button.state);
794       break;
795     case GDK_KEY_PRESS: 
796     case GDK_KEY_RELEASE:
797       if (event->key.length == 0)
798         escaped = g_strdup ("");
799       else
800         escaped = g_strescape (event->key.string, NULL);
801       kvname = gdk_keyval_name (event->key.keyval);
802       g_print ("%#.02x group:%d %s %d:\"%s\" ",
803                event->key.hardware_keycode, event->key.group,
804                (kvname ? kvname : "??"),
805                event->key.length,
806                escaped);
807       g_free (escaped);
808       print_event_state (event->key.state);
809       break;
810     case GDK_ENTER_NOTIFY:
811     case GDK_LEAVE_NOTIFY:
812       g_print ("%p (%.4g,%.4g) (%.4g,%.4g) %s %s%s",
813                event->crossing.subwindow == NULL ? NULL : GDK_WINDOW_HWND (event->crossing.subwindow),
814                event->crossing.x, event->crossing.y,
815                event->crossing.x_root, event->crossing.y_root,
816                (event->crossing.mode == GDK_CROSSING_NORMAL ? "NORMAL" :
817                 (event->crossing.mode == GDK_CROSSING_GRAB ? "GRAB" :
818                  (event->crossing.mode == GDK_CROSSING_UNGRAB ? "UNGRAB" :
819                   "???"))),
820                (event->crossing.detail == GDK_NOTIFY_ANCESTOR ? "ANCESTOR" :
821                 (event->crossing.detail == GDK_NOTIFY_VIRTUAL ? "VIRTUAL" :
822                  (event->crossing.detail == GDK_NOTIFY_INFERIOR ? "INFERIOR" :
823                   (event->crossing.detail == GDK_NOTIFY_NONLINEAR ? "NONLINEAR" :
824                    (event->crossing.detail == GDK_NOTIFY_NONLINEAR_VIRTUAL ? "NONLINEAR_VIRTUAL" :
825                     (event->crossing.detail == GDK_NOTIFY_UNKNOWN ? "UNKNOWN" :
826                      "???")))))),
827                event->crossing.focus ? " FOCUS" : "");
828       print_event_state (event->crossing.state);
829       break;
830     case GDK_FOCUS_CHANGE:
831       g_print ("%s", (event->focus_change.in ? "IN" : "OUT"));
832       break;
833     case GDK_CONFIGURE:
834       g_print ("x:%d y:%d w:%d h:%d",
835                event->configure.x, event->configure.y,
836                event->configure.width, event->configure.height);
837       break;
838     case GDK_SELECTION_CLEAR:
839     case GDK_SELECTION_REQUEST:
840     case GDK_SELECTION_NOTIFY:
841       selection_name = gdk_atom_name (event->selection.selection);
842       target_name = gdk_atom_name (event->selection.target);
843       property_name = gdk_atom_name (event->selection.property);
844       g_print ("sel:%s tgt:%s prop:%s",
845                selection_name, target_name, property_name);
846       g_free (selection_name);
847       g_free (target_name);
848       g_free (property_name);
849       break;
850     case GDK_DRAG_ENTER:
851     case GDK_DRAG_LEAVE:
852     case GDK_DRAG_MOTION:
853     case GDK_DRAG_STATUS:
854     case GDK_DROP_START:
855     case GDK_DROP_FINISHED:
856       if (event->dnd.context != NULL)
857         g_print ("ctx:%p: %s %s src:%p dest:%p",
858                  event->dnd.context,
859                  _gdk_win32_drag_protocol_to_string (event->dnd.context->protocol),
860                  event->dnd.context->is_source ? "SOURCE" : "DEST",
861                  event->dnd.context->source_window == NULL ? NULL : GDK_WINDOW_HWND (event->dnd.context->source_window),
862                  event->dnd.context->dest_window == NULL ? NULL : GDK_WINDOW_HWND (event->dnd.context->dest_window));
863       break;
864     case GDK_CLIENT_EVENT:
865       g_print ("%s %d %ld %ld %ld %ld %ld",
866                gdk_atom_name (event->client.message_type),
867                event->client.data_format,
868                event->client.data.l[0],
869                event->client.data.l[1],
870                event->client.data.l[2],
871                event->client.data.l[3],
872                event->client.data.l[4]);
873       break;
874     case GDK_SCROLL:
875       g_print ("(%.4g,%.4g) (%.4g,%.4g) %s ",
876                event->scroll.x, event->scroll.y,
877                event->scroll.x_root, event->scroll.y_root,
878                (event->scroll.direction == GDK_SCROLL_UP ? "UP" :
879                 (event->scroll.direction == GDK_SCROLL_DOWN ? "DOWN" :
880                  (event->scroll.direction == GDK_SCROLL_LEFT ? "LEFT" :
881                   (event->scroll.direction == GDK_SCROLL_RIGHT ? "RIGHT" :
882                    "???")))));
883       print_event_state (event->scroll.state);
884       break;
885     case GDK_WINDOW_STATE:
886       g_print ("%s: %s",
887                _gdk_win32_window_state_to_string (event->window_state.changed_mask),
888                _gdk_win32_window_state_to_string (event->window_state.new_window_state));
889     case GDK_SETTING:
890       g_print ("%s: %s",
891                (event->setting.action == GDK_SETTING_ACTION_NEW ? "NEW" :
892                 (event->setting.action == GDK_SETTING_ACTION_CHANGED ? "CHANGED" :
893                  (event->setting.action == GDK_SETTING_ACTION_DELETED ? "DELETED" :
894                   "???"))),
895                (event->setting.name ? event->setting.name : "NULL"));
896     case GDK_GRAB_BROKEN:
897       g_print ("%s %s %p",
898                (event->grab_broken.keyboard ? "KEYBOARD" : "POINTER"),
899                (event->grab_broken.implicit ? "IMPLICIT" : "EXPLICIT"),
900                (event->grab_broken.grab_window ? GDK_WINDOW_HWND (event->grab_broken.grab_window) : 0));
901     default:
902       /* Nothing */
903       break;
904     }  
905   g_print ("%s", (debug_indent == 0 ? "\n" : "")); 
906 }
907
908 static char *
909 decode_key_lparam (LPARAM lParam)
910 {
911   static char buf[100];
912   char *p = buf;
913
914   if (HIWORD (lParam) & KF_UP)
915     p += g_sprintf (p, "KF_UP ");
916   if (HIWORD (lParam) & KF_REPEAT)
917     p += g_sprintf (p, "KF_REPEAT ");
918   if (HIWORD (lParam) & KF_ALTDOWN)
919     p += g_sprintf (p, "KF_ALTDOWN ");
920   if (HIWORD (lParam) & KF_EXTENDED)
921     p += g_sprintf (p, "KF_EXTENDED ");
922   p += g_sprintf (p, "sc:%d rep:%d", LOBYTE (HIWORD (lParam)), LOWORD (lParam));
923
924   return buf;
925 }
926
927 #endif
928
929 static void
930 fixup_event (GdkEvent *event)
931 {
932   if (event->any.window)
933     g_object_ref (event->any.window);
934   if (((event->any.type == GDK_ENTER_NOTIFY) ||
935        (event->any.type == GDK_LEAVE_NOTIFY)) &&
936       (event->crossing.subwindow != NULL))
937     g_object_ref (event->crossing.subwindow);
938   event->any.send_event = InSendMessage (); 
939 }
940
941 static void
942 append_event (GdkEvent *event)
943 {
944   GList *link;
945   
946   fixup_event (event);
947 #if 1
948   link = _gdk_event_queue_append (_gdk_display, event);
949   GDK_NOTE (EVENTS, _gdk_win32_print_event (event));
950   /* event morphing, the passed in may not be valid afterwards */
951   _gdk_windowing_got_event (_gdk_display, link, event, 0);
952 #else
953   _gdk_event_queue_append (_gdk_display, event);
954   GDK_NOTE (EVENTS, _gdk_win32_print_event (event));
955 #endif
956 }
957
958 static void
959 fill_key_event_string (GdkEvent *event)
960 {
961   gunichar c;
962   gchar buf[256];
963
964   /* Fill in event->string crudely, since various programs
965    * depend on it.
966    */
967   
968   c = 0;
969   if (event->key.keyval != GDK_VoidSymbol)
970     c = gdk_keyval_to_unicode (event->key.keyval);
971
972   if (c)
973     {
974       gsize bytes_written;
975       gint len;
976       
977       /* Apply the control key - Taken from Xlib
978        */
979       if (event->key.state & GDK_CONTROL_MASK)
980         {
981           if ((c >= '@' && c < '\177') || c == ' ')
982             c &= 0x1F;
983           else if (c == '2')
984             {
985               event->key.string = g_memdup ("\0\0", 2);
986               event->key.length = 1;
987               return;
988             }
989           else if (c >= '3' && c <= '7')
990             c -= ('3' - '\033');
991           else if (c == '8')
992             c = '\177';
993           else if (c == '/')
994             c = '_' & 0x1F;
995         }
996       
997       len = g_unichar_to_utf8 (c, buf);
998       buf[len] = '\0';
999           
1000       event->key.string = g_locale_from_utf8 (buf, len,
1001                                               NULL, &bytes_written,
1002                                               NULL);
1003       if (event->key.string)
1004         event->key.length = bytes_written;
1005     }
1006   else if (event->key.keyval == GDK_Escape)
1007     {
1008       event->key.length = 1;
1009       event->key.string = g_strdup ("\033");
1010     }
1011   else if (event->key.keyval == GDK_Return ||
1012            event->key.keyval == GDK_KP_Enter)
1013     {
1014       event->key.length = 1;
1015       event->key.string = g_strdup ("\r");
1016     }
1017   
1018   if (!event->key.string)
1019     {
1020       event->key.length = 0;
1021       event->key.string = g_strdup ("");
1022     }
1023 }
1024
1025 static GdkFilterReturn
1026 apply_event_filters (GdkWindow  *window,
1027                      MSG        *msg,
1028                      GList      *filters)
1029 {
1030   GdkFilterReturn result = GDK_FILTER_CONTINUE;
1031   GdkEvent *event;
1032   GList *node;
1033   GList *tmp_list;
1034
1035   event = gdk_event_new (GDK_NOTHING);
1036   if (window != NULL)
1037     event->any.window = g_object_ref (window);
1038   ((GdkEventPrivate *)event)->flags |= GDK_EVENT_PENDING;
1039
1040   /* I think GdkFilterFunc semantics require the passed-in event
1041    * to already be in the queue. The filter func can generate
1042    * more events and append them after it if it likes.
1043    */
1044   node = _gdk_event_queue_append (_gdk_display, event);
1045   
1046   tmp_list = filters;
1047   while (tmp_list)
1048     {
1049       GdkEventFilter *filter = (GdkEventFilter *) tmp_list->data;
1050       
1051       tmp_list = tmp_list->next;
1052       result = filter->function (msg, event, filter->data);
1053       if (result !=  GDK_FILTER_CONTINUE)
1054         break;
1055     }
1056
1057   if (result == GDK_FILTER_CONTINUE || result == GDK_FILTER_REMOVE)
1058     {
1059       _gdk_event_queue_remove_link (_gdk_display, node);
1060       g_list_free_1 (node);
1061       gdk_event_free (event);
1062     }
1063   else /* GDK_FILTER_TRANSLATE */
1064     {
1065       ((GdkEventPrivate *)event)->flags &= ~GDK_EVENT_PENDING;
1066       fixup_event (event);
1067       GDK_NOTE (EVENTS, _gdk_win32_print_event (event));
1068     }
1069   return result;
1070 }
1071
1072 /*
1073  * On Windows, transient windows will not have their own taskbar entries.
1074  * Because of this, we must hide and restore groups of transients in both
1075  * directions.  That is, all transient children must be hidden or restored
1076  * with this window, but if this window's transient owner also has a
1077  * transient owner then this window's transient owner must be hidden/restored
1078  * with this one.  And etc, up the chain until we hit an ancestor that has no
1079  * transient owner.
1080  *
1081  * It would be a good idea if applications don't chain transient windows
1082  * together.  There's a limit to how much evil GTK can try to shield you
1083  * from.
1084  */
1085 static void
1086 show_window_recurse (GdkWindow *window, gboolean hide_window)
1087 {
1088   GdkWindowImplWin32 *impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (window)->impl);
1089   GSList *children = impl->transient_children;
1090   GdkWindow *child = NULL;
1091
1092   if (!impl->changing_state)
1093     {
1094       impl->changing_state = TRUE;
1095
1096       if (children != NULL)
1097         {
1098           while (children != NULL)
1099             {
1100               child = children->data;
1101               show_window_recurse (child, hide_window);
1102
1103               children = g_slist_next (children);
1104             }
1105         }
1106
1107       if (GDK_WINDOW_IS_MAPPED (window))
1108         {
1109           if (!hide_window)
1110             {
1111               if (GDK_WINDOW_OBJECT (window)->state & GDK_WINDOW_STATE_ICONIFIED)
1112                 {
1113                   if (GDK_WINDOW_OBJECT (window)->state & GDK_WINDOW_STATE_MAXIMIZED)
1114                     {
1115                       ShowWindow (GDK_WINDOW_HWND (window), SW_SHOWMAXIMIZED);
1116                     }
1117                   else
1118                     {
1119                       ShowWindow (GDK_WINDOW_HWND (window), SW_RESTORE);
1120                     }
1121                 }
1122             }
1123           else
1124             {
1125               ShowWindow (GDK_WINDOW_HWND (window), SW_MINIMIZE);
1126             }
1127         }
1128
1129       impl->changing_state = FALSE;
1130     }
1131 }
1132
1133 static void
1134 do_show_window (GdkWindow *window, gboolean hide_window)
1135 {
1136   GdkWindow *tmp_window = NULL;
1137   GdkWindowImplWin32 *tmp_impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (window)->impl);
1138
1139   if (!tmp_impl->changing_state)
1140     {
1141       /* Find the top-level window in our transient chain. */
1142       while (tmp_impl->transient_owner != NULL)
1143         {
1144           tmp_window = tmp_impl->transient_owner;
1145           tmp_impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (tmp_window)->impl);
1146         }
1147
1148       /* If we couldn't find one, use the window provided. */
1149       if (tmp_window == NULL)
1150         {
1151           tmp_window = window;
1152         }
1153
1154       /* Recursively show/hide every window in the chain. */
1155       if (tmp_window != window)
1156         {
1157           show_window_recurse (tmp_window, hide_window);
1158         }
1159     }
1160 }
1161
1162 static void
1163 synthesize_enter_or_leave_event (GdkWindow        *window,
1164                                  MSG              *msg,
1165                                  GdkEventType      type,
1166                                  GdkCrossingMode   mode,
1167                                  GdkNotifyType     detail)
1168 {
1169   GdkEvent *event;
1170   POINT pt;
1171
1172   pt = msg->pt;
1173   ScreenToClient (GDK_WINDOW_HWND (window), &pt);
1174   
1175   event = gdk_event_new (type);
1176   event->crossing.window = window;
1177   event->crossing.subwindow = NULL;
1178   event->crossing.time = _gdk_win32_get_next_tick (msg->time);
1179   event->crossing.x = pt.x;
1180   event->crossing.y = pt.y;
1181   event->crossing.x_root = msg->pt.x + _gdk_offset_x;
1182   event->crossing.y_root = msg->pt.y + _gdk_offset_y;
1183   event->crossing.mode = mode;
1184   event->crossing.detail = detail;
1185   event->crossing.focus = TRUE; /* FIXME: Set correctly */
1186   event->crossing.state = 0;    /* FIXME: Set correctly */
1187   gdk_event_set_device (event, _gdk_display->core_pointer);
1188
1189   append_event (event);
1190   
1191   if (type == GDK_ENTER_NOTIFY &&
1192       ((GdkWindowObject *) window)->extension_events != 0)
1193     _gdk_device_wintab_update_window_coords (window);
1194 }
1195                          
1196 static void
1197 synthesize_expose_events (GdkWindow *window)
1198 {
1199   RECT r;
1200   HDC hdc;
1201   GdkDrawableImplWin32 *impl = GDK_DRAWABLE_IMPL_WIN32 (((GdkWindowObject *) window)->impl);
1202   GList *list = gdk_window_get_children (window);
1203   GList *head = list;
1204   GdkEvent *event;
1205   int k;
1206   
1207   while (list)
1208     {
1209       synthesize_expose_events ((GdkWindow *) list->data);
1210       list = list->next;
1211     }
1212
1213   g_list_free (head);
1214
1215   if (((GdkWindowObject *) window)->input_only)
1216     ;
1217   else if (!(hdc = GetDC (impl->handle)))
1218     WIN32_GDI_FAILED ("GetDC");
1219   else
1220     {
1221       if ((k = GetClipBox (hdc, &r)) == ERROR)
1222         WIN32_GDI_FAILED ("GetClipBox");
1223       else if (k != NULLREGION)
1224         {
1225           event = gdk_event_new (GDK_EXPOSE);
1226           event->expose.window = window;
1227           event->expose.area.x = r.left;
1228           event->expose.area.y = r.top;
1229           event->expose.area.width = r.right - r.left;
1230           event->expose.area.height = r.bottom - r.top;
1231           event->expose.region = cairo_region_create_rectangle (&(event->expose.area));
1232           event->expose.count = 0;
1233   
1234           append_event (event);
1235         }
1236       GDI_CALL (ReleaseDC, (impl->handle, hdc));
1237     }
1238 }
1239
1240 static void
1241 update_colors (GdkWindow *window,
1242                gboolean   top)
1243 {
1244   HDC hdc;
1245   GdkDrawableImplWin32 *impl = GDK_DRAWABLE_IMPL_WIN32 (((GdkWindowObject *) window)->impl);
1246   GList *list = gdk_window_get_children (window);
1247   GList *head = list;
1248
1249   GDK_NOTE (COLORMAP, (top ? g_print ("update_colors:") : (void) 0));
1250
1251   while (list)
1252     {
1253       update_colors ((GdkWindow *) list->data, FALSE);
1254       list = list->next;
1255     }
1256   g_list_free (head);
1257
1258   if (((GdkWindowObject *) window)->input_only ||
1259       impl->colormap == NULL)
1260     return;
1261
1262   if (!(hdc = GetDC (impl->handle)))
1263     WIN32_GDI_FAILED ("GetDC");
1264   else
1265     {
1266       GdkColormapPrivateWin32 *cmapp = GDK_WIN32_COLORMAP_DATA (impl->colormap);
1267       HPALETTE holdpal;
1268       gint k;
1269       
1270       if ((holdpal = SelectPalette (hdc, cmapp->hpal, TRUE)) == NULL)
1271         WIN32_GDI_FAILED ("SelectPalette");
1272       else if ((k = RealizePalette (hdc)) == GDI_ERROR)
1273         WIN32_GDI_FAILED ("RealizePalette");
1274       else
1275         {
1276           GDK_NOTE (COLORMAP,
1277                     (k > 0 ?
1278                      g_print (" %p pal=%p: realized %d colors\n"
1279                               "update_colors:",
1280                               impl->handle, cmapp->hpal, k) :
1281                      (void) 0,
1282                      g_print (" %p", impl->handle)));
1283           GDI_CALL (UpdateColors, (hdc));
1284           SelectPalette (hdc, holdpal, TRUE);
1285           RealizePalette (hdc);
1286         }
1287       GDI_CALL (ReleaseDC, (impl->handle, hdc));
1288     }
1289   GDK_NOTE (COLORMAP, (top ? g_print ("\n") : (void) 0));
1290 }
1291
1292 /* The check_extended flag controls whether to check if the windows want
1293  * events from extended input devices and if the message should be skipped
1294  * because an extended input device is active
1295  */
1296 static gboolean
1297 propagate (GdkWindow  **window,
1298            MSG         *msg,
1299            GdkWindow   *grab_window,
1300            gboolean     grab_owner_events,
1301            gint         grab_mask,
1302            gboolean   (*doesnt_want_it) (gint mask,
1303                                          MSG *msg),
1304            gboolean     check_extended)
1305 {
1306   if (grab_window != NULL && !grab_owner_events)
1307     {
1308       /* Event source is grabbed with owner_events FALSE */
1309
1310       /* See if the event should be ignored because an extended input
1311        * device is used
1312        */
1313       if (check_extended &&
1314           ((GdkWindowObject *) grab_window)->extension_events != 0 &&
1315           _gdk_input_ignore_core)
1316         {
1317           GDK_NOTE (EVENTS, g_print (" (ignored for grabber)"));
1318           return FALSE;
1319         }
1320       if ((*doesnt_want_it) (grab_mask, msg))
1321         {
1322           GDK_NOTE (EVENTS, g_print (" (grabber doesn't want it)"));
1323           return FALSE;
1324         }
1325       else
1326         {
1327           GDK_NOTE (EVENTS, g_print (" (to grabber)"));
1328           assign_object (window, grab_window);
1329           return TRUE;
1330         }
1331     }
1332
1333   /* If we come here, we know that if grab_window != NULL then
1334    * grab_owner_events is TRUE
1335    */
1336   while (TRUE)
1337     {
1338       if (check_extended &&
1339           ((GdkWindowObject *) *window)->extension_events != 0 &&
1340           _gdk_input_ignore_core)
1341         {
1342           GDK_NOTE (EVENTS, g_print (" (ignored)"));
1343           return FALSE;
1344         }
1345       if ((*doesnt_want_it) (((GdkWindowObject *) *window)->event_mask, msg))
1346         {
1347           /* Owner doesn't want it, propagate to parent. */
1348           GdkWindow *parent = gdk_window_get_parent (*window);
1349           if (parent == _gdk_root || parent == NULL)
1350             {
1351               /* No parent; check if grabbed */
1352               if (grab_window != NULL)
1353                 {
1354                   /* Event source is grabbed with owner_events TRUE */
1355
1356                   if (check_extended &&
1357                       ((GdkWindowObject *) grab_window)->extension_events != 0 &&
1358                       _gdk_input_ignore_core)
1359                     {
1360                       GDK_NOTE (EVENTS, g_print (" (ignored for grabber)"));
1361                       return FALSE;
1362                     }
1363                   if ((*doesnt_want_it) (grab_mask, msg))
1364                     {
1365                       /* Grabber doesn't want it either */
1366                       GDK_NOTE (EVENTS, g_print (" (grabber doesn't want it)"));
1367                       return FALSE;
1368                     }
1369                   else
1370                     {
1371                       /* Grabbed! */
1372                       GDK_NOTE (EVENTS, g_print (" (to grabber)"));
1373                       assign_object (window, grab_window);
1374                       return TRUE;
1375                     }
1376                 }
1377               else
1378                 {
1379                   GDK_NOTE (EVENTS, g_print (" (undelivered)"));
1380                   return FALSE;
1381                 }
1382             }
1383           else
1384             {
1385               assign_object (window, parent);
1386               /* The only branch where we actually continue the loop */
1387             }
1388         }
1389       else
1390         return TRUE;
1391     }
1392 }
1393
1394 static gboolean
1395 doesnt_want_key (gint mask,
1396                  MSG *msg)
1397 {
1398   return (((msg->message == WM_KEYUP || msg->message == WM_SYSKEYUP) &&
1399            !(mask & GDK_KEY_RELEASE_MASK)) ||
1400           ((msg->message == WM_KEYDOWN || msg->message == WM_SYSKEYDOWN) &&
1401            !(mask & GDK_KEY_PRESS_MASK)));
1402 }
1403
1404 static gboolean
1405 doesnt_want_char (gint mask,
1406                   MSG *msg)
1407 {
1408   return !(mask & (GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK));
1409 }
1410
1411 static void
1412 handle_configure_event (MSG       *msg,
1413                         GdkWindow *window)
1414 {
1415   RECT client_rect;
1416   POINT point;
1417   GdkWindowObject *window_object;
1418
1419   GetClientRect (msg->hwnd, &client_rect);
1420   point.x = client_rect.left; /* always 0 */
1421   point.y = client_rect.top;
1422
1423   /* top level windows need screen coords */
1424   if (gdk_window_get_parent (window) == _gdk_root)
1425     {
1426       ClientToScreen (msg->hwnd, &point);
1427       point.x += _gdk_offset_x;
1428       point.y += _gdk_offset_y;
1429     }
1430
1431   window_object = GDK_WINDOW_OBJECT (window);
1432
1433   window_object->width = client_rect.right - client_rect.left;
1434   window_object->height = client_rect.bottom - client_rect.top;
1435   
1436   window_object->x = point.x;
1437   window_object->y = point.y;
1438
1439   _gdk_window_update_size (window);
1440   
1441   if (window_object->event_mask & GDK_STRUCTURE_MASK)
1442     {
1443       GdkEvent *event = gdk_event_new (GDK_CONFIGURE);
1444
1445       event->configure.window = window;
1446
1447       event->configure.width = client_rect.right - client_rect.left;
1448       event->configure.height = client_rect.bottom - client_rect.top;
1449       
1450       event->configure.x = point.x;
1451       event->configure.y = point.y;
1452
1453       append_event (event);
1454     }
1455 }
1456
1457 cairo_region_t *
1458 _gdk_win32_hrgn_to_region (HRGN hrgn)
1459 {
1460   RGNDATA *rgndata;
1461   RECT *rects;
1462   cairo_region_t *result;
1463   gint nbytes;
1464   guint i;
1465
1466   if ((nbytes = GetRegionData (hrgn, 0, NULL)) == 0)
1467     {
1468       WIN32_GDI_FAILED ("GetRegionData");
1469       return NULL;
1470     }
1471
1472   rgndata = (RGNDATA *) g_malloc (nbytes);
1473
1474   if (GetRegionData (hrgn, nbytes, rgndata) == 0)
1475     {
1476       WIN32_GDI_FAILED ("GetRegionData");
1477       g_free (rgndata);
1478       return NULL;
1479     }
1480
1481   result = cairo_region_create ();
1482   rects = (RECT *) rgndata->Buffer;
1483   for (i = 0; i < rgndata->rdh.nCount; i++)
1484     {
1485       GdkRectangle r;
1486
1487       r.x = rects[i].left;
1488       r.y = rects[i].top;
1489       r.width = rects[i].right - r.x;
1490       r.height = rects[i].bottom - r.y;
1491
1492       cairo_region_union_rectangle (result, &r);
1493     }
1494
1495   g_free (rgndata);
1496
1497   return result;
1498 }
1499
1500 static void
1501 adjust_drag (LONG *drag,
1502              LONG  curr,
1503              gint  inc)
1504 {
1505   if (*drag > curr)
1506     *drag = curr + ((*drag + inc/2 - curr) / inc) * inc;
1507   else
1508     *drag = curr - ((curr - *drag + inc/2) / inc) * inc;
1509 }
1510
1511 static void
1512 handle_wm_paint (MSG        *msg,
1513                  GdkWindow  *window,
1514                  gboolean    return_exposes,
1515                  GdkEvent  **event)
1516 {
1517   HRGN hrgn = CreateRectRgn (0, 0, 0, 0);
1518   HDC hdc;
1519   PAINTSTRUCT paintstruct;
1520   cairo_region_t *update_region;
1521
1522   if (GetUpdateRgn (msg->hwnd, hrgn, FALSE) == ERROR)
1523     {
1524       WIN32_GDI_FAILED ("GetUpdateRgn");
1525       DeleteObject (hrgn);
1526       return;
1527     }
1528
1529   hdc = BeginPaint (msg->hwnd, &paintstruct);
1530
1531   GDK_NOTE (EVENTS, g_print (" %s %s dc %p%s",
1532                              _gdk_win32_rect_to_string (&paintstruct.rcPaint),
1533                              (paintstruct.fErase ? "erase" : ""),
1534                              hdc,
1535                              (return_exposes ? " return_exposes" : "")));
1536
1537   EndPaint (msg->hwnd, &paintstruct);
1538
1539   if ((paintstruct.rcPaint.right == paintstruct.rcPaint.left) ||
1540       (paintstruct.rcPaint.bottom == paintstruct.rcPaint.top))
1541     {
1542       GDK_NOTE (EVENTS, g_print (" (empty paintstruct, ignored)"));
1543       DeleteObject (hrgn);
1544       return;
1545     }
1546
1547   if (return_exposes)
1548     {
1549       if (!GDK_WINDOW_DESTROYED (window))
1550         {
1551           GList *list = _gdk_display->queued_events;
1552
1553           *event = gdk_event_new (GDK_EXPOSE);
1554           (*event)->expose.window = window;
1555           (*event)->expose.area.x = paintstruct.rcPaint.left;
1556           (*event)->expose.area.y = paintstruct.rcPaint.top;
1557           (*event)->expose.area.width = paintstruct.rcPaint.right - paintstruct.rcPaint.left;
1558           (*event)->expose.area.height = paintstruct.rcPaint.bottom - paintstruct.rcPaint.top;
1559           (*event)->expose.region = _gdk_win32_hrgn_to_region (hrgn);
1560           (*event)->expose.count = 0;
1561
1562           while (list != NULL)
1563             {
1564               GdkEventPrivate *evp = list->data;
1565
1566               if (evp->event.any.type == GDK_EXPOSE &&
1567                   evp->event.any.window == window &&
1568                   !(evp->flags & GDK_EVENT_PENDING))
1569                 evp->event.expose.count++;
1570
1571               list = list->next;
1572             }
1573         }
1574
1575       DeleteObject (hrgn);
1576       return;
1577     }
1578
1579   update_region = _gdk_win32_hrgn_to_region (hrgn);
1580   if (!cairo_region_is_empty (update_region))
1581     _gdk_window_invalidate_for_expose (window, update_region);
1582   cairo_region_destroy (update_region);
1583
1584   DeleteObject (hrgn);
1585 }
1586
1587 static VOID CALLBACK 
1588 modal_timer_proc (HWND     hwnd,
1589                   UINT     msg,
1590                   UINT_PTR id,
1591                   DWORD    time)
1592 {
1593   int arbitrary_limit = 1;
1594
1595   while (_modal_operation_in_progress &&
1596          g_main_context_pending (NULL) &&
1597          arbitrary_limit--)
1598     g_main_context_iteration (NULL, FALSE);
1599 }
1600
1601 void
1602 _gdk_win32_begin_modal_call (void)
1603 {
1604   g_assert (!_modal_operation_in_progress);
1605
1606   _modal_operation_in_progress = TRUE;
1607
1608   modal_timer = SetTimer (NULL, 0, 10, modal_timer_proc);
1609   if (modal_timer == 0)
1610     WIN32_API_FAILED ("SetTimer");
1611 }
1612
1613 void
1614 _gdk_win32_end_modal_call (void)
1615 {
1616   g_assert (_modal_operation_in_progress);
1617
1618   _modal_operation_in_progress = FALSE;
1619
1620   if (modal_timer != 0)
1621     {
1622       API_CALL (KillTimer, (NULL, modal_timer));
1623       modal_timer = 0;
1624    }
1625 }
1626
1627 static VOID CALLBACK
1628 sync_timer_proc (HWND     hwnd,
1629                  UINT     msg,
1630                  UINT_PTR id,
1631                  DWORD    time)
1632 {
1633   MSG message;
1634   if (PeekMessageW (&message, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
1635     {
1636       return;
1637     }
1638
1639   RedrawWindow (hwnd, NULL, NULL, RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
1640
1641   KillTimer (hwnd, sync_timer);
1642 }
1643
1644 static void
1645 handle_display_change (void)
1646 {
1647   _gdk_monitor_init ();
1648   _gdk_root_window_size_init ();
1649   g_signal_emit_by_name (_gdk_screen, "size_changed");
1650 }
1651
1652 static void
1653 generate_button_event (GdkEventType      type,
1654                        gint              button,
1655                        GdkWindow        *window,
1656                        MSG              *msg)
1657 {
1658   GdkEvent *event = gdk_event_new (type);
1659
1660   event->button.window = window;
1661   event->button.time = _gdk_win32_get_next_tick (msg->time);
1662   event->button.x = current_x = (gint16) GET_X_LPARAM (msg->lParam);
1663   event->button.y = current_y = (gint16) GET_Y_LPARAM (msg->lParam);
1664   event->button.x_root = msg->pt.x + _gdk_offset_x;
1665   event->button.y_root = msg->pt.y + _gdk_offset_y;
1666   event->button.axes = NULL;
1667   event->button.state = build_pointer_event_state (msg);
1668   event->button.button = button;
1669   gdk_event_set_device (event, _gdk_display->core_pointer);
1670
1671   append_event (event);
1672 }
1673
1674 static void
1675 ensure_stacking_on_unminimize (MSG *msg)
1676 {
1677   HWND rover;
1678   HWND lowest_transient = NULL;
1679
1680   rover = msg->hwnd;
1681   while ((rover = GetNextWindow (rover, GW_HWNDNEXT)))
1682     {
1683       GdkWindow *rover_gdkw = gdk_win32_handle_table_lookup (rover);
1684
1685       /* Checking window group not implemented yet */
1686       if (rover_gdkw)
1687         {
1688           GdkWindowImplWin32 *rover_impl =
1689             (GdkWindowImplWin32 *)((GdkWindowObject *)rover_gdkw)->impl;
1690
1691           if (GDK_WINDOW_IS_MAPPED (rover_gdkw) &&
1692               (rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_UTILITY ||
1693                rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_DIALOG ||
1694                rover_impl->transient_owner != NULL))
1695             {
1696               lowest_transient = rover;
1697             }
1698         }
1699     }
1700   if (lowest_transient != NULL)
1701     {
1702       GDK_NOTE (EVENTS, g_print (" restacking: %p", lowest_transient));
1703       SetWindowPos (msg->hwnd, lowest_transient, 0, 0, 0, 0,
1704                     SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1705     }
1706 }
1707
1708 static gboolean
1709 ensure_stacking_on_window_pos_changing (MSG       *msg,
1710                                         GdkWindow *window)
1711 {
1712   GdkWindowImplWin32 *impl = (GdkWindowImplWin32 *)((GdkWindowObject *) window)->impl;
1713   WINDOWPOS *windowpos = (WINDOWPOS *) msg->lParam;
1714
1715   if (GetActiveWindow () == msg->hwnd &&
1716       impl->type_hint != GDK_WINDOW_TYPE_HINT_UTILITY &&
1717       impl->type_hint != GDK_WINDOW_TYPE_HINT_DIALOG &&
1718       impl->transient_owner == NULL)
1719     {
1720       /* Make sure the window stays behind any transient-type windows
1721        * of the same window group.
1722        *
1723        * If the window is not active and being activated, we let
1724        * Windows bring it to the top and rely on the WM_ACTIVATEAPP
1725        * handling to bring any utility windows on top of it.
1726        */
1727       HWND rover;
1728       gboolean restacking;
1729
1730       rover = windowpos->hwndInsertAfter;
1731       restacking = FALSE;
1732       while (rover)
1733         {
1734           GdkWindow *rover_gdkw = gdk_win32_handle_table_lookup (rover);
1735
1736           /* Checking window group not implemented yet */
1737           if (rover_gdkw)
1738             {
1739               GdkWindowImplWin32 *rover_impl =
1740                 (GdkWindowImplWin32 *)((GdkWindowObject *)rover_gdkw)->impl;
1741
1742               if (GDK_WINDOW_IS_MAPPED (rover_gdkw) &&
1743                   (rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_UTILITY ||
1744                    rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_DIALOG ||
1745                    rover_impl->transient_owner != NULL))
1746                 {
1747                   restacking = TRUE;
1748                   windowpos->hwndInsertAfter = rover;
1749                 }
1750             }
1751           rover = GetNextWindow (rover, GW_HWNDNEXT);
1752         }
1753
1754       if (restacking)
1755         {
1756           GDK_NOTE (EVENTS, g_print (" restacking: %p", windowpos->hwndInsertAfter));
1757           return TRUE;
1758         }
1759     }
1760   return FALSE;
1761 }
1762
1763 static void
1764 ensure_stacking_on_activate_app (MSG       *msg,
1765                                  GdkWindow *window)
1766 {
1767   GdkWindowImplWin32 *impl = (GdkWindowImplWin32 *)((GdkWindowObject *) window)->impl;
1768
1769   if (impl->type_hint == GDK_WINDOW_TYPE_HINT_UTILITY ||
1770       impl->type_hint == GDK_WINDOW_TYPE_HINT_DIALOG ||
1771       impl->transient_owner != NULL)
1772     {
1773       SetWindowPos (msg->hwnd, HWND_TOP, 0, 0, 0, 0,
1774                     SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1775       return;
1776     }
1777
1778   if (IsWindowVisible (msg->hwnd) &&
1779       msg->hwnd == GetActiveWindow ())
1780     {
1781       /* This window is not a transient-type window and it is the
1782        * activated window. Make sure this window is as visible as
1783        * possible, just below the lowest transient-type window of this
1784        * app.
1785        */
1786       HWND rover;
1787
1788       rover = msg->hwnd;
1789       while ((rover = GetNextWindow (rover, GW_HWNDPREV)))
1790         {
1791           GdkWindow *rover_gdkw = gdk_win32_handle_table_lookup (rover);
1792
1793           /* Checking window group not implemented yet */
1794           if (rover_gdkw)
1795             {
1796               GdkWindowImplWin32 *rover_impl =
1797                 (GdkWindowImplWin32 *)((GdkWindowObject *)rover_gdkw)->impl;
1798
1799               if (GDK_WINDOW_IS_MAPPED (rover_gdkw) &&
1800                   (rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_UTILITY ||
1801                    rover_impl->type_hint == GDK_WINDOW_TYPE_HINT_DIALOG ||
1802                    rover_impl->transient_owner != NULL))
1803                 {
1804                   GDK_NOTE (EVENTS, g_print (" restacking: %p", rover));
1805                   SetWindowPos (msg->hwnd, rover, 0, 0, 0, 0,
1806                                 SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1807                   break;
1808                 }
1809             }
1810         }
1811     }
1812 }
1813
1814 static gboolean
1815 gdk_event_translate (MSG  *msg,
1816                      gint *ret_valp)
1817 {
1818   RECT rect, *drag, orig_drag;
1819   POINT point;
1820   MINMAXINFO *mmi;
1821   HWND hwnd;
1822   HCURSOR hcursor;
1823   BYTE key_state[256];
1824   HIMC himc;
1825   WINDOWPOS *windowpos;
1826
1827   GdkEvent *event;
1828
1829   wchar_t wbuf[100];
1830   gint ccount;
1831
1832   GdkWindow *window = NULL;
1833   GdkWindowImplWin32 *impl;
1834
1835   GdkWindow *orig_window, *new_window, *toplevel;
1836
1837   GdkDeviceManager *device_manager;
1838
1839   GdkDeviceGrabInfo *keyboard_grab = NULL;
1840   GdkDeviceGrabInfo *pointer_grab = NULL;
1841   GdkWindow *grab_window = NULL;
1842
1843   static gint update_colors_counter = 0;
1844   gint button;
1845   GdkAtom target;
1846
1847   gchar buf[256];
1848   gboolean return_val = FALSE;
1849
1850   int i;
1851
1852   if (_gdk_default_filters)
1853     {
1854       /* Apply global filters */
1855
1856       GdkFilterReturn result = apply_event_filters (NULL, msg, _gdk_default_filters);
1857       
1858       /* If result is GDK_FILTER_CONTINUE, we continue as if nothing
1859        * happened. If it is GDK_FILTER_REMOVE or GDK_FILTER_TRANSLATE,
1860        * we return TRUE, and DefWindowProcW() will not be called.
1861        */
1862       if (result == GDK_FILTER_REMOVE || result == GDK_FILTER_TRANSLATE)
1863         return TRUE;
1864     }
1865
1866   window = gdk_win32_handle_table_lookup ((GdkNativeWindow) msg->hwnd);
1867   orig_window = window;
1868
1869   if (window == NULL)
1870     {
1871       /* XXX Handle WM_QUIT here ? */
1872       if (msg->message == WM_QUIT)
1873         {
1874           GDK_NOTE (EVENTS, g_print (" %d", (int) msg->wParam));
1875           exit (msg->wParam);
1876         }
1877       else if (msg->message == WM_MOVE ||
1878                msg->message == WM_SIZE)
1879         {
1880           /* It's quite normal to get these messages before we have
1881            * had time to register the window in our lookup table, or
1882            * when the window is being destroyed and we already have
1883            * removed it. Repost the same message to our queue so that
1884            * we will get it later when we are prepared.
1885            */
1886           GDK_NOTE (EVENTS, g_print (" (posted)"));
1887         
1888           PostMessageW (msg->hwnd, msg->message, msg->wParam, msg->lParam);
1889         }
1890       else if (msg->message == WM_CREATE)
1891         {
1892           window = (UNALIGNED GdkWindow*) (((LPCREATESTRUCTW) msg->lParam)->lpCreateParams);
1893           GDK_WINDOW_HWND (window) = msg->hwnd;
1894         }
1895       else
1896         {
1897           GDK_NOTE (EVENTS, g_print (" (no GdkWindow)"));
1898         }
1899       return FALSE;
1900     }
1901
1902   device_manager = gdk_display_get_device_manager (_gdk_display);
1903
1904   keyboard_grab = _gdk_display_get_last_device_grab (_gdk_display,
1905                                                      GDK_DEVICE_MANAGER_WIN32 (device_manager)->core_keyboard);
1906   pointer_grab = _gdk_display_get_last_device_grab (_gdk_display,
1907                                                     GDK_DEVICE_MANAGER_WIN32 (device_manager)->core_pointer);
1908
1909   g_object_ref (window);
1910
1911   /* window's refcount has now been increased, so code below should
1912    * not just return from this function, but instead goto done (or
1913    * break out of the big switch). To protect against forgetting this,
1914    * #define return to a syntax error...
1915    */
1916 #define return GOTO_DONE_INSTEAD
1917   
1918   if (!GDK_WINDOW_DESTROYED (window) && ((GdkWindowObject *) window)->filters)
1919     {
1920       /* Apply per-window filters */
1921
1922       GdkFilterReturn result = apply_event_filters (window, msg, ((GdkWindowObject *) window)->filters);
1923
1924       if (result == GDK_FILTER_REMOVE || result == GDK_FILTER_TRANSLATE)
1925         {
1926           return_val = TRUE;
1927           goto done;
1928         }
1929     }
1930
1931   if (msg->message == client_message)
1932     {
1933       GList *tmp_list;
1934       GdkFilterReturn result = GDK_FILTER_CONTINUE;
1935       GList *node;
1936
1937       GDK_NOTE (EVENTS, g_print (" client_message"));
1938
1939       event = gdk_event_new (GDK_NOTHING);
1940       ((GdkEventPrivate *)event)->flags |= GDK_EVENT_PENDING;
1941
1942       node = _gdk_event_queue_append (_gdk_display, event);
1943
1944       tmp_list = client_filters;
1945       while (tmp_list)
1946         {
1947           GdkClientFilter *filter = tmp_list->data;
1948
1949           tmp_list = tmp_list->next;
1950
1951           if (filter->type == GDK_POINTER_TO_ATOM (msg->wParam))
1952             {
1953               GDK_NOTE (EVENTS, g_print (" (match)"));
1954
1955               result = (*filter->function) (msg, event, filter->data);
1956
1957               if (result != GDK_FILTER_CONTINUE)
1958                 break;
1959             }
1960         }
1961
1962       switch (result)
1963         {
1964         case GDK_FILTER_REMOVE:
1965           _gdk_event_queue_remove_link (_gdk_display, node);
1966           g_list_free_1 (node);
1967           gdk_event_free (event);
1968           return_val = TRUE;
1969           goto done;
1970
1971         case GDK_FILTER_TRANSLATE:
1972           ((GdkEventPrivate *)event)->flags &= ~GDK_EVENT_PENDING;
1973           GDK_NOTE (EVENTS, _gdk_win32_print_event (event));
1974           return_val = TRUE;
1975           goto done;
1976
1977         case GDK_FILTER_CONTINUE:
1978           /* Send unknown client messages on to Gtk for it to use */
1979
1980           event->client.type = GDK_CLIENT_EVENT;
1981           event->client.window = window;
1982           event->client.message_type = GDK_POINTER_TO_ATOM (msg->wParam);
1983           event->client.data_format = 32;
1984           event->client.data.l[0] = msg->lParam;
1985           for (i = 1; i < 5; i++)
1986             event->client.data.l[i] = 0;
1987           GDK_NOTE (EVENTS, _gdk_win32_print_event (event));
1988           return_val = TRUE;
1989           goto done;
1990         }
1991     }
1992
1993   switch (msg->message)
1994     {
1995     case WM_INPUTLANGCHANGE:
1996       _gdk_input_locale = (HKL) msg->lParam;
1997       _gdk_input_locale_is_ime = ImmIsIME (_gdk_input_locale);
1998       GetLocaleInfo (MAKELCID (LOWORD (_gdk_input_locale), SORT_DEFAULT),
1999                      LOCALE_IDEFAULTANSICODEPAGE,
2000                      buf, sizeof (buf));
2001       _gdk_input_codepage = atoi (buf);
2002       _gdk_keymap_serial++;
2003       GDK_NOTE (EVENTS,
2004                 g_print (" cs:%lu hkl:%p%s cp:%d",
2005                          (gulong) msg->wParam,
2006                          (gpointer) msg->lParam, _gdk_input_locale_is_ime ? " (IME)" : "",
2007                          _gdk_input_codepage));
2008       break;
2009
2010     case WM_SYSKEYUP:
2011     case WM_SYSKEYDOWN:
2012       GDK_NOTE (EVENTS,
2013                 g_print (" %s ch:%.02x %s",
2014                          _gdk_win32_key_to_string (msg->lParam),
2015                          (int) msg->wParam,
2016                          decode_key_lparam (msg->lParam)));
2017
2018       /* If posted without us having keyboard focus, ignore */
2019       if ((msg->wParam != VK_F10 && msg->wParam != VK_MENU) &&
2020           !(HIWORD (msg->lParam) & KF_ALTDOWN))
2021         break;
2022
2023       /* Let the system handle Alt-Tab, Alt-Space and Alt-F4 unless
2024        * the keyboard is grabbed.
2025        */
2026       if (!keyboard_grab &&
2027           (msg->wParam == VK_TAB ||
2028            msg->wParam == VK_SPACE ||
2029            msg->wParam == VK_F4))
2030         break;
2031
2032       /* Jump to code in common with WM_KEYUP and WM_KEYDOWN */
2033       goto keyup_or_down;
2034
2035     case WM_KEYUP:
2036     case WM_KEYDOWN:
2037       GDK_NOTE (EVENTS, 
2038                 g_print (" %s ch:%.02x %s",
2039                          _gdk_win32_key_to_string (msg->lParam),
2040                          (int) msg->wParam,
2041                          decode_key_lparam (msg->lParam)));
2042
2043     keyup_or_down:
2044
2045       /* Ignore key messages intended for the IME */
2046       if (msg->wParam == VK_PROCESSKEY ||
2047           in_ime_composition)
2048         break;
2049
2050       if (keyboard_grab &&
2051           !propagate (&window, msg,
2052                       keyboard_grab->window,
2053                       keyboard_grab->owner_events,
2054                       GDK_ALL_EVENTS_MASK,
2055                       doesnt_want_key, FALSE))
2056         break;
2057
2058       if (GDK_WINDOW_DESTROYED (window))
2059         break;
2060
2061       event = gdk_event_new ((msg->message == WM_KEYDOWN ||
2062                               msg->message == WM_SYSKEYDOWN) ?
2063                              GDK_KEY_PRESS : GDK_KEY_RELEASE);
2064       event->key.window = window;
2065       event->key.time = _gdk_win32_get_next_tick (msg->time);
2066       event->key.keyval = GDK_VoidSymbol;
2067       event->key.string = NULL;
2068       event->key.length = 0;
2069       event->key.hardware_keycode = msg->wParam;
2070       gdk_event_set_device (event, GDK_DEVICE_MANAGER_WIN32 (device_manager)->core_keyboard);
2071       if (HIWORD (msg->lParam) & KF_EXTENDED)
2072         {
2073           switch (msg->wParam)
2074             {
2075             case VK_CONTROL:
2076               event->key.hardware_keycode = VK_RCONTROL;
2077               break;
2078             case VK_SHIFT:      /* Actually, KF_EXTENDED is not set
2079                                  * for the right shift key.
2080                                  */
2081               event->key.hardware_keycode = VK_RSHIFT;
2082               break;
2083             case VK_MENU:
2084               event->key.hardware_keycode = VK_RMENU;
2085               break;
2086             }
2087         }
2088       else if (msg->wParam == VK_SHIFT &&
2089                LOBYTE (HIWORD (msg->lParam)) == _scancode_rshift)
2090         event->key.hardware_keycode = VK_RSHIFT;
2091
2092       API_CALL (GetKeyboardState, (key_state));
2093
2094       /* 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]); */
2095       
2096       build_key_event_state (event, key_state);
2097
2098       gdk_keymap_translate_keyboard_state (NULL,
2099                                            event->key.hardware_keycode,
2100                                            event->key.state,
2101                                            event->key.group,
2102                                            &event->key.keyval,
2103                                            NULL, NULL, NULL);
2104
2105       fill_key_event_string (event);
2106
2107       /* Reset MOD1_MASK if it is the Alt key itself */
2108       if (msg->wParam == VK_MENU)
2109         event->key.state &= ~GDK_MOD1_MASK;
2110
2111       append_event (event);
2112
2113       return_val = TRUE;
2114       break;
2115
2116     case WM_SYSCHAR:
2117       if (msg->wParam != VK_SPACE)
2118         {
2119           /* To prevent beeps, don't let DefWindowProcW() be called */
2120           return_val = TRUE;
2121           goto done;
2122         }
2123       break;
2124
2125     case WM_IME_STARTCOMPOSITION:
2126       in_ime_composition = TRUE;
2127       break;
2128
2129     case WM_IME_ENDCOMPOSITION:
2130       in_ime_composition = FALSE;
2131       break;
2132
2133     case WM_IME_COMPOSITION:
2134       /* On Win2k WM_IME_CHAR doesn't work correctly for non-Unicode
2135        * applications. Thus, handle WM_IME_COMPOSITION with
2136        * GCS_RESULTSTR instead, fetch the Unicode chars from the IME
2137        * with ImmGetCompositionStringW().
2138        *
2139        * See for instance
2140        * http://groups.google.com/groups?selm=natX5.57%24g77.19788%40nntp2.onemain.com
2141        * and
2142        * http://groups.google.com/groups?selm=u2XfrXw5BHA.1628%40tkmsftngp02
2143        * for comments by other people that seems to have the same
2144        * experience. WM_IME_CHAR just gives question marks, apparently
2145        * because of going through some conversion to the current code
2146        * page.
2147        *
2148        * WM_IME_CHAR might work on NT4 or Win9x with ActiveIMM, but
2149        * use WM_IME_COMPOSITION there, too, to simplify the code.
2150        */
2151       GDK_NOTE (EVENTS, g_print (" %#lx", (long) msg->lParam));
2152
2153       if (!(msg->lParam & GCS_RESULTSTR))
2154         break;
2155
2156       if (keyboard_grab &&
2157           !propagate (&window, msg,
2158                       keyboard_grab->window,
2159                       keyboard_grab->owner_events,
2160                       GDK_ALL_EVENTS_MASK,
2161                       doesnt_want_char, FALSE))
2162         break;
2163
2164       if (GDK_WINDOW_DESTROYED (window))
2165         break;
2166
2167       himc = ImmGetContext (msg->hwnd);
2168       ccount = ImmGetCompositionStringW (himc, GCS_RESULTSTR,
2169                                          wbuf, sizeof (wbuf));
2170       ImmReleaseContext (msg->hwnd, himc);
2171
2172       ccount /= 2;
2173
2174       API_CALL (GetKeyboardState, (key_state));
2175
2176       for (i = 0; i < ccount; i++)
2177         {
2178           if (((GdkWindowObject *) window)->event_mask & GDK_KEY_PRESS_MASK)
2179             {
2180               /* Build a key press event */
2181               event = gdk_event_new (GDK_KEY_PRESS);
2182               event->key.window = window;
2183         gdk_event_set_device (event, GDK_DEVICE_MANAGER_WIN32 (device_manager)->core_keyboard);
2184               build_wm_ime_composition_event (event, msg, wbuf[i], key_state);
2185
2186               append_event (event);
2187             }
2188           
2189           if (((GdkWindowObject *) window)->event_mask & GDK_KEY_RELEASE_MASK)
2190             {
2191               /* Build a key release event.  */
2192               event = gdk_event_new (GDK_KEY_RELEASE);
2193               event->key.window = window;
2194         gdk_event_set_device (event, GDK_DEVICE_MANAGER_WIN32 (device_manager)->core_keyboard);
2195               build_wm_ime_composition_event (event, msg, wbuf[i], key_state);
2196
2197               append_event (event);
2198             }
2199         }
2200       return_val = TRUE;
2201       break;
2202
2203     case WM_LBUTTONDOWN:
2204       button = 1;
2205       goto buttondown0;
2206
2207     case WM_MBUTTONDOWN:
2208       button = 2;
2209       goto buttondown0;
2210
2211     case WM_RBUTTONDOWN:
2212       button = 3;
2213       goto buttondown0;
2214
2215     case WM_XBUTTONDOWN:
2216       if (HIWORD (msg->wParam) == XBUTTON1)
2217         button = 4;
2218       else
2219         button = 5;
2220
2221     buttondown0:
2222       GDK_NOTE (EVENTS, 
2223                 g_print (" (%d,%d)",
2224                          GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
2225
2226       assign_object (&window, find_window_for_mouse_event (window, msg));
2227       /* TODO_CSW?: there used to some synthesize and propagate */
2228       if (GDK_WINDOW_DESTROYED (window))
2229         break;
2230
2231       /* TODO_CSW? Emulate X11's automatic active grab */
2232       generate_button_event (GDK_BUTTON_PRESS, button,
2233                              window, msg);
2234
2235       return_val = TRUE;
2236       break;
2237
2238     case WM_LBUTTONUP:
2239       button = 1;
2240       goto buttonup0;
2241
2242     case WM_MBUTTONUP:
2243       button = 2;
2244       goto buttonup0;
2245
2246     case WM_RBUTTONUP:
2247       button = 3;
2248       goto buttonup0;
2249
2250     case WM_XBUTTONUP:
2251       if (HIWORD (msg->wParam) == XBUTTON1)
2252         button = 4;
2253       else
2254         button = 5;
2255
2256     buttonup0:
2257       GDK_NOTE (EVENTS, 
2258                 g_print (" (%d,%d)",
2259                          GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
2260
2261       assign_object (&window, find_window_for_mouse_event (window, msg));
2262 #if 0
2263       if (((GdkWindowObject *) window)->extension_events != 0 &&
2264           _gdk_input_ignore_core)
2265         {
2266           GDK_NOTE (EVENTS, g_print (" (ignored)"));
2267           break;
2268         }
2269 #endif
2270
2271       generate_button_event (GDK_BUTTON_RELEASE, button,
2272                              window, msg);
2273
2274       return_val = TRUE;
2275       break;
2276
2277     case WM_MOUSEMOVE:
2278       GDK_NOTE (EVENTS,
2279                 g_print (" %p (%d,%d)",
2280                          (gpointer) msg->wParam,
2281                          GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
2282
2283       assign_object (&window, find_window_for_mouse_event (window, msg));
2284       toplevel = gdk_window_get_toplevel (window);
2285       if (current_toplevel != toplevel)
2286         {
2287           GDK_NOTE (EVENTS, g_print (" toplevel %p -> %p", 
2288               current_toplevel ? GDK_WINDOW_HWND (current_toplevel) : NULL, 
2289               toplevel ? GDK_WINDOW_HWND (toplevel) : NULL));
2290           if (current_toplevel)
2291             synthesize_enter_or_leave_event (current_toplevel, msg,
2292                                        GDK_LEAVE_NOTIFY, GDK_CROSSING_NORMAL, GDK_NOTIFY_ANCESTOR);
2293           synthesize_enter_or_leave_event (toplevel, msg,
2294                                      GDK_ENTER_NOTIFY, GDK_CROSSING_NORMAL, GDK_NOTIFY_ANCESTOR);
2295           assign_object (&current_toplevel, toplevel);
2296           track_mouse_event (TME_LEAVE, GDK_WINDOW_HWND (toplevel));
2297         }
2298
2299       /* If we haven't moved, don't create any GDK event. Windows
2300        * sends WM_MOUSEMOVE messages after a new window is shows under
2301        * the mouse, even if the mouse hasn't moved. This disturbs gtk.
2302        */
2303       if (msg->pt.x + _gdk_offset_x == current_root_x &&
2304           msg->pt.y + _gdk_offset_y == current_root_y)
2305         break;
2306
2307       current_root_x = msg->pt.x + _gdk_offset_x;
2308       current_root_y = msg->pt.y + _gdk_offset_y;
2309
2310       event = gdk_event_new (GDK_MOTION_NOTIFY);
2311       event->motion.window = window;
2312       event->motion.time = _gdk_win32_get_next_tick (msg->time);
2313       event->motion.x = current_x = (gint16) GET_X_LPARAM (msg->lParam);
2314       event->motion.y = current_y = (gint16) GET_Y_LPARAM (msg->lParam);
2315       event->motion.x_root = current_root_x;
2316       event->motion.y_root = current_root_y;
2317       event->motion.axes = NULL;
2318       event->motion.state = build_pointer_event_state (msg);
2319       event->motion.is_hint = FALSE;
2320       gdk_event_set_device (event, _gdk_display->core_pointer);
2321
2322       append_event (event);
2323
2324       return_val = TRUE;
2325       break;
2326
2327     case WM_NCMOUSEMOVE:
2328       GDK_NOTE (EVENTS,
2329                 g_print (" (%d,%d)",
2330                          GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
2331 #if 0 /* TODO_CSW? */
2332       if (current_toplevel != NULL &&
2333           (((GdkWindowObject *) current_toplevel)->event_mask & GDK_LEAVE_NOTIFY_MASK))
2334         {
2335           synthesize_enter_or_leave_event (current_toplevel, msg,
2336                                            GDK_LEAVE_NOTIFY, GDK_CROSSING_NORMAL, GDK_NOTIFY_ANCESTOR);
2337         }
2338 #endif
2339       break;
2340
2341     case WM_MOUSELEAVE:
2342       GDK_NOTE (EVENTS, g_print (" %d (%ld,%ld)",
2343                                  HIWORD (msg->wParam), msg->pt.x, msg->pt.y));
2344
2345       if (!gdk_win32_handle_table_lookup ((GdkNativeWindow) WindowFromPoint (msg->pt)))
2346         {
2347           /* we are only interested if we don't know the new window */
2348           if (current_toplevel)
2349             synthesize_enter_or_leave_event (current_toplevel, msg,
2350                                        GDK_LEAVE_NOTIFY, GDK_CROSSING_NORMAL, GDK_NOTIFY_ANCESTOR);
2351           assign_object (&current_toplevel, NULL);
2352         }
2353       else
2354         {
2355           GDK_NOTE (EVENTS, g_print (" (ignored)"));
2356         }
2357       
2358       return_val = TRUE;
2359       break;
2360
2361     case WM_MOUSEWHEEL:
2362       GDK_NOTE (EVENTS, g_print (" %d", (short) HIWORD (msg->wParam)));
2363
2364       /* WM_MOUSEWHEEL is delivered to the focus window. Work around
2365        * that. Also, the position is in screen coordinates, not client
2366        * coordinates as with the button messages. I love the
2367        * consistency of Windows.
2368        */
2369       point.x = GET_X_LPARAM (msg->lParam);
2370       point.y = GET_Y_LPARAM (msg->lParam);
2371
2372       if ((hwnd = WindowFromPoint (point)) == NULL)
2373         break;
2374
2375       msg->hwnd = hwnd;
2376       if ((new_window = gdk_win32_handle_table_lookup ((GdkNativeWindow) msg->hwnd)) == NULL)
2377         break;
2378
2379       if (new_window != window)
2380         {
2381           assign_object (&window, new_window);
2382         }
2383
2384       ScreenToClient (msg->hwnd, &point);
2385
2386       event = gdk_event_new (GDK_SCROLL);
2387       event->scroll.window = window;
2388       event->scroll.direction = (((short) HIWORD (msg->wParam)) > 0) ?
2389         GDK_SCROLL_UP : GDK_SCROLL_DOWN;
2390       event->scroll.time = _gdk_win32_get_next_tick (msg->time);
2391       event->scroll.x = (gint16) point.x;
2392       event->scroll.y = (gint16) point.y;
2393       event->scroll.x_root = (gint16) GET_X_LPARAM (msg->lParam) + _gdk_offset_x;
2394       event->scroll.y_root = (gint16) GET_Y_LPARAM (msg->lParam) + _gdk_offset_y;
2395       event->scroll.state = build_pointer_event_state (msg);
2396       gdk_event_set_device (event, _gdk_display->core_pointer);
2397
2398       append_event (event);
2399       
2400       return_val = TRUE;
2401       break;
2402
2403     case WM_HSCROLL:
2404       /* Just print more debugging information, don't actually handle it. */
2405       GDK_NOTE (EVENTS,
2406                 (g_print (" %s",
2407                           (LOWORD (msg->wParam) == SB_ENDSCROLL ? "ENDSCROLL" :
2408                            (LOWORD (msg->wParam) == SB_LEFT ? "LEFT" :
2409                             (LOWORD (msg->wParam) == SB_RIGHT ? "RIGHT" :
2410                              (LOWORD (msg->wParam) == SB_LINELEFT ? "LINELEFT" :
2411                               (LOWORD (msg->wParam) == SB_LINERIGHT ? "LINERIGHT" :
2412                                (LOWORD (msg->wParam) == SB_PAGELEFT ? "PAGELEFT" :
2413                                 (LOWORD (msg->wParam) == SB_PAGERIGHT ? "PAGERIGHT" :
2414                                  (LOWORD (msg->wParam) == SB_THUMBPOSITION ? "THUMBPOSITION" :
2415                                   (LOWORD (msg->wParam) == SB_THUMBTRACK ? "THUMBTRACK" :
2416                                    "???")))))))))),
2417                  (LOWORD (msg->wParam) == SB_THUMBPOSITION ||
2418                   LOWORD (msg->wParam) == SB_THUMBTRACK) ?
2419                  (g_print (" %d", HIWORD (msg->wParam)), 0) : 0));
2420       break;
2421
2422     case WM_VSCROLL:
2423       /* Just print more debugging information, don't actually handle it. */
2424       GDK_NOTE (EVENTS,
2425                 (g_print (" %s",
2426                           (LOWORD (msg->wParam) == SB_ENDSCROLL ? "ENDSCROLL" :
2427                            (LOWORD (msg->wParam) == SB_BOTTOM ? "BOTTOM" :
2428                             (LOWORD (msg->wParam) == SB_TOP ? "TOP" :
2429                              (LOWORD (msg->wParam) == SB_LINEDOWN ? "LINDOWN" :
2430                               (LOWORD (msg->wParam) == SB_LINEUP ? "LINEUP" :
2431                                (LOWORD (msg->wParam) == SB_PAGEDOWN ? "PAGEDOWN" :
2432                                 (LOWORD (msg->wParam) == SB_PAGEUP ? "PAGEUP" :
2433                                  (LOWORD (msg->wParam) == SB_THUMBPOSITION ? "THUMBPOSITION" :
2434                                   (LOWORD (msg->wParam) == SB_THUMBTRACK ? "THUMBTRACK" :
2435                                    "???")))))))))),
2436                  (LOWORD (msg->wParam) == SB_THUMBPOSITION ||
2437                   LOWORD (msg->wParam) == SB_THUMBTRACK) ?
2438                  (g_print (" %d", HIWORD (msg->wParam)), 0) : 0));
2439       break;
2440
2441     case WM_QUERYNEWPALETTE:
2442       if (gdk_visual_get_system ()->type == GDK_VISUAL_PSEUDO_COLOR)
2443         {
2444           synthesize_expose_events (window);
2445           update_colors_counter = 0;
2446         }
2447       return_val = TRUE;
2448       break;
2449
2450     case WM_PALETTECHANGED:
2451       GDK_NOTE (EVENTS_OR_COLORMAP, g_print (" %p", (HWND) msg->wParam));
2452       if (gdk_visual_get_system ()->type != GDK_VISUAL_PSEUDO_COLOR)
2453         break;
2454
2455       return_val = TRUE;
2456
2457       if (msg->hwnd == (HWND) msg->wParam)
2458         break;
2459
2460       if (++update_colors_counter == 5)
2461         {
2462           synthesize_expose_events (window);
2463           update_colors_counter = 0;
2464           break;
2465         }
2466       
2467       update_colors (window, TRUE);
2468       break;
2469
2470      case WM_MOUSEACTIVATE:
2471        {
2472          GdkWindow *tmp;
2473
2474          if (gdk_window_get_window_type (window) == GDK_WINDOW_TEMP 
2475              || !((GdkWindowObject *)window)->accept_focus)
2476            {
2477              *ret_valp = MA_NOACTIVATE;
2478              return_val = TRUE;
2479            }
2480
2481          tmp = _gdk_modal_current ();
2482
2483          if (tmp != NULL)
2484            {
2485              if (gdk_window_get_toplevel (window) != tmp)
2486                {
2487                  *ret_valp = MA_NOACTIVATEANDEAT;
2488                  return_val = TRUE;
2489                }
2490            }
2491        }
2492
2493        break;
2494
2495     case WM_KILLFOCUS:
2496       if (keyboard_grab != NULL &&
2497           !GDK_WINDOW_DESTROYED (keyboard_grab->window))
2498         {
2499           generate_grab_broken_event (device_manager, keyboard_grab->window, TRUE, NULL);
2500         }
2501
2502       /* fallthrough */
2503     case WM_SETFOCUS:
2504       if (keyboard_grab != NULL &&
2505           !keyboard_grab->owner_events)
2506         break;
2507
2508       if (!(((GdkWindowObject *) window)->event_mask & GDK_FOCUS_CHANGE_MASK))
2509         break;
2510
2511       if (GDK_WINDOW_DESTROYED (window))
2512         break;
2513
2514       generate_focus_event (device_manager, window, (msg->message == WM_SETFOCUS));
2515       return_val = TRUE;
2516       break;
2517
2518     case WM_ERASEBKGND:
2519       GDK_NOTE (EVENTS, g_print (" %p", (HANDLE) msg->wParam));
2520       
2521       if (GDK_WINDOW_DESTROYED (window))
2522         break;
2523
2524       return_val = TRUE;
2525       *ret_valp = 1;
2526       break;
2527
2528     case WM_SYNCPAINT:
2529       sync_timer = SetTimer (GDK_WINDOW_HWND (window),
2530                              1,
2531                              200, sync_timer_proc);
2532       break;
2533
2534     case WM_PAINT:
2535       handle_wm_paint (msg, window, FALSE, NULL);
2536       break;
2537
2538     case WM_SETCURSOR:
2539       GDK_NOTE (EVENTS, g_print (" %#x %#x",
2540                                  LOWORD (msg->lParam), HIWORD (msg->lParam)));
2541
2542       if (pointer_grab != NULL)
2543         grab_window = pointer_grab->window;
2544
2545       if (grab_window == NULL && LOWORD (msg->lParam) != HTCLIENT)
2546         break;
2547
2548       if (grab_window != NULL && p_grab_cursor != NULL)
2549         hcursor = p_grab_cursor;
2550       else if (!GDK_WINDOW_DESTROYED (window))
2551         hcursor = GDK_WINDOW_IMPL_WIN32 (((GdkWindowObject *) window)->impl)->hcursor;
2552       else
2553         hcursor = NULL;
2554
2555       if (hcursor != NULL)
2556         {
2557           GDK_NOTE (EVENTS, g_print (" (SetCursor(%p)", hcursor));
2558           SetCursor (hcursor);
2559           return_val = TRUE;
2560           *ret_valp = TRUE;
2561         }
2562       break;
2563
2564     case WM_SHOWWINDOW:
2565       GDK_NOTE (EVENTS, g_print (" %s %s",
2566                                  (msg->wParam ? "YES" : "NO"),
2567                                  (msg->lParam == 0 ? "ShowWindow" :
2568                                   (msg->lParam == SW_OTHERUNZOOM ? "OTHERUNZOOM" :
2569                                    (msg->lParam == SW_OTHERZOOM ? "OTHERZOOM" :
2570                                     (msg->lParam == SW_PARENTCLOSING ? "PARENTCLOSING" :
2571                                      (msg->lParam == SW_PARENTOPENING ? "PARENTOPENING" :
2572                                       "???")))))));
2573
2574       if (!(((GdkWindowObject *) window)->event_mask & GDK_STRUCTURE_MASK))
2575         break;
2576
2577       if (msg->lParam == SW_OTHERUNZOOM ||
2578           msg->lParam == SW_OTHERZOOM)
2579         break;
2580
2581       if (GDK_WINDOW_DESTROYED (window))
2582         break;
2583
2584       event = gdk_event_new (msg->wParam ? GDK_MAP : GDK_UNMAP);
2585       event->any.window = window;
2586
2587       append_event (event);
2588
2589       if (event->any.type == GDK_UNMAP)
2590         {
2591           impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (window)->impl);
2592
2593           if (impl->transient_owner && GetForegroundWindow () == GDK_WINDOW_HWND (window))
2594             {
2595               SetForegroundWindow (GDK_WINDOW_HWND (impl->transient_owner));
2596             }
2597
2598           if (pointer_grab != NULL)
2599             {
2600               if (pointer_grab->window == window)
2601                 gdk_pointer_ungrab (msg->time);
2602             }
2603
2604           if (keyboard_grab &&
2605         keyboard_grab->window == window)
2606             gdk_keyboard_ungrab (msg->time);
2607         }
2608
2609       return_val = TRUE;
2610       break;
2611
2612     case WM_SYSCOMMAND:
2613       switch (msg->wParam)
2614         {
2615         case SC_MINIMIZE:
2616         case SC_RESTORE:
2617           do_show_window (window, msg->wParam == SC_MINIMIZE ? TRUE : FALSE);
2618           break;
2619         }
2620
2621       break;
2622
2623     case WM_SIZE:
2624       GDK_NOTE (EVENTS,
2625                 g_print (" %s %dx%d",
2626                          (msg->wParam == SIZE_MAXHIDE ? "MAXHIDE" :
2627                           (msg->wParam == SIZE_MAXIMIZED ? "MAXIMIZED" :
2628                            (msg->wParam == SIZE_MAXSHOW ? "MAXSHOW" :
2629                             (msg->wParam == SIZE_MINIMIZED ? "MINIMIZED" :
2630                              (msg->wParam == SIZE_RESTORED ? "RESTORED" : "?"))))),
2631                          LOWORD (msg->lParam), HIWORD (msg->lParam)));
2632
2633       if (msg->wParam == SIZE_MINIMIZED)
2634         {
2635           /* Don't generate any GDK event. This is *not* an UNMAP. */
2636           if (pointer_grab != NULL)
2637             {
2638               if (pointer_grab->window == window)
2639                 gdk_pointer_ungrab (msg->time);
2640             }
2641           if (keyboard_grab &&
2642         keyboard_grab->window == window)
2643             gdk_keyboard_ungrab (msg->time);
2644
2645           gdk_synthesize_window_state (window,
2646                                        GDK_WINDOW_STATE_WITHDRAWN,
2647                                        GDK_WINDOW_STATE_ICONIFIED);
2648           do_show_window (window, TRUE);
2649         }
2650       else if ((msg->wParam == SIZE_RESTORED ||
2651                 msg->wParam == SIZE_MAXIMIZED) &&
2652                GDK_WINDOW_TYPE (window) != GDK_WINDOW_CHILD)
2653         {
2654           GdkWindowState withdrawn_bit =
2655             IsWindowVisible (msg->hwnd) ? GDK_WINDOW_STATE_WITHDRAWN : 0;
2656
2657           if (((GdkWindowObject *) window)->state & GDK_WINDOW_STATE_ICONIFIED)
2658             ensure_stacking_on_unminimize (msg);
2659
2660           if (!GDK_WINDOW_DESTROYED (window))
2661             handle_configure_event (msg, window);
2662           
2663           if (msg->wParam == SIZE_RESTORED)
2664             {
2665               gdk_synthesize_window_state (window,
2666                                            GDK_WINDOW_STATE_ICONIFIED |
2667                                            GDK_WINDOW_STATE_MAXIMIZED |
2668                                            withdrawn_bit,
2669                                            0);
2670
2671               if (GDK_WINDOW_TYPE (window) != GDK_WINDOW_TEMP && !GDK_WINDOW_IS_MAPPED (window))
2672                 {
2673                   do_show_window (window, FALSE);
2674                 }
2675             }
2676           else if (msg->wParam == SIZE_MAXIMIZED)
2677             {
2678               gdk_synthesize_window_state (window,
2679                                            GDK_WINDOW_STATE_ICONIFIED |
2680                                            withdrawn_bit,
2681                                            GDK_WINDOW_STATE_MAXIMIZED);
2682             }
2683
2684           if (((GdkWindowObject *) window)->resize_count > 1)
2685             ((GdkWindowObject *) window)->resize_count -= 1;
2686           
2687           if (((GdkWindowObject *) window)->extension_events != 0)
2688       _gdk_device_wintab_update_window_coords (window);
2689
2690           return_val = TRUE;
2691         }
2692       break;
2693
2694     case WM_ENTERSIZEMOVE:
2695     case WM_ENTERMENULOOP:
2696       _gdk_win32_begin_modal_call ();
2697       break;
2698
2699     case WM_EXITSIZEMOVE:
2700     case WM_EXITMENULOOP:
2701       _gdk_win32_end_modal_call ();
2702       break;
2703
2704     case WM_WINDOWPOSCHANGING:
2705       GDK_NOTE (EVENTS, (windowpos = (WINDOWPOS *) msg->lParam,
2706                          g_print (" %s %s %dx%d@%+d%+d now below %p",
2707                                   _gdk_win32_window_pos_bits_to_string (windowpos->flags),
2708                                   (windowpos->hwndInsertAfter == HWND_BOTTOM ? "BOTTOM" :
2709                                    (windowpos->hwndInsertAfter == HWND_NOTOPMOST ? "NOTOPMOST" :
2710                                     (windowpos->hwndInsertAfter == HWND_TOP ? "TOP" :
2711                                      (windowpos->hwndInsertAfter == HWND_TOPMOST ? "TOPMOST" :
2712                                       (sprintf (buf, "%p", windowpos->hwndInsertAfter),
2713                                        buf))))),
2714                                   windowpos->cx, windowpos->cy, windowpos->x, windowpos->y,
2715                                   GetNextWindow (msg->hwnd, GW_HWNDPREV))));
2716
2717       if (GDK_WINDOW_IS_MAPPED (window))
2718         return_val = ensure_stacking_on_window_pos_changing (msg, window);
2719       break;
2720
2721     case WM_WINDOWPOSCHANGED:
2722       windowpos = (WINDOWPOS *) msg->lParam;
2723       GDK_NOTE (EVENTS, g_print (" %s %s %dx%d@%+d%+d",
2724                                  _gdk_win32_window_pos_bits_to_string (windowpos->flags),
2725                                  (windowpos->hwndInsertAfter == HWND_BOTTOM ? "BOTTOM" :
2726                                   (windowpos->hwndInsertAfter == HWND_NOTOPMOST ? "NOTOPMOST" :
2727                                    (windowpos->hwndInsertAfter == HWND_TOP ? "TOP" :
2728                                     (windowpos->hwndInsertAfter == HWND_TOPMOST ? "TOPMOST" :
2729                                      (sprintf (buf, "%p", windowpos->hwndInsertAfter),
2730                                       buf))))),
2731                                  windowpos->cx, windowpos->cy, windowpos->x, windowpos->y));
2732
2733       /* If position and size haven't changed, don't do anything */
2734       if (_modal_operation_in_progress &&
2735           (windowpos->flags & SWP_NOMOVE) &&
2736           (windowpos->flags & SWP_NOSIZE))
2737         break;
2738
2739       /* Once we've entered the moving or sizing modal loop, we won't
2740        * return to the main loop until we're done sizing or moving.
2741        */
2742       if (_modal_operation_in_progress &&
2743          GDK_WINDOW_TYPE (window) != GDK_WINDOW_CHILD &&
2744          !GDK_WINDOW_DESTROYED (window))
2745         {
2746           if (((GdkWindowObject *) window)->event_mask & GDK_STRUCTURE_MASK)
2747             {
2748               GDK_NOTE (EVENTS, g_print (" do magic"));
2749               if (((GdkWindowObject *) window)->resize_count > 1)
2750                 ((GdkWindowObject *) window)->resize_count -= 1;
2751
2752               handle_configure_event (msg, window);
2753               g_main_context_iteration (NULL, FALSE);
2754 #if 0
2755               /* Dispatch main loop - to realize resizes... */
2756               modal_timer_proc (msg->hwnd, msg->message, 0, msg->time);
2757 #endif
2758               /* Claim as handled, so that WM_SIZE and WM_MOVE are avoided */
2759               return_val = TRUE;
2760               *ret_valp = 1;
2761             }
2762         }
2763       break;
2764
2765     case WM_SIZING:
2766       GetWindowRect (GDK_WINDOW_HWND (window), &rect);
2767       drag = (RECT *) msg->lParam;
2768       GDK_NOTE (EVENTS, g_print (" %s curr:%s drag:%s",
2769                                  (msg->wParam == WMSZ_BOTTOM ? "BOTTOM" :
2770                                   (msg->wParam == WMSZ_BOTTOMLEFT ? "BOTTOMLEFT" :
2771                                    (msg->wParam == WMSZ_LEFT ? "LEFT" :
2772                                     (msg->wParam == WMSZ_TOPLEFT ? "TOPLEFT" :
2773                                      (msg->wParam == WMSZ_TOP ? "TOP" :
2774                                       (msg->wParam == WMSZ_TOPRIGHT ? "TOPRIGHT" :
2775                                        (msg->wParam == WMSZ_RIGHT ? "RIGHT" :
2776                                         
2777                                         (msg->wParam == WMSZ_BOTTOMRIGHT ? "BOTTOMRIGHT" :
2778                                          "???")))))))),
2779                                  _gdk_win32_rect_to_string (&rect),
2780                                  _gdk_win32_rect_to_string (drag)));
2781
2782       impl = GDK_WINDOW_IMPL_WIN32 (((GdkWindowObject *) window)->impl);
2783       orig_drag = *drag;
2784       if (impl->hint_flags & GDK_HINT_RESIZE_INC)
2785         {
2786           GDK_NOTE (EVENTS, g_print (" (RESIZE_INC)"));
2787           if (impl->hint_flags & GDK_HINT_BASE_SIZE)
2788             {
2789               /* Resize in increments relative to the base size */
2790               rect.left = rect.top = 0;
2791               rect.right = impl->hints.base_width;
2792               rect.bottom = impl->hints.base_height;
2793               _gdk_win32_adjust_client_rect (window, &rect);
2794               point.x = rect.left;
2795               point.y = rect.top;
2796               ClientToScreen (GDK_WINDOW_HWND (window), &point);
2797               rect.left = point.x;
2798               rect.top = point.y;
2799               point.x = rect.right;
2800               point.y = rect.bottom;
2801               ClientToScreen (GDK_WINDOW_HWND (window), &point);
2802               rect.right = point.x;
2803               rect.bottom = point.y;
2804               
2805               GDK_NOTE (EVENTS, g_print (" (also BASE_SIZE, using %s)",
2806                                          _gdk_win32_rect_to_string (&rect)));
2807             }
2808
2809           switch (msg->wParam)
2810             {
2811             case WMSZ_BOTTOM:
2812               if (drag->bottom == rect.bottom)
2813                 break;
2814               adjust_drag (&drag->bottom, rect.bottom, impl->hints.height_inc);
2815               break;
2816
2817             case WMSZ_BOTTOMLEFT:
2818               if (drag->bottom == rect.bottom && drag->left == rect.left)
2819                 break;
2820               adjust_drag (&drag->bottom, rect.bottom, impl->hints.height_inc);
2821               adjust_drag (&drag->left, rect.left, impl->hints.width_inc);
2822               break;
2823
2824             case WMSZ_LEFT:
2825               if (drag->left == rect.left)
2826                 break;
2827               adjust_drag (&drag->left, rect.left, impl->hints.width_inc);
2828               break;
2829
2830             case WMSZ_TOPLEFT:
2831               if (drag->top == rect.top && drag->left == rect.left)
2832                 break;
2833               adjust_drag (&drag->top, rect.top, impl->hints.height_inc);
2834               adjust_drag (&drag->left, rect.left, impl->hints.width_inc);
2835               break;
2836
2837             case WMSZ_TOP:
2838               if (drag->top == rect.top)
2839                 break;
2840               adjust_drag (&drag->top, rect.top, impl->hints.height_inc);
2841               break;
2842
2843             case WMSZ_TOPRIGHT:
2844               if (drag->top == rect.top && drag->right == rect.right)
2845                 break;
2846               adjust_drag (&drag->top, rect.top, impl->hints.height_inc);
2847               adjust_drag (&drag->right, rect.right, impl->hints.width_inc);
2848               break;
2849
2850             case WMSZ_RIGHT:
2851               if (drag->right == rect.right)
2852                 break;
2853               adjust_drag (&drag->right, rect.right, impl->hints.width_inc);
2854               break;
2855
2856             case WMSZ_BOTTOMRIGHT:
2857               if (drag->bottom == rect.bottom && drag->right == rect.right)
2858                 break;
2859               adjust_drag (&drag->bottom, rect.bottom, impl->hints.height_inc);
2860               adjust_drag (&drag->right, rect.right, impl->hints.width_inc);
2861               break;
2862             }
2863
2864           if (drag->bottom != orig_drag.bottom || drag->left != orig_drag.left ||
2865               drag->top != orig_drag.top || drag->right != orig_drag.right)
2866             {
2867               *ret_valp = TRUE;
2868               return_val = TRUE;
2869               GDK_NOTE (EVENTS, g_print (" (handled RESIZE_INC: %s)",
2870                                          _gdk_win32_rect_to_string (drag)));
2871             }
2872         }
2873
2874       /* WM_GETMINMAXINFO handles min_size and max_size hints? */
2875
2876       if (impl->hint_flags & GDK_HINT_ASPECT)
2877         {
2878           RECT decorated_rect;
2879           RECT undecorated_drag;
2880           int decoration_width, decoration_height;
2881           gdouble drag_aspect;
2882           int drag_width, drag_height, new_width, new_height;
2883
2884           GetClientRect (GDK_WINDOW_HWND (window), &rect);
2885           decorated_rect = rect;
2886           _gdk_win32_adjust_client_rect (window, &decorated_rect);
2887
2888           /* Set undecorated_drag to the client area being dragged
2889            * out, in screen coordinates.
2890            */
2891           undecorated_drag = *drag;
2892           undecorated_drag.left -= decorated_rect.left - rect.left;
2893           undecorated_drag.right -= decorated_rect.right - rect.right;
2894           undecorated_drag.top -= decorated_rect.top - rect.top;
2895           undecorated_drag.bottom -= decorated_rect.bottom - rect.bottom;
2896
2897           decoration_width = (decorated_rect.right - decorated_rect.left) - (rect.right - rect.left);
2898           decoration_height = (decorated_rect.bottom - decorated_rect.top) - (rect.bottom - rect.top);
2899
2900           drag_width = undecorated_drag.right - undecorated_drag.left;
2901           drag_height = undecorated_drag.bottom - undecorated_drag.top;
2902
2903           drag_aspect = (gdouble) drag_width / drag_height;
2904
2905           GDK_NOTE (EVENTS, g_print (" (ASPECT:%g--%g curr: %g)",
2906                                      impl->hints.min_aspect, impl->hints.max_aspect, drag_aspect));
2907
2908           if (drag_aspect < impl->hints.min_aspect)
2909             {
2910               /* Aspect is getting too narrow */
2911               switch (msg->wParam)
2912                 {
2913                 case WMSZ_BOTTOM:
2914                 case WMSZ_TOP:
2915                   /* User drags top or bottom edge outward. Keep height, increase width. */
2916                   new_width = impl->hints.min_aspect * drag_height;
2917                   drag->left -= (new_width - drag_width) / 2;
2918                   drag->right = drag->left + new_width + decoration_width;
2919                   break;
2920                 case WMSZ_BOTTOMLEFT:
2921                 case WMSZ_BOTTOMRIGHT:
2922                   /* User drags bottom-left or bottom-right corner down. Adjust height. */
2923                   new_height = drag_width / impl->hints.min_aspect;
2924                   drag->bottom = drag->top + new_height + decoration_height;
2925                   break;
2926                 case WMSZ_LEFT:
2927                 case WMSZ_RIGHT:
2928                   /* User drags left or right edge inward. Decrease height */
2929                   new_height = drag_width / impl->hints.min_aspect;
2930                   drag->top += (drag_height - new_height) / 2;
2931                   drag->bottom = drag->top + new_height + decoration_height;
2932                   break;
2933                 case WMSZ_TOPLEFT:
2934                 case WMSZ_TOPRIGHT:
2935                   /* User drags top-left or top-right corner up. Adjust height. */
2936                   new_height = drag_width / impl->hints.min_aspect;
2937                   drag->top = drag->bottom - new_height - decoration_height;
2938                 }
2939             }
2940           else if (drag_aspect > impl->hints.max_aspect)
2941             {
2942               /* Aspect is getting too wide */
2943               switch (msg->wParam)
2944                 {
2945                 case WMSZ_BOTTOM:
2946                 case WMSZ_TOP:
2947                   /* User drags top or bottom edge inward. Decrease width. */
2948                   new_width = impl->hints.max_aspect * drag_height;
2949                   drag->left += (drag_width - new_width) / 2;
2950                   drag->right = drag->left + new_width + decoration_width;
2951                   break;
2952                 case WMSZ_BOTTOMLEFT:
2953                 case WMSZ_TOPLEFT:
2954                   /* User drags bottom-left or top-left corner left. Adjust width. */
2955                   new_width = impl->hints.max_aspect * drag_height;
2956                   drag->left = drag->right - new_width - decoration_width;
2957                   break;
2958                 case WMSZ_BOTTOMRIGHT:
2959                 case WMSZ_TOPRIGHT:
2960                   /* User drags bottom-right or top-right corner right. Adjust width. */
2961                   new_width = impl->hints.max_aspect * drag_height;
2962                   drag->right = drag->left + new_width + decoration_width;
2963                   break;
2964                 case WMSZ_LEFT:
2965                 case WMSZ_RIGHT:
2966                   /* User drags left or right edge outward. Increase height. */
2967                   new_height = drag_width / impl->hints.max_aspect;
2968                   drag->top -= (new_height - drag_height) / 2;
2969                   drag->bottom = drag->top + new_height + decoration_height;
2970                   break;
2971                 }
2972             }
2973
2974           *ret_valp = TRUE;
2975           return_val = TRUE;
2976           GDK_NOTE (EVENTS, g_print (" (handled ASPECT: %s)",
2977                                      _gdk_win32_rect_to_string (drag)));
2978         }
2979       break;
2980
2981     case WM_GETMINMAXINFO:
2982       if (GDK_WINDOW_DESTROYED (window))
2983         break;
2984
2985       impl = GDK_WINDOW_IMPL_WIN32 (((GdkWindowObject *) window)->impl);
2986       mmi = (MINMAXINFO*) msg->lParam;
2987       GDK_NOTE (EVENTS, g_print (" (mintrack:%ldx%ld maxtrack:%ldx%ld "
2988                                  "maxpos:%+ld%+ld maxsize:%ldx%ld)",
2989                                  mmi->ptMinTrackSize.x, mmi->ptMinTrackSize.y,
2990                                  mmi->ptMaxTrackSize.x, mmi->ptMaxTrackSize.y,
2991                                  mmi->ptMaxPosition.x, mmi->ptMaxPosition.y,
2992                                  mmi->ptMaxSize.x, mmi->ptMaxSize.y));
2993
2994       if (impl->hint_flags & GDK_HINT_MIN_SIZE)
2995         {
2996           rect.left = rect.top = 0;
2997           rect.right = impl->hints.min_width;
2998           rect.bottom = impl->hints.min_height;
2999
3000           _gdk_win32_adjust_client_rect (window, &rect);
3001
3002           mmi->ptMinTrackSize.x = rect.right - rect.left;
3003           mmi->ptMinTrackSize.y = rect.bottom - rect.top;
3004         }
3005
3006       if (impl->hint_flags & GDK_HINT_MAX_SIZE)
3007         {
3008           int maxw, maxh;
3009
3010           rect.left = rect.top = 0;
3011           rect.right = impl->hints.max_width;
3012           rect.bottom = impl->hints.max_height;
3013
3014           _gdk_win32_adjust_client_rect (window, &rect);
3015
3016           /* at least on win9x we have the 16 bit trouble */
3017           maxw = rect.right - rect.left;
3018           maxh = rect.bottom - rect.top;
3019           mmi->ptMaxTrackSize.x = maxw > 0 && maxw < G_MAXSHORT ? maxw : G_MAXSHORT;
3020           mmi->ptMaxTrackSize.y = maxh > 0 && maxh < G_MAXSHORT ? maxh : G_MAXSHORT;
3021         }
3022
3023       if (impl->hint_flags & (GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE))
3024         {
3025           /* Don't call DefWindowProcW() */
3026           GDK_NOTE (EVENTS, g_print (" (handled, mintrack:%ldx%ld maxtrack:%ldx%ld "
3027                                      "maxpos:%+ld%+ld maxsize:%ldx%ld)",
3028                                      mmi->ptMinTrackSize.x, mmi->ptMinTrackSize.y,
3029                                      mmi->ptMaxTrackSize.x, mmi->ptMaxTrackSize.y,
3030                                      mmi->ptMaxPosition.x, mmi->ptMaxPosition.y,
3031                                      mmi->ptMaxSize.x, mmi->ptMaxSize.y));
3032           return_val = TRUE;
3033         }
3034       break;
3035
3036     case WM_MOVE:
3037       GDK_NOTE (EVENTS, g_print (" (%d,%d)",
3038                                  GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
3039
3040       if (GDK_WINDOW_TYPE (window) != GDK_WINDOW_CHILD &&
3041           !IsIconic (msg->hwnd))
3042         {
3043           if (!GDK_WINDOW_DESTROYED (window))
3044             handle_configure_event (msg, window);
3045
3046           return_val = TRUE;
3047         }
3048       break;
3049
3050     case WM_CLOSE:
3051       if (GDK_WINDOW_DESTROYED (window))
3052         break;
3053
3054       event = gdk_event_new (GDK_DELETE);
3055       event->any.window = window;
3056
3057       append_event (event);
3058
3059       impl = GDK_WINDOW_IMPL_WIN32 (GDK_WINDOW_OBJECT (window)->impl);
3060
3061       if (impl->transient_owner && GetForegroundWindow() == GDK_WINDOW_HWND (window))
3062         {
3063           SetForegroundWindow (GDK_WINDOW_HWND (impl->transient_owner));
3064         }
3065
3066       return_val = TRUE;
3067       break;
3068
3069     case WM_DESTROY:
3070       if (pointer_grab != NULL)
3071         {
3072           if (pointer_grab->window == window)
3073             gdk_pointer_ungrab (msg->time);
3074         }
3075
3076       if (keyboard_grab &&
3077           keyboard_grab->window == window)
3078         gdk_keyboard_ungrab (msg->time);
3079
3080       if ((window != NULL) && (msg->hwnd != GetDesktopWindow ()))
3081         gdk_window_destroy_notify (window);
3082
3083       if (window == NULL || GDK_WINDOW_DESTROYED (window))
3084         break;
3085
3086       event = gdk_event_new (GDK_DESTROY);
3087       event->any.window = window;
3088
3089       append_event (event);
3090
3091       return_val = TRUE;
3092       break;
3093
3094     case WM_DISPLAYCHANGE:
3095       handle_display_change ();
3096       break;
3097       
3098     case WM_DESTROYCLIPBOARD:
3099       if (!_ignore_destroy_clipboard)
3100         {
3101           event = gdk_event_new (GDK_SELECTION_CLEAR);
3102           event->selection.window = window;
3103           event->selection.selection = GDK_SELECTION_CLIPBOARD;
3104           event->selection.time = _gdk_win32_get_next_tick (msg->time);
3105           append_event (event);
3106         }
3107       else
3108         {
3109           return_val = TRUE;
3110         }
3111
3112       break;
3113
3114     case WM_RENDERFORMAT:
3115       GDK_NOTE (EVENTS, g_print (" %s", _gdk_win32_cf_to_string (msg->wParam)));
3116
3117       if (!(target = g_hash_table_lookup (_format_atom_table, GINT_TO_POINTER (msg->wParam))))
3118         {
3119           GDK_NOTE (EVENTS, g_print (" (target not found)"));
3120           return_val = TRUE;
3121           break;
3122         }
3123
3124       /* We need to render to clipboard immediately, don't call
3125        * append_event()
3126        */
3127       if (_gdk_event_func)
3128         {
3129           event = gdk_event_new (GDK_SELECTION_REQUEST);
3130           event->selection.window = window;
3131           event->selection.send_event = FALSE;
3132           event->selection.selection = GDK_SELECTION_CLIPBOARD;
3133           event->selection.target = target;
3134           event->selection.property = _gdk_selection;
3135           event->selection.requestor = msg->hwnd;
3136           event->selection.time = msg->time;
3137
3138           fixup_event (event);
3139           GDK_NOTE (EVENTS, g_print (" (calling gdk_event_func)"));
3140           GDK_NOTE (EVENTS, _gdk_win32_print_event (event));
3141           (*_gdk_event_func) (event, _gdk_event_data);
3142           gdk_event_free (event);
3143
3144           /* Now the clipboard owner should have rendered */
3145           if (!_delayed_rendering_data)
3146             {
3147               GDK_NOTE (EVENTS, g_print (" (no _delayed_rendering_data?)"));
3148             }
3149           else
3150             {
3151               if (msg->wParam == CF_DIB)
3152                 {
3153                   _delayed_rendering_data =
3154                     _gdk_win32_selection_convert_to_dib (_delayed_rendering_data,
3155                                                          target);
3156                   if (!_delayed_rendering_data)
3157                     {
3158                       g_warning ("Cannot convert to DIB from delayed rendered image");
3159                       break;
3160                     }
3161                 }
3162
3163               /* The requestor is holding the clipboard, no
3164                * OpenClipboard() is required/possible
3165                */
3166               GDK_NOTE (DND,
3167                         g_print (" SetClipboardData(%s,%p)",
3168                                  _gdk_win32_cf_to_string (msg->wParam),
3169                                  _delayed_rendering_data));
3170
3171               API_CALL (SetClipboardData, (msg->wParam, _delayed_rendering_data));
3172               _delayed_rendering_data = NULL;
3173             }
3174         }
3175       break;
3176
3177     case WM_ACTIVATE:
3178       GDK_NOTE (EVENTS, g_print (" %s%s %p",
3179                                  (LOWORD (msg->wParam) == WA_ACTIVE ? "ACTIVE" :
3180                                   (LOWORD (msg->wParam) == WA_CLICKACTIVE ? "CLICKACTIVE" :
3181                                    (LOWORD (msg->wParam) == WA_INACTIVE ? "INACTIVE" : "???"))),
3182                                  HIWORD (msg->wParam) ? " minimized" : "",
3183                                  (HWND) msg->lParam));
3184       /* We handle mouse clicks for modally-blocked windows under WM_MOUSEACTIVATE,
3185        * but we still need to deal with alt-tab, or with SetActiveWindow() type
3186        * situations.
3187        */
3188       if (is_modally_blocked (window) && LOWORD (msg->wParam) == WA_ACTIVE)
3189         {
3190           GdkWindow *modal_current = _gdk_modal_current ();
3191           SetActiveWindow (GDK_WINDOW_HWND (modal_current));
3192           *ret_valp = 0;
3193           return_val = TRUE;
3194           break;
3195         }
3196
3197       /* Bring any tablet contexts to the top of the overlap order when
3198        * one of our windows is activated.
3199        * NOTE: It doesn't seem to work well if it is done in WM_ACTIVATEAPP
3200        * instead
3201        */
3202       if (LOWORD(msg->wParam) != WA_INACTIVE)
3203         _gdk_input_set_tablet_active ();
3204       break;
3205
3206     case WM_ACTIVATEAPP:
3207       GDK_NOTE (EVENTS, g_print (" %s thread: %I64d",
3208                                  msg->wParam ? "YES" : "NO",
3209                                  (gint64) msg->lParam));
3210       if (msg->wParam && GDK_WINDOW_IS_MAPPED (window))
3211         ensure_stacking_on_activate_app (msg, window);
3212       break;
3213
3214       /* Handle WINTAB events here, as we know that gdkinput.c will
3215        * use the fixed WT_DEFBASE as lcMsgBase, and we thus can use the
3216        * constants as case labels.
3217        */
3218     case WT_PACKET:
3219       GDK_NOTE (EVENTS, g_print (" %d %p",
3220                                  (int) msg->wParam, (gpointer) msg->lParam));
3221       goto wintab;
3222       
3223     case WT_CSRCHANGE:
3224       GDK_NOTE (EVENTS, g_print (" %d %p",
3225                                  (int) msg->wParam, (gpointer) msg->lParam));
3226       goto wintab;
3227       
3228     case WT_PROXIMITY:
3229       GDK_NOTE (EVENTS, g_print (" %p %d %d",
3230                                  (gpointer) msg->wParam,
3231                                  LOWORD (msg->lParam),
3232                                  HIWORD (msg->lParam)));
3233       /* Fall through */
3234     wintab:
3235
3236       event = gdk_event_new (GDK_NOTHING);
3237       event->any.window = window;
3238       g_object_ref (window);
3239
3240       if (_gdk_input_other_event (event, msg, window))
3241         append_event (event);
3242       else
3243         gdk_event_free (event);
3244
3245       break;
3246     }
3247
3248 done:
3249
3250   if (window)
3251     g_object_unref (window);
3252   
3253 #undef return
3254   return return_val;
3255 }
3256
3257 void
3258 _gdk_events_queue (GdkDisplay *display)
3259 {
3260   MSG msg;
3261
3262   if (modal_win32_dialog != NULL)
3263     return;
3264   
3265   while (!_gdk_event_queue_find_first (display) &&
3266          PeekMessageW (&msg, NULL, 0, 0, PM_REMOVE))
3267     {
3268       TranslateMessage (&msg);
3269       DispatchMessageW (&msg);
3270     }
3271 }
3272
3273 static gboolean
3274 gdk_event_prepare (GSource *source,
3275                    gint    *timeout)
3276 {
3277   MSG msg;
3278   gboolean retval;
3279
3280   GDK_THREADS_ENTER ();
3281
3282   *timeout = -1;
3283
3284   retval = (_gdk_event_queue_find_first (_gdk_display) != NULL ||
3285             (modal_win32_dialog == NULL &&
3286              PeekMessageW (&msg, NULL, 0, 0, PM_NOREMOVE)));
3287
3288   GDK_THREADS_LEAVE ();
3289
3290   return retval;
3291 }
3292
3293 static gboolean
3294 gdk_event_check (GSource *source)
3295 {
3296   MSG msg;
3297   gboolean retval;
3298   
3299   GDK_THREADS_ENTER ();
3300
3301   if (event_poll_fd.revents & G_IO_IN)
3302     {
3303       retval = (_gdk_event_queue_find_first (_gdk_display) != NULL ||
3304                 (modal_win32_dialog == NULL &&
3305                  PeekMessageW (&msg, NULL, 0, 0, PM_NOREMOVE)));
3306     }
3307   else
3308     {
3309       retval = FALSE;
3310     }
3311
3312   GDK_THREADS_LEAVE ();
3313
3314   return retval;
3315 }
3316
3317 static gboolean
3318 gdk_event_dispatch (GSource     *source,
3319                     GSourceFunc  callback,
3320                     gpointer     user_data)
3321 {
3322   GdkEvent *event;
3323  
3324   GDK_THREADS_ENTER ();
3325
3326   _gdk_events_queue (_gdk_display);
3327   event = _gdk_event_unqueue (_gdk_display);
3328
3329   if (event)
3330     {
3331       if (_gdk_event_func)
3332         (*_gdk_event_func) (event, _gdk_event_data);
3333       
3334       gdk_event_free (event);
3335
3336       /* Do drag & drop if it is still pending */
3337       if (_dnd_source_state == GDK_WIN32_DND_PENDING) 
3338         {
3339           _dnd_source_state = GDK_WIN32_DND_DRAGGING;
3340           _gdk_win32_dnd_do_dragdrop ();
3341           _dnd_source_state = GDK_WIN32_DND_NONE;
3342         }
3343     }
3344   
3345   GDK_THREADS_LEAVE ();
3346
3347   return TRUE;
3348 }
3349
3350 void
3351 gdk_win32_set_modal_dialog_libgtk_only (HWND window)
3352 {
3353   modal_win32_dialog = window;
3354 }
3355
3356 static gboolean
3357 is_modally_blocked (GdkWindow *window)
3358 {
3359   GdkWindow *modal_current = _gdk_modal_current ();
3360   return modal_current != NULL ? gdk_window_get_toplevel (window) != modal_current : FALSE;
3361 }
3362
3363 static void
3364 check_for_too_much_data (GdkEvent *event)
3365 {
3366   if (event->client.data.l[1] ||
3367       event->client.data.l[2] ||
3368       event->client.data.l[3] ||
3369       event->client.data.l[4])
3370     {
3371       g_warning ("Only four bytes of data are passed in client messages on Win32\n");
3372     }
3373 }
3374
3375 gboolean
3376 gdk_event_send_client_message_for_display (GdkDisplay     *display,
3377                                            GdkEvent       *event, 
3378                                            GdkNativeWindow winid)
3379 {
3380   check_for_too_much_data (event);
3381
3382   return PostMessageW ((HWND) winid, client_message,
3383                        (WPARAM) event->client.message_type,
3384                        event->client.data.l[0]);
3385 }
3386
3387 void
3388 gdk_screen_broadcast_client_message (GdkScreen *screen, 
3389                                      GdkEvent  *event)
3390 {
3391   check_for_too_much_data (event);
3392
3393   PostMessageW (HWND_BROADCAST, client_message,
3394                (WPARAM) event->client.message_type,
3395                 event->client.data.l[0]);
3396 }
3397
3398 void
3399 gdk_flush (void)
3400 {
3401 #if 0
3402   MSG msg;
3403
3404   /* Process all messages currently available */
3405   while (PeekMessageW (&msg, NULL, 0, 0, PM_REMOVE))
3406     {
3407       TranslateMessage (&msg);
3408       DispatchMessageW (&msg);
3409     }
3410 #endif
3411
3412   GdiFlush ();
3413 }
3414
3415 void
3416 gdk_display_sync (GdkDisplay * display)
3417 {
3418   MSG msg;
3419
3420   g_return_if_fail (display == _gdk_display);
3421
3422   /* Process all messages currently available */
3423   while (PeekMessageW (&msg, NULL, 0, 0, PM_REMOVE))
3424     DispatchMessageW (&msg);
3425 }
3426
3427 void
3428 gdk_display_flush (GdkDisplay * display)
3429 {
3430   g_return_if_fail (display == _gdk_display);
3431
3432   /* Nothing */
3433 }
3434
3435 gboolean
3436 gdk_net_wm_supports (GdkAtom property)
3437 {
3438   return FALSE;
3439 }
3440
3441 void
3442 _gdk_windowing_event_data_copy (const GdkEvent *src,
3443                                 GdkEvent       *dst)
3444 {
3445 }
3446
3447 void
3448 _gdk_windowing_event_data_free (GdkEvent *event)
3449 {
3450 }