]> Pileus Git - ~andy/gtk/blob - gdk/x11/gdkdisplay-x11.c
gdk/*: Use g_list_free_full convenience function
[~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                                    XkbGroupLockMask|XkbModifierLockMask);
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   GdkDevice *device = data;
1583
1584   _gdk_display_device_grab_update (display, device, NULL, serial);
1585 }
1586
1587 #define XSERVER_TIME_IS_LATER(time1, time2)                        \
1588   ( (( time1 > time2 ) && ( time1 - time2 < ((guint32)-1)/2 )) ||  \
1589     (( time1 < time2 ) && ( time2 - time1 > ((guint32)-1)/2 ))     \
1590   )
1591
1592 void
1593 _gdk_x11_display_update_grab_info (GdkDisplay *display,
1594                                    GdkDevice  *device,
1595                                    gint        status)
1596 {
1597   if (status == GrabSuccess)
1598     _gdk_x11_roundtrip_async (display, device_grab_update_callback, device);
1599 }
1600
1601 void
1602 _gdk_x11_display_update_grab_info_ungrab (GdkDisplay *display,
1603                                           GdkDevice  *device,
1604                                           guint32     time,
1605                                           gulong      serial)
1606 {
1607   GdkDeviceGrabInfo *grab;
1608
1609   XFlush (GDK_DISPLAY_XDISPLAY (display));
1610
1611   grab = _gdk_display_get_last_device_grab (display, device);
1612   if (grab &&
1613       (time == GDK_CURRENT_TIME ||
1614        grab->time == GDK_CURRENT_TIME ||
1615        !XSERVER_TIME_IS_LATER (grab->time, time)))
1616     {
1617       grab->serial_end = serial;
1618       _gdk_x11_roundtrip_async (display, device_grab_update_callback, device);
1619     }
1620 }
1621
1622 static void
1623 gdk_x11_display_beep (GdkDisplay *display)
1624 {
1625 #ifdef HAVE_XKB
1626   XkbBell (GDK_DISPLAY_XDISPLAY (display), None, 0, None);
1627 #else
1628   XBell (GDK_DISPLAY_XDISPLAY (display), 0);
1629 #endif
1630 }
1631
1632 static void
1633 gdk_x11_display_sync (GdkDisplay *display)
1634 {
1635   XSync (GDK_DISPLAY_XDISPLAY (display), False);
1636 }
1637
1638 static void
1639 gdk_x11_display_flush (GdkDisplay *display)
1640 {
1641   if (!display->closed)
1642     XFlush (GDK_DISPLAY_XDISPLAY (display));
1643 }
1644
1645 static gboolean
1646 gdk_x11_display_has_pending (GdkDisplay *display)
1647 {
1648   return XPending (GDK_DISPLAY_XDISPLAY (display));
1649 }
1650
1651 static GdkWindow *
1652 gdk_x11_display_get_default_group (GdkDisplay *display)
1653 {
1654   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
1655
1656   return GDK_X11_DISPLAY (display)->leader_gdk_window;
1657 }
1658
1659 /**
1660  * gdk_x11_display_grab:
1661  * @display: (type GdkX11Display): a #GdkDisplay 
1662  * 
1663  * Call XGrabServer() on @display. 
1664  * To ungrab the display again, use gdk_x11_display_ungrab(). 
1665  *
1666  * gdk_x11_display_grab()/gdk_x11_display_ungrab() calls can be nested.
1667  *
1668  * Since: 2.2
1669  **/
1670 void
1671 gdk_x11_display_grab (GdkDisplay *display)
1672 {
1673   GdkX11Display *display_x11;
1674   
1675   g_return_if_fail (GDK_IS_DISPLAY (display));
1676   
1677   display_x11 = GDK_X11_DISPLAY (display);
1678   
1679   if (display_x11->grab_count == 0)
1680     XGrabServer (display_x11->xdisplay);
1681   display_x11->grab_count++;
1682 }
1683
1684 /**
1685  * gdk_x11_display_ungrab:
1686  * @display: (type GdkX11Display): a #GdkDisplay
1687  * 
1688  * Ungrab @display after it has been grabbed with 
1689  * gdk_x11_display_grab(). 
1690  *
1691  * Since: 2.2
1692  **/
1693 void
1694 gdk_x11_display_ungrab (GdkDisplay *display)
1695 {
1696   GdkX11Display *display_x11;
1697   
1698   g_return_if_fail (GDK_IS_DISPLAY (display));
1699   
1700   display_x11 = GDK_X11_DISPLAY (display);;
1701   g_return_if_fail (display_x11->grab_count > 0);
1702   
1703   display_x11->grab_count--;
1704   if (display_x11->grab_count == 0)
1705     {
1706       XUngrabServer (display_x11->xdisplay);
1707       XFlush (display_x11->xdisplay);
1708     }
1709 }
1710
1711 static void
1712 gdk_x11_display_dispose (GObject *object)
1713 {
1714   GdkDisplay *display = GDK_DISPLAY (object);
1715   GdkX11Display *display_x11 = GDK_X11_DISPLAY (object);
1716   gint           i;
1717
1718   _gdk_x11_display_manager_remove_display (gdk_display_manager_get (), display);
1719
1720   g_list_foreach (display_x11->input_devices, (GFunc) g_object_run_dispose, NULL);
1721
1722   for (i = 0; i < ScreenCount (display_x11->xdisplay); i++)
1723     _gdk_screen_close (display_x11->screens[i]);
1724
1725   if (display_x11->event_source)
1726     {
1727       g_source_destroy (display_x11->event_source);
1728       g_source_unref (display_x11->event_source);
1729       display_x11->event_source = NULL;
1730     }
1731
1732   G_OBJECT_CLASS (gdk_x11_display_parent_class)->dispose (object);
1733 }
1734
1735 static void
1736 gdk_x11_display_finalize (GObject *object)
1737 {
1738   GdkX11Display *display_x11 = GDK_X11_DISPLAY (object);
1739   gint           i;
1740
1741   /* Keymap */
1742   if (display_x11->keymap)
1743     g_object_unref (display_x11->keymap);
1744
1745   /* Free motif Dnd */
1746   if (display_x11->motif_target_lists)
1747     {
1748       for (i = 0; i < display_x11->motif_n_target_lists; i++)
1749         g_list_free (display_x11->motif_target_lists[i]);
1750       g_free (display_x11->motif_target_lists);
1751     }
1752
1753   _gdk_x11_cursor_display_finalize (GDK_DISPLAY (display_x11));
1754
1755   /* Empty the event queue */
1756   _gdk_x11_display_free_translate_queue (GDK_DISPLAY (display_x11));
1757
1758   /* Atom Hashtable */
1759   g_hash_table_destroy (display_x11->atom_from_virtual);
1760   g_hash_table_destroy (display_x11->atom_to_virtual);
1761
1762   /* Leader Window */
1763   XDestroyWindow (display_x11->xdisplay, display_x11->leader_window);
1764
1765   /* List of event window extraction functions */
1766   g_slist_foreach (display_x11->event_types, (GFunc)g_free, NULL);
1767   g_slist_free (display_x11->event_types);
1768
1769   /* input GdkDevice list */
1770   g_list_free_full (display_x11->input_devices, g_object_unref);
1771
1772   /* input GdkWindow list */
1773   g_list_free_full (display_x11->input_windows, g_free);
1774
1775   /* Free all GdkScreens */
1776   for (i = 0; i < ScreenCount (display_x11->xdisplay); i++)
1777     g_object_unref (display_x11->screens[i]);
1778   g_free (display_x11->screens);
1779
1780   g_free (display_x11->startup_notification_id);
1781
1782   /* X ID hashtable */
1783   g_hash_table_destroy (display_x11->xid_ht);
1784
1785   XCloseDisplay (display_x11->xdisplay);
1786
1787   /* error traps */
1788   while (display_x11->error_traps != NULL)
1789     {
1790       GdkErrorTrap *trap = display_x11->error_traps->data;
1791
1792       display_x11->error_traps =
1793         g_slist_delete_link (display_x11->error_traps,
1794                              display_x11->error_traps);
1795
1796       if (trap->end_sequence == 0)
1797         g_warning ("Display finalized with an unpopped error trap");
1798
1799       g_slice_free (GdkErrorTrap, trap);
1800     }
1801
1802   G_OBJECT_CLASS (gdk_x11_display_parent_class)->finalize (object);
1803 }
1804
1805 /**
1806  * gdk_x11_lookup_xdisplay:
1807  * @xdisplay: a pointer to an X Display
1808  * 
1809  * Find the #GdkDisplay corresponding to @display, if any exists.
1810  * 
1811  * Return value: (transfer none): the #GdkDisplay, if found, otherwise %NULL.
1812  *
1813  * Since: 2.2
1814  **/
1815 GdkDisplay *
1816 gdk_x11_lookup_xdisplay (Display *xdisplay)
1817 {
1818   GSList *list, *l;
1819   GdkDisplay *display;
1820
1821   display = NULL;
1822
1823   list = gdk_display_manager_list_displays (gdk_display_manager_get ());
1824
1825   for (l = list; l; l = l->next)
1826     {
1827       if (GDK_DISPLAY_XDISPLAY (l->data) == xdisplay)
1828         {
1829           display = l->data;
1830           break;
1831         }
1832     }
1833
1834   g_slist_free (list);
1835
1836   return display;
1837 }
1838
1839 /**
1840  * _gdk_x11_display_screen_for_xrootwin:
1841  * @display: a #GdkDisplay
1842  * @xrootwin: window ID for one of of the screen's of the display.
1843  * 
1844  * Given the root window ID of one of the screen's of a #GdkDisplay,
1845  * finds the screen.
1846  * 
1847  * Return value: (transfer none): the #GdkScreen corresponding to
1848  *     @xrootwin, or %NULL.
1849  **/
1850 GdkScreen *
1851 _gdk_x11_display_screen_for_xrootwin (GdkDisplay *display,
1852                                       Window      xrootwin)
1853 {
1854   gint i;
1855
1856   for (i = 0; i < ScreenCount (GDK_X11_DISPLAY (display)->xdisplay); i++)
1857     {
1858       GdkScreen *screen = gdk_display_get_screen (display, i);
1859       if (GDK_SCREEN_XROOTWIN (screen) == xrootwin)
1860         return screen;
1861     }
1862
1863   return NULL;
1864 }
1865
1866 /**
1867  * gdk_x11_display_get_xdisplay:
1868  * @display: (type GdkX11Display): a #GdkDisplay
1869  *
1870  * Returns the X display of a #GdkDisplay.
1871  *
1872  * Returns: (transfer none): an X display
1873  *
1874  * Since: 2.2
1875  */
1876 Display *
1877 gdk_x11_display_get_xdisplay (GdkDisplay *display)
1878 {
1879   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
1880   return GDK_X11_DISPLAY (display)->xdisplay;
1881 }
1882
1883 void
1884 _gdk_x11_display_make_default (GdkDisplay *display)
1885 {
1886   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
1887   const gchar *startup_id;
1888
1889   g_free (display_x11->startup_notification_id);
1890   display_x11->startup_notification_id = NULL;
1891
1892   startup_id = g_getenv ("DESKTOP_STARTUP_ID");
1893   if (startup_id && *startup_id != '\0')
1894     {
1895       if (!g_utf8_validate (startup_id, -1, NULL))
1896         g_warning ("DESKTOP_STARTUP_ID contains invalid UTF-8");
1897       else
1898         gdk_x11_display_set_startup_notification_id (display, startup_id);
1899
1900       /* Clear the environment variable so it won't be inherited by
1901        * child processes and confuse things.
1902        */
1903       g_unsetenv ("DESKTOP_STARTUP_ID");
1904     }
1905 }
1906
1907 static void
1908 broadcast_xmessage (GdkDisplay *display,
1909                     const char *message_type,
1910                     const char *message_type_begin,
1911                     const char *message)
1912 {
1913   Display *xdisplay = GDK_DISPLAY_XDISPLAY (display);
1914   GdkScreen *screen = gdk_display_get_default_screen (display);
1915   GdkWindow *root_window = gdk_screen_get_root_window (screen);
1916   Window xroot_window = GDK_WINDOW_XID (root_window);
1917   
1918   Atom type_atom;
1919   Atom type_atom_begin;
1920   Window xwindow;
1921
1922   if (!G_LIKELY (GDK_X11_DISPLAY (display)->trusted_client))
1923     return;
1924
1925   {
1926     XSetWindowAttributes attrs;
1927
1928     attrs.override_redirect = True;
1929     attrs.event_mask = PropertyChangeMask | StructureNotifyMask;
1930
1931     xwindow =
1932       XCreateWindow (xdisplay,
1933                      xroot_window,
1934                      -100, -100, 1, 1,
1935                      0,
1936                      CopyFromParent,
1937                      CopyFromParent,
1938                      (Visual *)CopyFromParent,
1939                      CWOverrideRedirect | CWEventMask,
1940                      &attrs);
1941   }
1942
1943   type_atom = gdk_x11_get_xatom_by_name_for_display (display,
1944                                                      message_type);
1945   type_atom_begin = gdk_x11_get_xatom_by_name_for_display (display,
1946                                                            message_type_begin);
1947   
1948   {
1949     XClientMessageEvent xclient;
1950     const char *src;
1951     const char *src_end;
1952     char *dest;
1953     char *dest_end;
1954     
1955                 memset(&xclient, 0, sizeof (xclient));
1956     xclient.type = ClientMessage;
1957     xclient.message_type = type_atom_begin;
1958     xclient.display =xdisplay;
1959     xclient.window = xwindow;
1960     xclient.format = 8;
1961
1962     src = message;
1963     src_end = message + strlen (message) + 1; /* +1 to include nul byte */
1964     
1965     while (src != src_end)
1966       {
1967         dest = &xclient.data.b[0];
1968         dest_end = dest + 20;        
1969         
1970         while (dest != dest_end &&
1971                src != src_end)
1972           {
1973             *dest = *src;
1974             ++dest;
1975             ++src;
1976           }
1977
1978         while (dest != dest_end)
1979           {
1980             *dest = 0;
1981             ++dest;
1982           }
1983         
1984         XSendEvent (xdisplay,
1985                     xroot_window,
1986                     False,
1987                     PropertyChangeMask,
1988                     (XEvent *)&xclient);
1989
1990         xclient.message_type = type_atom;
1991       }
1992   }
1993
1994   XDestroyWindow (xdisplay, xwindow);
1995   XFlush (xdisplay);
1996 }
1997
1998 /**
1999  * gdk_x11_display_broadcast_startup_message:
2000  * @display: (type GdkX11Display): a #GdkDisplay
2001  * @message_type: startup notification message type ("new", "change",
2002  * or "remove")
2003  * @...: a list of key/value pairs (as strings), terminated by a
2004  * %NULL key. (A %NULL value for a key will cause that key to be
2005  * skipped in the output.)
2006  *
2007  * Sends a startup notification message of type @message_type to
2008  * @display. 
2009  *
2010  * This is a convenience function for use by code that implements the
2011  * freedesktop startup notification specification. Applications should
2012  * not normally need to call it directly. See the <ulink
2013  * url="http://standards.freedesktop.org/startup-notification-spec/startup-notification-latest.txt">Startup
2014  * Notification Protocol specification</ulink> for
2015  * definitions of the message types and keys that can be used.
2016  *
2017  * Since: 2.12
2018  **/
2019 void
2020 gdk_x11_display_broadcast_startup_message (GdkDisplay *display,
2021                                            const char *message_type,
2022                                            ...)
2023 {
2024   GString *message;
2025   va_list ap;
2026   const char *key, *value, *p;
2027
2028   message = g_string_new (message_type);
2029   g_string_append_c (message, ':');
2030
2031   va_start (ap, message_type);
2032   while ((key = va_arg (ap, const char *)))
2033     {
2034       value = va_arg (ap, const char *);
2035       if (!value)
2036         continue;
2037
2038       g_string_append_printf (message, " %s=\"", key);
2039       for (p = value; *p; p++)
2040         {
2041           switch (*p)
2042             {
2043             case ' ':
2044             case '"':
2045             case '\\':
2046               g_string_append_c (message, '\\');
2047               break;
2048             }
2049
2050           g_string_append_c (message, *p);
2051         }
2052       g_string_append_c (message, '\"');
2053     }
2054   va_end (ap);
2055
2056   broadcast_xmessage (display,
2057                       "_NET_STARTUP_INFO",
2058                       "_NET_STARTUP_INFO_BEGIN",
2059                       message->str);
2060
2061   g_string_free (message, TRUE);
2062 }
2063
2064 static void
2065 gdk_x11_display_notify_startup_complete (GdkDisplay  *display,
2066                                          const gchar *startup_id)
2067 {
2068   if (startup_id == NULL)
2069     {
2070       startup_id = GDK_X11_DISPLAY (display)->startup_notification_id;
2071       if (startup_id == NULL)
2072         return;
2073     }
2074
2075   gdk_x11_display_broadcast_startup_message (display, "remove",
2076                                              "ID", startup_id,
2077                                              NULL);
2078 }
2079
2080 static gboolean
2081 gdk_x11_display_supports_selection_notification (GdkDisplay *display)
2082 {
2083   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
2084
2085   return display_x11->have_xfixes;
2086 }
2087
2088 static gboolean
2089 gdk_x11_display_request_selection_notification (GdkDisplay *display,
2090                                                 GdkAtom     selection)
2091
2092 {
2093 #ifdef HAVE_XFIXES
2094   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
2095   Atom atom;
2096
2097   if (display_x11->have_xfixes)
2098     {
2099       atom = gdk_x11_atom_to_xatom_for_display (display, 
2100                                                 selection);
2101       XFixesSelectSelectionInput (display_x11->xdisplay, 
2102                                   display_x11->leader_window,
2103                                   atom,
2104                                   XFixesSetSelectionOwnerNotifyMask |
2105                                   XFixesSelectionWindowDestroyNotifyMask |
2106                                   XFixesSelectionClientCloseNotifyMask);
2107       return TRUE;
2108     }
2109   else
2110 #endif
2111     return FALSE;
2112 }
2113
2114 static gboolean
2115 gdk_x11_display_supports_clipboard_persistence (GdkDisplay *display)
2116 {
2117   Atom clipboard_manager;
2118
2119   /* It might make sense to cache this */
2120   clipboard_manager = gdk_x11_get_xatom_by_name_for_display (display, "CLIPBOARD_MANAGER");
2121   return XGetSelectionOwner (GDK_X11_DISPLAY (display)->xdisplay, clipboard_manager) != None;
2122 }
2123
2124 static void
2125 gdk_x11_display_store_clipboard (GdkDisplay    *display,
2126                                  GdkWindow     *clipboard_window,
2127                                  guint32        time_,
2128                                  const GdkAtom *targets,
2129                                  gint           n_targets)
2130 {
2131   GdkX11Display *display_x11 = GDK_X11_DISPLAY (display);
2132   Atom clipboard_manager, save_targets;
2133
2134   g_return_if_fail (GDK_WINDOW_IS_X11 (clipboard_window));
2135
2136   clipboard_manager = gdk_x11_get_xatom_by_name_for_display (display, "CLIPBOARD_MANAGER");
2137   save_targets = gdk_x11_get_xatom_by_name_for_display (display, "SAVE_TARGETS");
2138
2139   gdk_x11_display_error_trap_push (display);
2140
2141   if (XGetSelectionOwner (display_x11->xdisplay, clipboard_manager) != None)
2142     {
2143       Atom property_name = None;
2144       Atom *xatoms;
2145       int i;
2146
2147       if (n_targets > 0)
2148         {
2149           property_name = gdk_x11_get_xatom_by_name_for_display (display, "GDK_SELECTION");
2150
2151           xatoms = g_new (Atom, n_targets);
2152           for (i = 0; i < n_targets; i++)
2153             xatoms[i] = gdk_x11_atom_to_xatom_for_display (display, targets[i]);
2154
2155           XChangeProperty (display_x11->xdisplay, GDK_WINDOW_XID (clipboard_window),
2156                            property_name, XA_ATOM,
2157                            32, PropModeReplace, (guchar *)xatoms, n_targets);
2158           g_free (xatoms);
2159
2160         }
2161
2162       XConvertSelection (display_x11->xdisplay,
2163                          clipboard_manager, save_targets, property_name,
2164                          GDK_WINDOW_XID (clipboard_window), time_);
2165
2166     }
2167   gdk_x11_display_error_trap_pop_ignored (display);
2168
2169 }
2170
2171 /**
2172  * gdk_x11_display_get_user_time:
2173  * @display: (type GdkX11Display): a #GdkDisplay
2174  *
2175  * Returns the timestamp of the last user interaction on 
2176  * @display. The timestamp is taken from events caused
2177  * by user interaction such as key presses or pointer 
2178  * movements. See gdk_x11_window_set_user_time().
2179  *
2180  * Returns: the timestamp of the last user interaction 
2181  *
2182  * Since: 2.8
2183  */
2184 guint32
2185 gdk_x11_display_get_user_time (GdkDisplay *display)
2186 {
2187   return GDK_X11_DISPLAY (display)->user_time;
2188 }
2189
2190 static gboolean
2191 gdk_x11_display_supports_shapes (GdkDisplay *display)
2192 {
2193   return GDK_X11_DISPLAY (display)->have_shapes;
2194 }
2195
2196 static gboolean
2197 gdk_x11_display_supports_input_shapes (GdkDisplay *display)
2198 {
2199   return GDK_X11_DISPLAY (display)->have_input_shapes;
2200 }
2201
2202
2203 /**
2204  * gdk_x11_display_get_startup_notification_id:
2205  * @display: (type GdkX11Display): a #GdkDisplay
2206  *
2207  * Gets the startup notification ID for a display.
2208  * 
2209  * Returns: the startup notification ID for @display
2210  *
2211  * Since: 2.12
2212  */
2213 const gchar *
2214 gdk_x11_display_get_startup_notification_id (GdkDisplay *display)
2215 {
2216   return GDK_X11_DISPLAY (display)->startup_notification_id;
2217 }
2218
2219 /**
2220  * gdk_x11_display_set_startup_notification_id:
2221  * @display: (type GdkX11Display): a #GdkDisplay
2222  * @startup_id: the startup notification ID (must be valid utf8)
2223  *
2224  * Sets the startup notification ID for a display.
2225  *
2226  * This is usually taken from the value of the DESKTOP_STARTUP_ID
2227  * environment variable, but in some cases (such as the application not
2228  * being launched using exec()) it can come from other sources.
2229  *
2230  * If the ID contains the string "_TIME" then the portion following that
2231  * string is taken to be the X11 timestamp of the event that triggered
2232  * the application to be launched and the GDK current event time is set
2233  * accordingly.
2234  *
2235  * The startup ID is also what is used to signal that the startup is
2236  * complete (for example, when opening a window or when calling
2237  * gdk_notify_startup_complete()).
2238  *
2239  * Since: 3.0
2240  **/
2241 void
2242 gdk_x11_display_set_startup_notification_id (GdkDisplay  *display,
2243                                              const gchar *startup_id)
2244 {
2245   GdkX11Display *display_x11;
2246   gchar *time_str;
2247
2248   display_x11 = GDK_X11_DISPLAY (display);
2249
2250   g_free (display_x11->startup_notification_id);
2251   display_x11->startup_notification_id = g_strdup (startup_id);
2252
2253   /* Find the launch time from the startup_id, if it's there.  Newer spec
2254    * states that the startup_id is of the form <unique>_TIME<timestamp>
2255    */
2256   time_str = g_strrstr (startup_id, "_TIME");
2257   if (time_str != NULL)
2258     {
2259       gulong retval;
2260       gchar *end;
2261       errno = 0;
2262
2263       /* Skip past the "_TIME" part */
2264       time_str += 5;
2265
2266       retval = strtoul (time_str, &end, 0);
2267       if (end != time_str && errno == 0)
2268         display_x11->user_time = retval;
2269     }
2270
2271   /* Set the startup id on the leader window so it
2272    * applies to all windows we create on this display
2273    */
2274   XChangeProperty (display_x11->xdisplay,
2275                    display_x11->leader_window,
2276                    gdk_x11_get_xatom_by_name_for_display (display, "_NET_STARTUP_ID"),
2277                    gdk_x11_get_xatom_by_name_for_display (display, "UTF8_STRING"), 8,
2278                    PropModeReplace,
2279                    (guchar *)startup_id, strlen (startup_id));
2280 }
2281
2282 static gboolean
2283 gdk_x11_display_supports_composite (GdkDisplay *display)
2284 {
2285   GdkX11Display *x11_display = GDK_X11_DISPLAY (display);
2286
2287   return x11_display->have_xcomposite &&
2288          x11_display->have_xdamage &&
2289          x11_display->have_xfixes;
2290 }
2291
2292 static GList *
2293 gdk_x11_display_list_devices (GdkDisplay *display)
2294 {
2295   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
2296
2297   return GDK_X11_DISPLAY (display)->input_devices;
2298 }
2299
2300 /**
2301  * gdk_x11_register_standard_event_type:
2302  * @display: a #GdkDisplay
2303  * @event_base: first event type code to register
2304  * @n_events: number of event type codes to register
2305  *
2306  * Registers interest in receiving extension events with type codes
2307  * between @event_base and <literal>event_base + n_events - 1</literal>.
2308  * The registered events must have the window field in the same place
2309  * as core X events (this is not the case for e.g. XKB extension events).
2310  *
2311  * If an event type is registered, events of this type will go through
2312  * global and window-specific filters (see gdk_window_add_filter()).
2313  * Unregistered events will only go through global filters.
2314  * GDK may register the events of some X extensions on its own.
2315  *
2316  * This function should only be needed in unusual circumstances, e.g.
2317  * when filtering XInput extension events on the root window.
2318  *
2319  * Since: 2.4
2320  **/
2321 void
2322 gdk_x11_register_standard_event_type (GdkDisplay *display,
2323                                       gint        event_base,
2324                                       gint        n_events)
2325 {
2326   GdkEventTypeX11 *event_type;
2327   GdkX11Display *display_x11;
2328
2329   display_x11 = GDK_X11_DISPLAY (display);
2330   event_type = g_new (GdkEventTypeX11, 1);
2331
2332   event_type->base = event_base;
2333   event_type->n_events = n_events;
2334
2335   display_x11->event_types = g_slist_prepend (display_x11->event_types, event_type);
2336 }
2337
2338 /* compare X sequence numbers handling wraparound */
2339 #define SEQUENCE_COMPARE(a,op,b) (((long) (a) - (long) (b)) op 0)
2340
2341 /* delivers an error event from the error handler in gdkmain-x11.c */
2342 void
2343 _gdk_x11_display_error_event (GdkDisplay  *display,
2344                               XErrorEvent *error)
2345 {
2346   GdkX11Display *display_x11;
2347   GSList *tmp_list;
2348   gboolean ignore;
2349
2350   display_x11 = GDK_X11_DISPLAY (display);
2351
2352   ignore = FALSE;
2353   for (tmp_list = display_x11->error_traps;
2354        tmp_list != NULL;
2355        tmp_list = tmp_list->next)
2356     {
2357       GdkErrorTrap *trap;
2358
2359       trap = tmp_list->data;
2360
2361       if (SEQUENCE_COMPARE (trap->start_sequence, <=, error->serial) &&
2362           (trap->end_sequence == 0 ||
2363            SEQUENCE_COMPARE (trap->end_sequence, >, error->serial)))
2364         {
2365           ignore = TRUE;
2366           trap->error_code = error->error_code;
2367           break; /* only innermost trap gets the error code */
2368         }
2369     }
2370
2371   if (!ignore)
2372     {
2373       gchar buf[64];
2374       gchar *msg;
2375
2376       XGetErrorText (display_x11->xdisplay, error->error_code, buf, 63);
2377
2378       msg =
2379         g_strdup_printf ("The program '%s' received an X Window System error.\n"
2380                          "This probably reflects a bug in the program.\n"
2381                          "The error was '%s'.\n"
2382                          "  (Details: serial %ld error_code %d request_code %d minor_code %d)\n"
2383                          "  (Note to programmers: normally, X errors are reported asynchronously;\n"
2384                          "   that is, you will receive the error a while after causing it.\n"
2385                          "   To debug your program, run it with the GDK_SYNCHRONIZE environment\n"
2386                          "   variable to change this behavior. You can then get a meaningful\n"
2387                          "   backtrace from your debugger if you break on the gdk_x_error() function.)",
2388                          g_get_prgname (),
2389                          buf,
2390                          error->serial,
2391                          error->error_code,
2392                          error->request_code,
2393                          error->minor_code);
2394
2395 #ifdef G_ENABLE_DEBUG
2396       g_error ("%s", msg);
2397 #else /* !G_ENABLE_DEBUG */
2398       g_warning ("%s\n", msg);
2399
2400       _exit (1);
2401 #endif /* G_ENABLE_DEBUG */
2402     }
2403 }
2404
2405 static void
2406 delete_outdated_error_traps (GdkX11Display *display_x11)
2407 {
2408   GSList *tmp_list;
2409   gulong processed_sequence;
2410
2411   processed_sequence = XLastKnownRequestProcessed (display_x11->xdisplay);
2412
2413   tmp_list = display_x11->error_traps;
2414   while (tmp_list != NULL)
2415     {
2416       GdkErrorTrap *trap = tmp_list->data;
2417
2418       if (trap->end_sequence != 0 &&
2419           SEQUENCE_COMPARE (trap->end_sequence, <=, processed_sequence))
2420         {
2421           GSList *free_me = tmp_list;
2422
2423           tmp_list = tmp_list->next;
2424           display_x11->error_traps =
2425             g_slist_delete_link (display_x11->error_traps, free_me);
2426           g_slice_free (GdkErrorTrap, trap);
2427         }
2428       else
2429         {
2430           tmp_list = tmp_list->next;
2431         }
2432     }
2433 }
2434
2435 /**
2436  * gdk_x11_display_error_trap_push:
2437  * @display: (type GdkX11Display): a #GdkDisplay
2438  *
2439  * Begins a range of X requests on @display for which X error events
2440  * will be ignored. Unignored errors (when no trap is pushed) will abort
2441  * the application. Use gdk_x11_display_error_trap_pop() or
2442  * gdk_x11_display_error_trap_pop_ignored()to lift a trap pushed
2443  * with this function.
2444  *
2445  * See also gdk_error_trap_push() to push a trap on all displays.
2446  *
2447  * Since: 3.0
2448  */
2449 void
2450 gdk_x11_display_error_trap_push (GdkDisplay *display)
2451 {
2452   GdkX11Display *display_x11;
2453   GdkErrorTrap *trap;
2454
2455   display_x11 = GDK_X11_DISPLAY (display);
2456
2457   delete_outdated_error_traps (display_x11);
2458
2459   /* set up the Xlib callback to tell us about errors */
2460   _gdk_x11_error_handler_push ();
2461
2462   trap = g_slice_new0 (GdkErrorTrap);
2463
2464   trap->start_sequence = XNextRequest (display_x11->xdisplay);
2465   trap->error_code = Success;
2466
2467   display_x11->error_traps =
2468     g_slist_prepend (display_x11->error_traps, trap);
2469 }
2470
2471 static gint
2472 gdk_x11_display_error_trap_pop_internal (GdkDisplay *display,
2473                                          gboolean    need_code)
2474 {
2475   GdkX11Display *display_x11;
2476   GdkErrorTrap *trap;
2477   GSList *tmp_list;
2478   int result;
2479
2480   display_x11 = GDK_X11_DISPLAY (display);
2481
2482   g_return_val_if_fail (display_x11->error_traps != NULL, Success);
2483
2484   /* Find the first trap that hasn't been popped already */
2485   trap = NULL; /* quiet gcc */
2486   for (tmp_list = display_x11->error_traps;
2487        tmp_list != NULL;
2488        tmp_list = tmp_list->next)
2489     {
2490       trap = tmp_list->data;
2491
2492       if (trap->end_sequence == 0)
2493         break;
2494     }
2495
2496   g_return_val_if_fail (trap != NULL, Success);
2497   g_assert (trap->end_sequence == 0);
2498
2499   /* May need to sync to fill in trap->error_code if we care about
2500    * getting an error code.
2501    */
2502   if (need_code)
2503     {
2504       gulong processed_sequence;
2505       gulong next_sequence;
2506
2507       next_sequence = XNextRequest (display_x11->xdisplay);
2508       processed_sequence = XLastKnownRequestProcessed (display_x11->xdisplay);
2509
2510       /* If our last request was already processed, there is no point
2511        * in syncing. i.e. if last request was a round trip (or even if
2512        * we got an event with the serial of a non-round-trip)
2513        */
2514       if ((next_sequence - 1) != processed_sequence)
2515         {
2516           XSync (display_x11->xdisplay, False);
2517         }
2518
2519       result = trap->error_code;
2520     }
2521   else
2522     {
2523       result = Success;
2524     }
2525
2526   /* record end of trap, giving us a range of
2527    * error sequences we'll ignore.
2528    */
2529   trap->end_sequence = XNextRequest (display_x11->xdisplay);
2530
2531   /* remove the Xlib callback */
2532   _gdk_x11_error_handler_pop ();
2533
2534   /* we may already be outdated */
2535   delete_outdated_error_traps (display_x11);
2536
2537   return result;
2538 }
2539
2540 /**
2541  * gdk_x11_display_error_trap_pop:
2542  * @display: (type GdkX11Display): the display
2543  *
2544  * Pops the error trap pushed by gdk_x11_display_error_trap_push().
2545  * Will XSync() if necessary and will always block until
2546  * the error is known to have occurred or not occurred,
2547  * so the error code can be returned.
2548  *
2549  * If you don't need to use the return value,
2550  * gdk_x11_display_error_trap_pop_ignored() would be more efficient.
2551  *
2552  * See gdk_error_trap_pop() for the all-displays-at-once
2553  * equivalent.
2554  *
2555  * Since: 3.0
2556  *
2557  * Return value: X error code or 0 on success
2558  */
2559 gint
2560 gdk_x11_display_error_trap_pop (GdkDisplay *display)
2561 {
2562   g_return_val_if_fail (GDK_IS_X11_DISPLAY (display), Success);
2563
2564   return gdk_x11_display_error_trap_pop_internal (display, TRUE);
2565 }
2566
2567 /**
2568  * gdk_x11_display_error_trap_pop_ignored:
2569  * @display: (type GdkX11Display): the display
2570  *
2571  * Pops the error trap pushed by gdk_x11_display_error_trap_push().
2572  * Does not block to see if an error occurred; merely records the
2573  * range of requests to ignore errors for, and ignores those errors
2574  * if they arrive asynchronously.
2575  *
2576  * See gdk_error_trap_pop_ignored() for the all-displays-at-once
2577  * equivalent.
2578  *
2579  * Since: 3.0
2580  */
2581 void
2582 gdk_x11_display_error_trap_pop_ignored (GdkDisplay *display)
2583 {
2584   g_return_if_fail (GDK_IS_X11_DISPLAY (display));
2585
2586   gdk_x11_display_error_trap_pop_internal (display, FALSE);
2587 }
2588
2589 /**
2590  * gdk_x11_set_sm_client_id:
2591  * @sm_client_id: the client id assigned by the session manager when the
2592  *    connection was opened, or %NULL to remove the property.
2593  *
2594  * Sets the <literal>SM_CLIENT_ID</literal> property on the application's leader window so that
2595  * the window manager can save the application's state using the X11R6 ICCCM
2596  * session management protocol.
2597  *
2598  * See the X Session Management Library documentation for more information on
2599  * session management and the Inter-Client Communication Conventions Manual
2600  *
2601  * Since: 2.24
2602  */
2603 void
2604 gdk_x11_set_sm_client_id (const gchar *sm_client_id)
2605 {
2606  GSList *displays, *l;
2607
2608   g_free (gdk_sm_client_id);
2609   gdk_sm_client_id = g_strdup (sm_client_id);
2610
2611   displays = gdk_display_manager_list_displays (gdk_display_manager_get ());
2612   for (l = displays; l; l = l->next)
2613     set_sm_client_id (l->data, sm_client_id);
2614
2615   g_slist_free (displays);
2616 }
2617
2618 static void
2619 gdk_x11_display_event_data_copy (GdkDisplay    *display,
2620                                 const GdkEvent *src,
2621                                 GdkEvent       *dst)
2622 {
2623 }
2624
2625 static void
2626 gdk_x11_display_event_data_free (GdkDisplay *display,
2627                                  GdkEvent *event)
2628 {
2629 }
2630
2631 static gint
2632 pop_error_trap (GdkDisplay *display,
2633                 gboolean    ignored)
2634 {
2635   if (ignored)
2636     {
2637       gdk_x11_display_error_trap_pop_ignored (display);
2638       return Success;
2639     }
2640   else
2641     {
2642       return gdk_x11_display_error_trap_pop (display);
2643     }
2644 }
2645
2646 static GdkKeymap *
2647 gdk_x11_display_get_keymap (GdkDisplay *display)
2648 {
2649   GdkX11Display *display_x11;
2650   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
2651   display_x11 = GDK_X11_DISPLAY (display);
2652
2653   if (!display_x11->keymap)
2654     display_x11->keymap = g_object_new (GDK_TYPE_X11_KEYMAP, NULL);
2655
2656   display_x11->keymap->display = display;
2657
2658   return display_x11->keymap;
2659 }
2660
2661 static void
2662 gdk_x11_display_class_init (GdkX11DisplayClass * class)
2663 {
2664   GObjectClass *object_class = G_OBJECT_CLASS (class);
2665   GdkDisplayClass *display_class = GDK_DISPLAY_CLASS (class);
2666
2667   object_class->dispose = gdk_x11_display_dispose;
2668   object_class->finalize = gdk_x11_display_finalize;
2669
2670   display_class->window_type = GDK_TYPE_X11_WINDOW;
2671
2672   display_class->get_name = gdk_x11_display_get_name;
2673   display_class->get_n_screens = gdk_x11_display_get_n_screens;
2674   display_class->get_screen = gdk_x11_display_get_screen;
2675   display_class->get_default_screen = gdk_x11_display_get_default_screen;
2676   display_class->beep = gdk_x11_display_beep;
2677   display_class->sync = gdk_x11_display_sync;
2678   display_class->flush = gdk_x11_display_flush;
2679   display_class->has_pending = gdk_x11_display_has_pending;
2680   display_class->queue_events = _gdk_x11_display_queue_events;
2681   display_class->get_default_group = gdk_x11_display_get_default_group;
2682   display_class->supports_selection_notification = gdk_x11_display_supports_selection_notification;
2683   display_class->request_selection_notification = gdk_x11_display_request_selection_notification;
2684   display_class->supports_clipboard_persistence = gdk_x11_display_supports_clipboard_persistence;
2685   display_class->store_clipboard = gdk_x11_display_store_clipboard;
2686   display_class->supports_shapes = gdk_x11_display_supports_shapes;
2687   display_class->supports_input_shapes = gdk_x11_display_supports_input_shapes;
2688   display_class->supports_composite = gdk_x11_display_supports_composite;
2689   display_class->list_devices = gdk_x11_display_list_devices;
2690   display_class->get_app_launch_context = _gdk_x11_display_get_app_launch_context;
2691   display_class->get_cursor_for_type = _gdk_x11_display_get_cursor_for_type;
2692   display_class->get_cursor_for_name = _gdk_x11_display_get_cursor_for_name;
2693   display_class->get_cursor_for_pixbuf = _gdk_x11_display_get_cursor_for_pixbuf;
2694   display_class->get_default_cursor_size = _gdk_x11_display_get_default_cursor_size;
2695   display_class->get_maximal_cursor_size = _gdk_x11_display_get_maximal_cursor_size;
2696   display_class->supports_cursor_alpha = _gdk_x11_display_supports_cursor_alpha;
2697   display_class->supports_cursor_color = _gdk_x11_display_supports_cursor_color;
2698
2699   display_class->before_process_all_updates = _gdk_x11_display_before_process_all_updates;
2700   display_class->after_process_all_updates = _gdk_x11_display_after_process_all_updates;
2701   display_class->get_next_serial = gdk_x11_display_get_next_serial;
2702   display_class->notify_startup_complete = gdk_x11_display_notify_startup_complete;
2703   display_class->event_data_copy = gdk_x11_display_event_data_copy;
2704   display_class->event_data_free = gdk_x11_display_event_data_free;
2705   display_class->create_window_impl = _gdk_x11_display_create_window_impl;
2706   display_class->get_keymap = gdk_x11_display_get_keymap;
2707   display_class->push_error_trap = gdk_x11_display_error_trap_push;
2708   display_class->pop_error_trap = pop_error_trap;
2709   display_class->get_selection_owner = _gdk_x11_display_get_selection_owner;
2710   display_class->set_selection_owner = _gdk_x11_display_set_selection_owner;
2711   display_class->send_selection_notify = _gdk_x11_display_send_selection_notify;
2712   display_class->get_selection_property = _gdk_x11_display_get_selection_property;
2713   display_class->convert_selection = _gdk_x11_display_convert_selection;
2714   display_class->text_property_to_utf8_list = _gdk_x11_display_text_property_to_utf8_list;
2715   display_class->utf8_to_string_target = _gdk_x11_display_utf8_to_string_target;
2716 }