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