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