]> Pileus Git - ~andy/gtk/blob - gdk/x11/gdkdisplay-x11.c
x11: Fix window manager change detection
[~andy/gtk] / gdk / x11 / gdkdisplay-x11.c
1 /* GDK - The GIMP Drawing Kit
2  * gdkdisplay-x11.c
3  * 
4  * Copyright 2001 Sun Microsystems Inc.
5  * Copyright (C) 2004 Nokia Corporation
6  *
7  * Erwann Chenede <erwann.chenede@sun.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 #include "config.h"
26
27 #include "gdkasync.h"
28 #include "gdkdisplay.h"
29 #include "gdkeventsource.h"
30 #include "gdkeventtranslator.h"
31 #include "gdkinternals.h"
32 #include "gdkscreen.h"
33 #include "gdkinternals.h"
34 #include "gdkdeviceprivate.h"
35 #include "gdkkeysprivate.h"
36 #include "gdkdevicemanager.h"
37 #include "xsettings-client.h"
38 #include "gdkdisplay-x11.h"
39 #include "gdkprivate-x11.h"
40 #include "gdkscreen-x11.h"
41
42 #include <glib.h>
43 #include <glib/gprintf.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <errno.h>
47 #include <unistd.h>
48
49 #include <X11/Xatom.h>
50
51 #ifdef HAVE_XKB
52 #include <X11/XKBlib.h>
53 #endif
54
55 #ifdef HAVE_XFIXES
56 #include <X11/extensions/Xfixes.h>
57 #endif
58
59 #include <X11/extensions/shape.h>
60
61 #ifdef HAVE_XCOMPOSITE
62 #include <X11/extensions/Xcomposite.h>
63 #endif
64
65 #ifdef HAVE_XDAMAGE
66 #include <X11/extensions/Xdamage.h>
67 #endif
68
69 #ifdef HAVE_RANDR
70 #include <X11/extensions/Xrandr.h>
71 #endif
72
73 typedef struct _GdkErrorTrap  GdkErrorTrap;
74
75 struct _GdkErrorTrap
76 {
77   /* Next sequence when trap was pushed, i.e. first sequence to
78    * ignore
79    */
80   gulong start_sequence;
81
82   /* Next sequence when trap was popped, i.e. first sequence
83    * to not ignore. 0 if trap is still active.
84    */
85   gulong end_sequence;
86
87   /* Most recent error code within the sequence */
88   int error_code;
89 };
90
91 static void   gdk_x11_display_dispose            (GObject            *object);
92 static void   gdk_x11_display_finalize           (GObject            *object);
93
94 static void     gdk_x11_display_event_translator_init (GdkEventTranslatorIface *iface);
95
96 static gboolean gdk_x11_display_translate_event (GdkEventTranslator *translator,
97                                                  GdkDisplay         *display,
98                                                  GdkEvent           *event,
99                                                  XEvent             *xevent);
100
101 #ifdef HAVE_X11R6
102 static void gdk_internal_connection_watch (Display  *display,
103                                            XPointer  arg,
104                                            gint      fd,
105                                            gboolean  opening,
106                                            XPointer *watch_data);
107 #endif /* HAVE_X11R6 */
108
109 typedef struct _GdkEventTypeX11 GdkEventTypeX11;
110
111 struct _GdkEventTypeX11
112 {
113   gint base;
114   gint n_events;
115 };
116
117 /* Note that we never *directly* use WM_LOCALE_NAME, WM_PROTOCOLS,
118  * but including them here has the side-effect of getting them
119  * into the internal Xlib cache
120  */
121 static const char *const precache_atoms[] = {
122   "UTF8_STRING",
123   "WM_CLIENT_LEADER",
124   "WM_DELETE_WINDOW",
125   "WM_ICON_NAME",
126   "WM_LOCALE_NAME",
127   "WM_NAME",
128   "WM_PROTOCOLS",
129   "WM_TAKE_FOCUS",
130   "WM_WINDOW_ROLE",
131   "_NET_ACTIVE_WINDOW",
132   "_NET_CURRENT_DESKTOP",
133   "_NET_FRAME_EXTENTS",
134   "_NET_STARTUP_ID",
135   "_NET_WM_CM_S0",
136   "_NET_WM_DESKTOP",
137   "_NET_WM_ICON",
138   "_NET_WM_ICON_NAME",
139   "_NET_WM_NAME",
140   "_NET_WM_PID",
141   "_NET_WM_PING",
142   "_NET_WM_STATE",
143   "_NET_WM_STATE_ABOVE",
144   "_NET_WM_STATE_BELOW",
145   "_NET_WM_STATE_FULLSCREEN",
146   "_NET_WM_STATE_MODAL",
147   "_NET_WM_STATE_MAXIMIZED_VERT",
148   "_NET_WM_STATE_MAXIMIZED_HORZ",
149   "_NET_WM_STATE_SKIP_TASKBAR",
150   "_NET_WM_STATE_SKIP_PAGER",
151   "_NET_WM_STATE_STICKY",
152   "_NET_WM_SYNC_REQUEST",
153   "_NET_WM_SYNC_REQUEST_COUNTER",
154   "_NET_WM_WINDOW_TYPE",
155   "_NET_WM_WINDOW_TYPE_NORMAL",
156   "_NET_WM_USER_TIME",
157   "_NET_VIRTUAL_ROOTS",
158   "GDK_SELECTION"
159 };
160
161 static char *gdk_sm_client_id;
162
163 G_DEFINE_TYPE_WITH_CODE (GdkX11Display, gdk_x11_display, GDK_TYPE_DISPLAY,
164                          G_IMPLEMENT_INTERFACE (GDK_TYPE_EVENT_TRANSLATOR,
165                                                 gdk_x11_display_event_translator_init))
166
167
168 static void
169 gdk_x11_display_init (GdkX11Display *display)
170 {
171   _gdk_x11_display_manager_add_display (gdk_display_manager_get (),
172                                         GDK_DISPLAY (display));
173 }
174
175 static void
176 gdk_x11_display_event_translator_init (GdkEventTranslatorIface *iface)
177 {
178   iface->translate_event = gdk_x11_display_translate_event;
179 }
180
181 static void
182 do_net_wm_state_changes (GdkWindow *window)
183 {
184   GdkToplevelX11 *toplevel = _gdk_x11_window_get_toplevel (window);
185   GdkWindowState old_state;
186
187   if (GDK_WINDOW_DESTROYED (window) ||
188       gdk_window_get_window_type (window) != GDK_WINDOW_TOPLEVEL)
189     return;
190
191   old_state = gdk_window_get_state (window);
192
193   /* For found_sticky to remain TRUE, we have to also be on desktop
194    * 0xFFFFFFFF
195    */
196   if (old_state & GDK_WINDOW_STATE_STICKY)
197     {
198       if (!(toplevel->have_sticky && toplevel->on_all_desktops))
199         gdk_synthesize_window_state (window,
200                                      GDK_WINDOW_STATE_STICKY,
201                                      0);
202     }
203   else
204     {
205       if (toplevel->have_sticky || toplevel->on_all_desktops)
206         gdk_synthesize_window_state (window,
207                                      0,
208                                      GDK_WINDOW_STATE_STICKY);
209     }
210
211   if (old_state & GDK_WINDOW_STATE_FULLSCREEN)
212     {
213       if (!toplevel->have_fullscreen)
214         gdk_synthesize_window_state (window,
215                                      GDK_WINDOW_STATE_FULLSCREEN,
216                                      0);
217     }
218   else
219     {
220       if (toplevel->have_fullscreen)
221         gdk_synthesize_window_state (window,
222                                      0,
223                                      GDK_WINDOW_STATE_FULLSCREEN);
224     }
225
226   /* Our "maximized" means both vertical and horizontal; if only one,
227    * we don't expose that via GDK
228    */
229   if (old_state & GDK_WINDOW_STATE_MAXIMIZED)
230     {
231       if (!(toplevel->have_maxvert && toplevel->have_maxhorz))
232         gdk_synthesize_window_state (window,
233                                      GDK_WINDOW_STATE_MAXIMIZED,
234                                      0);
235     }
236   else
237     {
238       if (toplevel->have_maxvert && toplevel->have_maxhorz)
239         gdk_synthesize_window_state (window,
240                                      0,
241                                      GDK_WINDOW_STATE_MAXIMIZED);
242     }
243 }
244
245 static void
246 gdk_check_wm_desktop_changed (GdkWindow *window)
247 {
248   GdkToplevelX11 *toplevel = _gdk_x11_window_get_toplevel (window);
249   GdkDisplay *display = GDK_WINDOW_DISPLAY (window);
250
251   Atom type;
252   gint format;
253   gulong nitems;
254   gulong bytes_after;
255   guchar *data;
256   gulong *desktop;
257
258   type = None;
259   gdk_x11_display_error_trap_push (display);
260   XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display),
261                       GDK_WINDOW_XID (window),
262                       gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_DESKTOP"),
263                       0, G_MAXLONG, False, XA_CARDINAL, &type,
264                       &format, &nitems,
265                       &bytes_after, &data);
266   gdk_x11_display_error_trap_pop_ignored (display);
267
268   if (type != None)
269     {
270       desktop = (gulong *)data;
271       toplevel->on_all_desktops = (*desktop == 0xFFFFFFFF);
272       XFree (desktop);
273     }
274   else
275     toplevel->on_all_desktops = FALSE;
276
277   do_net_wm_state_changes (window);
278 }
279
280 static void
281 gdk_check_wm_state_changed (GdkWindow *window)
282 {
283   GdkToplevelX11 *toplevel = _gdk_x11_window_get_toplevel (window);
284   GdkDisplay *display = GDK_WINDOW_DISPLAY (window);
285
286   Atom type;
287   gint format;
288   gulong nitems;
289   gulong bytes_after;
290   guchar *data;
291   Atom *atoms = NULL;
292   gulong i;
293
294   gboolean had_sticky = toplevel->have_sticky;
295
296   toplevel->have_sticky = FALSE;
297   toplevel->have_maxvert = FALSE;
298   toplevel->have_maxhorz = FALSE;
299   toplevel->have_fullscreen = FALSE;
300
301   type = None;
302   gdk_x11_display_error_trap_push (display);
303   XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display), GDK_WINDOW_XID (window),
304                       gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_STATE"),
305                       0, G_MAXLONG, False, XA_ATOM, &type, &format, &nitems,
306                       &bytes_after, &data);
307   gdk_x11_display_error_trap_pop_ignored (display);
308
309   if (type != None)
310     {
311       Atom sticky_atom = gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_STATE_STICKY");
312       Atom maxvert_atom = gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_STATE_MAXIMIZED_VERT");
313       Atom maxhorz_atom = gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_STATE_MAXIMIZED_HORZ");
314       Atom fullscreen_atom = gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_STATE_FULLSCREEN");
315
316       atoms = (Atom *)data;
317
318       i = 0;
319       while (i < nitems)
320         {
321           if (atoms[i] == sticky_atom)
322             toplevel->have_sticky = TRUE;
323           else if (atoms[i] == maxvert_atom)
324             toplevel->have_maxvert = TRUE;
325           else if (atoms[i] == maxhorz_atom)
326             toplevel->have_maxhorz = TRUE;
327           else if (atoms[i] == fullscreen_atom)
328             toplevel->have_fullscreen = TRUE;
329
330           ++i;
331         }
332
333       XFree (atoms);
334     }
335
336   /* When have_sticky is turned on, we have to check the DESKTOP property
337    * as well.
338    */
339   if (toplevel->have_sticky && !had_sticky)
340     gdk_check_wm_desktop_changed (window);
341   else
342     do_net_wm_state_changes (window);
343 }
344
345 static GdkWindow *
346 get_event_window (GdkEventTranslator *translator,
347                   XEvent             *xevent)
348 {
349   GdkDisplay *display;
350   Window xwindow;
351
352   display = (GdkDisplay *) translator;
353
354   switch (xevent->type)
355     {
356     case DestroyNotify:
357       xwindow = xevent->xdestroywindow.window;
358       break;
359     case UnmapNotify:
360       xwindow = xevent->xunmap.window;
361       break;
362     case MapNotify:
363       xwindow = xevent->xmap.window;
364       break;
365     case ConfigureNotify:
366       xwindow = xevent->xconfigure.window;
367       break;
368     default:
369       xwindow = xevent->xany.window;
370     }
371
372   return gdk_x11_window_lookup_for_display (display, xwindow);
373 }
374
375 static gboolean
376 gdk_x11_display_translate_event (GdkEventTranslator *translator,
377                                  GdkDisplay         *display,
378                                  GdkEvent           *event,
379                                  XEvent             *xevent)
380 {
381   GdkWindow *window;
382   GdkWindowImplX11 *window_impl = NULL;
383   GdkScreen *screen = NULL;
384   GdkX11Screen *x11_screen = NULL;
385   GdkToplevelX11 *toplevel = NULL;
386   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
387   gboolean return_val;
388
389   /* Find the GdkWindow that this event relates to.
390    * Basically this means substructure events
391    * are reported same as structure events
392    */
393   window = get_event_window (translator, xevent);
394
395   if (window)
396     {
397       /* We may receive events such as NoExpose/GraphicsExpose
398        * and ShmCompletion for pixmaps
399        */
400       if (!GDK_IS_WINDOW (window))
401         return FALSE;
402
403       screen = GDK_WINDOW_SCREEN (window);
404       x11_screen = GDK_X11_SCREEN (screen);
405       toplevel = _gdk_x11_window_get_toplevel (window);
406       window_impl = GDK_WINDOW_IMPL_X11 (window->impl);
407
408       g_object_ref (window);
409     }
410
411   event->any.window = window;
412   event->any.send_event = xevent->xany.send_event ? TRUE : FALSE;
413
414   if (window && GDK_WINDOW_DESTROYED (window))
415     {
416       if (xevent->type != DestroyNotify)
417         {
418           return_val = FALSE;
419           goto done;
420         }
421     }
422
423   if (xevent->type == DestroyNotify)
424     {
425       int i, n;
426
427       n = gdk_display_get_n_screens (display);
428       for (i = 0; i < n; i++)
429         {
430           screen = gdk_display_get_screen (display, i);
431           x11_screen = GDK_X11_SCREEN (screen);
432
433           if (x11_screen->wmspec_check_window == xevent->xdestroywindow.window)
434             {
435               x11_screen->wmspec_check_window = None;
436               x11_screen->last_wmspec_check_time = 0;
437               g_free (x11_screen->window_manager_name);
438               x11_screen->window_manager_name = g_strdup ("unknown");
439
440               /* careful, reentrancy */
441               _gdk_x11_screen_window_manager_changed (screen);
442
443               return_val = FALSE;
444               goto done;
445             }
446         }
447     }
448
449   /* We do a "manual" conversion of the XEvent to a
450    *  GdkEvent. The structures are mostly the same so
451    *  the conversion is fairly straightforward. We also
452    *  optionally print debugging info regarding events
453    *  received.
454    */
455
456   return_val = TRUE;
457
458   switch (xevent->type)
459     {
460     case KeymapNotify:
461       GDK_NOTE (EVENTS,
462                 g_message ("keymap notify"));
463
464       /* Not currently handled */
465       return_val = FALSE;
466       break;
467
468     case Expose:
469       GDK_NOTE (EVENTS,
470                 g_message ("expose:\t\twindow: %ld  %d  x,y: %d %d  w,h: %d %d%s",
471                            xevent->xexpose.window, xevent->xexpose.count,
472                            xevent->xexpose.x, xevent->xexpose.y,
473                            xevent->xexpose.width, xevent->xexpose.height,
474                            event->any.send_event ? " (send)" : ""));
475
476       if (window == NULL)
477         {
478           return_val = FALSE;
479           break;
480         }
481
482       {
483         GdkRectangle expose_rect;
484
485         expose_rect.x = xevent->xexpose.x;
486         expose_rect.y = xevent->xexpose.y;
487         expose_rect.width = xevent->xexpose.width;
488         expose_rect.height = xevent->xexpose.height;
489
490         _gdk_x11_window_process_expose (window, xevent->xexpose.serial, &expose_rect);
491         return_val = FALSE;
492       }
493
494       break;
495
496     case GraphicsExpose:
497       {
498         GdkRectangle expose_rect;
499
500         GDK_NOTE (EVENTS,
501                   g_message ("graphics expose:\tdrawable: %ld",
502                              xevent->xgraphicsexpose.drawable));
503
504         if (window == NULL)
505           {
506             return_val = FALSE;
507             break;
508           }
509
510         expose_rect.x = xevent->xgraphicsexpose.x;
511         expose_rect.y = xevent->xgraphicsexpose.y;
512         expose_rect.width = xevent->xgraphicsexpose.width;
513         expose_rect.height = xevent->xgraphicsexpose.height;
514
515         _gdk_x11_window_process_expose (window, xevent->xgraphicsexpose.serial, &expose_rect);
516         return_val = FALSE;
517       }
518       break;
519
520     case VisibilityNotify:
521 #ifdef G_ENABLE_DEBUG
522       if (_gdk_debug_flags & GDK_DEBUG_EVENTS)
523         switch (xevent->xvisibility.state)
524           {
525           case VisibilityFullyObscured:
526             g_message ("visibility notify:\twindow: %ld  none",
527                        xevent->xvisibility.window);
528             break;
529           case VisibilityPartiallyObscured:
530             g_message ("visibility notify:\twindow: %ld  partial",
531                        xevent->xvisibility.window);
532             break;
533           case VisibilityUnobscured:
534             g_message ("visibility notify:\twindow: %ld  full",
535                        xevent->xvisibility.window);
536             break;
537           }
538 #endif /* G_ENABLE_DEBUG */
539
540       if (window == NULL)
541         {
542           return_val = FALSE;
543           break;
544         }
545
546       event->visibility.type = GDK_VISIBILITY_NOTIFY;
547       event->visibility.window = window;
548
549       switch (xevent->xvisibility.state)
550         {
551         case VisibilityFullyObscured:
552           event->visibility.state = GDK_VISIBILITY_FULLY_OBSCURED;
553           break;
554
555         case VisibilityPartiallyObscured:
556           event->visibility.state = GDK_VISIBILITY_PARTIAL;
557           break;
558
559         case VisibilityUnobscured:
560           event->visibility.state = GDK_VISIBILITY_UNOBSCURED;
561           break;
562         }
563
564       break;
565
566     case CreateNotify:
567       GDK_NOTE (EVENTS,
568                 g_message ("create notify:\twindow: %ld  x,y: %d %d     w,h: %d %d  b-w: %d  parent: %ld         ovr: %d",
569                            xevent->xcreatewindow.window,
570                            xevent->xcreatewindow.x,
571                            xevent->xcreatewindow.y,
572                            xevent->xcreatewindow.width,
573                            xevent->xcreatewindow.height,
574                            xevent->xcreatewindow.border_width,
575                            xevent->xcreatewindow.parent,
576                            xevent->xcreatewindow.override_redirect));
577       /* not really handled */
578       break;
579
580     case DestroyNotify:
581       GDK_NOTE (EVENTS,
582                 g_message ("destroy notify:\twindow: %ld",
583                            xevent->xdestroywindow.window));
584
585       /* Ignore DestroyNotify from SubstructureNotifyMask */
586       if (xevent->xdestroywindow.window == xevent->xdestroywindow.event)
587         {
588           event->any.type = GDK_DESTROY;
589           event->any.window = window;
590
591           return_val = window && !GDK_WINDOW_DESTROYED (window);
592
593           if (window && GDK_WINDOW_XID (window) != x11_screen->xroot_window)
594             gdk_window_destroy_notify (window);
595         }
596       else
597         return_val = FALSE;
598
599       break;
600
601     case UnmapNotify:
602       GDK_NOTE (EVENTS,
603                 g_message ("unmap notify:\t\twindow: %ld",
604                            xevent->xmap.window));
605
606       event->any.type = GDK_UNMAP;
607       event->any.window = window;
608
609       /* If we are shown (not withdrawn) and get an unmap, it means we
610        * were iconified in the X sense. If we are withdrawn, and get
611        * an unmap, it means we hid the window ourselves, so we
612        * will have already flipped the iconified bit off.
613        */
614       if (window)
615         {
616           if (GDK_WINDOW_IS_MAPPED (window))
617             gdk_synthesize_window_state (window,
618                                          0,
619                                          GDK_WINDOW_STATE_ICONIFIED);
620
621           _gdk_x11_window_grab_check_unmap (window, xevent->xany.serial);
622         }
623
624       break;
625
626     case MapNotify:
627       GDK_NOTE (EVENTS,
628                 g_message ("map notify:\t\twindow: %ld",
629                            xevent->xmap.window));
630
631       event->any.type = GDK_MAP;
632       event->any.window = window;
633
634       /* Unset iconified if it was set */
635       if (window && (window->state & GDK_WINDOW_STATE_ICONIFIED))
636         gdk_synthesize_window_state (window,
637                                      GDK_WINDOW_STATE_ICONIFIED,
638                                      0);
639
640       break;
641
642     case ReparentNotify:
643       GDK_NOTE (EVENTS,
644                 g_message ("reparent notify:\twindow: %ld  x,y: %d %d  parent: %ld      ovr: %d",
645                            xevent->xreparent.window,
646                            xevent->xreparent.x,
647                            xevent->xreparent.y,
648                            xevent->xreparent.parent,
649                            xevent->xreparent.override_redirect));
650
651       /* Not currently handled */
652       return_val = FALSE;
653       break;
654
655     case ConfigureNotify:
656       GDK_NOTE (EVENTS,
657                 g_message ("configure notify:\twindow: %ld  x,y: %d %d  w,h: %d %d  b-w: %d  above: %ld  ovr: %d%s",
658                            xevent->xconfigure.window,
659                            xevent->xconfigure.x,
660                            xevent->xconfigure.y,
661                            xevent->xconfigure.width,
662                            xevent->xconfigure.height,
663                            xevent->xconfigure.border_width,
664                            xevent->xconfigure.above,
665                            xevent->xconfigure.override_redirect,
666                            !window
667                            ? " (discarding)"
668                            : window->window_type == GDK_WINDOW_CHILD
669                            ? " (discarding child)"
670                            : xevent->xconfigure.event != xevent->xconfigure.window
671                            ? " (discarding substructure)"
672                            : ""));
673       if (window && GDK_WINDOW_TYPE (window) == GDK_WINDOW_ROOT)
674         {
675           window->width = xevent->xconfigure.width;
676           window->height = xevent->xconfigure.height;
677
678           _gdk_window_update_size (window);
679           _gdk_x11_window_update_size (GDK_WINDOW_IMPL_X11 (window->impl));
680           _gdk_x11_screen_size_changed (screen, xevent);
681         }
682
683 #ifdef HAVE_XSYNC
684       if (toplevel && display_x11->use_sync && !XSyncValueIsZero (toplevel->pending_counter_value))
685         {
686           toplevel->current_counter_value = toplevel->pending_counter_value;
687           XSyncIntToValue (&toplevel->pending_counter_value, 0);
688         }
689 #endif
690
691     if (!window ||
692           xevent->xconfigure.event != xevent->xconfigure.window ||
693           GDK_WINDOW_TYPE (window) == GDK_WINDOW_CHILD ||
694           GDK_WINDOW_TYPE (window) == GDK_WINDOW_ROOT)
695         return_val = FALSE;
696       else
697         {
698           event->configure.type = GDK_CONFIGURE;
699           event->configure.window = window;
700           event->configure.width = xevent->xconfigure.width;
701           event->configure.height = xevent->xconfigure.height;
702
703           if (!xevent->xconfigure.send_event &&
704               !xevent->xconfigure.override_redirect &&
705               !GDK_WINDOW_DESTROYED (window))
706             {
707               gint tx = 0;
708               gint ty = 0;
709               Window child_window = 0;
710
711               gdk_x11_display_error_trap_push (display);
712               if (XTranslateCoordinates (GDK_WINDOW_XDISPLAY (window),
713                                          GDK_WINDOW_XID (window),
714                                          x11_screen->xroot_window,
715                                          0, 0,
716                                          &tx, &ty,
717                                          &child_window))
718                 {
719                   event->configure.x = tx;
720                   event->configure.y = ty;
721                 }
722               gdk_x11_display_error_trap_pop_ignored (display);
723             }
724           else
725             {
726               event->configure.x = xevent->xconfigure.x;
727               event->configure.y = xevent->xconfigure.y;
728             }
729           window->x = event->configure.x;
730           window->y = event->configure.y;
731           window->width = xevent->xconfigure.width;
732           window->height = xevent->xconfigure.height;
733
734           _gdk_window_update_size (window);
735           _gdk_x11_window_update_size (GDK_WINDOW_IMPL_X11 (window->impl));
736
737           if (window->resize_count >= 1)
738             {
739               window->resize_count -= 1;
740
741               if (window->resize_count == 0)
742                 _gdk_x11_moveresize_configure_done (display, window);
743             }
744         }
745       break;
746
747     case PropertyNotify:
748       GDK_NOTE (EVENTS,
749                 g_message ("property notify:\twindow: %ld, atom(%ld): %s%s%s",
750                            xevent->xproperty.window,
751                            xevent->xproperty.atom,
752                            "\"",
753                            gdk_x11_get_xatom_name_for_display (display, xevent->xproperty.atom),
754                            "\""));
755
756       if (window == NULL)
757         {
758           return_val = FALSE;
759           break;
760         }
761
762       /* We compare with the serial of the last time we mapped the
763        * window to avoid refetching properties that we set ourselves
764        */
765       if (toplevel &&
766           xevent->xproperty.serial >= toplevel->map_serial)
767         {
768           if (xevent->xproperty.atom == gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_STATE"))
769             gdk_check_wm_state_changed (window);
770
771           if (xevent->xproperty.atom == gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_DESKTOP"))
772             gdk_check_wm_desktop_changed (window);
773         }
774
775       if (window->event_mask & GDK_PROPERTY_CHANGE_MASK)
776         {
777           event->property.type = GDK_PROPERTY_NOTIFY;
778           event->property.window = window;
779           event->property.atom = gdk_x11_xatom_to_atom_for_display (display, xevent->xproperty.atom);
780           event->property.time = xevent->xproperty.time;
781           event->property.state = xevent->xproperty.state;
782         }
783       else
784         return_val = FALSE;
785
786       break;
787
788     case SelectionClear:
789       GDK_NOTE (EVENTS,
790                 g_message ("selection clear:\twindow: %ld",
791                            xevent->xproperty.window));
792
793       if (_gdk_x11_selection_filter_clear_event (&xevent->xselectionclear))
794         {
795           event->selection.type = GDK_SELECTION_CLEAR;
796           event->selection.window = window;
797           event->selection.selection = gdk_x11_xatom_to_atom_for_display (display, xevent->xselectionclear.selection);
798           event->selection.time = xevent->xselectionclear.time;
799         }
800       else
801         return_val = FALSE;
802
803       break;
804
805     case SelectionRequest:
806       GDK_NOTE (EVENTS,
807                 g_message ("selection request:\twindow: %ld",
808                            xevent->xproperty.window));
809
810       event->selection.type = GDK_SELECTION_REQUEST;
811       event->selection.window = window;
812       event->selection.selection = gdk_x11_xatom_to_atom_for_display (display, xevent->xselectionrequest.selection);
813       event->selection.target = gdk_x11_xatom_to_atom_for_display (display, xevent->xselectionrequest.target);
814       event->selection.property = gdk_x11_xatom_to_atom_for_display (display, xevent->xselectionrequest.property);
815       if (xevent->xselectionrequest.requestor != None)
816         event->selection.requestor = gdk_x11_window_foreign_new_for_display (display,
817                                                                              xevent->xselectionrequest.requestor);
818       else
819         event->selection.requestor = NULL;
820       event->selection.time = xevent->xselectionrequest.time;
821
822       break;
823
824     case SelectionNotify:
825       GDK_NOTE (EVENTS,
826                 g_message ("selection notify:\twindow: %ld",
827                            xevent->xproperty.window));
828
829       event->selection.type = GDK_SELECTION_NOTIFY;
830       event->selection.window = window;
831       event->selection.selection = gdk_x11_xatom_to_atom_for_display (display, xevent->xselection.selection);
832       event->selection.target = gdk_x11_xatom_to_atom_for_display (display, xevent->xselection.target);
833       if (xevent->xselection.property == None)
834         event->selection.property = GDK_NONE;
835       else
836         event->selection.property = gdk_x11_xatom_to_atom_for_display (display, xevent->xselection.property);
837       event->selection.time = xevent->xselection.time;
838
839       break;
840
841     case ColormapNotify:
842       GDK_NOTE (EVENTS,
843                 g_message ("colormap notify:\twindow: %ld",
844                            xevent->xcolormap.window));
845
846       /* Not currently handled */
847       return_val = FALSE;
848       break;
849
850     case ClientMessage:
851       GDK_NOTE (EVENTS,
852                 g_message ("client message:\twindow: %ld",
853                            xevent->xclient.window));
854
855       /* Not currently handled */
856       return_val = FALSE;
857       break;
858
859     case MappingNotify:
860       GDK_NOTE (EVENTS,
861                 g_message ("mapping notify"));
862
863       /* Let XLib know that there is a new keyboard mapping.
864        */
865       XRefreshKeyboardMapping (&xevent->xmapping);
866       _gdk_x11_keymap_keys_changed (display);
867       return_val = FALSE;
868       break;
869
870     default:
871 #ifdef HAVE_XFIXES
872       if (xevent->type - display_x11->xfixes_event_base == XFixesSelectionNotify)
873         {
874           XFixesSelectionNotifyEvent *selection_notify = (XFixesSelectionNotifyEvent *)xevent;
875
876           _gdk_x11_screen_process_owner_change (screen, xevent);
877           
878           event->owner_change.type = GDK_OWNER_CHANGE;
879           event->owner_change.window = window;
880           if (selection_notify->owner != None)
881             event->owner_change.owner = gdk_x11_window_foreign_new_for_display (display,
882                                                                                 selection_notify->owner);
883           else
884             event->owner_change.owner = NULL;
885           event->owner_change.reason = selection_notify->subtype;
886           event->owner_change.selection = 
887             gdk_x11_xatom_to_atom_for_display (display, 
888                                                selection_notify->selection);
889           event->owner_change.time = selection_notify->timestamp;
890           event->owner_change.selection_time = selection_notify->selection_timestamp;
891           
892           return_val = TRUE;
893         }
894       else
895 #endif
896 #ifdef HAVE_RANDR
897       if (xevent->type - display_x11->xrandr_event_base == RRScreenChangeNotify ||
898           xevent->type - display_x11->xrandr_event_base == RRNotify)
899         {
900           if (screen)
901             _gdk_x11_screen_size_changed (screen, xevent);
902         }
903       else
904 #endif
905 #if defined(HAVE_XCOMPOSITE) && defined (HAVE_XDAMAGE) && defined (HAVE_XFIXES)
906       if (display_x11->have_xdamage && window && window->composited &&
907           xevent->type == display_x11->xdamage_event_base + XDamageNotify &&
908           ((XDamageNotifyEvent *) xevent)->damage == window_impl->damage)
909         {
910           XDamageNotifyEvent *damage_event = (XDamageNotifyEvent *) xevent;
911           XserverRegion repair;
912           GdkRectangle rect;
913
914           rect.x = window->x + damage_event->area.x;
915           rect.y = window->y + damage_event->area.y;
916           rect.width = damage_event->area.width;
917           rect.height = damage_event->area.height;
918
919           repair = XFixesCreateRegion (display_x11->xdisplay,
920                                        &damage_event->area, 1);
921           XDamageSubtract (display_x11->xdisplay,
922                            window_impl->damage,
923                            repair, None);
924           XFixesDestroyRegion (display_x11->xdisplay, repair);
925
926           if (window->parent != NULL)
927            _gdk_x11_window_process_expose (window->parent,
928                                            damage_event->serial, &rect);
929
930           return_val = TRUE;
931         }
932       else
933 #endif
934 #ifdef HAVE_XKB
935       if (xevent->type == display_x11->xkb_event_type)
936         {
937           XkbEvent *xkb_event = (XkbEvent *) xevent;
938
939           switch (xkb_event->any.xkb_type)
940             {
941             case XkbNewKeyboardNotify:
942             case XkbMapNotify:
943               _gdk_x11_keymap_keys_changed (display);
944
945               return_val = FALSE;
946               break;
947
948             case XkbStateNotify:
949               _gdk_x11_keymap_state_changed (display, xevent);
950               break;
951             }
952         }
953       else
954 #endif
955         return_val = FALSE;
956     }
957
958  done:
959   if (return_val)
960     {
961       if (event->any.window)
962         g_object_ref (event->any.window);
963     }
964   else
965     {
966       /* Mark this event as having no resources to be freed */
967       event->any.window = NULL;
968       event->any.type = GDK_NOTHING;
969     }
970
971   if (window)
972     g_object_unref (window);
973
974   return return_val;
975 }
976
977 GdkFilterReturn
978 _gdk_wm_protocols_filter (GdkXEvent *xev,
979                           GdkEvent  *event,
980                           gpointer   data)
981 {
982   XEvent *xevent = (XEvent *)xev;
983   GdkWindow *win = event->any.window;
984   GdkDisplay *display;
985   Atom atom;
986
987   if (!GDK_IS_X11_WINDOW (win))
988     return GDK_FILTER_CONTINUE;
989
990   if (xevent->type != ClientMessage)
991     return GDK_FILTER_CONTINUE;
992
993   display = GDK_WINDOW_DISPLAY (win);
994
995   if (xevent->xclient.message_type != gdk_x11_get_xatom_by_name_for_display (display, "WM_PROTOCOLS"))
996     return GDK_FILTER_CONTINUE;
997
998   atom = (Atom) xevent->xclient.data.l[0];
999
1000   if (atom == gdk_x11_get_xatom_by_name_for_display (display, "WM_DELETE_WINDOW"))
1001     {
1002   /* The delete window request specifies a window
1003    *  to delete. We don't actually destroy the
1004    *  window because "it is only a request". (The
1005    *  window might contain vital data that the
1006    *  program does not want destroyed). Instead
1007    *  the event is passed along to the program,
1008    *  which should then destroy the window.
1009    */
1010       GDK_NOTE (EVENTS,
1011                 g_message ("delete window:\t\twindow: %ld",
1012                            xevent->xclient.window));
1013
1014       event->any.type = GDK_DELETE;
1015
1016       gdk_x11_window_set_user_time (win, xevent->xclient.data.l[1]);
1017
1018       return GDK_FILTER_TRANSLATE;
1019     }
1020   else if (atom == gdk_x11_get_xatom_by_name_for_display (display, "WM_TAKE_FOCUS"))
1021     {
1022       GdkToplevelX11 *toplevel = _gdk_x11_window_get_toplevel (event->any.window);
1023
1024       /* There is no way of knowing reliably whether we are viewable;
1025        * so trap errors asynchronously around the XSetInputFocus call
1026        */
1027       if (toplevel && win->accept_focus)
1028         {
1029           gdk_x11_display_error_trap_push (display);
1030           XSetInputFocus (GDK_DISPLAY_XDISPLAY (display),
1031                           toplevel->focus_window,
1032                           RevertToParent,
1033                           xevent->xclient.data.l[1]);
1034           gdk_x11_display_error_trap_pop_ignored (display);
1035        }
1036
1037       return GDK_FILTER_REMOVE;
1038     }
1039   else if (atom == gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_PING") &&
1040            !_gdk_x11_display_is_root_window (display,
1041                                              xevent->xclient.window))
1042     {
1043       XClientMessageEvent xclient = xevent->xclient;
1044
1045       xclient.window = GDK_WINDOW_XROOTWIN (win);
1046       XSendEvent (GDK_WINDOW_XDISPLAY (win),
1047                   xclient.window,
1048                   False,
1049                   SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xclient);
1050
1051       return GDK_FILTER_REMOVE;
1052     }
1053   else if (atom == gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_SYNC_REQUEST") &&
1054            GDK_X11_DISPLAY (display)->use_sync)
1055     {
1056       GdkToplevelX11 *toplevel = _gdk_x11_window_get_toplevel (event->any.window);
1057       if (toplevel)
1058         {
1059 #ifdef HAVE_XSYNC
1060           XSyncIntsToValue (&toplevel->pending_counter_value,
1061                             xevent->xclient.data.l[2],
1062                             xevent->xclient.data.l[3]);
1063 #endif
1064         }
1065       return GDK_FILTER_REMOVE;
1066     }
1067
1068   return GDK_FILTER_CONTINUE;
1069 }
1070
1071 static void
1072 gdk_event_init (GdkDisplay *display)
1073 {
1074   GdkX11Display *display_x11;
1075   GdkDeviceManager *device_manager;
1076
1077   display_x11 = GDK_X11_DISPLAY (display);
1078   display_x11->event_source = gdk_x11_event_source_new (display);
1079
1080   gdk_x11_event_source_add_translator ((GdkEventSource *) display_x11->event_source,
1081                                        GDK_EVENT_TRANSLATOR (display));
1082
1083   device_manager = gdk_display_get_device_manager (display);
1084   gdk_x11_event_source_add_translator ((GdkEventSource *) display_x11->event_source,
1085                                         GDK_EVENT_TRANSLATOR (device_manager));
1086 }
1087
1088 static void
1089 gdk_x11_display_init_input (GdkDisplay *display)
1090 {
1091   GdkX11Display *display_x11;
1092   GdkDeviceManager *device_manager;
1093   GdkDevice *device;
1094   GList *list, *l;
1095
1096   display_x11 = GDK_X11_DISPLAY (display);
1097   device_manager = gdk_display_get_device_manager (display);
1098
1099   /* For backwards compatibility, just add
1100    * floating devices that are not keyboards.
1101    */
1102   list = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_FLOATING);
1103
1104   for (l = list; l; l = l->next)
1105     {
1106       device = l->data;
1107
1108       if (gdk_device_get_source (device) == GDK_SOURCE_KEYBOARD)
1109         continue;
1110
1111       display_x11->input_devices = g_list_prepend (display_x11->input_devices,
1112                                                    g_object_ref (l->data));
1113     }
1114
1115   g_list_free (list);
1116
1117   /* Now set "core" pointer to the first
1118    * master device that is a pointer.
1119    */
1120   list = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_MASTER);
1121
1122   for (l = list; l; l = l->next)
1123     {
1124       device = l->data;
1125
1126       if (gdk_device_get_source (device) != GDK_SOURCE_MOUSE)
1127         continue;
1128
1129       display->core_pointer = device;
1130       break;
1131     }
1132
1133   /* Add the core pointer to the devices list */
1134   display_x11->input_devices = g_list_prepend (display_x11->input_devices,
1135                                                g_object_ref (display->core_pointer));
1136
1137   g_list_free (list);
1138 }
1139
1140 static void
1141 set_sm_client_id (GdkDisplay  *display,
1142                   const gchar *sm_client_id)
1143 {
1144   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
1145
1146   if (gdk_display_is_closed (display))
1147     return;
1148
1149   if (sm_client_id && strcmp (sm_client_id, ""))
1150     XChangeProperty (display_x11->xdisplay, display_x11->leader_window,
1151                      gdk_x11_get_xatom_by_name_for_display (display, "SM_CLIENT_ID"),
1152                      XA_STRING, 8, PropModeReplace, (guchar *)sm_client_id,
1153                      strlen (sm_client_id));
1154   else
1155     XDeleteProperty (display_x11->xdisplay, display_x11->leader_window,
1156                      gdk_x11_get_xatom_by_name_for_display (display, "SM_CLIENT_ID"));
1157 }
1158
1159 GdkDisplay *
1160 _gdk_x11_display_open (const gchar *display_name)
1161 {
1162   Display *xdisplay;
1163   GdkDisplay *display;
1164   GdkX11Display *display_x11;
1165   GdkWindowAttr attr;
1166   gint argc;
1167   gchar *argv[1];
1168
1169   XClassHint *class_hint;
1170   gulong pid;
1171   gint i;
1172   gint ignore;
1173   gint maj, min;
1174
1175   xdisplay = XOpenDisplay (display_name);
1176   if (!xdisplay)
1177     return NULL;
1178   
1179   display = g_object_new (GDK_TYPE_X11_DISPLAY, NULL);
1180   display_x11 = GDK_X11_DISPLAY (display);
1181
1182   display_x11->xdisplay = xdisplay;
1183
1184 #ifdef HAVE_X11R6  
1185   /* Set up handlers for Xlib internal connections */
1186   XAddConnectionWatch (xdisplay, gdk_internal_connection_watch, NULL);
1187 #endif /* HAVE_X11R6 */
1188   
1189   _gdk_x11_precache_atoms (display, precache_atoms, G_N_ELEMENTS (precache_atoms));
1190
1191   /* RandR must be initialized before we initialize the screens */
1192   display_x11->have_randr12 = FALSE;
1193   display_x11->have_randr13 = FALSE;
1194 #ifdef HAVE_RANDR
1195   if (XRRQueryExtension (display_x11->xdisplay,
1196                          &display_x11->xrandr_event_base, &ignore))
1197   {
1198       int major, minor;
1199
1200       XRRQueryVersion (display_x11->xdisplay, &major, &minor);
1201
1202       if ((major == 1 && minor >= 2) || major > 1) {
1203           display_x11->have_randr12 = TRUE;
1204           if (minor >= 3 || major > 1)
1205               display_x11->have_randr13 = TRUE;
1206       }
1207
1208        gdk_x11_register_standard_event_type (display, display_x11->xrandr_event_base, RRNumberEvents);
1209   }
1210 #endif
1211
1212   /* initialize the display's screens */ 
1213   display_x11->screens = g_new (GdkScreen *, ScreenCount (display_x11->xdisplay));
1214   for (i = 0; i < ScreenCount (display_x11->xdisplay); i++)
1215     display_x11->screens[i] = _gdk_x11_screen_new (display, i);
1216
1217   /* We need to initialize events after we have the screen
1218    * structures in places
1219    */
1220   for (i = 0; i < ScreenCount (display_x11->xdisplay); i++)
1221     _gdk_x11_screen_init_events (display_x11->screens[i]);
1222
1223   /*set the default screen */
1224   display_x11->default_screen = display_x11->screens[DefaultScreen (display_x11->xdisplay)];
1225
1226   display->device_manager = _gdk_x11_device_manager_new (display);
1227
1228   gdk_event_init (display);
1229
1230   attr.window_type = GDK_WINDOW_TOPLEVEL;
1231   attr.wclass = GDK_INPUT_OUTPUT;
1232   attr.x = 10;
1233   attr.y = 10;
1234   attr.width = 10;
1235   attr.height = 10;
1236   attr.event_mask = 0;
1237
1238   display_x11->leader_gdk_window = gdk_window_new (GDK_X11_SCREEN (display_x11->default_screen)->root_window, 
1239                                                    &attr, GDK_WA_X | GDK_WA_Y);
1240   (_gdk_x11_window_get_toplevel (display_x11->leader_gdk_window))->is_leader = TRUE;
1241
1242   display_x11->leader_window = GDK_WINDOW_XID (display_x11->leader_gdk_window);
1243
1244   display_x11->leader_window_title_set = FALSE;
1245
1246 #ifdef HAVE_XFIXES
1247   if (XFixesQueryExtension (display_x11->xdisplay, 
1248                             &display_x11->xfixes_event_base, 
1249                             &ignore))
1250     {
1251       display_x11->have_xfixes = TRUE;
1252
1253       gdk_x11_register_standard_event_type (display,
1254                                             display_x11->xfixes_event_base, 
1255                                             XFixesNumberEvents);
1256     }
1257   else
1258 #endif
1259     display_x11->have_xfixes = FALSE;
1260
1261 #ifdef HAVE_XCOMPOSITE
1262   if (XCompositeQueryExtension (display_x11->xdisplay,
1263                                 &ignore, &ignore))
1264     {
1265       int major, minor;
1266
1267       XCompositeQueryVersion (display_x11->xdisplay, &major, &minor);
1268
1269       /* Prior to Composite version 0.4, composited windows clipped their
1270        * parents, so you had to use IncludeInferiors to draw to the parent
1271        * This isn't useful for our purposes, so require 0.4
1272        */
1273       display_x11->have_xcomposite = major > 0 || (major == 0 && minor >= 4);
1274     }
1275   else
1276 #endif
1277     display_x11->have_xcomposite = FALSE;
1278
1279 #ifdef HAVE_XDAMAGE
1280   if (XDamageQueryExtension (display_x11->xdisplay,
1281                              &display_x11->xdamage_event_base,
1282                              &ignore))
1283     {
1284       display_x11->have_xdamage = TRUE;
1285
1286       gdk_x11_register_standard_event_type (display,
1287                                             display_x11->xdamage_event_base,
1288                                             XDamageNumberEvents);
1289     }
1290   else
1291 #endif
1292     display_x11->have_xdamage = FALSE;
1293
1294   display_x11->have_shapes = FALSE;
1295   display_x11->have_input_shapes = FALSE;
1296
1297   if (XShapeQueryExtension (GDK_DISPLAY_XDISPLAY (display), &display_x11->shape_event_base, &ignore))
1298     {
1299       display_x11->have_shapes = TRUE;
1300 #ifdef ShapeInput
1301       if (XShapeQueryVersion (GDK_DISPLAY_XDISPLAY (display), &maj, &min))
1302         display_x11->have_input_shapes = (maj == 1 && min >= 1);
1303 #endif
1304     }
1305
1306   display_x11->trusted_client = TRUE;
1307   {
1308     Window root, child;
1309     int rootx, rooty, winx, winy;
1310     unsigned int xmask;
1311
1312     gdk_x11_display_error_trap_push (display);
1313     XQueryPointer (display_x11->xdisplay,
1314                    GDK_X11_SCREEN (display_x11->default_screen)->xroot_window,
1315                    &root, &child, &rootx, &rooty, &winx, &winy, &xmask);
1316     if (G_UNLIKELY (gdk_x11_display_error_trap_pop (display) == BadWindow))
1317       {
1318         g_warning ("Connection to display %s appears to be untrusted. Pointer and keyboard grabs and inter-client communication may not work as expected.", gdk_display_get_name (display));
1319         display_x11->trusted_client = FALSE;
1320       }
1321   }
1322
1323   if (g_getenv ("GDK_SYNCHRONIZE"))
1324     XSynchronize (display_x11->xdisplay, True);
1325
1326   class_hint = XAllocClassHint();
1327   class_hint->res_name = g_get_prgname ();
1328
1329   class_hint->res_class = (char *)gdk_get_program_class ();
1330
1331   /* XmbSetWMProperties sets the RESOURCE_NAME environment variable
1332    * from argv[0], so we just synthesize an argument array here.
1333    */
1334   argc = 1;
1335   argv[0] = g_get_prgname ();
1336
1337   XmbSetWMProperties (display_x11->xdisplay,
1338                       display_x11->leader_window,
1339                       NULL, NULL, argv, argc, NULL, NULL,
1340                       class_hint);
1341   XFree (class_hint);
1342
1343   if (gdk_sm_client_id)
1344     set_sm_client_id (display, gdk_sm_client_id);
1345
1346   pid = getpid ();
1347   XChangeProperty (display_x11->xdisplay,
1348                    display_x11->leader_window,
1349                    gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_PID"),
1350                    XA_CARDINAL, 32, PropModeReplace, (guchar *) & pid, 1);
1351
1352   /* We don't yet know a valid time. */
1353   display_x11->user_time = 0;
1354   
1355 #ifdef HAVE_XKB
1356   {
1357     gint xkb_major = XkbMajorVersion;
1358     gint xkb_minor = XkbMinorVersion;
1359     if (XkbLibraryVersion (&xkb_major, &xkb_minor))
1360       {
1361         xkb_major = XkbMajorVersion;
1362         xkb_minor = XkbMinorVersion;
1363             
1364         if (XkbQueryExtension (display_x11->xdisplay, 
1365                                NULL, &display_x11->xkb_event_type, NULL,
1366                                &xkb_major, &xkb_minor))
1367           {
1368             Bool detectable_autorepeat_supported;
1369             
1370             display_x11->use_xkb = TRUE;
1371
1372             XkbSelectEvents (display_x11->xdisplay,
1373                              XkbUseCoreKbd,
1374                              XkbNewKeyboardNotifyMask | XkbMapNotifyMask | XkbStateNotifyMask,
1375                              XkbNewKeyboardNotifyMask | XkbMapNotifyMask | XkbStateNotifyMask);
1376
1377             /* keep this in sync with _gdk_x11_keymap_state_changed() */
1378             XkbSelectEventDetails (display_x11->xdisplay,
1379                                    XkbUseCoreKbd, XkbStateNotify,
1380                                    XkbAllStateComponentsMask,
1381                                    XkbGroupLockMask|XkbModifierLockMask);
1382
1383             XkbSetDetectableAutoRepeat (display_x11->xdisplay,
1384                                         True,
1385                                         &detectable_autorepeat_supported);
1386
1387             GDK_NOTE (MISC, g_message ("Detectable autorepeat %s.",
1388                                        detectable_autorepeat_supported ?
1389                                        "supported" : "not supported"));
1390             
1391             display_x11->have_xkb_autorepeat = detectable_autorepeat_supported;
1392           }
1393       }
1394   }
1395 #endif
1396
1397   display_x11->use_sync = FALSE;
1398 #ifdef HAVE_XSYNC
1399   {
1400     int major, minor;
1401     int error_base, event_base;
1402     
1403     if (XSyncQueryExtension (display_x11->xdisplay,
1404                              &event_base, &error_base) &&
1405         XSyncInitialize (display_x11->xdisplay,
1406                          &major, &minor))
1407       display_x11->use_sync = TRUE;
1408   }
1409 #endif
1410
1411   gdk_x11_display_init_input (display);
1412
1413   for (i = 0; i < ScreenCount (display_x11->xdisplay); i++)
1414     _gdk_x11_screen_setup (display_x11->screens[i]);
1415
1416   g_signal_emit_by_name (display, "opened");
1417   g_signal_emit_by_name (gdk_display_manager_get (), "display-opened", display);
1418
1419   return display;
1420 }
1421
1422 #ifdef HAVE_X11R6
1423 /*
1424  * XLib internal connection handling
1425  */
1426 typedef struct _GdkInternalConnection GdkInternalConnection;
1427
1428 struct _GdkInternalConnection
1429 {
1430   gint           fd;
1431   GSource       *source;
1432   Display       *display;
1433 };
1434
1435 static gboolean
1436 process_internal_connection (GIOChannel  *gioc,
1437                              GIOCondition cond,
1438                              gpointer     data)
1439 {
1440   GdkInternalConnection *connection = (GdkInternalConnection *)data;
1441
1442   GDK_THREADS_ENTER ();
1443
1444   XProcessInternalConnection ((Display*)connection->display, connection->fd);
1445
1446   GDK_THREADS_LEAVE ();
1447
1448   return TRUE;
1449 }
1450
1451 static gulong
1452 gdk_x11_display_get_next_serial (GdkDisplay *display)
1453 {
1454   return NextRequest (GDK_DISPLAY_XDISPLAY (display));
1455 }
1456
1457
1458 static GdkInternalConnection *
1459 gdk_add_connection_handler (Display *display,
1460                             guint    fd)
1461 {
1462   GIOChannel *io_channel;
1463   GdkInternalConnection *connection;
1464
1465   connection = g_new (GdkInternalConnection, 1);
1466
1467   connection->fd = fd;
1468   connection->display = display;
1469   
1470   io_channel = g_io_channel_unix_new (fd);
1471   
1472   connection->source = g_io_create_watch (io_channel, G_IO_IN);
1473   g_source_set_callback (connection->source,
1474                          (GSourceFunc)process_internal_connection, connection, NULL);
1475   g_source_attach (connection->source, NULL);
1476   
1477   g_io_channel_unref (io_channel);
1478   
1479   return connection;
1480 }
1481
1482 static void
1483 gdk_remove_connection_handler (GdkInternalConnection *connection)
1484 {
1485   g_source_destroy (connection->source);
1486   g_free (connection);
1487 }
1488
1489 static void
1490 gdk_internal_connection_watch (Display  *display,
1491                                XPointer  arg,
1492                                gint      fd,
1493                                gboolean  opening,
1494                                XPointer *watch_data)
1495 {
1496   if (opening)
1497     *watch_data = (XPointer)gdk_add_connection_handler (display, fd);
1498   else
1499     gdk_remove_connection_handler ((GdkInternalConnection *)*watch_data);
1500 }
1501 #endif /* HAVE_X11R6 */
1502
1503 static const gchar *
1504 gdk_x11_display_get_name (GdkDisplay *display)
1505 {
1506   return (gchar *) DisplayString (GDK_X11_DISPLAY (display)->xdisplay);
1507 }
1508
1509 static gint
1510 gdk_x11_display_get_n_screens (GdkDisplay *display)
1511 {
1512   return ScreenCount (GDK_X11_DISPLAY (display)->xdisplay);
1513 }
1514
1515 static GdkScreen *
1516 gdk_x11_display_get_screen (GdkDisplay *display,
1517                             gint        screen_num)
1518 {
1519   g_return_val_if_fail (ScreenCount (GDK_X11_DISPLAY (display)->xdisplay) > screen_num, NULL);
1520
1521   return GDK_X11_DISPLAY (display)->screens[screen_num];
1522 }
1523
1524 static GdkScreen *
1525 gdk_x11_display_get_default_screen (GdkDisplay *display)
1526 {
1527   return GDK_X11_DISPLAY (display)->default_screen;
1528 }
1529
1530 gboolean
1531 _gdk_x11_display_is_root_window (GdkDisplay *display,
1532                                  Window      xroot_window)
1533 {
1534   GdkX11Display *display_x11;
1535   gint i;
1536
1537   display_x11 = GDK_X11_DISPLAY (display);
1538
1539   for (i = 0; i < ScreenCount (display_x11->xdisplay); i++)
1540     {
1541       if (GDK_SCREEN_XROOTWIN (display_x11->screens[i]) == xroot_window)
1542         return TRUE;
1543     }
1544   return FALSE;
1545 }
1546
1547 struct XPointerUngrabInfo {
1548   GdkDisplay *display;
1549   guint32 time;
1550 };
1551
1552 static void
1553 device_grab_update_callback (GdkDisplay *display,
1554                              gpointer    data,
1555                              gulong      serial)
1556 {
1557   GdkDevice *device = data;
1558
1559   _gdk_display_device_grab_update (display, device, NULL, serial);
1560 }
1561
1562 #define XSERVER_TIME_IS_LATER(time1, time2)                        \
1563   ( (( time1 > time2 ) && ( time1 - time2 < ((guint32)-1)/2 )) ||  \
1564     (( time1 < time2 ) && ( time2 - time1 > ((guint32)-1)/2 ))     \
1565   )
1566
1567 void
1568 _gdk_x11_display_update_grab_info (GdkDisplay *display,
1569                                    GdkDevice  *device,
1570                                    gint        status)
1571 {
1572   if (status == GrabSuccess)
1573     _gdk_x11_roundtrip_async (display, device_grab_update_callback, device);
1574 }
1575
1576 void
1577 _gdk_x11_display_update_grab_info_ungrab (GdkDisplay *display,
1578                                           GdkDevice  *device,
1579                                           guint32     time,
1580                                           gulong      serial)
1581 {
1582   GdkDeviceGrabInfo *grab;
1583
1584   XFlush (GDK_DISPLAY_XDISPLAY (display));
1585
1586   grab = _gdk_display_get_last_device_grab (display, device);
1587   if (grab &&
1588       (time == GDK_CURRENT_TIME ||
1589        grab->time == GDK_CURRENT_TIME ||
1590        !XSERVER_TIME_IS_LATER (grab->time, time)))
1591     {
1592       grab->serial_end = serial;
1593       _gdk_x11_roundtrip_async (display, device_grab_update_callback, device);
1594     }
1595 }
1596
1597 static void
1598 gdk_x11_display_beep (GdkDisplay *display)
1599 {
1600 #ifdef HAVE_XKB
1601   XkbBell (GDK_DISPLAY_XDISPLAY (display), None, 0, None);
1602 #else
1603   XBell (GDK_DISPLAY_XDISPLAY (display), 0);
1604 #endif
1605 }
1606
1607 static void
1608 gdk_x11_display_sync (GdkDisplay *display)
1609 {
1610   XSync (GDK_DISPLAY_XDISPLAY (display), False);
1611 }
1612
1613 static void
1614 gdk_x11_display_flush (GdkDisplay *display)
1615 {
1616   if (!display->closed)
1617     XFlush (GDK_DISPLAY_XDISPLAY (display));
1618 }
1619
1620 static gboolean
1621 gdk_x11_display_has_pending (GdkDisplay *display)
1622 {
1623   return XPending (GDK_DISPLAY_XDISPLAY (display));
1624 }
1625
1626 static GdkWindow *
1627 gdk_x11_display_get_default_group (GdkDisplay *display)
1628 {
1629   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
1630
1631   return GDK_X11_DISPLAY (display)->leader_gdk_window;
1632 }
1633
1634 /**
1635  * gdk_x11_display_grab:
1636  * @display: (type GdkX11Display): a #GdkDisplay 
1637  * 
1638  * Call XGrabServer() on @display. 
1639  * To ungrab the display again, use gdk_x11_display_ungrab(). 
1640  *
1641  * gdk_x11_display_grab()/gdk_x11_display_ungrab() calls can be nested.
1642  *
1643  * Since: 2.2
1644  **/
1645 void
1646 gdk_x11_display_grab (GdkDisplay *display)
1647 {
1648   GdkX11Display *display_x11;
1649   
1650   g_return_if_fail (GDK_IS_DISPLAY (display));
1651   
1652   display_x11 = GDK_X11_DISPLAY (display);
1653   
1654   if (display_x11->grab_count == 0)
1655     XGrabServer (display_x11->xdisplay);
1656   display_x11->grab_count++;
1657 }
1658
1659 /**
1660  * gdk_x11_display_ungrab:
1661  * @display: (type GdkX11Display): a #GdkDisplay
1662  * 
1663  * Ungrab @display after it has been grabbed with 
1664  * gdk_x11_display_grab(). 
1665  *
1666  * Since: 2.2
1667  **/
1668 void
1669 gdk_x11_display_ungrab (GdkDisplay *display)
1670 {
1671   GdkX11Display *display_x11;
1672   
1673   g_return_if_fail (GDK_IS_DISPLAY (display));
1674   
1675   display_x11 = GDK_X11_DISPLAY (display);;
1676   g_return_if_fail (display_x11->grab_count > 0);
1677   
1678   display_x11->grab_count--;
1679   if (display_x11->grab_count == 0)
1680     {
1681       XUngrabServer (display_x11->xdisplay);
1682       XFlush (display_x11->xdisplay);
1683     }
1684 }
1685
1686 static void
1687 gdk_x11_display_dispose (GObject *object)
1688 {
1689   GdkDisplay *display = GDK_DISPLAY (object);
1690   GdkX11Display *display_x11 = GDK_X11_DISPLAY (object);
1691   gint           i;
1692
1693   _gdk_x11_display_manager_remove_display (gdk_display_manager_get (), display);
1694
1695   g_list_foreach (display_x11->input_devices, (GFunc) g_object_run_dispose, NULL);
1696
1697   for (i = 0; i < ScreenCount (display_x11->xdisplay); i++)
1698     _gdk_screen_close (display_x11->screens[i]);
1699
1700   if (display_x11->event_source)
1701     {
1702       g_source_destroy (display_x11->event_source);
1703       g_source_unref (display_x11->event_source);
1704       display_x11->event_source = NULL;
1705     }
1706
1707   G_OBJECT_CLASS (gdk_x11_display_parent_class)->dispose (object);
1708 }
1709
1710 static void
1711 gdk_x11_display_finalize (GObject *object)
1712 {
1713   GdkX11Display *display_x11 = GDK_X11_DISPLAY (object);
1714   gint           i;
1715
1716   /* Keymap */
1717   if (display_x11->keymap)
1718     g_object_unref (display_x11->keymap);
1719
1720   /* Free motif Dnd */
1721   if (display_x11->motif_target_lists)
1722     {
1723       for (i = 0; i < display_x11->motif_n_target_lists; i++)
1724         g_list_free (display_x11->motif_target_lists[i]);
1725       g_free (display_x11->motif_target_lists);
1726     }
1727
1728   _gdk_x11_cursor_display_finalize (GDK_DISPLAY (display_x11));
1729
1730   /* Empty the event queue */
1731   _gdk_x11_display_free_translate_queue (GDK_DISPLAY (display_x11));
1732
1733   /* Atom Hashtable */
1734   g_hash_table_destroy (display_x11->atom_from_virtual);
1735   g_hash_table_destroy (display_x11->atom_to_virtual);
1736
1737   /* Leader Window */
1738   XDestroyWindow (display_x11->xdisplay, display_x11->leader_window);
1739
1740   /* List of event window extraction functions */
1741   g_slist_foreach (display_x11->event_types, (GFunc)g_free, NULL);
1742   g_slist_free (display_x11->event_types);
1743
1744   /* input GdkDevice list */
1745   g_list_foreach (display_x11->input_devices, (GFunc) g_object_unref, NULL);
1746   g_list_free (display_x11->input_devices);
1747
1748   /* input GdkWindow list */
1749   g_list_foreach (display_x11->input_windows, (GFunc) g_free, NULL);
1750   g_list_free (display_x11->input_windows);
1751
1752   /* Free all GdkScreens */
1753   for (i = 0; i < ScreenCount (display_x11->xdisplay); i++)
1754     g_object_unref (display_x11->screens[i]);
1755   g_free (display_x11->screens);
1756
1757   g_free (display_x11->startup_notification_id);
1758
1759   /* X ID hashtable */
1760   g_hash_table_destroy (display_x11->xid_ht);
1761
1762   XCloseDisplay (display_x11->xdisplay);
1763
1764   /* error traps */
1765   while (display_x11->error_traps != NULL)
1766     {
1767       GdkErrorTrap *trap = display_x11->error_traps->data;
1768
1769       display_x11->error_traps =
1770         g_slist_delete_link (display_x11->error_traps,
1771                              display_x11->error_traps);
1772
1773       if (trap->end_sequence == 0)
1774         g_warning ("Display finalized with an unpopped error trap");
1775
1776       g_slice_free (GdkErrorTrap, trap);
1777     }
1778
1779   G_OBJECT_CLASS (gdk_x11_display_parent_class)->finalize (object);
1780 }
1781
1782 /**
1783  * gdk_x11_lookup_xdisplay:
1784  * @xdisplay: a pointer to an X Display
1785  * 
1786  * Find the #GdkDisplay corresponding to @display, if any exists.
1787  * 
1788  * Return value: (transfer none): the #GdkDisplay, if found, otherwise %NULL.
1789  *
1790  * Since: 2.2
1791  **/
1792 GdkDisplay *
1793 gdk_x11_lookup_xdisplay (Display *xdisplay)
1794 {
1795   GSList *list, *l;
1796   GdkDisplay *display;
1797
1798   display = NULL;
1799
1800   list = gdk_display_manager_list_displays (gdk_display_manager_get ());
1801
1802   for (l = list; l; l = l->next)
1803     {
1804       if (GDK_DISPLAY_XDISPLAY (l->data) == xdisplay)
1805         {
1806           display = l->data;
1807           break;
1808         }
1809     }
1810
1811   g_slist_free (list);
1812
1813   return display;
1814 }
1815
1816 /**
1817  * _gdk_x11_display_screen_for_xrootwin:
1818  * @display: a #GdkDisplay
1819  * @xrootwin: window ID for one of of the screen's of the display.
1820  * 
1821  * Given the root window ID of one of the screen's of a #GdkDisplay,
1822  * finds the screen.
1823  * 
1824  * Return value: (transfer none): the #GdkScreen corresponding to
1825  *     @xrootwin, or %NULL.
1826  **/
1827 GdkScreen *
1828 _gdk_x11_display_screen_for_xrootwin (GdkDisplay *display,
1829                                       Window      xrootwin)
1830 {
1831   gint i;
1832
1833   for (i = 0; i < ScreenCount (GDK_X11_DISPLAY (display)->xdisplay); i++)
1834     {
1835       GdkScreen *screen = gdk_display_get_screen (display, i);
1836       if (GDK_SCREEN_XROOTWIN (screen) == xrootwin)
1837         return screen;
1838     }
1839
1840   return NULL;
1841 }
1842
1843 /**
1844  * gdk_x11_display_get_xdisplay:
1845  * @display: (type GdkX11Display): a #GdkDisplay
1846  * @returns: (transfer none): an X display.
1847  *
1848  * Returns the X display of a #GdkDisplay.
1849  *
1850  * Since: 2.2
1851  */
1852 Display *
1853 gdk_x11_display_get_xdisplay (GdkDisplay *display)
1854 {
1855   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
1856   return GDK_X11_DISPLAY (display)->xdisplay;
1857 }
1858
1859 void
1860 _gdk_x11_display_make_default (GdkDisplay *display)
1861 {
1862   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
1863   const gchar *startup_id;
1864
1865   g_free (display_x11->startup_notification_id);
1866   display_x11->startup_notification_id = NULL;
1867
1868   startup_id = g_getenv ("DESKTOP_STARTUP_ID");
1869   if (startup_id && *startup_id != '\0')
1870     {
1871       if (!g_utf8_validate (startup_id, -1, NULL))
1872         g_warning ("DESKTOP_STARTUP_ID contains invalid UTF-8");
1873       else
1874         gdk_x11_display_set_startup_notification_id (display, startup_id);
1875
1876       /* Clear the environment variable so it won't be inherited by
1877        * child processes and confuse things.
1878        */
1879       g_unsetenv ("DESKTOP_STARTUP_ID");
1880     }
1881 }
1882
1883 static void
1884 broadcast_xmessage (GdkDisplay *display,
1885                     const char *message_type,
1886                     const char *message_type_begin,
1887                     const char *message)
1888 {
1889   Display *xdisplay = GDK_DISPLAY_XDISPLAY (display);
1890   GdkScreen *screen = gdk_display_get_default_screen (display);
1891   GdkWindow *root_window = gdk_screen_get_root_window (screen);
1892   Window xroot_window = GDK_WINDOW_XID (root_window);
1893   
1894   Atom type_atom;
1895   Atom type_atom_begin;
1896   Window xwindow;
1897
1898   if (!G_LIKELY (GDK_X11_DISPLAY (display)->trusted_client))
1899     return;
1900
1901   {
1902     XSetWindowAttributes attrs;
1903
1904     attrs.override_redirect = True;
1905     attrs.event_mask = PropertyChangeMask | StructureNotifyMask;
1906
1907     xwindow =
1908       XCreateWindow (xdisplay,
1909                      xroot_window,
1910                      -100, -100, 1, 1,
1911                      0,
1912                      CopyFromParent,
1913                      CopyFromParent,
1914                      (Visual *)CopyFromParent,
1915                      CWOverrideRedirect | CWEventMask,
1916                      &attrs);
1917   }
1918
1919   type_atom = gdk_x11_get_xatom_by_name_for_display (display,
1920                                                      message_type);
1921   type_atom_begin = gdk_x11_get_xatom_by_name_for_display (display,
1922                                                            message_type_begin);
1923   
1924   {
1925     XClientMessageEvent xclient;
1926     const char *src;
1927     const char *src_end;
1928     char *dest;
1929     char *dest_end;
1930     
1931                 memset(&xclient, 0, sizeof (xclient));
1932     xclient.type = ClientMessage;
1933     xclient.message_type = type_atom_begin;
1934     xclient.display =xdisplay;
1935     xclient.window = xwindow;
1936     xclient.format = 8;
1937
1938     src = message;
1939     src_end = message + strlen (message) + 1; /* +1 to include nul byte */
1940     
1941     while (src != src_end)
1942       {
1943         dest = &xclient.data.b[0];
1944         dest_end = dest + 20;        
1945         
1946         while (dest != dest_end &&
1947                src != src_end)
1948           {
1949             *dest = *src;
1950             ++dest;
1951             ++src;
1952           }
1953
1954         while (dest != dest_end)
1955           {
1956             *dest = 0;
1957             ++dest;
1958           }
1959         
1960         XSendEvent (xdisplay,
1961                     xroot_window,
1962                     False,
1963                     PropertyChangeMask,
1964                     (XEvent *)&xclient);
1965
1966         xclient.message_type = type_atom;
1967       }
1968   }
1969
1970   XDestroyWindow (xdisplay, xwindow);
1971   XFlush (xdisplay);
1972 }
1973
1974 /**
1975  * gdk_x11_display_broadcast_startup_message:
1976  * @display: (type GdkX11Display): a #GdkDisplay
1977  * @message_type: startup notification message type ("new", "change",
1978  * or "remove")
1979  * @...: a list of key/value pairs (as strings), terminated by a
1980  * %NULL key. (A %NULL value for a key will cause that key to be
1981  * skipped in the output.)
1982  *
1983  * Sends a startup notification message of type @message_type to
1984  * @display. 
1985  *
1986  * This is a convenience function for use by code that implements the
1987  * freedesktop startup notification specification. Applications should
1988  * not normally need to call it directly. See the <ulink
1989  * url="http://standards.freedesktop.org/startup-notification-spec/startup-notification-latest.txt">Startup
1990  * Notification Protocol specification</ulink> for
1991  * definitions of the message types and keys that can be used.
1992  *
1993  * Since: 2.12
1994  **/
1995 void
1996 gdk_x11_display_broadcast_startup_message (GdkDisplay *display,
1997                                            const char *message_type,
1998                                            ...)
1999 {
2000   GString *message;
2001   va_list ap;
2002   const char *key, *value, *p;
2003
2004   message = g_string_new (message_type);
2005   g_string_append_c (message, ':');
2006
2007   va_start (ap, message_type);
2008   while ((key = va_arg (ap, const char *)))
2009     {
2010       value = va_arg (ap, const char *);
2011       if (!value)
2012         continue;
2013
2014       g_string_append_printf (message, " %s=\"", key);
2015       for (p = value; *p; p++)
2016         {
2017           switch (*p)
2018             {
2019             case ' ':
2020             case '"':
2021             case '\\':
2022               g_string_append_c (message, '\\');
2023               break;
2024             }
2025
2026           g_string_append_c (message, *p);
2027         }
2028       g_string_append_c (message, '\"');
2029     }
2030   va_end (ap);
2031
2032   broadcast_xmessage (display,
2033                       "_NET_STARTUP_INFO",
2034                       "_NET_STARTUP_INFO_BEGIN",
2035                       message->str);
2036
2037   g_string_free (message, TRUE);
2038 }
2039
2040 static void
2041 gdk_x11_display_notify_startup_complete (GdkDisplay  *display,
2042                                          const gchar *startup_id)
2043 {
2044   if (startup_id == NULL)
2045     {
2046       startup_id = GDK_X11_DISPLAY (display)->startup_notification_id;
2047       if (startup_id == NULL)
2048         return;
2049     }
2050
2051   gdk_x11_display_broadcast_startup_message (display, "remove",
2052                                              "ID", startup_id,
2053                                              NULL);
2054 }
2055
2056 static gboolean
2057 gdk_x11_display_supports_selection_notification (GdkDisplay *display)
2058 {
2059   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
2060
2061   return display_x11->have_xfixes;
2062 }
2063
2064 static gboolean
2065 gdk_x11_display_request_selection_notification (GdkDisplay *display,
2066                                                 GdkAtom     selection)
2067
2068 {
2069 #ifdef HAVE_XFIXES
2070   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
2071   Atom atom;
2072
2073   if (display_x11->have_xfixes)
2074     {
2075       atom = gdk_x11_atom_to_xatom_for_display (display, 
2076                                                 selection);
2077       XFixesSelectSelectionInput (display_x11->xdisplay, 
2078                                   display_x11->leader_window,
2079                                   atom,
2080                                   XFixesSetSelectionOwnerNotifyMask |
2081                                   XFixesSelectionWindowDestroyNotifyMask |
2082                                   XFixesSelectionClientCloseNotifyMask);
2083       return TRUE;
2084     }
2085   else
2086 #endif
2087     return FALSE;
2088 }
2089
2090 static gboolean
2091 gdk_x11_display_supports_clipboard_persistence (GdkDisplay *display)
2092 {
2093   Atom clipboard_manager;
2094
2095   /* It might make sense to cache this */
2096   clipboard_manager = gdk_x11_get_xatom_by_name_for_display (display, "CLIPBOARD_MANAGER");
2097   return XGetSelectionOwner (GDK_X11_DISPLAY (display)->xdisplay, clipboard_manager) != None;
2098 }
2099
2100 static void
2101 gdk_x11_display_store_clipboard (GdkDisplay    *display,
2102                                  GdkWindow     *clipboard_window,
2103                                  guint32        time_,
2104                                  const GdkAtom *targets,
2105                                  gint           n_targets)
2106 {
2107   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
2108   Atom clipboard_manager, save_targets;
2109
2110   g_return_if_fail (GDK_WINDOW_IS_X11 (clipboard_window));
2111
2112   clipboard_manager = gdk_x11_get_xatom_by_name_for_display (display, "CLIPBOARD_MANAGER");
2113   save_targets = gdk_x11_get_xatom_by_name_for_display (display, "SAVE_TARGETS");
2114
2115   gdk_x11_display_error_trap_push (display);
2116
2117   if (XGetSelectionOwner (display_x11->xdisplay, clipboard_manager) != None)
2118     {
2119       Atom property_name = None;
2120       Atom *xatoms;
2121       int i;
2122
2123       if (n_targets > 0)
2124         {
2125           property_name = gdk_x11_get_xatom_by_name_for_display (display, "GDK_SELECTION");
2126
2127           xatoms = g_new (Atom, n_targets);
2128           for (i = 0; i < n_targets; i++)
2129             xatoms[i] = gdk_x11_atom_to_xatom_for_display (display, targets[i]);
2130
2131           XChangeProperty (display_x11->xdisplay, GDK_WINDOW_XID (clipboard_window),
2132                            property_name, XA_ATOM,
2133                            32, PropModeReplace, (guchar *)xatoms, n_targets);
2134           g_free (xatoms);
2135
2136         }
2137
2138       XConvertSelection (display_x11->xdisplay,
2139                          clipboard_manager, save_targets, property_name,
2140                          GDK_WINDOW_XID (clipboard_window), time_);
2141
2142     }
2143   gdk_x11_display_error_trap_pop_ignored (display);
2144
2145 }
2146
2147 /**
2148  * gdk_x11_display_get_user_time:
2149  * @display: (type GdkX11Display): a #GdkDisplay
2150  *
2151  * Returns the timestamp of the last user interaction on 
2152  * @display. The timestamp is taken from events caused
2153  * by user interaction such as key presses or pointer 
2154  * movements. See gdk_x11_window_set_user_time().
2155  *
2156  * Returns: the timestamp of the last user interaction 
2157  *
2158  * Since: 2.8
2159  */
2160 guint32
2161 gdk_x11_display_get_user_time (GdkDisplay *display)
2162 {
2163   return GDK_X11_DISPLAY (display)->user_time;
2164 }
2165
2166 static gboolean
2167 gdk_x11_display_supports_shapes (GdkDisplay *display)
2168 {
2169   return GDK_X11_DISPLAY (display)->have_shapes;
2170 }
2171
2172 static gboolean
2173 gdk_x11_display_supports_input_shapes (GdkDisplay *display)
2174 {
2175   return GDK_X11_DISPLAY (display)->have_input_shapes;
2176 }
2177
2178
2179 /**
2180  * gdk_x11_display_get_startup_notification_id:
2181  * @display: (type GdkX11Display): a #GdkDisplay
2182  *
2183  * Gets the startup notification ID for a display.
2184  * 
2185  * Returns: the startup notification ID for @display
2186  *
2187  * Since: 2.12
2188  */
2189 const gchar *
2190 gdk_x11_display_get_startup_notification_id (GdkDisplay *display)
2191 {
2192   return GDK_X11_DISPLAY (display)->startup_notification_id;
2193 }
2194
2195 /**
2196  * gdk_x11_display_set_startup_notification_id:
2197  * @display: (type GdkX11Display): a #GdkDisplay
2198  * @startup_id: the startup notification ID (must be valid utf8)
2199  *
2200  * Sets the startup notification ID for a display.
2201  *
2202  * This is usually taken from the value of the DESKTOP_STARTUP_ID
2203  * environment variable, but in some cases (such as the application not
2204  * being launched using exec()) it can come from other sources.
2205  *
2206  * If the ID contains the string "_TIME" then the portion following that
2207  * string is taken to be the X11 timestamp of the event that triggered
2208  * the application to be launched and the GDK current event time is set
2209  * accordingly.
2210  *
2211  * The startup ID is also what is used to signal that the startup is
2212  * complete (for example, when opening a window or when calling
2213  * gdk_notify_startup_complete()).
2214  *
2215  * Since: 3.0
2216  **/
2217 void
2218 gdk_x11_display_set_startup_notification_id (GdkDisplay  *display,
2219                                              const gchar *startup_id)
2220 {
2221   GdkX11Display *display_x11;
2222   gchar *time_str;
2223
2224   display_x11 = GDK_X11_DISPLAY (display);
2225
2226   g_free (display_x11->startup_notification_id);
2227   display_x11->startup_notification_id = g_strdup (startup_id);
2228
2229   /* Find the launch time from the startup_id, if it's there.  Newer spec
2230    * states that the startup_id is of the form <unique>_TIME<timestamp>
2231    */
2232   time_str = g_strrstr (startup_id, "_TIME");
2233   if (time_str != NULL)
2234     {
2235       gulong retval;
2236       gchar *end;
2237       errno = 0;
2238
2239       /* Skip past the "_TIME" part */
2240       time_str += 5;
2241
2242       retval = strtoul (time_str, &end, 0);
2243       if (end != time_str && errno == 0)
2244         display_x11->user_time = retval;
2245     }
2246
2247   /* Set the startup id on the leader window so it
2248    * applies to all windows we create on this display
2249    */
2250   XChangeProperty (display_x11->xdisplay,
2251                    display_x11->leader_window,
2252                    gdk_x11_get_xatom_by_name_for_display (display, "_NET_STARTUP_ID"),
2253                    gdk_x11_get_xatom_by_name_for_display (display, "UTF8_STRING"), 8,
2254                    PropModeReplace,
2255                    (guchar *)startup_id, strlen (startup_id));
2256 }
2257
2258 static gboolean
2259 gdk_x11_display_supports_composite (GdkDisplay *display)
2260 {
2261   GdkX11Display *x11_display = GDK_X11_DISPLAY (display);
2262
2263   return x11_display->have_xcomposite &&
2264          x11_display->have_xdamage &&
2265          x11_display->have_xfixes;
2266 }
2267
2268 static GList *
2269 gdk_x11_display_list_devices (GdkDisplay *display)
2270 {
2271   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
2272
2273   return GDK_X11_DISPLAY (display)->input_devices;
2274 }
2275
2276 /**
2277  * gdk_x11_register_standard_event_type:
2278  * @display: a #GdkDisplay
2279  * @event_base: first event type code to register
2280  * @n_events: number of event type codes to register
2281  *
2282  * Registers interest in receiving extension events with type codes
2283  * between @event_base and <literal>event_base + n_events - 1</literal>.
2284  * The registered events must have the window field in the same place
2285  * as core X events (this is not the case for e.g. XKB extension events).
2286  *
2287  * If an event type is registered, events of this type will go through
2288  * global and window-specific filters (see gdk_window_add_filter()).
2289  * Unregistered events will only go through global filters.
2290  * GDK may register the events of some X extensions on its own.
2291  *
2292  * This function should only be needed in unusual circumstances, e.g.
2293  * when filtering XInput extension events on the root window.
2294  *
2295  * Since: 2.4
2296  **/
2297 void
2298 gdk_x11_register_standard_event_type (GdkDisplay *display,
2299                                       gint        event_base,
2300                                       gint        n_events)
2301 {
2302   GdkEventTypeX11 *event_type;
2303   GdkX11Display *display_x11;
2304
2305   display_x11 = GDK_X11_DISPLAY (display);
2306   event_type = g_new (GdkEventTypeX11, 1);
2307
2308   event_type->base = event_base;
2309   event_type->n_events = n_events;
2310
2311   display_x11->event_types = g_slist_prepend (display_x11->event_types, event_type);
2312 }
2313
2314 /* compare X sequence numbers handling wraparound */
2315 #define SEQUENCE_COMPARE(a,op,b) (((long) (a) - (long) (b)) op 0)
2316
2317 /* delivers an error event from the error handler in gdkmain-x11.c */
2318 void
2319 _gdk_x11_display_error_event (GdkDisplay  *display,
2320                               XErrorEvent *error)
2321 {
2322   GdkX11Display *display_x11;
2323   GSList *tmp_list;
2324   gboolean ignore;
2325
2326   display_x11 = GDK_X11_DISPLAY (display);
2327
2328   ignore = FALSE;
2329   for (tmp_list = display_x11->error_traps;
2330        tmp_list != NULL;
2331        tmp_list = tmp_list->next)
2332     {
2333       GdkErrorTrap *trap;
2334
2335       trap = tmp_list->data;
2336
2337       if (SEQUENCE_COMPARE (trap->start_sequence, <=, error->serial) &&
2338           (trap->end_sequence == 0 ||
2339            SEQUENCE_COMPARE (trap->end_sequence, >, error->serial)))
2340         {
2341           ignore = TRUE;
2342           trap->error_code = error->error_code;
2343           break; /* only innermost trap gets the error code */
2344         }
2345     }
2346
2347   if (!ignore)
2348     {
2349       gchar buf[64];
2350       gchar *msg;
2351
2352       XGetErrorText (display_x11->xdisplay, error->error_code, buf, 63);
2353
2354       msg =
2355         g_strdup_printf ("The program '%s' received an X Window System error.\n"
2356                          "This probably reflects a bug in the program.\n"
2357                          "The error was '%s'.\n"
2358                          "  (Details: serial %ld error_code %d request_code %d minor_code %d)\n"
2359                          "  (Note to programmers: normally, X errors are reported asynchronously;\n"
2360                          "   that is, you will receive the error a while after causing it.\n"
2361                          "   To debug your program, run it with the GDK_SYNCHRONIZE environment\n"
2362                          "   variable to change this behavior. You can then get a meaningful\n"
2363                          "   backtrace from your debugger if you break on the gdk_x_error() function.)",
2364                          g_get_prgname (),
2365                          buf,
2366                          error->serial,
2367                          error->error_code,
2368                          error->request_code,
2369                          error->minor_code);
2370
2371 #ifdef G_ENABLE_DEBUG
2372       g_error ("%s", msg);
2373 #else /* !G_ENABLE_DEBUG */
2374       g_warning ("%s\n", msg);
2375
2376       _exit (1);
2377 #endif /* G_ENABLE_DEBUG */
2378     }
2379 }
2380
2381 static void
2382 delete_outdated_error_traps (GdkX11Display *display_x11)
2383 {
2384   GSList *tmp_list;
2385   gulong processed_sequence;
2386
2387   processed_sequence = XLastKnownRequestProcessed (display_x11->xdisplay);
2388
2389   tmp_list = display_x11->error_traps;
2390   while (tmp_list != NULL)
2391     {
2392       GdkErrorTrap *trap = tmp_list->data;
2393
2394       if (trap->end_sequence != 0 &&
2395           SEQUENCE_COMPARE (trap->end_sequence, <=, processed_sequence))
2396         {
2397           GSList *free_me = tmp_list;
2398
2399           tmp_list = tmp_list->next;
2400           display_x11->error_traps =
2401             g_slist_delete_link (display_x11->error_traps, free_me);
2402           g_slice_free (GdkErrorTrap, trap);
2403         }
2404       else
2405         {
2406           tmp_list = tmp_list->next;
2407         }
2408     }
2409 }
2410
2411 /**
2412  * gdk_x11_display_error_trap_push:
2413  * @display: (type GdkX11Display): a #GdkDisplay
2414  *
2415  * Begins a range of X requests on @display for which X error events
2416  * will be ignored. Unignored errors (when no trap is pushed) will abort
2417  * the application. Use gdk_x11_display_error_trap_pop() or
2418  * gdk_x11_display_error_trap_pop_ignored()to lift a trap pushed
2419  * with this function.
2420  *
2421  * See also gdk_error_trap_push() to push a trap on all displays.
2422  *
2423  * Since: 3.0
2424  */
2425 void
2426 gdk_x11_display_error_trap_push (GdkDisplay *display)
2427 {
2428   GdkX11Display *display_x11;
2429   GdkErrorTrap *trap;
2430
2431   display_x11 = GDK_X11_DISPLAY (display);
2432
2433   delete_outdated_error_traps (display_x11);
2434
2435   /* set up the Xlib callback to tell us about errors */
2436   _gdk_x11_error_handler_push ();
2437
2438   trap = g_slice_new0 (GdkErrorTrap);
2439
2440   trap->start_sequence = XNextRequest (display_x11->xdisplay);
2441   trap->error_code = Success;
2442
2443   display_x11->error_traps =
2444     g_slist_prepend (display_x11->error_traps, trap);
2445 }
2446
2447 static gint
2448 gdk_x11_display_error_trap_pop_internal (GdkDisplay *display,
2449                                          gboolean    need_code)
2450 {
2451   GdkX11Display *display_x11;
2452   GdkErrorTrap *trap;
2453   GSList *tmp_list;
2454   int result;
2455
2456   display_x11 = GDK_X11_DISPLAY (display);
2457
2458   g_return_val_if_fail (display_x11->error_traps != NULL, Success);
2459
2460   /* Find the first trap that hasn't been popped already */
2461   trap = NULL; /* quiet gcc */
2462   for (tmp_list = display_x11->error_traps;
2463        tmp_list != NULL;
2464        tmp_list = tmp_list->next)
2465     {
2466       trap = tmp_list->data;
2467
2468       if (trap->end_sequence == 0)
2469         break;
2470     }
2471
2472   g_return_val_if_fail (trap != NULL, Success);
2473   g_assert (trap->end_sequence == 0);
2474
2475   /* May need to sync to fill in trap->error_code if we care about
2476    * getting an error code.
2477    */
2478   if (need_code)
2479     {
2480       gulong processed_sequence;
2481       gulong next_sequence;
2482
2483       next_sequence = XNextRequest (display_x11->xdisplay);
2484       processed_sequence = XLastKnownRequestProcessed (display_x11->xdisplay);
2485
2486       /* If our last request was already processed, there is no point
2487        * in syncing. i.e. if last request was a round trip (or even if
2488        * we got an event with the serial of a non-round-trip)
2489        */
2490       if ((next_sequence - 1) != processed_sequence)
2491         {
2492           XSync (display_x11->xdisplay, False);
2493         }
2494
2495       result = trap->error_code;
2496     }
2497   else
2498     {
2499       result = Success;
2500     }
2501
2502   /* record end of trap, giving us a range of
2503    * error sequences we'll ignore.
2504    */
2505   trap->end_sequence = XNextRequest (display_x11->xdisplay);
2506
2507   /* remove the Xlib callback */
2508   _gdk_x11_error_handler_pop ();
2509
2510   /* we may already be outdated */
2511   delete_outdated_error_traps (display_x11);
2512
2513   return result;
2514 }
2515
2516 /**
2517  * gdk_x11_display_error_trap_pop:
2518  * @display: (type GdkX11Display): the display
2519  *
2520  * Pops the error trap pushed by gdk_x11_display_error_trap_push().
2521  * Will XSync() if necessary and will always block until
2522  * the error is known to have occurred or not occurred,
2523  * so the error code can be returned.
2524  *
2525  * If you don't need to use the return value,
2526  * gdk_x11_display_error_trap_pop_ignored() would be more efficient.
2527  *
2528  * See gdk_error_trap_pop() for the all-displays-at-once
2529  * equivalent.
2530  *
2531  * Since: 3.0
2532  *
2533  * Return value: X error code or 0 on success
2534  */
2535 gint
2536 gdk_x11_display_error_trap_pop (GdkDisplay *display)
2537 {
2538   g_return_val_if_fail (GDK_IS_X11_DISPLAY (display), Success);
2539
2540   return gdk_x11_display_error_trap_pop_internal (display, TRUE);
2541 }
2542
2543 /**
2544  * gdk_x11_display_error_trap_pop_ignored:
2545  * @display: (type GdkX11Display): the display
2546  *
2547  * Pops the error trap pushed by gdk_x11_display_error_trap_push().
2548  * Does not block to see if an error occurred; merely records the
2549  * range of requests to ignore errors for, and ignores those errors
2550  * if they arrive asynchronously.
2551  *
2552  * See gdk_error_trap_pop_ignored() for the all-displays-at-once
2553  * equivalent.
2554  *
2555  * Since: 3.0
2556  */
2557 void
2558 gdk_x11_display_error_trap_pop_ignored (GdkDisplay *display)
2559 {
2560   g_return_if_fail (GDK_IS_X11_DISPLAY (display));
2561
2562   gdk_x11_display_error_trap_pop_internal (display, FALSE);
2563 }
2564
2565 /**
2566  * gdk_x11_set_sm_client_id:
2567  * @sm_client_id: the client id assigned by the session manager when the
2568  *    connection was opened, or %NULL to remove the property.
2569  *
2570  * Sets the <literal>SM_CLIENT_ID</literal> property on the application's leader window so that
2571  * the window manager can save the application's state using the X11R6 ICCCM
2572  * session management protocol.
2573  *
2574  * See the X Session Management Library documentation for more information on
2575  * session management and the Inter-Client Communication Conventions Manual
2576  *
2577  * Since: 2.24
2578  */
2579 void
2580 gdk_x11_set_sm_client_id (const gchar *sm_client_id)
2581 {
2582  GSList *displays, *l;
2583
2584   g_free (gdk_sm_client_id);
2585   gdk_sm_client_id = g_strdup (sm_client_id);
2586
2587   displays = gdk_display_manager_list_displays (gdk_display_manager_get ());
2588   for (l = displays; l; l = l->next)
2589     set_sm_client_id (l->data, sm_client_id);
2590
2591   g_slist_free (displays);
2592 }
2593
2594 static void
2595 gdk_x11_display_event_data_copy (GdkDisplay    *display,
2596                                 const GdkEvent *src,
2597                                 GdkEvent       *dst)
2598 {
2599 }
2600
2601 static void
2602 gdk_x11_display_event_data_free (GdkDisplay *display,
2603                                  GdkEvent *event)
2604 {
2605 }
2606
2607 static gint
2608 pop_error_trap (GdkDisplay *display,
2609                 gboolean    ignored)
2610 {
2611   if (ignored)
2612     {
2613       gdk_x11_display_error_trap_pop_ignored (display);
2614       return Success;
2615     }
2616   else
2617     {
2618       return gdk_x11_display_error_trap_pop (display);
2619     }
2620 }
2621
2622 static GdkKeymap *
2623 gdk_x11_display_get_keymap (GdkDisplay *display)
2624 {
2625   GdkX11Display *display_x11;
2626   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
2627   display_x11 = GDK_X11_DISPLAY (display);
2628
2629   if (!display_x11->keymap)
2630     display_x11->keymap = g_object_new (GDK_TYPE_X11_KEYMAP, NULL);
2631
2632   display_x11->keymap->display = display;
2633
2634   return display_x11->keymap;
2635 }
2636
2637 static void
2638 gdk_x11_display_class_init (GdkX11DisplayClass * class)
2639 {
2640   GObjectClass *object_class = G_OBJECT_CLASS (class);
2641   GdkDisplayClass *display_class = GDK_DISPLAY_CLASS (class);
2642
2643   object_class->dispose = gdk_x11_display_dispose;
2644   object_class->finalize = gdk_x11_display_finalize;
2645
2646   display_class->window_type = GDK_TYPE_X11_WINDOW;
2647
2648   display_class->get_name = gdk_x11_display_get_name;
2649   display_class->get_n_screens = gdk_x11_display_get_n_screens;
2650   display_class->get_screen = gdk_x11_display_get_screen;
2651   display_class->get_default_screen = gdk_x11_display_get_default_screen;
2652   display_class->beep = gdk_x11_display_beep;
2653   display_class->sync = gdk_x11_display_sync;
2654   display_class->flush = gdk_x11_display_flush;
2655   display_class->has_pending = gdk_x11_display_has_pending;
2656   display_class->queue_events = _gdk_x11_display_queue_events;
2657   display_class->get_default_group = gdk_x11_display_get_default_group;
2658   display_class->supports_selection_notification = gdk_x11_display_supports_selection_notification;
2659   display_class->request_selection_notification = gdk_x11_display_request_selection_notification;
2660   display_class->supports_clipboard_persistence = gdk_x11_display_supports_clipboard_persistence;
2661   display_class->store_clipboard = gdk_x11_display_store_clipboard;
2662   display_class->supports_shapes = gdk_x11_display_supports_shapes;
2663   display_class->supports_input_shapes = gdk_x11_display_supports_input_shapes;
2664   display_class->supports_composite = gdk_x11_display_supports_composite;
2665   display_class->list_devices = gdk_x11_display_list_devices;
2666   display_class->get_app_launch_context = _gdk_x11_display_get_app_launch_context;
2667   display_class->get_cursor_for_type = _gdk_x11_display_get_cursor_for_type;
2668   display_class->get_cursor_for_name = _gdk_x11_display_get_cursor_for_name;
2669   display_class->get_cursor_for_pixbuf = _gdk_x11_display_get_cursor_for_pixbuf;
2670   display_class->get_default_cursor_size = _gdk_x11_display_get_default_cursor_size;
2671   display_class->get_maximal_cursor_size = _gdk_x11_display_get_maximal_cursor_size;
2672   display_class->supports_cursor_alpha = _gdk_x11_display_supports_cursor_alpha;
2673   display_class->supports_cursor_color = _gdk_x11_display_supports_cursor_color;
2674
2675   display_class->before_process_all_updates = _gdk_x11_display_before_process_all_updates;
2676   display_class->after_process_all_updates = _gdk_x11_display_after_process_all_updates;
2677   display_class->get_next_serial = gdk_x11_display_get_next_serial;
2678   display_class->notify_startup_complete = gdk_x11_display_notify_startup_complete;
2679   display_class->event_data_copy = gdk_x11_display_event_data_copy;
2680   display_class->event_data_free = gdk_x11_display_event_data_free;
2681   display_class->create_window_impl = _gdk_x11_display_create_window_impl;
2682   display_class->get_keymap = gdk_x11_display_get_keymap;
2683   display_class->push_error_trap = gdk_x11_display_error_trap_push;
2684   display_class->pop_error_trap = pop_error_trap;
2685   display_class->get_selection_owner = _gdk_x11_display_get_selection_owner;
2686   display_class->set_selection_owner = _gdk_x11_display_set_selection_owner;
2687   display_class->send_selection_notify = _gdk_x11_display_send_selection_notify;
2688   display_class->get_selection_property = _gdk_x11_display_get_selection_property;
2689   display_class->convert_selection = _gdk_x11_display_convert_selection;
2690   display_class->text_property_to_utf8_list = _gdk_x11_display_text_property_to_utf8_list;
2691   display_class->utf8_to_string_target = _gdk_x11_display_utf8_to_string_target;
2692 }