]> Pileus Git - ~andy/gtk/blob - gtk/gtkmain.c
65df934ccbadb6123d70afb48b25f900a5c0ec57
[~andy/gtk] / gtk / gtkmain.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /*
19  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
20  * file for a list of people on the GTK+ Team.  See the ChangeLog
21  * files for a list of changes.  These files are distributed with
22  * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
23  */
24
25 /**
26  * SECTION:gtkmain
27  * @Short_description: Library initialization, main event loop, and events
28  * @Title: Main loop and Events
29  * @See_also:See the GLib manual, especially #GMainLoop and signal-related
30  *    functions such as g_signal_connect()
31  *
32  * Before using GTK+, you need to initialize it; initialization connects to the
33  * window system display, and parses some standard command line arguments. The
34  * gtk_init() macro initializes GTK+. gtk_init() exits the application if errors
35  * occur; to avoid this, use gtk_init_check(). gtk_init_check() allows you to
36  * recover from a failed GTK+ initialization - you might start up your
37  * application in text mode instead.
38  *
39  * Like all GUI toolkits, GTK+ uses an event-driven programming model. When the
40  * user is doing nothing, GTK+ sits in the <firstterm>main loop</firstterm> and
41  * waits for input. If the user performs some action - say, a mouse click - then
42  * the main loop "wakes up" and delivers an event to GTK+. GTK+ forwards the
43  * event to one or more widgets.
44  *
45  * When widgets receive an event, they frequently emit one or more
46  * <firstterm>signals</firstterm>. Signals notify your program that "something
47  * interesting happened" by invoking functions you've connected to the signal
48  * with g_signal_connect(). Functions connected to a signal are often termed
49  * <firstterm>callbacks</firstterm>.
50  *
51  * When your callbacks are invoked, you would typically take some action - for
52  * example, when an Open button is clicked you might display a
53  * #GtkFileChooserDialog. After a callback finishes, GTK+ will return to the
54  * main loop and await more user input.
55  * </para>
56  * <example>
57  * <title>Typical <function>main()</function> function for a GTK+ application</title>
58  * <programlisting>
59  * int
60  * main (int argc, char **argv)
61  * {
62  *   /&ast; Initialize i18n support &ast;/
63  *   gtk_set_locale ();
64  *
65  *   /&ast; Initialize the widget set &ast;/
66  *   gtk_init (&argc, &argv);
67  *
68  *   /&ast; Create the main window &ast;/
69  *   mainwin = gtk_window_new (GTK_WINDOW_TOPLEVEL);
70  *
71  *   /&ast; Set up our GUI elements &ast;/
72  *   ...
73  *
74  *   /&ast; Show the application window &ast;/
75  *   gtk_widget_show_all (mainwin);
76  *
77  *   /&ast; Enter the main event loop, and wait for user interaction &ast;/
78  *   gtk_main ();
79  *
80  *   /&ast; The user lost interest &ast;/
81  *   return 0;
82  * }
83  * </programlisting>
84  * </example>
85  * <para>
86  * It's OK to use the GLib main loop directly instead of gtk_main(), though it
87  * involves slightly more typing. See #GMainLoop in the GLib documentation.
88  */
89
90 #include "config.h"
91
92 #include "gdk/gdk.h"
93
94 #include <locale.h>
95
96 #include <stdio.h>
97 #include <stdlib.h>
98 #include <string.h>
99 #ifdef HAVE_UNISTD_H
100 #include <unistd.h>
101 #endif
102 #include <sys/types.h>          /* For uid_t, gid_t */
103
104 #ifdef G_OS_WIN32
105 #define STRICT
106 #include <windows.h>
107 #undef STRICT
108 #endif
109
110 #include "gtkintl.h"
111
112 #include "gtkaccelmapprivate.h"
113 #include "gtkbox.h"
114 #include "gtkclipboard.h"
115 #include "gtkdebug.h"
116 #include "gtkdnd.h"
117 #include "gtkmain.h"
118 #include "gtkmenu.h"
119 #include "gtkmodules.h"
120 #include "gtkmodulesprivate.h"
121 #include "gtkprivate.h"
122 #include "gtkrecentmanager.h"
123 #include "gtkresources.h"
124 #include "gtkselectionprivate.h"
125 #include "gtksettingsprivate.h"
126 #include "gtktooltip.h"
127 #include "gtkversion.h"
128 #include "gtkwidgetprivate.h"
129 #include "gtkwindowprivate.h"
130
131 #include "a11y/gailutil.h"
132
133 /* Private type definitions
134  */
135 typedef struct _GtkKeySnooperData        GtkKeySnooperData;
136
137 struct _GtkKeySnooperData
138 {
139   GtkKeySnoopFunc func;
140   gpointer func_data;
141   guint id;
142 };
143
144 static gint  gtk_invoke_key_snoopers     (GtkWidget          *grab_widget,
145                                           GdkEvent           *event);
146
147 static GtkWindowGroup *gtk_main_get_window_group (GtkWidget   *widget);
148
149 static guint gtk_main_loop_level = 0;
150 static gint pre_initialized = FALSE;
151 static gint gtk_initialized = FALSE;
152 static GList *current_events = NULL;
153
154 static GSList *main_loops = NULL;      /* stack of currently executing main loops */
155
156 static GSList *key_snoopers = NULL;
157
158 static guint debug_flags = 0;              /* Global GTK debug flag */
159
160 #ifdef G_ENABLE_DEBUG
161 static const GDebugKey gtk_debug_keys[] = {
162   {"misc", GTK_DEBUG_MISC},
163   {"plugsocket", GTK_DEBUG_PLUGSOCKET},
164   {"text", GTK_DEBUG_TEXT},
165   {"tree", GTK_DEBUG_TREE},
166   {"updates", GTK_DEBUG_UPDATES},
167   {"keybindings", GTK_DEBUG_KEYBINDINGS},
168   {"multihead", GTK_DEBUG_MULTIHEAD},
169   {"modules", GTK_DEBUG_MODULES},
170   {"geometry", GTK_DEBUG_GEOMETRY},
171   {"icontheme", GTK_DEBUG_ICONTHEME},
172   {"printing", GTK_DEBUG_PRINTING},
173   {"builder", GTK_DEBUG_BUILDER},
174   {"size-request", GTK_DEBUG_SIZE_REQUEST},
175 };
176 #endif /* G_ENABLE_DEBUG */
177
178 /**
179  * gtk_get_major_version:
180  *
181  * Returns the major version number of the GTK+ library.
182  * (e.g. in GTK+ version 3.1.5 this is 3.)
183  *
184  * This function is in the library, so it represents the GTK+ library
185  * your code is running against. Contrast with the #GTK_MAJOR_VERSION
186  * macro, which represents the major version of the GTK+ headers you
187  * have included when compiling your code.
188  *
189  * Returns: the major version number of the GTK+ library
190  *
191  * Since: 3.0
192  */
193 guint
194 gtk_get_major_version (void)
195 {
196   return GTK_MAJOR_VERSION;
197 }
198
199 /**
200  * gtk_get_minor_version:
201  *
202  * Returns the minor version number of the GTK+ library.
203  * (e.g. in GTK+ version 3.1.5 this is 1.)
204  *
205  * This function is in the library, so it represents the GTK+ library
206  * your code is are running against. Contrast with the
207  * #GTK_MINOR_VERSION macro, which represents the minor version of the
208  * GTK+ headers you have included when compiling your code.
209  *
210  * Returns: the minor version number of the GTK+ library
211  *
212  * Since: 3.0
213  */
214 guint
215 gtk_get_minor_version (void)
216 {
217   return GTK_MINOR_VERSION;
218 }
219
220 /**
221  * gtk_get_micro_version:
222  *
223  * Returns the micro version number of the GTK+ library.
224  * (e.g. in GTK+ version 3.1.5 this is 5.)
225  *
226  * This function is in the library, so it represents the GTK+ library
227  * your code is are running against. Contrast with the
228  * #GTK_MICRO_VERSION macro, which represents the micro version of the
229  * GTK+ headers you have included when compiling your code.
230  *
231  * Returns: the micro version number of the GTK+ library
232  *
233  * Since: 3.0
234  */
235 guint
236 gtk_get_micro_version (void)
237 {
238   return GTK_MICRO_VERSION;
239 }
240
241 /**
242  * gtk_get_binary_age:
243  *
244  * Returns the binary age as passed to <application>libtool</application>
245  * when building the GTK+ library the process is running against.
246  * If <application>libtool</application> means nothing to you, don't
247  * worry about it.
248  *
249  * Returns: the binary age of the GTK+ library
250  *
251  * Since: 3.0
252  */
253 guint
254 gtk_get_binary_age (void)
255 {
256   return GTK_BINARY_AGE;
257 }
258
259 /**
260  * gtk_get_interface_age:
261  *
262  * Returns the interface age as passed to <application>libtool</application>
263  * when building the GTK+ library the process is running against.
264  * If <application>libtool</application> means nothing to you, don't
265  * worry about it.
266  *
267  * Returns: the interface age of the GTK+ library
268  *
269  * Since: 3.0
270  */
271 guint
272 gtk_get_interface_age (void)
273 {
274   return GTK_INTERFACE_AGE;
275 }
276
277 /**
278  * gtk_check_version:
279  * @required_major: the required major version
280  * @required_minor: the required minor version
281  * @required_micro: the required micro version
282  *
283  * Checks that the GTK+ library in use is compatible with the
284  * given version. Generally you would pass in the constants
285  * #GTK_MAJOR_VERSION, #GTK_MINOR_VERSION, #GTK_MICRO_VERSION
286  * as the three arguments to this function; that produces
287  * a check that the library in use is compatible with
288  * the version of GTK+ the application or module was compiled
289  * against.
290  *
291  * Compatibility is defined by two things: first the version
292  * of the running library is newer than the version
293  * @required_major.required_minor.@required_micro. Second
294  * the running library must be binary compatible with the
295  * version @required_major.required_minor.@required_micro
296  * (same major version.)
297  *
298  * This function is primarily for GTK+ modules; the module
299  * can call this function to check that it wasn't loaded
300  * into an incompatible version of GTK+. However, such a
301  * check isn't completely reliable, since the module may be
302  * linked against an old version of GTK+ and calling the
303  * old version of gtk_check_version(), but still get loaded
304  * into an application using a newer version of GTK+.
305  *
306  * Return value: %NULL if the GTK+ library is compatible with the
307  *   given version, or a string describing the version mismatch.
308  *   The returned string is owned by GTK+ and should not be modified
309  *   or freed.
310  */
311 const gchar*
312 gtk_check_version (guint required_major,
313                    guint required_minor,
314                    guint required_micro)
315 {
316   gint gtk_effective_micro = 100 * GTK_MINOR_VERSION + GTK_MICRO_VERSION;
317   gint required_effective_micro = 100 * required_minor + required_micro;
318
319   if (required_major > GTK_MAJOR_VERSION)
320     return "GTK+ version too old (major mismatch)";
321   if (required_major < GTK_MAJOR_VERSION)
322     return "GTK+ version too new (major mismatch)";
323   if (required_effective_micro < gtk_effective_micro - GTK_BINARY_AGE)
324     return "GTK+ version too new (micro mismatch)";
325   if (required_effective_micro > gtk_effective_micro)
326     return "GTK+ version too old (micro mismatch)";
327   return NULL;
328 }
329
330 /* This checks to see if the process is running suid or sgid
331  * at the current time. If so, we don't allow GTK+ to be initialized.
332  * This is meant to be a mild check - we only error out if we
333  * can prove the programmer is doing something wrong, not if
334  * they could be doing something wrong. For this reason, we
335  * don't use issetugid() on BSD or prctl (PR_GET_DUMPABLE).
336  */
337 static gboolean
338 check_setugid (void)
339 {
340 /* this isn't at all relevant on MS Windows and doesn't compile ... --hb */
341 #ifndef G_OS_WIN32
342   uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
343   gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
344   
345 #ifdef HAVE_GETRESUID
346   /* These aren't in the header files, so we prototype them here.
347    */
348   int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
349   int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
350
351   if (getresuid (&ruid, &euid, &suid) != 0 ||
352       getresgid (&rgid, &egid, &sgid) != 0)
353 #endif /* HAVE_GETRESUID */
354     {
355       suid = ruid = getuid ();
356       sgid = rgid = getgid ();
357       euid = geteuid ();
358       egid = getegid ();
359     }
360
361   if (ruid != euid || ruid != suid ||
362       rgid != egid || rgid != sgid)
363     {
364       g_warning ("This process is currently running setuid or setgid.\n"
365                  "This is not a supported use of GTK+. You must create a helper\n"
366                  "program instead. For further details, see:\n\n"
367                  "    http://www.gtk.org/setuid.html\n\n"
368                  "Refusing to initialize GTK+.");
369       exit (1);
370     }
371 #endif
372   return TRUE;
373 }
374
375 static gboolean do_setlocale = TRUE;
376
377 /**
378  * gtk_disable_setlocale:
379  * 
380  * Prevents gtk_init(), gtk_init_check(), gtk_init_with_args() and
381  * gtk_parse_args() from automatically
382  * calling <literal>setlocale (LC_ALL, "")</literal>. You would
383  * want to use this function if you wanted to set the locale for
384  * your program to something other than the user's locale, or if
385  * you wanted to set different values for different locale categories.
386  *
387  * Most programs should not need to call this function.
388  **/
389 void
390 gtk_disable_setlocale (void)
391 {
392   if (pre_initialized)
393     g_warning ("gtk_disable_setlocale() must be called before gtk_init()");
394     
395   do_setlocale = FALSE;
396 }
397
398 #ifdef G_PLATFORM_WIN32
399 #undef gtk_init_check
400 #endif
401
402 static GString *gtk_modules_string = NULL;
403 static gboolean g_fatal_warnings = FALSE;
404
405 #ifdef G_ENABLE_DEBUG
406 static gboolean
407 gtk_arg_debug_cb (const char *key, const char *value, gpointer user_data)
408 {
409   debug_flags |= g_parse_debug_string (value,
410                                        gtk_debug_keys,
411                                        G_N_ELEMENTS (gtk_debug_keys));
412
413   return TRUE;
414 }
415
416 static gboolean
417 gtk_arg_no_debug_cb (const char *key, const char *value, gpointer user_data)
418 {
419   debug_flags &= ~g_parse_debug_string (value,
420                                         gtk_debug_keys,
421                                         G_N_ELEMENTS (gtk_debug_keys));
422
423   return TRUE;
424 }
425 #endif /* G_ENABLE_DEBUG */
426
427 static gboolean
428 gtk_arg_module_cb (const char *key, const char *value, gpointer user_data)
429 {
430   if (value && *value)
431     {
432       if (gtk_modules_string)
433         g_string_append_c (gtk_modules_string, G_SEARCHPATH_SEPARATOR);
434       else
435         gtk_modules_string = g_string_new (NULL);
436       
437       g_string_append (gtk_modules_string, value);
438     }
439
440   return TRUE;
441 }
442
443 static const GOptionEntry gtk_args[] = {
444   { "gtk-module",       0, 0, G_OPTION_ARG_CALLBACK, gtk_arg_module_cb,   
445     /* Description of --gtk-module=MODULES in --help output */ N_("Load additional GTK+ modules"), 
446     /* Placeholder in --gtk-module=MODULES in --help output */ N_("MODULES") },
447   { "g-fatal-warnings", 0, 0, G_OPTION_ARG_NONE, &g_fatal_warnings, 
448     /* Description of --g-fatal-warnings in --help output */   N_("Make all warnings fatal"), NULL },
449 #ifdef G_ENABLE_DEBUG
450   { "gtk-debug",        0, 0, G_OPTION_ARG_CALLBACK, gtk_arg_debug_cb,    
451     /* Description of --gtk-debug=FLAGS in --help output */    N_("GTK+ debugging flags to set"), 
452     /* Placeholder in --gtk-debug=FLAGS in --help output */    N_("FLAGS") },
453   { "gtk-no-debug",     0, 0, G_OPTION_ARG_CALLBACK, gtk_arg_no_debug_cb, 
454     /* Description of --gtk-no-debug=FLAGS in --help output */ N_("GTK+ debugging flags to unset"), 
455     /* Placeholder in --gtk-no-debug=FLAGS in --help output */ N_("FLAGS") },
456 #endif 
457   { NULL }
458 };
459
460 #ifdef G_OS_WIN32
461
462 static char *iso639_to_check = NULL;
463 static char *iso3166_to_check = NULL;
464 static char *script_to_check = NULL;
465 static gboolean setlocale_called = FALSE;
466
467 static BOOL CALLBACK
468 enum_locale_proc (LPTSTR locale)
469 {
470   LCID lcid;
471   char iso639[10];
472   char iso3166[10];
473   char *endptr;
474
475
476   lcid = strtoul (locale, &endptr, 16);
477   if (*endptr == '\0' &&
478       GetLocaleInfo (lcid, LOCALE_SISO639LANGNAME, iso639, sizeof (iso639)) &&
479       GetLocaleInfo (lcid, LOCALE_SISO3166CTRYNAME, iso3166, sizeof (iso3166)))
480     {
481       if (strcmp (iso639, iso639_to_check) == 0 &&
482           ((iso3166_to_check != NULL &&
483             strcmp (iso3166, iso3166_to_check) == 0) ||
484            (iso3166_to_check == NULL &&
485             SUBLANGID (LANGIDFROMLCID (lcid)) == SUBLANG_DEFAULT)))
486         {
487           char language[100], country[100];
488           char locale[300];
489
490           if (script_to_check != NULL)
491             {
492               /* If lcid is the "other" script for this language,
493                * return TRUE, i.e. continue looking.
494                */
495               if (strcmp (script_to_check, "Latn") == 0)
496                 {
497                   switch (LANGIDFROMLCID (lcid))
498                     {
499                     case MAKELANGID (LANG_AZERI, SUBLANG_AZERI_CYRILLIC):
500                       return TRUE;
501                     case MAKELANGID (LANG_UZBEK, SUBLANG_UZBEK_CYRILLIC):
502                       return TRUE;
503                     case MAKELANGID (LANG_SERBIAN, SUBLANG_SERBIAN_CYRILLIC):
504                       return TRUE;
505                     case MAKELANGID (LANG_SERBIAN, 0x07):
506                       /* Serbian in Bosnia and Herzegovina, Cyrillic */
507                       return TRUE;
508                     }
509                 }
510               else if (strcmp (script_to_check, "Cyrl") == 0)
511                 {
512                   switch (LANGIDFROMLCID (lcid))
513                     {
514                     case MAKELANGID (LANG_AZERI, SUBLANG_AZERI_LATIN):
515                       return TRUE;
516                     case MAKELANGID (LANG_UZBEK, SUBLANG_UZBEK_LATIN):
517                       return TRUE;
518                     case MAKELANGID (LANG_SERBIAN, SUBLANG_SERBIAN_LATIN):
519                       return TRUE;
520                     case MAKELANGID (LANG_SERBIAN, 0x06):
521                       /* Serbian in Bosnia and Herzegovina, Latin */
522                       return TRUE;
523                     }
524                 }
525             }
526
527           SetThreadLocale (lcid);
528
529           if (GetLocaleInfo (lcid, LOCALE_SENGLANGUAGE, language, sizeof (language)) &&
530               GetLocaleInfo (lcid, LOCALE_SENGCOUNTRY, country, sizeof (country)))
531             {
532               strcpy (locale, language);
533               strcat (locale, "_");
534               strcat (locale, country);
535
536               if (setlocale (LC_ALL, locale) != NULL)
537                 setlocale_called = TRUE;
538             }
539
540           return FALSE;
541         }
542     }
543
544   return TRUE;
545 }
546   
547 #endif
548
549 static void
550 setlocale_initialization (void)
551 {
552   static gboolean initialized = FALSE;
553
554   if (initialized)
555     return;
556   initialized = TRUE;
557
558   if (do_setlocale)
559     {
560 #ifdef G_OS_WIN32
561       /* If some of the POSIXish environment variables are set, set
562        * the Win32 thread locale correspondingly.
563        */ 
564       char *p = getenv ("LC_ALL");
565       if (p == NULL)
566         p = getenv ("LANG");
567
568       if (p != NULL)
569         {
570           p = g_strdup (p);
571           if (strcmp (p, "C") == 0)
572             SetThreadLocale (LOCALE_SYSTEM_DEFAULT);
573           else
574             {
575               /* Check if one of the supported locales match the
576                * environment variable. If so, use that locale.
577                */
578               iso639_to_check = p;
579               iso3166_to_check = strchr (iso639_to_check, '_');
580               if (iso3166_to_check != NULL)
581                 {
582                   *iso3166_to_check++ = '\0';
583
584                   script_to_check = strchr (iso3166_to_check, '@');
585                   if (script_to_check != NULL)
586                     *script_to_check++ = '\0';
587
588                   /* Handle special cases. */
589
590                   /* The standard code for Serbia and Montenegro was
591                    * "CS", but MSFT uses for some reason "SP". By now
592                    * (October 2006), SP has split into two, "RS" and
593                    * "ME", but don't bother trying to handle those
594                    * yet. Do handle the even older "YU", though.
595                    */
596                   if (strcmp (iso3166_to_check, "CS") == 0 ||
597                       strcmp (iso3166_to_check, "YU") == 0)
598                     iso3166_to_check = "SP";
599                 }
600               else
601                 {
602                   script_to_check = strchr (iso639_to_check, '@');
603                   if (script_to_check != NULL)
604                     *script_to_check++ = '\0';
605                   /* LANG_SERBIAN == LANG_CROATIAN, recognize just "sr" */
606                   if (strcmp (iso639_to_check, "sr") == 0)
607                     iso3166_to_check = "SP";
608                 }
609
610               EnumSystemLocales (enum_locale_proc, LCID_SUPPORTED);
611             }
612           g_free (p);
613         }
614       if (!setlocale_called)
615         setlocale (LC_ALL, "");
616 #else
617       if (!setlocale (LC_ALL, ""))
618         g_warning ("Locale not supported by C library.\n\tUsing the fallback 'C' locale.");
619 #endif
620     }
621 }
622
623 static void
624 do_pre_parse_initialization (int    *argc,
625                              char ***argv)
626 {
627   const gchar *env_string;
628   
629   if (pre_initialized)
630     return;
631
632   pre_initialized = TRUE;
633
634   if (_gtk_module_has_mixed_deps (NULL))
635     g_error ("GTK+ 2.x symbols detected. Using GTK+ 2.x and GTK+ 3 in the same process is not supported");
636
637   gdk_pre_parse_libgtk_only ();
638   gdk_event_handler_set ((GdkEventFunc)gtk_main_do_event, NULL, NULL);
639
640 #ifdef G_ENABLE_DEBUG
641   env_string = g_getenv ("GTK_DEBUG");
642   if (env_string != NULL)
643     {
644       debug_flags = g_parse_debug_string (env_string,
645                                           gtk_debug_keys,
646                                           G_N_ELEMENTS (gtk_debug_keys));
647       env_string = NULL;
648     }
649 #endif  /* G_ENABLE_DEBUG */
650
651   env_string = g_getenv ("GTK_MODULES");
652   if (env_string)
653     gtk_modules_string = g_string_new (env_string);
654 }
655
656 static void
657 gettext_initialization (void)
658 {
659   setlocale_initialization ();
660
661 #ifdef ENABLE_NLS
662   bindtextdomain (GETTEXT_PACKAGE, _gtk_get_localedir ());
663   bindtextdomain (GETTEXT_PACKAGE "-properties", _gtk_get_localedir ());
664 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
665   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
666   bind_textdomain_codeset (GETTEXT_PACKAGE "-properties", "UTF-8");
667 #    endif
668 #endif  
669 }
670
671 /* XXX: Remove me after getting rid of gail */
672 extern void _gtk_accessibility_init (void);
673
674 static void
675 do_post_parse_initialization (int    *argc,
676                               char ***argv)
677 {
678   if (gtk_initialized)
679     return;
680
681   gettext_initialization ();
682
683 #ifdef SIGPIPE
684   signal (SIGPIPE, SIG_IGN);
685 #endif
686
687   if (g_fatal_warnings)
688     {
689       GLogLevelFlags fatal_mask;
690
691       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
692       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
693       g_log_set_always_fatal (fatal_mask);
694     }
695
696   if (debug_flags & GTK_DEBUG_UPDATES)
697     gdk_window_set_debug_updates (TRUE);
698
699   {
700   /* Translate to default:RTL if you want your widgets
701    * to be RTL, otherwise translate to default:LTR.
702    * Do *not* translate it to "predefinito:LTR", if it
703    * it isn't default:LTR or default:RTL it will not work 
704    */
705     char *e = _("default:LTR");
706     if (strcmp (e, "default:RTL")==0) 
707       gtk_widget_set_default_direction (GTK_TEXT_DIR_RTL);
708     else if (strcmp (e, "default:LTR"))
709       g_warning ("Whoever translated default:LTR did so wrongly.\n");
710   }
711
712   _gtk_register_resource ();
713
714   /* do what the call to gtk_type_init() used to do */
715   g_type_init ();
716
717   _gtk_accel_map_init ();
718
719   /* Set the 'initialized' flag.
720    */
721   gtk_initialized = TRUE;
722
723   /* load gtk modules */
724   if (gtk_modules_string)
725     {
726       _gtk_modules_init (argc, argv, gtk_modules_string->str);
727       g_string_free (gtk_modules_string, TRUE);
728     }
729   else
730     {
731       _gtk_modules_init (argc, argv, NULL);
732     }
733
734   _gtk_accessibility_init ();
735 }
736
737
738 typedef struct
739 {
740   gboolean open_default_display;
741 } OptionGroupInfo;
742
743 static gboolean
744 pre_parse_hook (GOptionContext *context,
745                 GOptionGroup   *group,
746                 gpointer        data,
747                 GError        **error)
748 {
749   do_pre_parse_initialization (NULL, NULL);
750   
751   return TRUE;
752 }
753
754 static gboolean
755 post_parse_hook (GOptionContext *context,
756                  GOptionGroup   *group,
757                  gpointer       data,
758                  GError        **error)
759 {
760   OptionGroupInfo *info = data;
761
762   
763   do_post_parse_initialization (NULL, NULL);
764   
765   if (info->open_default_display)
766     {
767       if (gdk_display_open_default_libgtk_only () == NULL)
768         {
769           const char *display_name = gdk_get_display_arg_name ();
770           g_set_error (error,
771                        G_OPTION_ERROR,
772                        G_OPTION_ERROR_FAILED,
773                        _("Cannot open display: %s"),
774                        display_name ? display_name : "" );
775
776           return FALSE;
777         }
778     }
779
780   return TRUE;
781 }
782
783
784 /**
785  * gtk_get_debug_flags:
786  *
787  * Returns the GTK+ debug flags.
788  *
789  * This function is intended for GTK+ modules that want
790  * to adjust their debug output based on GTK+ debug flags.
791  *
792  * Returns: the GTK+ debug flags.
793  */
794 guint
795 gtk_get_debug_flags (void)
796 {
797   return debug_flags;
798 }
799
800 /**
801  * gtk_set_debug_flags:
802  *
803  * Sets the GTK+ debug flags.
804  */
805 void
806 gtk_set_debug_flags (guint flags)
807 {
808   debug_flags = flags;
809 }
810
811 /**
812  * gtk_get_option_group: (skip)
813  * @open_default_display: whether to open the default display
814  *     when parsing the commandline arguments
815  *
816  * Returns a #GOptionGroup for the commandline arguments recognized
817  * by GTK+ and GDK.
818  *
819  * You should add this group to your #GOptionContext
820  * with g_option_context_add_group(), if you are using
821  * g_option_context_parse() to parse your commandline arguments.
822  *
823  * Returns: a #GOptionGroup for the commandline arguments recognized
824  *     by GTK+
825  *
826  * Since: 2.6
827  */
828 GOptionGroup *
829 gtk_get_option_group (gboolean open_default_display)
830 {
831   GOptionGroup *group;
832   OptionGroupInfo *info;
833
834   gettext_initialization ();
835
836   info = g_new0 (OptionGroupInfo, 1);
837   info->open_default_display = open_default_display;
838   
839   group = g_option_group_new ("gtk", _("GTK+ Options"), _("Show GTK+ Options"), info, g_free);
840   g_option_group_set_parse_hooks (group, pre_parse_hook, post_parse_hook);
841
842   gdk_add_option_entries_libgtk_only (group);
843   g_option_group_add_entries (group, gtk_args);
844   g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
845   
846   return group;
847 }
848
849 /**
850  * gtk_init_with_args:
851  * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
852  *     your main() function (or 0 if @argv is %NULL). This will be changed if 
853  *     any arguments were handled.
854  * @argv: (array length=argc) (inout) (allow-none): Address of the
855  *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
856  *     understood by GTK+ are stripped before return.
857  * @parameter_string: a string which is displayed in
858  *    the first line of <option>--help</option> output, after
859  *    <literal><replaceable>programname</replaceable> [OPTION...]</literal>
860  * @entries: (array zero-terminated=1): a %NULL-terminated array
861  *    of #GOptionEntrys describing the options of your program
862  * @translation_domain: a translation domain to use for translating
863  *    the <option>--help</option> output for the options in @entries
864  *    and the @parameter_string with gettext(), or %NULL
865  * @error: a return location for errors
866  *
867  * This function does the same work as gtk_init_check().
868  * Additionally, it allows you to add your own commandline options,
869  * and it automatically generates nicely formatted
870  * <option>--help</option> output. Note that your program will
871  * be terminated after writing out the help output.
872  *
873  * Returns: %TRUE if the windowing system has been successfully
874  *     initialized, %FALSE otherwise
875  *
876  * Since: 2.6
877  */
878 gboolean
879 gtk_init_with_args (gint                 *argc,
880                     gchar              ***argv,
881                     const gchar          *parameter_string,
882                     const GOptionEntry   *entries,
883                     const gchar          *translation_domain,
884                     GError              **error)
885 {
886   GOptionContext *context;
887   GOptionGroup *gtk_group;
888   gboolean retval;
889
890   if (gtk_initialized)
891     return gdk_display_open_default_libgtk_only () != NULL;
892
893   gettext_initialization ();
894
895   if (!check_setugid ())
896     return FALSE;
897
898   gtk_group = gtk_get_option_group (TRUE);
899
900   context = g_option_context_new (parameter_string);
901   g_option_context_add_group (context, gtk_group);
902   g_option_context_set_translation_domain (context, translation_domain);
903
904   if (entries)
905     g_option_context_add_main_entries (context, entries, translation_domain);
906   retval = g_option_context_parse (context, argc, argv, error);
907
908   g_option_context_free (context);
909
910   return retval;
911 }
912
913
914 /**
915  * gtk_parse_args:
916  * @argc: (inout): a pointer to the number of command line arguments
917  * @argv: (array length=argc) (inout): a pointer to the array of
918  *     command line arguments
919  *
920  * Parses command line arguments, and initializes global
921  * attributes of GTK+, but does not actually open a connection
922  * to a display. (See gdk_display_open(), gdk_get_display_arg_name())
923  *
924  * Any arguments used by GTK+ or GDK are removed from the array and
925  * @argc and @argv are updated accordingly.
926  *
927  * There is no need to call this function explicitely if you are using
928  * gtk_init(), or gtk_init_check().
929  *
930  * Return value: %TRUE if initialization succeeded, otherwise %FALSE
931  */
932 gboolean
933 gtk_parse_args (int    *argc,
934                 char ***argv)
935 {
936   GOptionContext *option_context;
937   GOptionGroup *gtk_group;
938   GError *error = NULL;
939   
940   if (gtk_initialized)
941     return TRUE;
942
943   gettext_initialization ();
944
945   if (!check_setugid ())
946     return FALSE;
947
948   option_context = g_option_context_new (NULL);
949   g_option_context_set_ignore_unknown_options (option_context, TRUE);
950   g_option_context_set_help_enabled (option_context, FALSE);
951   gtk_group = gtk_get_option_group (FALSE);
952   g_option_context_set_main_group (option_context, gtk_group);
953   if (!g_option_context_parse (option_context, argc, argv, &error))
954     {
955       g_warning ("%s", error->message);
956       g_error_free (error);
957     }
958
959   g_option_context_free (option_context);
960
961   return TRUE;
962 }
963
964 #ifdef G_PLATFORM_WIN32
965 #undef gtk_init_check
966 #endif
967
968 /**
969  * gtk_init_check:
970  * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
971  *     your main() function (or 0 if @argv is %NULL). This will be changed if 
972  *     any arguments were handled.
973  * @argv: (array length=argc) (inout) (allow-none): Address of the
974  *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
975  *     understood by GTK+ are stripped before return.
976  *
977  * This function does the same work as gtk_init() with only a single
978  * change: It does not terminate the program if the windowing system
979  * can't be initialized. Instead it returns %FALSE on failure.
980  *
981  * This way the application can fall back to some other means of
982  * communication with the user - for example a curses or command line
983  * interface.
984  *
985  * Return value: %TRUE if the windowing system has been successfully
986  *     initialized, %FALSE otherwise
987  */
988 gboolean
989 gtk_init_check (int    *argc,
990                 char ***argv)
991 {
992   if (!gtk_parse_args (argc, argv))
993     return FALSE;
994
995   return gdk_display_open_default_libgtk_only () != NULL;
996 }
997
998 #ifdef G_PLATFORM_WIN32
999 #undef gtk_init
1000 #endif
1001
1002 /**
1003  * gtk_init:
1004  * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
1005  *     your main() function (or 0 if @argv is %NULL). This will be changed if 
1006  *     any arguments were handled.
1007  * @argv: (array length=argc) (inout) (allow-none): Address of the
1008  *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
1009  *     understood by GTK+ are stripped before return.
1010  *
1011  * Call this function before using any other GTK+ functions in your GUI
1012  * applications.  It will initialize everything needed to operate the
1013  * toolkit and parses some standard command line options.
1014  *
1015  * Although you are expected to pass the @argc, @argv parameters from main() to 
1016  * this function, it is possible to pass %NULL if @argv is not available or 
1017  * commandline handling is not required.
1018  *
1019  * @argc and @argv are adjusted accordingly so your own code will
1020  * never see those standard arguments.
1021  *
1022  * Note that there are some alternative ways to initialize GTK+:
1023  * if you are calling gtk_parse_args(), gtk_init_check(),
1024  * gtk_init_with_args() or g_option_context_parse() with
1025  * the option group returned by gtk_get_option_group(),
1026  * you <emphasis>don't</emphasis> have to call gtk_init().
1027  *
1028  * <note><para>
1029  * This function will terminate your program if it was unable to
1030  * initialize the windowing system for some reason. If you want
1031  * your program to fall back to a textual interface you want to
1032  * call gtk_init_check() instead.
1033  * </para></note>
1034  *
1035  * <note><para>
1036  * Since 2.18, GTK+ calls <literal>signal (SIGPIPE, SIG_IGN)</literal>
1037  * during initialization, to ignore SIGPIPE signals, since these are
1038  * almost never wanted in graphical applications. If you do need to
1039  * handle SIGPIPE for some reason, reset the handler after gtk_init(),
1040  * but notice that other libraries (e.g. libdbus or gvfs) might do
1041  * similar things.
1042  * </para></note>
1043  */
1044 void
1045 gtk_init (int *argc, char ***argv)
1046 {
1047   if (!gtk_init_check (argc, argv))
1048     {
1049       const char *display_name_arg = gdk_get_display_arg_name ();
1050       if (display_name_arg == NULL)
1051         display_name_arg = getenv("DISPLAY");
1052       g_warning ("cannot open display: %s", display_name_arg ? display_name_arg : "");
1053       exit (1);
1054     }
1055 }
1056
1057 #ifdef G_OS_WIN32
1058
1059 /* This is relevant when building with gcc for Windows (MinGW),
1060  * where we want to be struct packing compatible with MSVC,
1061  * i.e. use the -mms-bitfields switch.
1062  * For Cygwin there should be no need to be compatible with MSVC,
1063  * so no need to use G_PLATFORM_WIN32.
1064  */
1065
1066 static void
1067 check_sizeof_GtkWindow (size_t sizeof_GtkWindow)
1068 {
1069   if (sizeof_GtkWindow != sizeof (GtkWindow))
1070     g_error ("Incompatible build!\n"
1071              "The code using GTK+ thinks GtkWindow is of different\n"
1072              "size than it actually is in this build of GTK+.\n"
1073              "On Windows, this probably means that you have compiled\n"
1074              "your code with gcc without the -mms-bitfields switch,\n"
1075              "or that you are using an unsupported compiler.");
1076 }
1077
1078 /* In GTK+ 2.0 the GtkWindow struct actually is the same size in
1079  * gcc-compiled code on Win32 whether compiled with -fnative-struct or
1080  * not. Unfortunately this wan't noticed until after GTK+ 2.0.1. So,
1081  * from GTK+ 2.0.2 on, check some other struct, too, where the use of
1082  * -fnative-struct still matters. GtkBox is one such.
1083  */
1084 static void
1085 check_sizeof_GtkBox (size_t sizeof_GtkBox)
1086 {
1087   if (sizeof_GtkBox != sizeof (GtkBox))
1088     g_error ("Incompatible build!\n"
1089              "The code using GTK+ thinks GtkBox is of different\n"
1090              "size than it actually is in this build of GTK+.\n"
1091              "On Windows, this probably means that you have compiled\n"
1092              "your code with gcc without the -mms-bitfields switch,\n"
1093              "or that you are using an unsupported compiler.");
1094 }
1095
1096 /* These two functions might get more checks added later, thus pass
1097  * in the number of extra args.
1098  */
1099 void
1100 gtk_init_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
1101 {
1102   check_sizeof_GtkWindow (sizeof_GtkWindow);
1103   if (num_checks >= 2)
1104     check_sizeof_GtkBox (sizeof_GtkBox);
1105   gtk_init (argc, argv);
1106 }
1107
1108 gboolean
1109 gtk_init_check_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
1110 {
1111   check_sizeof_GtkWindow (sizeof_GtkWindow);
1112   if (num_checks >= 2)
1113     check_sizeof_GtkBox (sizeof_GtkBox);
1114   return gtk_init_check (argc, argv);
1115 }
1116
1117 #endif
1118
1119 /**
1120  * gtk_get_default_language:
1121  *
1122  * Returns the #PangoLanguage for the default language currently in
1123  * effect. (Note that this can change over the life of an
1124  * application.) The default language is derived from the current
1125  * locale. It determines, for example, whether GTK+ uses the
1126  * right-to-left or left-to-right text direction.
1127  *
1128  * This function is equivalent to pango_language_get_default().
1129  * See that function for details.
1130  *
1131  * Return value: the default language as a #PangoLanguage,
1132  *     must not be freed
1133  */
1134 PangoLanguage *
1135 gtk_get_default_language (void)
1136 {
1137   return pango_language_get_default ();
1138 }
1139
1140 /**
1141  * gtk_main:
1142  *
1143  * Runs the main loop until gtk_main_quit() is called.
1144  *
1145  * You can nest calls to gtk_main(). In that case gtk_main_quit()
1146  * will make the innermost invocation of the main loop return.
1147  */
1148 void
1149 gtk_main (void)
1150 {
1151   GMainLoop *loop;
1152
1153   gtk_main_loop_level++;
1154
1155   loop = g_main_loop_new (NULL, TRUE);
1156   main_loops = g_slist_prepend (main_loops, loop);
1157
1158   if (g_main_loop_is_running (main_loops->data))
1159     {
1160       GDK_THREADS_LEAVE ();
1161       g_main_loop_run (loop);
1162       GDK_THREADS_ENTER ();
1163       gdk_flush ();
1164     }
1165
1166   main_loops = g_slist_remove (main_loops, loop);
1167
1168   g_main_loop_unref (loop);
1169
1170   gtk_main_loop_level--;
1171
1172   if (gtk_main_loop_level == 0)
1173     {
1174       /* Try storing all clipboard data we have */
1175       _gtk_clipboard_store_all ();
1176
1177       /* Synchronize the recent manager singleton */
1178       _gtk_recent_manager_sync ();
1179     }
1180 }
1181
1182 /**
1183  * gtk_main_level:
1184  *
1185  * Asks for the current nesting level of the main loop.
1186  *
1187  * Returns: the nesting level of the current invocation
1188  *     of the main loop
1189  */
1190 guint
1191 gtk_main_level (void)
1192 {
1193   return gtk_main_loop_level;
1194 }
1195
1196 /**
1197  * gtk_main_quit:
1198  *
1199  * Makes the innermost invocation of the main loop return
1200  * when it regains control.
1201  */
1202 void
1203 gtk_main_quit (void)
1204 {
1205   g_return_if_fail (main_loops != NULL);
1206
1207   g_main_loop_quit (main_loops->data);
1208 }
1209
1210 /**
1211  * gtk_events_pending:
1212  *
1213  * Checks if any events are pending.
1214  *
1215  * This can be used to update the UI and invoke timeouts etc.
1216  * while doing some time intensive computation.
1217  *
1218  * <example>
1219  * <title>Updating the UI during a long computation</title>
1220  * <programlisting>
1221  *  /&ast; computation going on... &ast;/
1222  *
1223  *  while (gtk_events_pending ())
1224  *    gtk_main_iteration ();
1225  *
1226  *  /&ast; ...computation continued &ast;/
1227  * </programlisting>
1228  * </example>
1229  *
1230  * Returns: %TRUE if any events are pending, %FALSE otherwise
1231  */
1232 gboolean
1233 gtk_events_pending (void)
1234 {
1235   gboolean result;
1236
1237   GDK_THREADS_LEAVE ();
1238   result = g_main_context_pending (NULL);
1239   GDK_THREADS_ENTER ();
1240
1241   return result;
1242 }
1243
1244 /**
1245  * gtk_main_iteration:
1246  *
1247  * Runs a single iteration of the mainloop.
1248  *
1249  * If no events are waiting to be processed GTK+ will block
1250  * until the next event is noticed. If you don't want to block
1251  * look at gtk_main_iteration_do() or check if any events are
1252  * pending with gtk_events_pending() first.
1253  *
1254  * Returns: %TRUE if gtk_main_quit() has been called for the
1255  *     innermost mainloop
1256  */
1257 gboolean
1258 gtk_main_iteration (void)
1259 {
1260   GDK_THREADS_LEAVE ();
1261   g_main_context_iteration (NULL, TRUE);
1262   GDK_THREADS_ENTER ();
1263
1264   if (main_loops)
1265     return !g_main_loop_is_running (main_loops->data);
1266   else
1267     return TRUE;
1268 }
1269
1270 /**
1271  * gtk_main_iteration_do:
1272  * @blocking: %TRUE if you want GTK+ to block if no events are pending
1273  *
1274  * Runs a single iteration of the mainloop.
1275  * If no events are available either return or block depending on
1276  * the value of @blocking.
1277  *
1278  * Returns: %TRUE if gtk_main_quit() has been called for the
1279  *     innermost mainloop
1280  */
1281 gboolean
1282 gtk_main_iteration_do (gboolean blocking)
1283 {
1284   GDK_THREADS_LEAVE ();
1285   g_main_context_iteration (NULL, blocking);
1286   GDK_THREADS_ENTER ();
1287
1288   if (main_loops)
1289     return !g_main_loop_is_running (main_loops->data);
1290   else
1291     return TRUE;
1292 }
1293
1294 /* private libgtk to libgdk interfaces */
1295 gboolean gdk_device_grab_info_libgtk_only (GdkDisplay  *display,
1296                                            GdkDevice   *device,
1297                                            GdkWindow  **grab_window,
1298                                            gboolean    *owner_events);
1299
1300 static void
1301 rewrite_events_translate (GdkWindow *old_window,
1302                           GdkWindow *new_window,
1303                           gdouble   *x,
1304                           gdouble   *y)
1305 {
1306   gint old_origin_x, old_origin_y;
1307   gint new_origin_x, new_origin_y;
1308
1309   gdk_window_get_origin (old_window, &old_origin_x, &old_origin_y);
1310   gdk_window_get_origin (new_window, &new_origin_x, &new_origin_y);
1311
1312   *x += old_origin_x - new_origin_x;
1313   *y += old_origin_y - new_origin_y;
1314 }
1315
1316 static GdkEvent *
1317 rewrite_event_for_window (GdkEvent  *event,
1318                           GdkWindow *new_window)
1319 {
1320   event = gdk_event_copy (event);
1321
1322   switch (event->type)
1323     {
1324     case GDK_SCROLL:
1325       rewrite_events_translate (event->any.window,
1326                                 new_window,
1327                                 &event->scroll.x, &event->scroll.y);
1328       break;
1329     case GDK_BUTTON_PRESS:
1330     case GDK_2BUTTON_PRESS:
1331     case GDK_3BUTTON_PRESS:
1332     case GDK_BUTTON_RELEASE:
1333       rewrite_events_translate (event->any.window,
1334                                 new_window,
1335                                 &event->button.x, &event->button.y);
1336       break;
1337     case GDK_MOTION_NOTIFY:
1338       rewrite_events_translate (event->any.window,
1339                                 new_window,
1340                                 &event->motion.x, &event->motion.y);
1341       break;
1342     case GDK_TOUCH_BEGIN:
1343     case GDK_TOUCH_UPDATE:
1344     case GDK_TOUCH_END:
1345     case GDK_TOUCH_CANCEL:
1346       rewrite_events_translate (event->any.window,
1347                                 new_window,
1348                                 &event->touch.x, &event->touch.y);
1349       break;
1350     case GDK_KEY_PRESS:
1351     case GDK_KEY_RELEASE:
1352     case GDK_PROXIMITY_IN:
1353     case GDK_PROXIMITY_OUT:
1354       break;
1355
1356     default:
1357       return event;
1358     }
1359
1360   g_object_unref (event->any.window);
1361   event->any.window = g_object_ref (new_window);
1362
1363   return event;
1364 }
1365
1366 /* If there is a pointer or keyboard grab in effect with owner_events = TRUE,
1367  * then what X11 does is deliver the event normally if it was going to this
1368  * client, otherwise, delivers it in terms of the grab window. This function
1369  * rewrites events to the effect that events going to the same window group
1370  * are delivered normally, otherwise, the event is delivered in terms of the
1371  * grab window.
1372  */
1373 static GdkEvent *
1374 rewrite_event_for_grabs (GdkEvent *event)
1375 {
1376   GdkWindow *grab_window;
1377   GtkWidget *event_widget, *grab_widget;
1378   gpointer grab_widget_ptr;
1379   gboolean owner_events;
1380   GdkDisplay *display;
1381   GdkDevice *device;
1382
1383   switch (event->type)
1384     {
1385     case GDK_SCROLL:
1386     case GDK_BUTTON_PRESS:
1387     case GDK_2BUTTON_PRESS:
1388     case GDK_3BUTTON_PRESS:
1389     case GDK_BUTTON_RELEASE:
1390     case GDK_MOTION_NOTIFY:
1391     case GDK_PROXIMITY_IN:
1392     case GDK_PROXIMITY_OUT:
1393     case GDK_KEY_PRESS:
1394     case GDK_KEY_RELEASE:
1395     case GDK_TOUCH_BEGIN:
1396     case GDK_TOUCH_UPDATE:
1397     case GDK_TOUCH_END:
1398     case GDK_TOUCH_CANCEL:
1399       display = gdk_window_get_display (event->any.window);
1400       device = gdk_event_get_device (event);
1401
1402       if (!gdk_device_grab_info_libgtk_only (display, device, &grab_window, &owner_events) ||
1403           !owner_events)
1404         return NULL;
1405       break;
1406     default:
1407       return NULL;
1408     }
1409
1410   event_widget = gtk_get_event_widget (event);
1411   gdk_window_get_user_data (grab_window, &grab_widget_ptr);
1412   grab_widget = grab_widget_ptr;
1413
1414   if (grab_widget &&
1415       gtk_main_get_window_group (grab_widget) != gtk_main_get_window_group (event_widget))
1416     return rewrite_event_for_window (event, grab_window);
1417   else
1418     return NULL;
1419 }
1420
1421 /**
1422  * gtk_main_do_event:
1423  * @event: An event to process (normally passed by GDK)
1424  *
1425  * Processes a single GDK event.
1426  *
1427  * This is public only to allow filtering of events between GDK and GTK+.
1428  * You will not usually need to call this function directly.
1429  *
1430  * While you should not call this function directly, you might want to
1431  * know how exactly events are handled. So here is what this function
1432  * does with the event:
1433  *
1434  * <orderedlist>
1435  * <listitem><para>
1436  *   Compress enter/leave notify events. If the event passed build an
1437  *   enter/leave pair together with the next event (peeked from GDK), both
1438  *   events are thrown away. This is to avoid a backlog of (de-)highlighting
1439  *   widgets crossed by the pointer.
1440  * </para></listitem>
1441  * <listitem><para>
1442  *   Find the widget which got the event. If the widget can't be determined
1443  *   the event is thrown away unless it belongs to a INCR transaction. In that
1444  *   case it is passed to gtk_selection_incr_event().
1445  * </para></listitem>
1446  * <listitem><para>
1447  *   Then the event is pushed onto a stack so you can query the currently
1448  *   handled event with gtk_get_current_event().
1449  * </para></listitem>
1450  * <listitem><para>
1451  *   The event is sent to a widget. If a grab is active all events for widgets
1452  *   that are not in the contained in the grab widget are sent to the latter
1453  *   with a few exceptions:
1454  *   <itemizedlist>
1455  *   <listitem><para>
1456  *     Deletion and destruction events are still sent to the event widget for
1457  *     obvious reasons.
1458  *   </para></listitem>
1459  *   <listitem><para>
1460  *     Events which directly relate to the visual representation of the event
1461  *     widget.
1462  *   </para></listitem>
1463  *   <listitem><para>
1464  *     Leave events are delivered to the event widget if there was an enter
1465  *     event delivered to it before without the paired leave event.
1466  *   </para></listitem>
1467  *   <listitem><para>
1468  *     Drag events are not redirected because it is unclear what the semantics
1469  *     of that would be.
1470  *   </para></listitem>
1471  *   </itemizedlist>
1472  *   Another point of interest might be that all key events are first passed
1473  *   through the key snooper functions if there are any. Read the description
1474  *   of gtk_key_snooper_install() if you need this feature.
1475  * </para></listitem>
1476  * <listitem><para>
1477  *   After finishing the delivery the event is popped from the event stack.
1478  * </para></listitem>
1479  * </orderedlist>
1480  */
1481 void
1482 gtk_main_do_event (GdkEvent *event)
1483 {
1484   GtkWidget *event_widget;
1485   GtkWidget *grab_widget = NULL;
1486   GtkWidget *topmost_widget = NULL;
1487   GtkWindowGroup *window_group;
1488   GdkEvent *rewritten_event = NULL;
1489   GdkDevice *device;
1490   GList *tmp_list;
1491
1492   if (event->type == GDK_SETTING)
1493     {
1494       _gtk_settings_handle_event (&event->setting);
1495       return;
1496     }
1497
1498   if (event->type == GDK_OWNER_CHANGE)
1499     {
1500       _gtk_clipboard_handle_event (&event->owner_change);
1501       return;
1502     }
1503
1504   /* Find the widget which got the event. We store the widget
1505    * in the user_data field of GdkWindow's. Ignore the event
1506    * if we don't have a widget for it, except for GDK_PROPERTY_NOTIFY
1507    * events which are handled specially. Though this happens rarely,
1508    * bogus events can occur for e.g. destroyed GdkWindows.
1509    */
1510   event_widget = gtk_get_event_widget (event);
1511   if (!event_widget)
1512     {
1513       /* To handle selection INCR transactions, we select
1514        * PropertyNotify events on the requestor window and create
1515        * a corresponding (fake) GdkWindow so that events get here.
1516        * There won't be a widget though, so we have to handle
1517        * them specially
1518        */
1519       if (event->type == GDK_PROPERTY_NOTIFY)
1520         _gtk_selection_incr_event (event->any.window,
1521                                    &event->property);
1522
1523       return;
1524     }
1525
1526   /* If pointer or keyboard grabs are in effect, munge the events
1527    * so that each window group looks like a separate app.
1528    */
1529   rewritten_event = rewrite_event_for_grabs (event);
1530   if (rewritten_event)
1531     {
1532       event = rewritten_event;
1533       event_widget = gtk_get_event_widget (event);
1534     }
1535
1536   window_group = gtk_main_get_window_group (event_widget);
1537   device = gdk_event_get_device (event);
1538
1539   /* check whether there is a (device) grab in effect... */
1540   if (device)
1541     grab_widget = gtk_window_group_get_current_device_grab (window_group, device);
1542
1543   if (!grab_widget)
1544     grab_widget = gtk_window_group_get_current_grab (window_group);
1545
1546   /* Find out the topmost widget where captured event propagation
1547    * should start, which is the widget holding the GTK+ grab
1548    * if any, otherwise it's left NULL and events are emitted
1549    * from the toplevel (or topmost parentless parent).
1550    */
1551   if (grab_widget)
1552     topmost_widget = grab_widget;
1553
1554   /* If the grab widget is an ancestor of the event widget
1555    * then we send the event to the original event widget.
1556    * This is the key to implementing modality.
1557    */
1558   if (!grab_widget ||
1559       (gtk_widget_is_sensitive (event_widget) &&
1560        gtk_widget_is_ancestor (event_widget, grab_widget)))
1561     grab_widget = event_widget;
1562
1563   /* If the widget receiving events is actually blocked by another
1564    * device GTK+ grab
1565    */
1566   if (device &&
1567       _gtk_window_group_widget_is_blocked_for_device (window_group, grab_widget, device))
1568     {
1569       if (rewritten_event)
1570         gdk_event_free (rewritten_event);
1571
1572       return;
1573     }
1574
1575   /* Push the event onto a stack of current events for
1576    * gtk_current_event_get().
1577    */
1578   current_events = g_list_prepend (current_events, event);
1579
1580   /* Not all events get sent to the grabbing widget.
1581    * The delete, destroy, expose, focus change and resize
1582    * events still get sent to the event widget because
1583    * 1) these events have no meaning for the grabbing widget
1584    * and 2) redirecting these events to the grabbing widget
1585    * could cause the display to be messed up.
1586    *
1587    * Drag events are also not redirected, since it isn't
1588    * clear what the semantics of that would be.
1589    */
1590   switch (event->type)
1591     {
1592     case GDK_NOTHING:
1593       break;
1594
1595     case GDK_DELETE:
1596       g_object_ref (event_widget);
1597       if ((!gtk_window_group_get_current_grab (window_group) || gtk_widget_get_toplevel (gtk_window_group_get_current_grab (window_group)) == event_widget) &&
1598           !gtk_widget_event (event_widget, event))
1599         gtk_widget_destroy (event_widget);
1600       g_object_unref (event_widget);
1601       break;
1602
1603     case GDK_DESTROY:
1604       /* Unexpected GDK_DESTROY from the outside, ignore for
1605        * child windows, handle like a GDK_DELETE for toplevels
1606        */
1607       if (!gtk_widget_get_parent (event_widget))
1608         {
1609           g_object_ref (event_widget);
1610           if (!gtk_widget_event (event_widget, event) &&
1611               gtk_widget_get_realized (event_widget))
1612             gtk_widget_destroy (event_widget);
1613           g_object_unref (event_widget);
1614         }
1615       break;
1616
1617     case GDK_EXPOSE:
1618       if (event->any.window && gtk_widget_get_double_buffered (event_widget))
1619         {
1620           gdk_window_begin_paint_region (event->any.window, event->expose.region);
1621           gtk_widget_send_expose (event_widget, event);
1622           gdk_window_end_paint (event->any.window);
1623         }
1624       else
1625         {
1626           /* The app may paint with a previously allocated cairo_t,
1627            * which will draw directly to the window. We can't catch cairo
1628            * draw operations to automatically flush the window, thus we
1629            * need to explicitly flush any outstanding moves or double
1630            * buffering
1631            */
1632           gdk_window_flush (event->any.window);
1633           gtk_widget_send_expose (event_widget, event);
1634         }
1635       break;
1636
1637     case GDK_PROPERTY_NOTIFY:
1638     case GDK_FOCUS_CHANGE:
1639     case GDK_CONFIGURE:
1640     case GDK_MAP:
1641     case GDK_UNMAP:
1642     case GDK_SELECTION_CLEAR:
1643     case GDK_SELECTION_REQUEST:
1644     case GDK_SELECTION_NOTIFY:
1645     case GDK_CLIENT_EVENT:
1646     case GDK_VISIBILITY_NOTIFY:
1647     case GDK_WINDOW_STATE:
1648     case GDK_GRAB_BROKEN:
1649     case GDK_DAMAGE:
1650       if (!_gtk_widget_captured_event (event_widget, event))
1651         gtk_widget_event (event_widget, event);
1652       break;
1653
1654     case GDK_SCROLL:
1655     case GDK_BUTTON_PRESS:
1656     case GDK_2BUTTON_PRESS:
1657     case GDK_3BUTTON_PRESS:
1658     case GDK_TOUCH_BEGIN:
1659       if (!_gtk_propagate_captured_event (grab_widget, event, topmost_widget))
1660         gtk_propagate_event (grab_widget, event);
1661       break;
1662
1663     case GDK_KEY_PRESS:
1664     case GDK_KEY_RELEASE:
1665       if (gtk_invoke_key_snoopers (grab_widget, event))
1666         break;
1667
1668       /* make focus visible in a window that receives a key event */
1669       {
1670         GtkWidget *window;
1671         GtkPolicyType visible_focus;
1672
1673         window = gtk_widget_get_toplevel (grab_widget);
1674         g_object_get (gtk_widget_get_settings (grab_widget), "gtk-visible-focus", &visible_focus, NULL);
1675         if (GTK_IS_WINDOW (window) && visible_focus != GTK_POLICY_NEVER)
1676           gtk_window_set_focus_visible (GTK_WINDOW (window), TRUE);
1677       }
1678
1679       /* Catch alt press to enable auto-mnemonics;
1680        * menus are handled elsewhere
1681        * FIXME: this does not work with mnemonic modifiers other than Alt
1682        */
1683       if ((event->key.keyval == GDK_KEY_Alt_L || event->key.keyval == GDK_KEY_Alt_R) &&
1684           ((event->key.state & (gtk_accelerator_get_default_mod_mask ()) & ~(GDK_RELEASE_MASK|GDK_MOD1_MASK)) == 0) &&
1685           !GTK_IS_MENU_SHELL (grab_widget))
1686         {
1687           gboolean auto_mnemonics;
1688
1689           g_object_get (gtk_widget_get_settings (grab_widget),
1690                         "gtk-auto-mnemonics", &auto_mnemonics, NULL);
1691
1692           if (auto_mnemonics)
1693             {
1694               gboolean mnemonics_visible;
1695               GtkWidget *window;
1696
1697               mnemonics_visible = (event->type == GDK_KEY_PRESS);
1698
1699               window = gtk_widget_get_toplevel (grab_widget);
1700               if (GTK_IS_WINDOW (window))
1701                 gtk_window_set_mnemonics_visible (GTK_WINDOW (window), mnemonics_visible);
1702             }
1703         }
1704       /* else fall through */
1705     case GDK_MOTION_NOTIFY:
1706     case GDK_BUTTON_RELEASE:
1707     case GDK_PROXIMITY_IN:
1708     case GDK_PROXIMITY_OUT:
1709     case GDK_TOUCH_UPDATE:
1710     case GDK_TOUCH_END:
1711     case GDK_TOUCH_CANCEL:
1712       if (!_gtk_propagate_captured_event (grab_widget, event, topmost_widget))
1713         gtk_propagate_event (grab_widget, event);
1714       break;
1715
1716     case GDK_ENTER_NOTIFY:
1717       if (event->crossing.detail != GDK_NOTIFY_VIRTUAL &&
1718           event->crossing.detail != GDK_NOTIFY_NONLINEAR_VIRTUAL)
1719         _gtk_widget_set_device_window (event_widget,
1720                                        gdk_event_get_device (event),
1721                                        event->any.window);
1722       if (gtk_widget_is_sensitive (grab_widget) &&
1723           !_gtk_propagate_captured_event (grab_widget, event, topmost_widget))
1724         gtk_widget_event (grab_widget, event);
1725       break;
1726
1727     case GDK_LEAVE_NOTIFY:
1728       if (event->crossing.detail != GDK_NOTIFY_VIRTUAL &&
1729           event->crossing.detail != GDK_NOTIFY_NONLINEAR_VIRTUAL)
1730         _gtk_widget_set_device_window (event_widget,
1731                                        gdk_event_get_device (event),
1732                                        NULL);
1733       if (gtk_widget_is_sensitive (grab_widget) &&
1734           !_gtk_propagate_captured_event (grab_widget, event, topmost_widget))
1735         gtk_widget_event (grab_widget, event);
1736       break;
1737
1738     case GDK_DRAG_STATUS:
1739     case GDK_DROP_FINISHED:
1740       _gtk_drag_source_handle_event (event_widget, event);
1741       break;
1742     case GDK_DRAG_ENTER:
1743     case GDK_DRAG_LEAVE:
1744     case GDK_DRAG_MOTION:
1745     case GDK_DROP_START:
1746       _gtk_drag_dest_handle_event (event_widget, event);
1747       break;
1748     default:
1749       g_assert_not_reached ();
1750       break;
1751     }
1752
1753   if (event->type == GDK_ENTER_NOTIFY
1754       || event->type == GDK_LEAVE_NOTIFY
1755       || event->type == GDK_BUTTON_PRESS
1756       || event->type == GDK_2BUTTON_PRESS
1757       || event->type == GDK_3BUTTON_PRESS
1758       || event->type == GDK_KEY_PRESS
1759       || event->type == GDK_DRAG_ENTER
1760       || event->type == GDK_GRAB_BROKEN
1761       || event->type == GDK_MOTION_NOTIFY
1762       || event->type == GDK_TOUCH_UPDATE
1763       || event->type == GDK_SCROLL)
1764     {
1765       _gtk_tooltip_handle_event (event);
1766     }
1767
1768   tmp_list = current_events;
1769   current_events = g_list_remove_link (current_events, tmp_list);
1770   g_list_free_1 (tmp_list);
1771
1772   if (rewritten_event)
1773     gdk_event_free (rewritten_event);
1774 }
1775
1776 /**
1777  * gtk_true:
1778  *
1779  * All this function does it to return %TRUE.
1780  *
1781  * This can be useful for example if you want to inhibit the deletion
1782  * of a window. Of course you should not do this as the user expects
1783  * a reaction from clicking the close icon of the window...
1784  *
1785  * <example>
1786  * <title>A persistent window</title>
1787  * <programlisting>
1788  * #include &lt;gtk/gtk.h>&lt;
1789  *
1790  * int
1791  * main (int argc, char **argv)
1792  * {
1793  *   GtkWidget *win, *but;
1794  *
1795  *   gtk_init (&amp;argc, &amp;argv);
1796  *
1797  *   win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1798  *   g_signal_connect (win, "delete-event",
1799  *                     G_CALLBACK (gtk_true), NULL);
1800  *   g_signal_connect (win, "destroy",
1801  *                     G_CALLBACK (gtk_main_quit), NULL);
1802  *
1803  *   but = gtk_button_new_with_label ("Close yourself. I mean it!");
1804  *   g_signal_connect_swapped (but, "clicked",
1805  *                             G_CALLBACK (gtk_object_destroy), win);
1806  *   gtk_container_add (GTK_CONTAINER (win), but);
1807  *
1808  *   gtk_widget_show_all (win);
1809  *
1810  *   gtk_main ();
1811  *
1812  *   return 0;
1813  * }
1814  * </programlisting>
1815  * </example>
1816  *
1817  * Returns: %TRUE
1818  */
1819 gboolean
1820 gtk_true (void)
1821 {
1822   return TRUE;
1823 }
1824
1825 /**
1826  * gtk_false:
1827  *
1828  * Analogical to gtk_true(), this function does nothing
1829  * but always returns %FALSE.
1830  *
1831  * Returns: %FALSE
1832  */
1833 gboolean
1834 gtk_false (void)
1835 {
1836   return FALSE;
1837 }
1838
1839 static GtkWindowGroup *
1840 gtk_main_get_window_group (GtkWidget *widget)
1841 {
1842   GtkWidget *toplevel = NULL;
1843
1844   if (widget)
1845     toplevel = gtk_widget_get_toplevel (widget);
1846
1847   if (GTK_IS_WINDOW (toplevel))
1848     return gtk_window_get_group (GTK_WINDOW (toplevel));
1849   else
1850     return gtk_window_get_group (NULL);
1851 }
1852
1853 typedef struct
1854 {
1855   GtkWidget *old_grab_widget;
1856   GtkWidget *new_grab_widget;
1857   gboolean   was_grabbed;
1858   gboolean   is_grabbed;
1859   gboolean   from_grab;
1860   GList     *notified_windows;
1861   GdkDevice *device;
1862 } GrabNotifyInfo;
1863
1864 static void
1865 synth_crossing_for_grab_notify (GtkWidget       *from,
1866                                 GtkWidget       *to,
1867                                 GrabNotifyInfo  *info,
1868                                 GList           *devices,
1869                                 GdkCrossingMode  mode)
1870 {
1871   while (devices)
1872     {
1873       GdkDevice *device = devices->data;
1874       GdkWindow *from_window, *to_window;
1875
1876       /* Do not propagate events more than once to
1877        * the same windows if non-multidevice aware.
1878        */
1879       if (!from)
1880         from_window = NULL;
1881       else
1882         {
1883           from_window = _gtk_widget_get_device_window (from, device);
1884
1885           if (from_window &&
1886               !gdk_window_get_support_multidevice (from_window) &&
1887               g_list_find (info->notified_windows, from_window))
1888             from_window = NULL;
1889         }
1890
1891       if (!to)
1892         to_window = NULL;
1893       else
1894         {
1895           to_window = _gtk_widget_get_device_window (to, device);
1896
1897           if (to_window &&
1898               !gdk_window_get_support_multidevice (to_window) &&
1899               g_list_find (info->notified_windows, to_window))
1900             to_window = NULL;
1901         }
1902
1903       if (from_window || to_window)
1904         {
1905           _gtk_widget_synthesize_crossing ((from_window) ? from : NULL,
1906                                            (to_window) ? to : NULL,
1907                                            device, mode);
1908
1909           if (from_window)
1910             info->notified_windows = g_list_prepend (info->notified_windows, from_window);
1911
1912           if (to_window)
1913             info->notified_windows = g_list_prepend (info->notified_windows, to_window);
1914         }
1915
1916       devices = devices->next;
1917     }
1918 }
1919
1920 static void
1921 gtk_grab_notify_foreach (GtkWidget *child,
1922                          gpointer   data)
1923 {
1924   GrabNotifyInfo *info = data;
1925   gboolean was_grabbed, is_grabbed, was_shadowed, is_shadowed;
1926   GList *devices;
1927
1928   was_grabbed = info->was_grabbed;
1929   is_grabbed = info->is_grabbed;
1930
1931   info->was_grabbed = info->was_grabbed || (child == info->old_grab_widget);
1932   info->is_grabbed = info->is_grabbed || (child == info->new_grab_widget);
1933
1934   was_shadowed = info->old_grab_widget && !info->was_grabbed;
1935   is_shadowed = info->new_grab_widget && !info->is_grabbed;
1936
1937   g_object_ref (child);
1938
1939   if ((was_shadowed || is_shadowed) && GTK_IS_CONTAINER (child))
1940     gtk_container_forall (GTK_CONTAINER (child), gtk_grab_notify_foreach, info);
1941
1942   if (info->device &&
1943       _gtk_widget_get_device_window (child, info->device))
1944     {
1945       /* Device specified and is on widget */
1946       devices = g_list_prepend (NULL, info->device);
1947     }
1948   else
1949     devices = _gtk_widget_list_devices (child);
1950
1951   if (is_shadowed)
1952     {
1953       _gtk_widget_set_shadowed (child, TRUE);
1954       if (!was_shadowed && devices &&
1955           gtk_widget_is_sensitive (child))
1956         synth_crossing_for_grab_notify (child, info->new_grab_widget,
1957                                         info, devices,
1958                                         GDK_CROSSING_GTK_GRAB);
1959     }
1960   else
1961     {
1962       _gtk_widget_set_shadowed (child, FALSE);
1963       if (was_shadowed && devices &&
1964           gtk_widget_is_sensitive (child))
1965         synth_crossing_for_grab_notify (info->old_grab_widget, child,
1966                                         info, devices,
1967                                         info->from_grab ? GDK_CROSSING_GTK_GRAB :
1968                                         GDK_CROSSING_GTK_UNGRAB);
1969     }
1970
1971   if (was_shadowed != is_shadowed)
1972     _gtk_widget_grab_notify (child, was_shadowed);
1973
1974   g_object_unref (child);
1975   g_list_free (devices);
1976
1977   info->was_grabbed = was_grabbed;
1978   info->is_grabbed = is_grabbed;
1979 }
1980
1981 static void
1982 gtk_grab_notify (GtkWindowGroup *group,
1983                  GdkDevice      *device,
1984                  GtkWidget      *old_grab_widget,
1985                  GtkWidget      *new_grab_widget,
1986                  gboolean        from_grab)
1987 {
1988   GList *toplevels;
1989   GrabNotifyInfo info = { 0 };
1990
1991   if (old_grab_widget == new_grab_widget)
1992     return;
1993
1994   info.old_grab_widget = old_grab_widget;
1995   info.new_grab_widget = new_grab_widget;
1996   info.from_grab = from_grab;
1997   info.device = device;
1998
1999   g_object_ref (group);
2000
2001   toplevels = gtk_window_list_toplevels ();
2002   g_list_foreach (toplevels, (GFunc)g_object_ref, NULL);
2003
2004   while (toplevels)
2005     {
2006       GtkWindow *toplevel = toplevels->data;
2007       toplevels = g_list_delete_link (toplevels, toplevels);
2008
2009       info.was_grabbed = FALSE;
2010       info.is_grabbed = FALSE;
2011
2012       if (group == gtk_window_get_group (toplevel))
2013         gtk_grab_notify_foreach (GTK_WIDGET (toplevel), &info);
2014       g_object_unref (toplevel);
2015     }
2016
2017   g_list_free (info.notified_windows);
2018   g_object_unref (group);
2019 }
2020
2021 /**
2022  * gtk_grab_add: (method)
2023  * @widget: The widget that grabs keyboard and pointer events
2024  *
2025  * Makes @widget the current grabbed widget.
2026  *
2027  * This means that interaction with other widgets in the same
2028  * application is blocked and mouse as well as keyboard events
2029  * are delivered to this widget.
2030  *
2031  * If @widget is not sensitive, it is not set as the current
2032  * grabbed widget and this function does nothing.
2033  */
2034 void
2035 gtk_grab_add (GtkWidget *widget)
2036 {
2037   GtkWindowGroup *group;
2038   GtkWidget *old_grab_widget;
2039
2040   g_return_if_fail (widget != NULL);
2041
2042   if (!gtk_widget_has_grab (widget) && gtk_widget_is_sensitive (widget))
2043     {
2044       _gtk_widget_set_has_grab (widget, TRUE);
2045
2046       group = gtk_main_get_window_group (widget);
2047
2048       old_grab_widget = gtk_window_group_get_current_grab (group);
2049
2050       g_object_ref (widget);
2051       _gtk_window_group_add_grab (group, widget);
2052
2053       gtk_grab_notify (group, NULL, old_grab_widget, widget, TRUE);
2054     }
2055 }
2056
2057 /**
2058  * gtk_grab_get_current:
2059  *
2060  * Queries the current grab of the default window group.
2061  *
2062  * Return value: (transfer none): The widget which currently
2063  *     has the grab or %NULL if no grab is active
2064  */
2065 GtkWidget*
2066 gtk_grab_get_current (void)
2067 {
2068   GtkWindowGroup *group;
2069
2070   group = gtk_main_get_window_group (NULL);
2071
2072   return gtk_window_group_get_current_grab (group);
2073 }
2074
2075 /**
2076  * gtk_grab_remove: (method)
2077  * @widget: The widget which gives up the grab
2078  *
2079  * Removes the grab from the given widget.
2080  *
2081  * You have to pair calls to gtk_grab_add() and gtk_grab_remove().
2082  *
2083  * If @widget does not have the grab, this function does nothing.
2084  */
2085 void
2086 gtk_grab_remove (GtkWidget *widget)
2087 {
2088   GtkWindowGroup *group;
2089   GtkWidget *new_grab_widget;
2090
2091   g_return_if_fail (widget != NULL);
2092
2093   if (gtk_widget_has_grab (widget))
2094     {
2095       _gtk_widget_set_has_grab (widget, FALSE);
2096
2097       group = gtk_main_get_window_group (widget);
2098       _gtk_window_group_remove_grab (group, widget);
2099       new_grab_widget = gtk_window_group_get_current_grab (group);
2100
2101       gtk_grab_notify (group, NULL, widget, new_grab_widget, FALSE);
2102
2103       g_object_unref (widget);
2104     }
2105 }
2106
2107 /**
2108  * gtk_device_grab_add:
2109  * @widget: a #GtkWidget
2110  * @device: a #GtkDevice to grab on.
2111  * @block_others: %TRUE to prevent other devices to interact with @widget.
2112  *
2113  * Adds a GTK+ grab on @device, so all the events on @device and its
2114  * associated pointer or keyboard (if any) are delivered to @widget.
2115  * If the @block_others parameter is %TRUE, any other devices will be
2116  * unable to interact with @widget during the grab.
2117  *
2118  * Since: 3.0
2119  */
2120 void
2121 gtk_device_grab_add (GtkWidget *widget,
2122                      GdkDevice *device,
2123                      gboolean   block_others)
2124 {
2125   GtkWindowGroup *group;
2126   GtkWidget *old_grab_widget;
2127
2128   g_return_if_fail (GTK_IS_WIDGET (widget));
2129   g_return_if_fail (GDK_IS_DEVICE (device));
2130
2131   group = gtk_main_get_window_group (widget);
2132   old_grab_widget = gtk_window_group_get_current_device_grab (group, device);
2133
2134   if (old_grab_widget != widget)
2135     _gtk_window_group_add_device_grab (group, widget, device, block_others);
2136
2137   gtk_grab_notify (group, device, old_grab_widget, widget, TRUE);
2138 }
2139
2140 /**
2141  * gtk_device_grab_remove:
2142  * @widget: a #GtkWidget
2143  * @device: a #GdkDevice
2144  *
2145  * Removes a device grab from the given widget.
2146  *
2147  * You have to pair calls to gtk_device_grab_add() and
2148  * gtk_device_grab_remove().
2149  *
2150  * Since: 3.0
2151  */
2152 void
2153 gtk_device_grab_remove (GtkWidget *widget,
2154                         GdkDevice *device)
2155 {
2156   GtkWindowGroup *group;
2157   GtkWidget *new_grab_widget;
2158
2159   g_return_if_fail (GTK_IS_WIDGET (widget));
2160   g_return_if_fail (GDK_IS_DEVICE (device));
2161
2162   group = gtk_main_get_window_group (widget);
2163   _gtk_window_group_remove_device_grab (group, widget, device);
2164   new_grab_widget = gtk_window_group_get_current_device_grab (group, device);
2165
2166   gtk_grab_notify (group, device, widget, new_grab_widget, FALSE);
2167 }
2168
2169 /**
2170  * gtk_key_snooper_install: (skip)
2171  * @snooper: a #GtkKeySnoopFunc
2172  * @func_data: data to pass to @snooper
2173  *
2174  * Installs a key snooper function, which will get called on all
2175  * key events before delivering them normally.
2176  *
2177  * Returns: a unique id for this key snooper for use with
2178  *    gtk_key_snooper_remove().
2179  *
2180  * Deprecated: 3.4: Key snooping should not be done. Events should
2181  *     be handled by widgets.
2182  */
2183 guint
2184 gtk_key_snooper_install (GtkKeySnoopFunc snooper,
2185                          gpointer        func_data)
2186 {
2187   GtkKeySnooperData *data;
2188   static guint snooper_id = 1;
2189
2190   g_return_val_if_fail (snooper != NULL, 0);
2191
2192   data = g_new (GtkKeySnooperData, 1);
2193   data->func = snooper;
2194   data->func_data = func_data;
2195   data->id = snooper_id++;
2196   key_snoopers = g_slist_prepend (key_snoopers, data);
2197
2198   return data->id;
2199 }
2200
2201 /**
2202  * gtk_key_snooper_remove:
2203  * @snooper_handler_id: Identifies the key snooper to remove
2204  *
2205  * Removes the key snooper function with the given id.
2206  *
2207  * Deprecated: 3.4: Key snooping should not be done. Events should
2208  *     be handled by widgets.
2209  */
2210 void
2211 gtk_key_snooper_remove (guint snooper_id)
2212 {
2213   GtkKeySnooperData *data = NULL;
2214   GSList *slist;
2215
2216   slist = key_snoopers;
2217   while (slist)
2218     {
2219       data = slist->data;
2220       if (data->id == snooper_id)
2221         break;
2222
2223       slist = slist->next;
2224       data = NULL;
2225     }
2226   if (data)
2227     {
2228       key_snoopers = g_slist_remove (key_snoopers, data);
2229       g_free (data);
2230     }
2231 }
2232
2233 static gint
2234 gtk_invoke_key_snoopers (GtkWidget *grab_widget,
2235                          GdkEvent  *event)
2236 {
2237   GSList *slist;
2238   gint return_val = FALSE;
2239
2240   return_val = _gail_util_key_snooper (grab_widget, (GdkEventKey *) event);
2241
2242   slist = key_snoopers;
2243   while (slist && !return_val)
2244     {
2245       GtkKeySnooperData *data;
2246
2247       data = slist->data;
2248       slist = slist->next;
2249       return_val = (*data->func) (grab_widget, (GdkEventKey*) event, data->func_data);
2250     }
2251
2252   return return_val;
2253 }
2254
2255 /**
2256  * gtk_get_current_event:
2257  *
2258  * Obtains a copy of the event currently being processed by GTK+.
2259  *
2260  * For example, if you are handling a #GtkButton::clicked signal,
2261  * the current event will be the #GdkEventButton that triggered
2262  * the ::clicked signal.
2263  *
2264  * Return value: (transfer full): a copy of the current event, or
2265  *     %NULL if there is no current event. The returned event must be
2266  *     freed with gdk_event_free().
2267  */
2268 GdkEvent*
2269 gtk_get_current_event (void)
2270 {
2271   if (current_events)
2272     return gdk_event_copy (current_events->data);
2273   else
2274     return NULL;
2275 }
2276
2277 /**
2278  * gtk_get_current_event_time:
2279  *
2280  * If there is a current event and it has a timestamp,
2281  * return that timestamp, otherwise return %GDK_CURRENT_TIME.
2282  *
2283  * Return value: the timestamp from the current event,
2284  *     or %GDK_CURRENT_TIME.
2285  */
2286 guint32
2287 gtk_get_current_event_time (void)
2288 {
2289   if (current_events)
2290     return gdk_event_get_time (current_events->data);
2291   else
2292     return GDK_CURRENT_TIME;
2293 }
2294
2295 /**
2296  * gtk_get_current_event_state:
2297  * @state: (out): a location to store the state of the current event
2298  *
2299  * If there is a current event and it has a state field, place
2300  * that state field in @state and return %TRUE, otherwise return
2301  * %FALSE.
2302  *
2303  * Return value: %TRUE if there was a current event and it
2304  *     had a state field
2305  */
2306 gboolean
2307 gtk_get_current_event_state (GdkModifierType *state)
2308 {
2309   g_return_val_if_fail (state != NULL, FALSE);
2310
2311   if (current_events)
2312     return gdk_event_get_state (current_events->data, state);
2313   else
2314     {
2315       *state = 0;
2316       return FALSE;
2317     }
2318 }
2319
2320 /**
2321  * gtk_get_current_event_device:
2322  *
2323  * If there is a current event and it has a device, return that
2324  * device, otherwise return %NULL.
2325  *
2326  * Returns: (transfer none): a #GdkDevice, or %NULL
2327  */
2328 GdkDevice *
2329 gtk_get_current_event_device (void)
2330 {
2331   if (current_events)
2332     return gdk_event_get_device (current_events->data);
2333   else
2334     return NULL;
2335 }
2336
2337 /**
2338  * gtk_get_event_widget:
2339  * @event: a #GdkEvent
2340  *
2341  * If @event is %NULL or the event was not associated with any widget,
2342  * returns %NULL, otherwise returns the widget that received the event
2343  * originally.
2344  *
2345  * Return value: (transfer none): the widget that originally
2346  *     received @event, or %NULL
2347  */
2348 GtkWidget*
2349 gtk_get_event_widget (GdkEvent *event)
2350 {
2351   GtkWidget *widget;
2352   gpointer widget_ptr;
2353
2354   widget = NULL;
2355   if (event && event->any.window &&
2356       (event->type == GDK_DESTROY || !gdk_window_is_destroyed (event->any.window)))
2357     {
2358       gdk_window_get_user_data (event->any.window, &widget_ptr);
2359       widget = widget_ptr;
2360     }
2361
2362   return widget;
2363 }
2364
2365 static gboolean
2366 propagate_event_up (GtkWidget *widget,
2367                     GdkEvent  *event,
2368                     GtkWidget *topmost)
2369 {
2370   gboolean handled_event = FALSE;
2371
2372   /* Propagate event up the widget tree so that
2373    * parents can see the button and motion
2374    * events of the children.
2375    */
2376   while (TRUE)
2377     {
2378       GtkWidget *tmp;
2379
2380       g_object_ref (widget);
2381
2382       /* Scroll events are special cased here because it
2383        * feels wrong when scrolling a GtkViewport, say,
2384        * to have children of the viewport eat the scroll
2385        * event
2386        */
2387       if (!gtk_widget_is_sensitive (widget))
2388         handled_event = event->type != GDK_SCROLL;
2389       else
2390         handled_event = gtk_widget_event (widget, event);
2391
2392       tmp = gtk_widget_get_parent (widget);
2393       g_object_unref (widget);
2394
2395       if (widget == topmost)
2396         break;
2397
2398       widget = tmp;
2399
2400       if (handled_event || !widget)
2401         break;
2402     }
2403
2404   return handled_event;
2405 }
2406
2407 static gboolean
2408 propagate_event_down (GtkWidget *widget,
2409                       GdkEvent  *event,
2410                       GtkWidget *topmost)
2411 {
2412   gint handled_event = FALSE;
2413   GList *widgets = NULL;
2414   GList *l;
2415
2416   widgets = g_list_prepend (widgets, g_object_ref (widget));
2417   while (widget && widget != topmost)
2418     {
2419       widget = gtk_widget_get_parent (widget);
2420       if (!widget)
2421         break;
2422
2423       widgets = g_list_prepend (widgets, g_object_ref (widget));
2424
2425       if (widget == topmost)
2426         break;
2427     }
2428
2429   for (l = widgets; l && !handled_event; l = g_list_next (l))
2430     {
2431       widget = (GtkWidget *)l->data;
2432
2433       if (!gtk_widget_is_sensitive (widget))
2434         handled_event = TRUE;
2435       else
2436         handled_event = _gtk_widget_captured_event (widget, event);
2437     }
2438   g_list_free_full (widgets, (GDestroyNotify)g_object_unref);
2439
2440   return handled_event;
2441 }
2442
2443 static gboolean
2444 propagate_event (GtkWidget *widget,
2445                  GdkEvent  *event,
2446                  gboolean   captured,
2447                  GtkWidget *topmost)
2448 {
2449   gboolean handled_event = FALSE;
2450   gboolean (* propagate_func) (GtkWidget *widget, GdkEvent  *event);
2451
2452   propagate_func = captured ? _gtk_widget_captured_event : gtk_widget_event;
2453
2454   if (event->type == GDK_KEY_PRESS || event->type == GDK_KEY_RELEASE)
2455     {
2456       /* Only send key events within Window widgets to the Window
2457        * The Window widget will in turn pass the
2458        * key event on to the currently focused widget
2459        * for that window.
2460        */
2461       GtkWidget *window;
2462
2463       window = gtk_widget_get_toplevel (widget);
2464       if (GTK_IS_WINDOW (window))
2465         {
2466           g_object_ref (widget);
2467           /* If there is a grab within the window, give the grab widget
2468            * a first crack at the key event
2469            */
2470           if (widget != window && gtk_widget_has_grab (widget))
2471             handled_event = propagate_func (widget, event);
2472
2473           if (!handled_event)
2474             {
2475               window = gtk_widget_get_toplevel (widget);
2476               if (GTK_IS_WINDOW (window))
2477                 {
2478                   if (gtk_widget_is_sensitive (window))
2479                     handled_event = propagate_func (window, event);
2480                 }
2481             }
2482
2483           g_object_unref (widget);
2484           return handled_event;
2485         }
2486     }
2487
2488   /* Other events get propagated up/down the widget tree */
2489   return captured ?
2490     propagate_event_down (widget, event, topmost) :
2491     propagate_event_up (widget, event, topmost);
2492 }
2493
2494 /**
2495  * gtk_propagate_event:
2496  * @widget: a #GtkWidget
2497  * @event: an event
2498  *
2499  * Sends an event to a widget, propagating the event to parent widgets
2500  * if the event remains unhandled.
2501  *
2502  * Events received by GTK+ from GDK normally begin in gtk_main_do_event().
2503  * Depending on the type of event, existence of modal dialogs, grabs, etc.,
2504  * the event may be propagated; if so, this function is used.
2505  *
2506  * gtk_propagate_event() calls gtk_widget_event() on each widget it
2507  * decides to send the event to. So gtk_widget_event() is the lowest-level
2508  * function; it simply emits the #GtkWidget::event and possibly an
2509  * event-specific signal on a widget. gtk_propagate_event() is a bit
2510  * higher-level, and gtk_main_do_event() is the highest level.
2511  *
2512  * All that said, you most likely don't want to use any of these
2513  * functions; synthesizing events is rarely needed. There are almost
2514  * certainly better ways to achieve your goals. For example, use
2515  * gdk_window_invalidate_rect() or gtk_widget_queue_draw() instead
2516  * of making up expose events.
2517  */
2518 void
2519 gtk_propagate_event (GtkWidget *widget,
2520                      GdkEvent  *event)
2521 {
2522   g_return_if_fail (GTK_IS_WIDGET (widget));
2523   g_return_if_fail (event != NULL);
2524
2525   propagate_event (widget, event, FALSE, NULL);
2526 }
2527
2528 gboolean
2529 _gtk_propagate_captured_event (GtkWidget *widget,
2530                                GdkEvent  *event,
2531                                GtkWidget *topmost)
2532 {
2533   return propagate_event (widget, event, TRUE, topmost);
2534 }