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