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