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