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