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