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