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