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