]> Pileus Git - ~andy/gtk/blob - gtk/gtkmain.c
Some renaming
[~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/gtkaccessibility.h"
132 #include "a11y/gailutil.h"
133
134 /* Private type definitions
135  */
136 typedef struct _GtkKeySnooperData        GtkKeySnooperData;
137
138 struct _GtkKeySnooperData
139 {
140   GtkKeySnoopFunc func;
141   gpointer func_data;
142   guint id;
143 };
144
145 static gint  gtk_invoke_key_snoopers     (GtkWidget          *grab_widget,
146                                           GdkEvent           *event);
147
148 static GtkWindowGroup *gtk_main_get_window_group (GtkWidget   *widget);
149
150 static guint gtk_main_loop_level = 0;
151 static gint pre_initialized = FALSE;
152 static gint gtk_initialized = FALSE;
153 static GList *current_events = NULL;
154
155 static GSList *main_loops = NULL;      /* stack of currently executing main loops */
156
157 static GSList *key_snoopers = NULL;
158
159 static guint debug_flags = 0;              /* Global GTK debug flag */
160
161 #ifdef G_ENABLE_DEBUG
162 static const GDebugKey gtk_debug_keys[] = {
163   {"misc", GTK_DEBUG_MISC},
164   {"plugsocket", GTK_DEBUG_PLUGSOCKET},
165   {"text", GTK_DEBUG_TEXT},
166   {"tree", GTK_DEBUG_TREE},
167   {"updates", GTK_DEBUG_UPDATES},
168   {"keybindings", GTK_DEBUG_KEYBINDINGS},
169   {"multihead", GTK_DEBUG_MULTIHEAD},
170   {"modules", GTK_DEBUG_MODULES},
171   {"geometry", GTK_DEBUG_GEOMETRY},
172   {"icontheme", GTK_DEBUG_ICONTHEME},
173   {"printing", GTK_DEBUG_PRINTING},
174   {"builder", GTK_DEBUG_BUILDER},
175   {"size-request", GTK_DEBUG_SIZE_REQUEST},
176   {"no-css-cache", GTK_DEBUG_NO_CSS_CACHE}
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 static void
674 do_post_parse_initialization (int    *argc,
675                               char ***argv)
676 {
677   if (gtk_initialized)
678     return;
679
680   gettext_initialization ();
681
682 #ifdef SIGPIPE
683   signal (SIGPIPE, SIG_IGN);
684 #endif
685
686   if (g_fatal_warnings)
687     {
688       GLogLevelFlags fatal_mask;
689
690       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
691       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
692       g_log_set_always_fatal (fatal_mask);
693     }
694
695   if (debug_flags & GTK_DEBUG_UPDATES)
696     gdk_window_set_debug_updates (TRUE);
697
698   {
699   /* Translate to default:RTL if you want your widgets
700    * to be RTL, otherwise translate to default:LTR.
701    * Do *not* translate it to "predefinito:LTR", if it
702    * it isn't default:LTR or default:RTL it will not work 
703    */
704     char *e = _("default:LTR");
705     if (strcmp (e, "default:RTL")==0) 
706       gtk_widget_set_default_direction (GTK_TEXT_DIR_RTL);
707     else if (strcmp (e, "default:LTR"))
708       g_warning ("Whoever translated default:LTR did so wrongly.\n");
709   }
710
711   _gtk_register_resource ();
712
713   _gtk_accel_map_init ();
714
715   /* Set the 'initialized' flag.
716    */
717   gtk_initialized = TRUE;
718
719   /* load gtk modules */
720   if (gtk_modules_string)
721     {
722       _gtk_modules_init (argc, argv, gtk_modules_string->str);
723       g_string_free (gtk_modules_string, TRUE);
724     }
725   else
726     {
727       _gtk_modules_init (argc, argv, NULL);
728     }
729
730   _gtk_accessibility_init ();
731 }
732
733
734 typedef struct
735 {
736   gboolean open_default_display;
737 } OptionGroupInfo;
738
739 static gboolean
740 pre_parse_hook (GOptionContext *context,
741                 GOptionGroup   *group,
742                 gpointer        data,
743                 GError        **error)
744 {
745   do_pre_parse_initialization (NULL, NULL);
746   
747   return TRUE;
748 }
749
750 static gboolean
751 post_parse_hook (GOptionContext *context,
752                  GOptionGroup   *group,
753                  gpointer       data,
754                  GError        **error)
755 {
756   OptionGroupInfo *info = data;
757
758   
759   do_post_parse_initialization (NULL, NULL);
760   
761   if (info->open_default_display)
762     {
763       if (gdk_display_open_default_libgtk_only () == NULL)
764         {
765           const char *display_name = gdk_get_display_arg_name ();
766           g_set_error (error,
767                        G_OPTION_ERROR,
768                        G_OPTION_ERROR_FAILED,
769                        _("Cannot open display: %s"),
770                        display_name ? display_name : "" );
771
772           return FALSE;
773         }
774     }
775
776   return TRUE;
777 }
778
779
780 /**
781  * gtk_get_debug_flags:
782  *
783  * Returns the GTK+ debug flags.
784  *
785  * This function is intended for GTK+ modules that want
786  * to adjust their debug output based on GTK+ debug flags.
787  *
788  * Returns: the GTK+ debug flags.
789  */
790 guint
791 gtk_get_debug_flags (void)
792 {
793   return debug_flags;
794 }
795
796 /**
797  * gtk_set_debug_flags:
798  *
799  * Sets the GTK+ debug flags.
800  */
801 void
802 gtk_set_debug_flags (guint flags)
803 {
804   debug_flags = flags;
805 }
806
807 /**
808  * gtk_get_option_group: (skip)
809  * @open_default_display: whether to open the default display
810  *     when parsing the commandline arguments
811  *
812  * Returns a #GOptionGroup for the commandline arguments recognized
813  * by GTK+ and GDK.
814  *
815  * You should add this group to your #GOptionContext
816  * with g_option_context_add_group(), if you are using
817  * g_option_context_parse() to parse your commandline arguments.
818  *
819  * Returns: a #GOptionGroup for the commandline arguments recognized
820  *     by GTK+
821  *
822  * Since: 2.6
823  */
824 GOptionGroup *
825 gtk_get_option_group (gboolean open_default_display)
826 {
827   GOptionGroup *group;
828   OptionGroupInfo *info;
829
830   gettext_initialization ();
831
832   info = g_new0 (OptionGroupInfo, 1);
833   info->open_default_display = open_default_display;
834   
835   group = g_option_group_new ("gtk", _("GTK+ Options"), _("Show GTK+ Options"), info, g_free);
836   g_option_group_set_parse_hooks (group, pre_parse_hook, post_parse_hook);
837
838   gdk_add_option_entries_libgtk_only (group);
839   g_option_group_add_entries (group, gtk_args);
840   g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
841   
842   return group;
843 }
844
845 /**
846  * gtk_init_with_args:
847  * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
848  *     your main() function (or 0 if @argv is %NULL). This will be changed if 
849  *     any arguments were handled.
850  * @argv: (array length=argc) (inout) (allow-none): Address of the
851  *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
852  *     understood by GTK+ are stripped before return.
853  * @parameter_string: a string which is displayed in
854  *    the first line of <option>--help</option> output, after
855  *    <literal><replaceable>programname</replaceable> [OPTION...]</literal>
856  * @entries: (array zero-terminated=1): a %NULL-terminated array
857  *    of #GOptionEntrys describing the options of your program
858  * @translation_domain: a translation domain to use for translating
859  *    the <option>--help</option> output for the options in @entries
860  *    and the @parameter_string with gettext(), or %NULL
861  * @error: a return location for errors
862  *
863  * This function does the same work as gtk_init_check().
864  * Additionally, it allows you to add your own commandline options,
865  * and it automatically generates nicely formatted
866  * <option>--help</option> output. Note that your program will
867  * be terminated after writing out the help output.
868  *
869  * Returns: %TRUE if the windowing system has been successfully
870  *     initialized, %FALSE otherwise
871  *
872  * Since: 2.6
873  */
874 gboolean
875 gtk_init_with_args (gint                 *argc,
876                     gchar              ***argv,
877                     const gchar          *parameter_string,
878                     const GOptionEntry   *entries,
879                     const gchar          *translation_domain,
880                     GError              **error)
881 {
882   GOptionContext *context;
883   GOptionGroup *gtk_group;
884   gboolean retval;
885
886   if (gtk_initialized)
887     return gdk_display_open_default_libgtk_only () != NULL;
888
889   gettext_initialization ();
890
891   if (!check_setugid ())
892     return FALSE;
893
894   gtk_group = gtk_get_option_group (TRUE);
895
896   context = g_option_context_new (parameter_string);
897   g_option_context_add_group (context, gtk_group);
898   g_option_context_set_translation_domain (context, translation_domain);
899
900   if (entries)
901     g_option_context_add_main_entries (context, entries, translation_domain);
902   retval = g_option_context_parse (context, argc, argv, error);
903
904   g_option_context_free (context);
905
906   return retval;
907 }
908
909
910 /**
911  * gtk_parse_args:
912  * @argc: (inout): a pointer to the number of command line arguments
913  * @argv: (array length=argc) (inout): a pointer to the array of
914  *     command line arguments
915  *
916  * Parses command line arguments, and initializes global
917  * attributes of GTK+, but does not actually open a connection
918  * to a display. (See gdk_display_open(), gdk_get_display_arg_name())
919  *
920  * Any arguments used by GTK+ or GDK are removed from the array and
921  * @argc and @argv are updated accordingly.
922  *
923  * There is no need to call this function explicitely if you are using
924  * gtk_init(), or gtk_init_check().
925  *
926  * Return value: %TRUE if initialization succeeded, otherwise %FALSE
927  */
928 gboolean
929 gtk_parse_args (int    *argc,
930                 char ***argv)
931 {
932   GOptionContext *option_context;
933   GOptionGroup *gtk_group;
934   GError *error = NULL;
935   
936   if (gtk_initialized)
937     return TRUE;
938
939   gettext_initialization ();
940
941   if (!check_setugid ())
942     return FALSE;
943
944   option_context = g_option_context_new (NULL);
945   g_option_context_set_ignore_unknown_options (option_context, TRUE);
946   g_option_context_set_help_enabled (option_context, FALSE);
947   gtk_group = gtk_get_option_group (FALSE);
948   g_option_context_set_main_group (option_context, gtk_group);
949   if (!g_option_context_parse (option_context, argc, argv, &error))
950     {
951       g_warning ("%s", error->message);
952       g_error_free (error);
953     }
954
955   g_option_context_free (option_context);
956
957   return TRUE;
958 }
959
960 #ifdef G_PLATFORM_WIN32
961 #undef gtk_init_check
962 #endif
963
964 /**
965  * gtk_init_check:
966  * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
967  *     your main() function (or 0 if @argv is %NULL). This will be changed if 
968  *     any arguments were handled.
969  * @argv: (array length=argc) (inout) (allow-none): Address of the
970  *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
971  *     understood by GTK+ are stripped before return.
972  *
973  * This function does the same work as gtk_init() with only a single
974  * change: It does not terminate the program if the windowing system
975  * can't be initialized. Instead it returns %FALSE on failure.
976  *
977  * This way the application can fall back to some other means of
978  * communication with the user - for example a curses or command line
979  * interface.
980  *
981  * Return value: %TRUE if the windowing system has been successfully
982  *     initialized, %FALSE otherwise
983  */
984 gboolean
985 gtk_init_check (int    *argc,
986                 char ***argv)
987 {
988   if (!gtk_parse_args (argc, argv))
989     return FALSE;
990
991   return gdk_display_open_default_libgtk_only () != NULL;
992 }
993
994 #ifdef G_PLATFORM_WIN32
995 #undef gtk_init
996 #endif
997
998 /**
999  * gtk_init:
1000  * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
1001  *     your main() function (or 0 if @argv is %NULL). This will be changed if 
1002  *     any arguments were handled.
1003  * @argv: (array length=argc) (inout) (allow-none): Address of the
1004  *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
1005  *     understood by GTK+ are stripped before return.
1006  *
1007  * Call this function before using any other GTK+ functions in your GUI
1008  * applications.  It will initialize everything needed to operate the
1009  * toolkit and parses some standard command line options.
1010  *
1011  * Although you are expected to pass the @argc, @argv parameters from main() to 
1012  * this function, it is possible to pass %NULL if @argv is not available or 
1013  * commandline handling is not required.
1014  *
1015  * @argc and @argv are adjusted accordingly so your own code will
1016  * never see those standard arguments.
1017  *
1018  * Note that there are some alternative ways to initialize GTK+:
1019  * if you are calling gtk_parse_args(), gtk_init_check(),
1020  * gtk_init_with_args() or g_option_context_parse() with
1021  * the option group returned by gtk_get_option_group(),
1022  * you <emphasis>don't</emphasis> have to call gtk_init().
1023  *
1024  * <note><para>
1025  * This function will terminate your program if it was unable to
1026  * initialize the windowing system for some reason. If you want
1027  * your program to fall back to a textual interface you want to
1028  * call gtk_init_check() instead.
1029  * </para></note>
1030  *
1031  * <note><para>
1032  * Since 2.18, GTK+ calls <literal>signal (SIGPIPE, SIG_IGN)</literal>
1033  * during initialization, to ignore SIGPIPE signals, since these are
1034  * almost never wanted in graphical applications. If you do need to
1035  * handle SIGPIPE for some reason, reset the handler after gtk_init(),
1036  * but notice that other libraries (e.g. libdbus or gvfs) might do
1037  * similar things.
1038  * </para></note>
1039  */
1040 void
1041 gtk_init (int *argc, char ***argv)
1042 {
1043   if (!gtk_init_check (argc, argv))
1044     {
1045       const char *display_name_arg = gdk_get_display_arg_name ();
1046       if (display_name_arg == NULL)
1047         display_name_arg = getenv("DISPLAY");
1048       g_warning ("cannot open display: %s", display_name_arg ? display_name_arg : "");
1049       exit (1);
1050     }
1051 }
1052
1053 #ifdef G_OS_WIN32
1054
1055 /* This is relevant when building with gcc for Windows (MinGW),
1056  * where we want to be struct packing compatible with MSVC,
1057  * i.e. use the -mms-bitfields switch.
1058  * For Cygwin there should be no need to be compatible with MSVC,
1059  * so no need to use G_PLATFORM_WIN32.
1060  */
1061
1062 static void
1063 check_sizeof_GtkWindow (size_t sizeof_GtkWindow)
1064 {
1065   if (sizeof_GtkWindow != sizeof (GtkWindow))
1066     g_error ("Incompatible build!\n"
1067              "The code using GTK+ thinks GtkWindow is of different\n"
1068              "size than it actually is in this build of GTK+.\n"
1069              "On Windows, this probably means that you have compiled\n"
1070              "your code with gcc without the -mms-bitfields switch,\n"
1071              "or that you are using an unsupported compiler.");
1072 }
1073
1074 /* In GTK+ 2.0 the GtkWindow struct actually is the same size in
1075  * gcc-compiled code on Win32 whether compiled with -fnative-struct or
1076  * not. Unfortunately this wan't noticed until after GTK+ 2.0.1. So,
1077  * from GTK+ 2.0.2 on, check some other struct, too, where the use of
1078  * -fnative-struct still matters. GtkBox is one such.
1079  */
1080 static void
1081 check_sizeof_GtkBox (size_t sizeof_GtkBox)
1082 {
1083   if (sizeof_GtkBox != sizeof (GtkBox))
1084     g_error ("Incompatible build!\n"
1085              "The code using GTK+ thinks GtkBox is of different\n"
1086              "size than it actually is in this build of GTK+.\n"
1087              "On Windows, this probably means that you have compiled\n"
1088              "your code with gcc without the -mms-bitfields switch,\n"
1089              "or that you are using an unsupported compiler.");
1090 }
1091
1092 /* These two functions might get more checks added later, thus pass
1093  * in the number of extra args.
1094  */
1095 void
1096 gtk_init_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
1097 {
1098   check_sizeof_GtkWindow (sizeof_GtkWindow);
1099   if (num_checks >= 2)
1100     check_sizeof_GtkBox (sizeof_GtkBox);
1101   gtk_init (argc, argv);
1102 }
1103
1104 gboolean
1105 gtk_init_check_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
1106 {
1107   check_sizeof_GtkWindow (sizeof_GtkWindow);
1108   if (num_checks >= 2)
1109     check_sizeof_GtkBox (sizeof_GtkBox);
1110   return gtk_init_check (argc, argv);
1111 }
1112
1113 #endif
1114
1115 /**
1116  * gtk_get_default_language:
1117  *
1118  * Returns the #PangoLanguage for the default language currently in
1119  * effect. (Note that this can change over the life of an
1120  * application.) The default language is derived from the current
1121  * locale. It determines, for example, whether GTK+ uses the
1122  * right-to-left or left-to-right text direction.
1123  *
1124  * This function is equivalent to pango_language_get_default().
1125  * See that function for details.
1126  *
1127  * Return value: the default language as a #PangoLanguage,
1128  *     must not be freed
1129  */
1130 PangoLanguage *
1131 gtk_get_default_language (void)
1132 {
1133   return pango_language_get_default ();
1134 }
1135
1136 /**
1137  * gtk_main:
1138  *
1139  * Runs the main loop until gtk_main_quit() is called.
1140  *
1141  * You can nest calls to gtk_main(). In that case gtk_main_quit()
1142  * will make the innermost invocation of the main loop return.
1143  */
1144 void
1145 gtk_main (void)
1146 {
1147   GMainLoop *loop;
1148
1149   gtk_main_loop_level++;
1150
1151   loop = g_main_loop_new (NULL, TRUE);
1152   main_loops = g_slist_prepend (main_loops, loop);
1153
1154   if (g_main_loop_is_running (main_loops->data))
1155     {
1156       gdk_threads_leave ();
1157       g_main_loop_run (loop);
1158       gdk_threads_enter ();
1159       gdk_flush ();
1160     }
1161
1162   main_loops = g_slist_remove (main_loops, loop);
1163
1164   g_main_loop_unref (loop);
1165
1166   gtk_main_loop_level--;
1167
1168   if (gtk_main_loop_level == 0)
1169     {
1170       /* Keep this section in sync with gtk_application_shutdown() */
1171
1172       /* Try storing all clipboard data we have */
1173       _gtk_clipboard_store_all ();
1174
1175       /* Synchronize the recent manager singleton */
1176       _gtk_recent_manager_sync ();
1177
1178       _gtk_accessibility_shutdown ();
1179     }
1180 }
1181
1182 /**
1183  * gtk_main_level:
1184  *
1185  * Asks for the current nesting level of the main loop.
1186  *
1187  * Returns: the nesting level of the current invocation
1188  *     of the main loop
1189  */
1190 guint
1191 gtk_main_level (void)
1192 {
1193   return gtk_main_loop_level;
1194 }
1195
1196 /**
1197  * gtk_main_quit:
1198  *
1199  * Makes the innermost invocation of the main loop return
1200  * when it regains control.
1201  */
1202 void
1203 gtk_main_quit (void)
1204 {
1205   g_return_if_fail (main_loops != NULL);
1206
1207   g_main_loop_quit (main_loops->data);
1208 }
1209
1210 /**
1211  * gtk_events_pending:
1212  *
1213  * Checks if any events are pending.
1214  *
1215  * This can be used to update the UI and invoke timeouts etc.
1216  * while doing some time intensive computation.
1217  *
1218  * <example>
1219  * <title>Updating the UI during a long computation</title>
1220  * <programlisting>
1221  *  /&ast; computation going on... &ast;/
1222  *
1223  *  while (gtk_events_pending ())
1224  *    gtk_main_iteration ();
1225  *
1226  *  /&ast; ...computation continued &ast;/
1227  * </programlisting>
1228  * </example>
1229  *
1230  * Returns: %TRUE if any events are pending, %FALSE otherwise
1231  */
1232 gboolean
1233 gtk_events_pending (void)
1234 {
1235   gboolean result;
1236
1237   gdk_threads_leave ();
1238   result = g_main_context_pending (NULL);
1239   gdk_threads_enter ();
1240
1241   return result;
1242 }
1243
1244 /**
1245  * gtk_main_iteration:
1246  *
1247  * Runs a single iteration of the mainloop.
1248  *
1249  * If no events are waiting to be processed GTK+ will block
1250  * until the next event is noticed. If you don't want to block
1251  * look at gtk_main_iteration_do() or check if any events are
1252  * pending with gtk_events_pending() first.
1253  *
1254  * Returns: %TRUE if gtk_main_quit() has been called for the
1255  *     innermost mainloop
1256  */
1257 gboolean
1258 gtk_main_iteration (void)
1259 {
1260   gdk_threads_leave ();
1261   g_main_context_iteration (NULL, TRUE);
1262   gdk_threads_enter ();
1263
1264   if (main_loops)
1265     return !g_main_loop_is_running (main_loops->data);
1266   else
1267     return TRUE;
1268 }
1269
1270 /**
1271  * gtk_main_iteration_do:
1272  * @blocking: %TRUE if you want GTK+ to block if no events are pending
1273  *
1274  * Runs a single iteration of the mainloop.
1275  * If no events are available either return or block depending on
1276  * the value of @blocking.
1277  *
1278  * Returns: %TRUE if gtk_main_quit() has been called for the
1279  *     innermost mainloop
1280  */
1281 gboolean
1282 gtk_main_iteration_do (gboolean blocking)
1283 {
1284   gdk_threads_leave ();
1285   g_main_context_iteration (NULL, blocking);
1286   gdk_threads_enter ();
1287
1288   if (main_loops)
1289     return !g_main_loop_is_running (main_loops->data);
1290   else
1291     return TRUE;
1292 }
1293
1294 /* private libgtk to libgdk interfaces */
1295 gboolean gdk_device_grab_info_libgtk_only (GdkDisplay  *display,
1296                                            GdkDevice   *device,
1297                                            GdkWindow  **grab_window,
1298                                            gboolean    *owner_events);
1299
1300 static void
1301 rewrite_events_translate (GdkWindow *old_window,
1302                           GdkWindow *new_window,
1303                           gdouble   *x,
1304                           gdouble   *y)
1305 {
1306   gint old_origin_x, old_origin_y;
1307   gint new_origin_x, new_origin_y;
1308
1309   gdk_window_get_origin (old_window, &old_origin_x, &old_origin_y);
1310   gdk_window_get_origin (new_window, &new_origin_x, &new_origin_y);
1311
1312   *x += old_origin_x - new_origin_x;
1313   *y += old_origin_y - new_origin_y;
1314 }
1315
1316 static GdkEvent *
1317 rewrite_event_for_window (GdkEvent  *event,
1318                           GdkWindow *new_window)
1319 {
1320   event = gdk_event_copy (event);
1321
1322   switch (event->type)
1323     {
1324     case GDK_SCROLL:
1325       rewrite_events_translate (event->any.window,
1326                                 new_window,
1327                                 &event->scroll.x, &event->scroll.y);
1328       break;
1329     case GDK_BUTTON_PRESS:
1330     case GDK_2BUTTON_PRESS:
1331     case GDK_3BUTTON_PRESS:
1332     case GDK_BUTTON_RELEASE:
1333       rewrite_events_translate (event->any.window,
1334                                 new_window,
1335                                 &event->button.x, &event->button.y);
1336       break;
1337     case GDK_MOTION_NOTIFY:
1338       rewrite_events_translate (event->any.window,
1339                                 new_window,
1340                                 &event->motion.x, &event->motion.y);
1341       break;
1342     case GDK_TOUCH_BEGIN:
1343     case GDK_TOUCH_UPDATE:
1344     case GDK_TOUCH_END:
1345     case GDK_TOUCH_CANCEL:
1346       rewrite_events_translate (event->any.window,
1347                                 new_window,
1348                                 &event->touch.x, &event->touch.y);
1349       break;
1350     case GDK_KEY_PRESS:
1351     case GDK_KEY_RELEASE:
1352     case GDK_PROXIMITY_IN:
1353     case GDK_PROXIMITY_OUT:
1354       break;
1355
1356     default:
1357       return event;
1358     }
1359
1360   g_object_unref (event->any.window);
1361   event->any.window = g_object_ref (new_window);
1362
1363   return event;
1364 }
1365
1366 /* If there is a pointer or keyboard grab in effect with owner_events = TRUE,
1367  * then what X11 does is deliver the event normally if it was going to this
1368  * client, otherwise, delivers it in terms of the grab window. This function
1369  * rewrites events to the effect that events going to the same window group
1370  * are delivered normally, otherwise, the event is delivered in terms of the
1371  * grab window.
1372  */
1373 static GdkEvent *
1374 rewrite_event_for_grabs (GdkEvent *event)
1375 {
1376   GdkWindow *grab_window;
1377   GtkWidget *event_widget, *grab_widget;
1378   gpointer grab_widget_ptr;
1379   gboolean owner_events;
1380   GdkDisplay *display;
1381   GdkDevice *device;
1382
1383   switch (event->type)
1384     {
1385     case GDK_SCROLL:
1386     case GDK_BUTTON_PRESS:
1387     case GDK_2BUTTON_PRESS:
1388     case GDK_3BUTTON_PRESS:
1389     case GDK_BUTTON_RELEASE:
1390     case GDK_MOTION_NOTIFY:
1391     case GDK_PROXIMITY_IN:
1392     case GDK_PROXIMITY_OUT:
1393     case GDK_KEY_PRESS:
1394     case GDK_KEY_RELEASE:
1395     case GDK_TOUCH_BEGIN:
1396     case GDK_TOUCH_UPDATE:
1397     case GDK_TOUCH_END:
1398     case GDK_TOUCH_CANCEL:
1399       display = gdk_window_get_display (event->any.window);
1400       device = gdk_event_get_device (event);
1401
1402       if (!gdk_device_grab_info_libgtk_only (display, device, &grab_window, &owner_events) ||
1403           !owner_events)
1404         return NULL;
1405       break;
1406     default:
1407       return NULL;
1408     }
1409
1410   event_widget = gtk_get_event_widget (event);
1411   gdk_window_get_user_data (grab_window, &grab_widget_ptr);
1412   grab_widget = grab_widget_ptr;
1413
1414   if (grab_widget &&
1415       gtk_main_get_window_group (grab_widget) != gtk_main_get_window_group (event_widget))
1416     return rewrite_event_for_window (event, grab_window);
1417   else
1418     return NULL;
1419 }
1420
1421 /**
1422  * gtk_main_do_event:
1423  * @event: An event to process (normally passed by GDK)
1424  *
1425  * Processes a single GDK event.
1426  *
1427  * This is public only to allow filtering of events between GDK and GTK+.
1428  * You will not usually need to call this function directly.
1429  *
1430  * While you should not call this function directly, you might want to
1431  * know how exactly events are handled. So here is what this function
1432  * does with the event:
1433  *
1434  * <orderedlist>
1435  * <listitem><para>
1436  *   Compress enter/leave notify events. If the event passed build an
1437  *   enter/leave pair together with the next event (peeked from GDK), both
1438  *   events are thrown away. This is to avoid a backlog of (de-)highlighting
1439  *   widgets crossed by the pointer.
1440  * </para></listitem>
1441  * <listitem><para>
1442  *   Find the widget which got the event. If the widget can't be determined
1443  *   the event is thrown away unless it belongs to a INCR transaction.
1444  * </para></listitem>
1445  * <listitem><para>
1446  *   Then the event is pushed onto a stack so you can query the currently
1447  *   handled event with gtk_get_current_event().
1448  * </para></listitem>
1449  * <listitem><para>
1450  *   The event is sent to a widget. If a grab is active all events for widgets
1451  *   that are not in the contained in the grab widget are sent to the latter
1452  *   with a few exceptions:
1453  *   <itemizedlist>
1454  *   <listitem><para>
1455  *     Deletion and destruction events are still sent to the event widget for
1456  *     obvious reasons.
1457  *   </para></listitem>
1458  *   <listitem><para>
1459  *     Events which directly relate to the visual representation of the event
1460  *     widget.
1461  *   </para></listitem>
1462  *   <listitem><para>
1463  *     Leave events are delivered to the event widget if there was an enter
1464  *     event delivered to it before without the paired leave event.
1465  *   </para></listitem>
1466  *   <listitem><para>
1467  *     Drag events are not redirected because it is unclear what the semantics
1468  *     of that would be.
1469  *   </para></listitem>
1470  *   </itemizedlist>
1471  *   Another point of interest might be that all key events are first passed
1472  *   through the key snooper functions if there are any. Read the description
1473  *   of gtk_key_snooper_install() if you need this feature.
1474  * </para></listitem>
1475  * <listitem><para>
1476  *   After finishing the delivery the event is popped from the event stack.
1477  * </para></listitem>
1478  * </orderedlist>
1479  */
1480 void
1481 gtk_main_do_event (GdkEvent *event)
1482 {
1483   GtkWidget *event_widget;
1484   GtkWidget *grab_widget = NULL;
1485   GtkWidget *topmost_widget = NULL;
1486   GtkWindowGroup *window_group;
1487   GdkEvent *rewritten_event = NULL;
1488   GdkDevice *device;
1489   GList *tmp_list;
1490
1491   if (event->type == GDK_SETTING)
1492     {
1493       _gtk_settings_handle_event (&event->setting);
1494       return;
1495     }
1496
1497   if (event->type == GDK_OWNER_CHANGE)
1498     {
1499       _gtk_clipboard_handle_event (&event->owner_change);
1500       return;
1501     }
1502
1503   /* Find the widget which got the event. We store the widget
1504    * in the user_data field of GdkWindow's. Ignore the event
1505    * if we don't have a widget for it, except for GDK_PROPERTY_NOTIFY
1506    * events which are handled specially. Though this happens rarely,
1507    * bogus events can occur for e.g. destroyed GdkWindows.
1508    */
1509   event_widget = gtk_get_event_widget (event);
1510   if (!event_widget)
1511     {
1512       /* To handle selection INCR transactions, we select
1513        * PropertyNotify events on the requestor window and create
1514        * a corresponding (fake) GdkWindow so that events get here.
1515        * There won't be a widget though, so we have to handle
1516        * them specially
1517        */
1518       if (event->type == GDK_PROPERTY_NOTIFY)
1519         _gtk_selection_incr_event (event->any.window,
1520                                    &event->property);
1521
1522       return;
1523     }
1524
1525   /* If pointer or keyboard grabs are in effect, munge the events
1526    * so that each window group looks like a separate app.
1527    */
1528   rewritten_event = rewrite_event_for_grabs (event);
1529   if (rewritten_event)
1530     {
1531       event = rewritten_event;
1532       event_widget = gtk_get_event_widget (event);
1533     }
1534
1535   window_group = gtk_main_get_window_group (event_widget);
1536   device = gdk_event_get_device (event);
1537
1538   /* check whether there is a (device) grab in effect... */
1539   if (device)
1540     grab_widget = gtk_window_group_get_current_device_grab (window_group, device);
1541
1542   if (!grab_widget)
1543     grab_widget = gtk_window_group_get_current_grab (window_group);
1544
1545   /* Find out the topmost widget where captured event propagation
1546    * should start, which is the widget holding the GTK+ grab
1547    * if any, otherwise it's left NULL and events are emitted
1548    * from the toplevel (or topmost parentless parent).
1549    */
1550   if (grab_widget)
1551     topmost_widget = grab_widget;
1552
1553   /* If the grab widget is an ancestor of the event widget
1554    * then we send the event to the original event widget.
1555    * This is the key to implementing modality.
1556    */
1557   if (!grab_widget ||
1558       ((gtk_widget_is_sensitive (event_widget) || event->type == GDK_SCROLL) &&
1559        gtk_widget_is_ancestor (event_widget, grab_widget)))
1560     grab_widget = event_widget;
1561
1562   /* If the widget receiving events is actually blocked by another
1563    * device GTK+ grab
1564    */
1565   if (device &&
1566       _gtk_window_group_widget_is_blocked_for_device (window_group, grab_widget, device))
1567     {
1568       if (rewritten_event)
1569         gdk_event_free (rewritten_event);
1570
1571       return;
1572     }
1573
1574   /* Push the event onto a stack of current events for
1575    * gtk_current_event_get().
1576    */
1577   current_events = g_list_prepend (current_events, event);
1578
1579   /* Not all events get sent to the grabbing widget.
1580    * The delete, destroy, expose, focus change and resize
1581    * events still get sent to the event widget because
1582    * 1) these events have no meaning for the grabbing widget
1583    * and 2) redirecting these events to the grabbing widget
1584    * could cause the display to be messed up.
1585    *
1586    * Drag events are also not redirected, since it isn't
1587    * clear what the semantics of that would be.
1588    */
1589   switch (event->type)
1590     {
1591     case GDK_NOTHING:
1592       break;
1593
1594     case GDK_DELETE:
1595       g_object_ref (event_widget);
1596       if ((!gtk_window_group_get_current_grab (window_group) || gtk_widget_get_toplevel (gtk_window_group_get_current_grab (window_group)) == event_widget) &&
1597           !gtk_widget_event (event_widget, event))
1598         gtk_widget_destroy (event_widget);
1599       g_object_unref (event_widget);
1600       break;
1601
1602     case GDK_DESTROY:
1603       /* Unexpected GDK_DESTROY from the outside, ignore for
1604        * child windows, handle like a GDK_DELETE for toplevels
1605        */
1606       if (!gtk_widget_get_parent (event_widget))
1607         {
1608           g_object_ref (event_widget);
1609           if (!gtk_widget_event (event_widget, event) &&
1610               gtk_widget_get_realized (event_widget))
1611             gtk_widget_destroy (event_widget);
1612           g_object_unref (event_widget);
1613         }
1614       break;
1615
1616     case GDK_EXPOSE:
1617       if (event->any.window && gtk_widget_get_double_buffered (event_widget))
1618         {
1619           gdk_window_begin_paint_region (event->any.window, event->expose.region);
1620           gtk_widget_send_expose (event_widget, event);
1621           gdk_window_end_paint (event->any.window);
1622         }
1623       else
1624         {
1625           /* The app may paint with a previously allocated cairo_t,
1626            * which will draw directly to the window. We can't catch cairo
1627            * draw operations to automatically flush the window, thus we
1628            * need to explicitly flush any outstanding moves or double
1629            * buffering
1630            */
1631           gdk_window_flush (event->any.window);
1632           gtk_widget_send_expose (event_widget, event);
1633         }
1634       break;
1635
1636     case GDK_PROPERTY_NOTIFY:
1637     case GDK_FOCUS_CHANGE:
1638     case GDK_CONFIGURE:
1639     case GDK_MAP:
1640     case GDK_UNMAP:
1641     case GDK_SELECTION_CLEAR:
1642     case GDK_SELECTION_REQUEST:
1643     case GDK_SELECTION_NOTIFY:
1644     case GDK_CLIENT_EVENT:
1645     case GDK_VISIBILITY_NOTIFY:
1646     case GDK_WINDOW_STATE:
1647     case GDK_GRAB_BROKEN:
1648     case GDK_DAMAGE:
1649       if (!_gtk_widget_captured_event (event_widget, event))
1650         gtk_widget_event (event_widget, event);
1651       break;
1652
1653     case GDK_SCROLL:
1654     case GDK_BUTTON_PRESS:
1655     case GDK_2BUTTON_PRESS:
1656     case GDK_3BUTTON_PRESS:
1657     case GDK_TOUCH_BEGIN:
1658       if (!_gtk_propagate_captured_event (grab_widget, event, topmost_widget))
1659         gtk_propagate_event (grab_widget, event);
1660       break;
1661
1662     case GDK_KEY_PRESS:
1663     case GDK_KEY_RELEASE:
1664       if (gtk_invoke_key_snoopers (grab_widget, event))
1665         break;
1666
1667       /* make focus visible in a window that receives a key event */
1668       {
1669         GtkWidget *window;
1670         GtkPolicyType visible_focus;
1671
1672         window = gtk_widget_get_toplevel (grab_widget);
1673         g_object_get (gtk_widget_get_settings (grab_widget), "gtk-visible-focus", &visible_focus, NULL);
1674         if (GTK_IS_WINDOW (window) && visible_focus != GTK_POLICY_NEVER)
1675           gtk_window_set_focus_visible (GTK_WINDOW (window), TRUE);
1676       }
1677
1678       /* Catch alt press to enable auto-mnemonics;
1679        * menus are handled elsewhere
1680        * FIXME: this does not work with mnemonic modifiers other than Alt
1681        */
1682       if ((event->key.keyval == GDK_KEY_Alt_L || event->key.keyval == GDK_KEY_Alt_R) &&
1683           ((event->key.state & (gtk_accelerator_get_default_mod_mask ()) & ~(GDK_RELEASE_MASK|GDK_MOD1_MASK)) == 0) &&
1684           !GTK_IS_MENU_SHELL (grab_widget))
1685         {
1686           gboolean auto_mnemonics;
1687
1688           g_object_get (gtk_widget_get_settings (grab_widget),
1689                         "gtk-auto-mnemonics", &auto_mnemonics, NULL);
1690
1691           if (auto_mnemonics)
1692             {
1693               gboolean mnemonics_visible;
1694               GtkWidget *window;
1695
1696               mnemonics_visible = (event->type == GDK_KEY_PRESS);
1697
1698               window = gtk_widget_get_toplevel (grab_widget);
1699               if (GTK_IS_WINDOW (window))
1700                 {
1701                   if (mnemonics_visible)
1702                     _gtk_window_set_auto_mnemonics_visible (GTK_WINDOW (window));
1703                   else
1704                     gtk_window_set_mnemonics_visible (GTK_WINDOW (window), FALSE);
1705                 }
1706             }
1707         }
1708       /* else fall through */
1709     case GDK_MOTION_NOTIFY:
1710     case GDK_BUTTON_RELEASE:
1711     case GDK_PROXIMITY_IN:
1712     case GDK_PROXIMITY_OUT:
1713     case GDK_TOUCH_UPDATE:
1714     case GDK_TOUCH_END:
1715     case GDK_TOUCH_CANCEL:
1716       if (!_gtk_propagate_captured_event (grab_widget, event, topmost_widget))
1717         gtk_propagate_event (grab_widget, event);
1718       break;
1719
1720     case GDK_ENTER_NOTIFY:
1721       if (event->crossing.detail != GDK_NOTIFY_VIRTUAL &&
1722           event->crossing.detail != GDK_NOTIFY_NONLINEAR_VIRTUAL)
1723         _gtk_widget_set_device_window (event_widget,
1724                                        gdk_event_get_device (event),
1725                                        event->any.window);
1726       if (gtk_widget_is_sensitive (grab_widget) &&
1727           !_gtk_propagate_captured_event (grab_widget, event, topmost_widget))
1728         gtk_widget_event (grab_widget, event);
1729       break;
1730
1731     case GDK_LEAVE_NOTIFY:
1732       if (event->crossing.detail != GDK_NOTIFY_VIRTUAL &&
1733           event->crossing.detail != GDK_NOTIFY_NONLINEAR_VIRTUAL)
1734         _gtk_widget_set_device_window (event_widget,
1735                                        gdk_event_get_device (event),
1736                                        NULL);
1737       if (gtk_widget_is_sensitive (grab_widget) &&
1738           !_gtk_propagate_captured_event (grab_widget, event, topmost_widget))
1739         gtk_widget_event (grab_widget, event);
1740       break;
1741
1742     case GDK_DRAG_STATUS:
1743     case GDK_DROP_FINISHED:
1744       _gtk_drag_source_handle_event (event_widget, event);
1745       break;
1746     case GDK_DRAG_ENTER:
1747     case GDK_DRAG_LEAVE:
1748     case GDK_DRAG_MOTION:
1749     case GDK_DROP_START:
1750       _gtk_drag_dest_handle_event (event_widget, event);
1751       break;
1752     default:
1753       g_assert_not_reached ();
1754       break;
1755     }
1756
1757   if (event->type == GDK_ENTER_NOTIFY
1758       || event->type == GDK_LEAVE_NOTIFY
1759       || event->type == GDK_BUTTON_PRESS
1760       || event->type == GDK_2BUTTON_PRESS
1761       || event->type == GDK_3BUTTON_PRESS
1762       || event->type == GDK_KEY_PRESS
1763       || event->type == GDK_DRAG_ENTER
1764       || event->type == GDK_GRAB_BROKEN
1765       || event->type == GDK_MOTION_NOTIFY
1766       || event->type == GDK_TOUCH_UPDATE
1767       || event->type == GDK_SCROLL)
1768     {
1769       _gtk_tooltip_handle_event (event);
1770     }
1771
1772   tmp_list = current_events;
1773   current_events = g_list_remove_link (current_events, tmp_list);
1774   g_list_free_1 (tmp_list);
1775
1776   if (rewritten_event)
1777     gdk_event_free (rewritten_event);
1778 }
1779
1780 /**
1781  * gtk_true:
1782  *
1783  * All this function does it to return %TRUE.
1784  *
1785  * This can be useful for example if you want to inhibit the deletion
1786  * of a window. Of course you should not do this as the user expects
1787  * a reaction from clicking the close icon of the window...
1788  *
1789  * <example>
1790  * <title>A persistent window</title>
1791  * <programlisting>
1792  * #include &lt;gtk/gtk.h>&lt;
1793  *
1794  * int
1795  * main (int argc, char **argv)
1796  * {
1797  *   GtkWidget *win, *but;
1798  *
1799  *   gtk_init (&amp;argc, &amp;argv);
1800  *
1801  *   win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1802  *   g_signal_connect (win, "delete-event",
1803  *                     G_CALLBACK (gtk_true), NULL);
1804  *   g_signal_connect (win, "destroy",
1805  *                     G_CALLBACK (gtk_main_quit), NULL);
1806  *
1807  *   but = gtk_button_new_with_label ("Close yourself. I mean it!");
1808  *   g_signal_connect_swapped (but, "clicked",
1809  *                             G_CALLBACK (gtk_object_destroy), win);
1810  *   gtk_container_add (GTK_CONTAINER (win), but);
1811  *
1812  *   gtk_widget_show_all (win);
1813  *
1814  *   gtk_main ();
1815  *
1816  *   return 0;
1817  * }
1818  * </programlisting>
1819  * </example>
1820  *
1821  * Returns: %TRUE
1822  */
1823 gboolean
1824 gtk_true (void)
1825 {
1826   return TRUE;
1827 }
1828
1829 /**
1830  * gtk_false:
1831  *
1832  * Analogical to gtk_true(), this function does nothing
1833  * but always returns %FALSE.
1834  *
1835  * Returns: %FALSE
1836  */
1837 gboolean
1838 gtk_false (void)
1839 {
1840   return FALSE;
1841 }
1842
1843 static GtkWindowGroup *
1844 gtk_main_get_window_group (GtkWidget *widget)
1845 {
1846   GtkWidget *toplevel = NULL;
1847
1848   if (widget)
1849     toplevel = gtk_widget_get_toplevel (widget);
1850
1851   if (GTK_IS_WINDOW (toplevel))
1852     return gtk_window_get_group (GTK_WINDOW (toplevel));
1853   else
1854     return gtk_window_get_group (NULL);
1855 }
1856
1857 typedef struct
1858 {
1859   GtkWidget *old_grab_widget;
1860   GtkWidget *new_grab_widget;
1861   gboolean   was_grabbed;
1862   gboolean   is_grabbed;
1863   gboolean   from_grab;
1864   GList     *notified_windows;
1865   GdkDevice *device;
1866 } GrabNotifyInfo;
1867
1868 static void
1869 synth_crossing_for_grab_notify (GtkWidget       *from,
1870                                 GtkWidget       *to,
1871                                 GrabNotifyInfo  *info,
1872                                 GList           *devices,
1873                                 GdkCrossingMode  mode)
1874 {
1875   while (devices)
1876     {
1877       GdkDevice *device = devices->data;
1878       GdkWindow *from_window, *to_window;
1879
1880       /* Do not propagate events more than once to
1881        * the same windows if non-multidevice aware.
1882        */
1883       if (!from)
1884         from_window = NULL;
1885       else
1886         {
1887           from_window = _gtk_widget_get_device_window (from, device);
1888
1889           if (from_window &&
1890               !gdk_window_get_support_multidevice (from_window) &&
1891               g_list_find (info->notified_windows, from_window))
1892             from_window = NULL;
1893         }
1894
1895       if (!to)
1896         to_window = NULL;
1897       else
1898         {
1899           to_window = _gtk_widget_get_device_window (to, device);
1900
1901           if (to_window &&
1902               !gdk_window_get_support_multidevice (to_window) &&
1903               g_list_find (info->notified_windows, to_window))
1904             to_window = NULL;
1905         }
1906
1907       if (from_window || to_window)
1908         {
1909           _gtk_widget_synthesize_crossing ((from_window) ? from : NULL,
1910                                            (to_window) ? to : NULL,
1911                                            device, mode);
1912
1913           if (from_window)
1914             info->notified_windows = g_list_prepend (info->notified_windows, from_window);
1915
1916           if (to_window)
1917             info->notified_windows = g_list_prepend (info->notified_windows, to_window);
1918         }
1919
1920       devices = devices->next;
1921     }
1922 }
1923
1924 static void
1925 gtk_grab_notify_foreach (GtkWidget *child,
1926                          gpointer   data)
1927 {
1928   GrabNotifyInfo *info = data;
1929   gboolean was_grabbed, is_grabbed, was_shadowed, is_shadowed;
1930   GList *devices;
1931
1932   was_grabbed = info->was_grabbed;
1933   is_grabbed = info->is_grabbed;
1934
1935   info->was_grabbed = info->was_grabbed || (child == info->old_grab_widget);
1936   info->is_grabbed = info->is_grabbed || (child == info->new_grab_widget);
1937
1938   was_shadowed = info->old_grab_widget && !info->was_grabbed;
1939   is_shadowed = info->new_grab_widget && !info->is_grabbed;
1940
1941   g_object_ref (child);
1942
1943   if ((was_shadowed || is_shadowed) && GTK_IS_CONTAINER (child))
1944     gtk_container_forall (GTK_CONTAINER (child), gtk_grab_notify_foreach, info);
1945
1946   if (info->device &&
1947       _gtk_widget_get_device_window (child, info->device))
1948     {
1949       /* Device specified and is on widget */
1950       devices = g_list_prepend (NULL, info->device);
1951     }
1952   else
1953     devices = _gtk_widget_list_devices (child);
1954
1955   if (is_shadowed)
1956     {
1957       _gtk_widget_set_shadowed (child, TRUE);
1958       if (!was_shadowed && devices &&
1959           gtk_widget_is_sensitive (child))
1960         synth_crossing_for_grab_notify (child, info->new_grab_widget,
1961                                         info, devices,
1962                                         GDK_CROSSING_GTK_GRAB);
1963     }
1964   else
1965     {
1966       _gtk_widget_set_shadowed (child, FALSE);
1967       if (was_shadowed && devices &&
1968           gtk_widget_is_sensitive (child))
1969         synth_crossing_for_grab_notify (info->old_grab_widget, child,
1970                                         info, devices,
1971                                         info->from_grab ? GDK_CROSSING_GTK_GRAB :
1972                                         GDK_CROSSING_GTK_UNGRAB);
1973     }
1974
1975   if (was_shadowed != is_shadowed)
1976     _gtk_widget_grab_notify (child, was_shadowed);
1977
1978   g_object_unref (child);
1979   g_list_free (devices);
1980
1981   info->was_grabbed = was_grabbed;
1982   info->is_grabbed = is_grabbed;
1983 }
1984
1985 static void
1986 gtk_grab_notify (GtkWindowGroup *group,
1987                  GdkDevice      *device,
1988                  GtkWidget      *old_grab_widget,
1989                  GtkWidget      *new_grab_widget,
1990                  gboolean        from_grab)
1991 {
1992   GList *toplevels;
1993   GrabNotifyInfo info = { 0 };
1994
1995   if (old_grab_widget == new_grab_widget)
1996     return;
1997
1998   info.old_grab_widget = old_grab_widget;
1999   info.new_grab_widget = new_grab_widget;
2000   info.from_grab = from_grab;
2001   info.device = device;
2002
2003   g_object_ref (group);
2004
2005   toplevels = gtk_window_list_toplevels ();
2006   g_list_foreach (toplevels, (GFunc)g_object_ref, NULL);
2007
2008   while (toplevels)
2009     {
2010       GtkWindow *toplevel = toplevels->data;
2011       toplevels = g_list_delete_link (toplevels, toplevels);
2012
2013       info.was_grabbed = FALSE;
2014       info.is_grabbed = FALSE;
2015
2016       if (group == gtk_window_get_group (toplevel))
2017         gtk_grab_notify_foreach (GTK_WIDGET (toplevel), &info);
2018       g_object_unref (toplevel);
2019     }
2020
2021   g_list_free (info.notified_windows);
2022   g_object_unref (group);
2023 }
2024
2025 /**
2026  * gtk_grab_add: (method)
2027  * @widget: The widget that grabs keyboard and pointer events
2028  *
2029  * Makes @widget the current grabbed widget.
2030  *
2031  * This means that interaction with other widgets in the same
2032  * application is blocked and mouse as well as keyboard events
2033  * are delivered to this widget.
2034  *
2035  * If @widget is not sensitive, it is not set as the current
2036  * grabbed widget and this function does nothing.
2037  */
2038 void
2039 gtk_grab_add (GtkWidget *widget)
2040 {
2041   GtkWindowGroup *group;
2042   GtkWidget *old_grab_widget;
2043
2044   g_return_if_fail (widget != NULL);
2045
2046   if (!gtk_widget_has_grab (widget) && gtk_widget_is_sensitive (widget))
2047     {
2048       _gtk_widget_set_has_grab (widget, TRUE);
2049
2050       group = gtk_main_get_window_group (widget);
2051
2052       old_grab_widget = gtk_window_group_get_current_grab (group);
2053
2054       g_object_ref (widget);
2055       _gtk_window_group_add_grab (group, widget);
2056
2057       gtk_grab_notify (group, NULL, old_grab_widget, widget, TRUE);
2058     }
2059 }
2060
2061 /**
2062  * gtk_grab_get_current:
2063  *
2064  * Queries the current grab of the default window group.
2065  *
2066  * Return value: (transfer none): The widget which currently
2067  *     has the grab or %NULL if no grab is active
2068  */
2069 GtkWidget*
2070 gtk_grab_get_current (void)
2071 {
2072   GtkWindowGroup *group;
2073
2074   group = gtk_main_get_window_group (NULL);
2075
2076   return gtk_window_group_get_current_grab (group);
2077 }
2078
2079 /**
2080  * gtk_grab_remove: (method)
2081  * @widget: The widget which gives up the grab
2082  *
2083  * Removes the grab from the given widget.
2084  *
2085  * You have to pair calls to gtk_grab_add() and gtk_grab_remove().
2086  *
2087  * If @widget does not have the grab, this function does nothing.
2088  */
2089 void
2090 gtk_grab_remove (GtkWidget *widget)
2091 {
2092   GtkWindowGroup *group;
2093   GtkWidget *new_grab_widget;
2094
2095   g_return_if_fail (widget != NULL);
2096
2097   if (gtk_widget_has_grab (widget))
2098     {
2099       _gtk_widget_set_has_grab (widget, FALSE);
2100
2101       group = gtk_main_get_window_group (widget);
2102       _gtk_window_group_remove_grab (group, widget);
2103       new_grab_widget = gtk_window_group_get_current_grab (group);
2104
2105       gtk_grab_notify (group, NULL, widget, new_grab_widget, FALSE);
2106
2107       g_object_unref (widget);
2108     }
2109 }
2110
2111 /**
2112  * gtk_device_grab_add:
2113  * @widget: a #GtkWidget
2114  * @device: a #GdkDevice to grab on.
2115  * @block_others: %TRUE to prevent other devices to interact with @widget.
2116  *
2117  * Adds a GTK+ grab on @device, so all the events on @device and its
2118  * associated pointer or keyboard (if any) are delivered to @widget.
2119  * If the @block_others parameter is %TRUE, any other devices will be
2120  * unable to interact with @widget during the grab.
2121  *
2122  * Since: 3.0
2123  */
2124 void
2125 gtk_device_grab_add (GtkWidget *widget,
2126                      GdkDevice *device,
2127                      gboolean   block_others)
2128 {
2129   GtkWindowGroup *group;
2130   GtkWidget *old_grab_widget;
2131
2132   g_return_if_fail (GTK_IS_WIDGET (widget));
2133   g_return_if_fail (GDK_IS_DEVICE (device));
2134
2135   group = gtk_main_get_window_group (widget);
2136   old_grab_widget = gtk_window_group_get_current_device_grab (group, device);
2137
2138   if (old_grab_widget != widget)
2139     _gtk_window_group_add_device_grab (group, widget, device, block_others);
2140
2141   gtk_grab_notify (group, device, old_grab_widget, widget, TRUE);
2142 }
2143
2144 /**
2145  * gtk_device_grab_remove:
2146  * @widget: a #GtkWidget
2147  * @device: a #GdkDevice
2148  *
2149  * Removes a device grab from the given widget.
2150  *
2151  * You have to pair calls to gtk_device_grab_add() and
2152  * gtk_device_grab_remove().
2153  *
2154  * Since: 3.0
2155  */
2156 void
2157 gtk_device_grab_remove (GtkWidget *widget,
2158                         GdkDevice *device)
2159 {
2160   GtkWindowGroup *group;
2161   GtkWidget *new_grab_widget;
2162
2163   g_return_if_fail (GTK_IS_WIDGET (widget));
2164   g_return_if_fail (GDK_IS_DEVICE (device));
2165
2166   group = gtk_main_get_window_group (widget);
2167   _gtk_window_group_remove_device_grab (group, widget, device);
2168   new_grab_widget = gtk_window_group_get_current_device_grab (group, device);
2169
2170   gtk_grab_notify (group, device, widget, new_grab_widget, FALSE);
2171 }
2172
2173 /**
2174  * gtk_key_snooper_install: (skip)
2175  * @snooper: a #GtkKeySnoopFunc
2176  * @func_data: data to pass to @snooper
2177  *
2178  * Installs a key snooper function, which will get called on all
2179  * key events before delivering them normally.
2180  *
2181  * Returns: a unique id for this key snooper for use with
2182  *    gtk_key_snooper_remove().
2183  *
2184  * Deprecated: 3.4: Key snooping should not be done. Events should
2185  *     be handled by widgets.
2186  */
2187 guint
2188 gtk_key_snooper_install (GtkKeySnoopFunc snooper,
2189                          gpointer        func_data)
2190 {
2191   GtkKeySnooperData *data;
2192   static guint snooper_id = 1;
2193
2194   g_return_val_if_fail (snooper != NULL, 0);
2195
2196   data = g_new (GtkKeySnooperData, 1);
2197   data->func = snooper;
2198   data->func_data = func_data;
2199   data->id = snooper_id++;
2200   key_snoopers = g_slist_prepend (key_snoopers, data);
2201
2202   return data->id;
2203 }
2204
2205 /**
2206  * gtk_key_snooper_remove:
2207  * @snooper_handler_id: Identifies the key snooper to remove
2208  *
2209  * Removes the key snooper function with the given id.
2210  *
2211  * Deprecated: 3.4: Key snooping should not be done. Events should
2212  *     be handled by widgets.
2213  */
2214 void
2215 gtk_key_snooper_remove (guint snooper_id)
2216 {
2217   GtkKeySnooperData *data = NULL;
2218   GSList *slist;
2219
2220   slist = key_snoopers;
2221   while (slist)
2222     {
2223       data = slist->data;
2224       if (data->id == snooper_id)
2225         break;
2226
2227       slist = slist->next;
2228       data = NULL;
2229     }
2230   if (data)
2231     {
2232       key_snoopers = g_slist_remove (key_snoopers, data);
2233       g_free (data);
2234     }
2235 }
2236
2237 static gint
2238 gtk_invoke_key_snoopers (GtkWidget *grab_widget,
2239                          GdkEvent  *event)
2240 {
2241   GSList *slist;
2242   gint return_val = FALSE;
2243
2244   return_val = _gail_util_key_snooper (grab_widget, (GdkEventKey *) event);
2245
2246   slist = key_snoopers;
2247   while (slist && !return_val)
2248     {
2249       GtkKeySnooperData *data;
2250
2251       data = slist->data;
2252       slist = slist->next;
2253       return_val = (*data->func) (grab_widget, (GdkEventKey*) event, data->func_data);
2254     }
2255
2256   return return_val;
2257 }
2258
2259 /**
2260  * gtk_get_current_event:
2261  *
2262  * Obtains a copy of the event currently being processed by GTK+.
2263  *
2264  * For example, if you are handling a #GtkButton::clicked signal,
2265  * the current event will be the #GdkEventButton that triggered
2266  * the ::clicked signal.
2267  *
2268  * Return value: (transfer full): a copy of the current event, or
2269  *     %NULL if there is no current event. The returned event must be
2270  *     freed with gdk_event_free().
2271  */
2272 GdkEvent*
2273 gtk_get_current_event (void)
2274 {
2275   if (current_events)
2276     return gdk_event_copy (current_events->data);
2277   else
2278     return NULL;
2279 }
2280
2281 /**
2282  * gtk_get_current_event_time:
2283  *
2284  * If there is a current event and it has a timestamp,
2285  * return that timestamp, otherwise return %GDK_CURRENT_TIME.
2286  *
2287  * Return value: the timestamp from the current event,
2288  *     or %GDK_CURRENT_TIME.
2289  */
2290 guint32
2291 gtk_get_current_event_time (void)
2292 {
2293   if (current_events)
2294     return gdk_event_get_time (current_events->data);
2295   else
2296     return GDK_CURRENT_TIME;
2297 }
2298
2299 /**
2300  * gtk_get_current_event_state:
2301  * @state: (out): a location to store the state of the current event
2302  *
2303  * If there is a current event and it has a state field, place
2304  * that state field in @state and return %TRUE, otherwise return
2305  * %FALSE.
2306  *
2307  * Return value: %TRUE if there was a current event and it
2308  *     had a state field
2309  */
2310 gboolean
2311 gtk_get_current_event_state (GdkModifierType *state)
2312 {
2313   g_return_val_if_fail (state != NULL, FALSE);
2314
2315   if (current_events)
2316     return gdk_event_get_state (current_events->data, state);
2317   else
2318     {
2319       *state = 0;
2320       return FALSE;
2321     }
2322 }
2323
2324 /**
2325  * gtk_get_current_event_device:
2326  *
2327  * If there is a current event and it has a device, return that
2328  * device, otherwise return %NULL.
2329  *
2330  * Returns: (transfer none): a #GdkDevice, or %NULL
2331  */
2332 GdkDevice *
2333 gtk_get_current_event_device (void)
2334 {
2335   if (current_events)
2336     return gdk_event_get_device (current_events->data);
2337   else
2338     return NULL;
2339 }
2340
2341 /**
2342  * gtk_get_event_widget:
2343  * @event: a #GdkEvent
2344  *
2345  * If @event is %NULL or the event was not associated with any widget,
2346  * returns %NULL, otherwise returns the widget that received the event
2347  * originally.
2348  *
2349  * Return value: (transfer none): the widget that originally
2350  *     received @event, or %NULL
2351  */
2352 GtkWidget*
2353 gtk_get_event_widget (GdkEvent *event)
2354 {
2355   GtkWidget *widget;
2356   gpointer widget_ptr;
2357
2358   widget = NULL;
2359   if (event && event->any.window &&
2360       (event->type == GDK_DESTROY || !gdk_window_is_destroyed (event->any.window)))
2361     {
2362       gdk_window_get_user_data (event->any.window, &widget_ptr);
2363       widget = widget_ptr;
2364     }
2365
2366   return widget;
2367 }
2368
2369 static gboolean
2370 propagate_event_up (GtkWidget *widget,
2371                     GdkEvent  *event,
2372                     GtkWidget *topmost)
2373 {
2374   gboolean handled_event = FALSE;
2375
2376   /* Propagate event up the widget tree so that
2377    * parents can see the button and motion
2378    * events of the children.
2379    */
2380   while (TRUE)
2381     {
2382       GtkWidget *tmp;
2383
2384       g_object_ref (widget);
2385
2386       /* Scroll events are special cased here because it
2387        * feels wrong when scrolling a GtkViewport, say,
2388        * to have children of the viewport eat the scroll
2389        * event
2390        */
2391       if (!gtk_widget_is_sensitive (widget))
2392         handled_event = event->type != GDK_SCROLL;
2393       else
2394         handled_event = gtk_widget_event (widget, event);
2395
2396       tmp = gtk_widget_get_parent (widget);
2397       g_object_unref (widget);
2398
2399       if (widget == topmost)
2400         break;
2401
2402       widget = tmp;
2403
2404       if (handled_event || !widget)
2405         break;
2406     }
2407
2408   return handled_event;
2409 }
2410
2411 static gboolean
2412 propagate_event_down (GtkWidget *widget,
2413                       GdkEvent  *event,
2414                       GtkWidget *topmost)
2415 {
2416   gint handled_event = FALSE;
2417   GList *widgets = NULL;
2418   GList *l;
2419
2420   widgets = g_list_prepend (widgets, g_object_ref (widget));
2421   while (widget && widget != topmost)
2422     {
2423       widget = gtk_widget_get_parent (widget);
2424       if (!widget)
2425         break;
2426
2427       widgets = g_list_prepend (widgets, g_object_ref (widget));
2428
2429       if (widget == topmost)
2430         break;
2431     }
2432
2433   for (l = widgets; l && !handled_event; l = g_list_next (l))
2434     {
2435       widget = (GtkWidget *)l->data;
2436
2437       if (!gtk_widget_is_sensitive (widget))
2438         {
2439           /* stop propagating on SCROLL, but don't handle the event, so it
2440            * can propagate up again and reach its handling widget
2441            */
2442           if (event->type == GDK_SCROLL)
2443             break;
2444           else
2445             handled_event = TRUE;
2446         }
2447       else
2448         handled_event = _gtk_widget_captured_event (widget, event);
2449     }
2450   g_list_free_full (widgets, (GDestroyNotify)g_object_unref);
2451
2452   return handled_event;
2453 }
2454
2455 static gboolean
2456 propagate_event (GtkWidget *widget,
2457                  GdkEvent  *event,
2458                  gboolean   captured,
2459                  GtkWidget *topmost)
2460 {
2461   gboolean handled_event = FALSE;
2462   gboolean (* propagate_func) (GtkWidget *widget, GdkEvent  *event);
2463
2464   propagate_func = captured ? _gtk_widget_captured_event : gtk_widget_event;
2465
2466   if (event->type == GDK_KEY_PRESS || event->type == GDK_KEY_RELEASE)
2467     {
2468       /* Only send key events within Window widgets to the Window
2469        * The Window widget will in turn pass the
2470        * key event on to the currently focused widget
2471        * for that window.
2472        */
2473       GtkWidget *window;
2474
2475       window = gtk_widget_get_toplevel (widget);
2476       if (GTK_IS_WINDOW (window))
2477         {
2478           g_object_ref (widget);
2479           /* If there is a grab within the window, give the grab widget
2480            * a first crack at the key event
2481            */
2482           if (widget != window && gtk_widget_has_grab (widget))
2483             handled_event = propagate_func (widget, event);
2484
2485           if (!handled_event)
2486             {
2487               window = gtk_widget_get_toplevel (widget);
2488               if (GTK_IS_WINDOW (window))
2489                 {
2490                   if (gtk_widget_is_sensitive (window))
2491                     handled_event = propagate_func (window, event);
2492                 }
2493             }
2494
2495           g_object_unref (widget);
2496           return handled_event;
2497         }
2498     }
2499
2500   /* Other events get propagated up/down the widget tree */
2501   return captured ?
2502     propagate_event_down (widget, event, topmost) :
2503     propagate_event_up (widget, event, topmost);
2504 }
2505
2506 /**
2507  * gtk_propagate_event:
2508  * @widget: a #GtkWidget
2509  * @event: an event
2510  *
2511  * Sends an event to a widget, propagating the event to parent widgets
2512  * if the event remains unhandled.
2513  *
2514  * Events received by GTK+ from GDK normally begin in gtk_main_do_event().
2515  * Depending on the type of event, existence of modal dialogs, grabs, etc.,
2516  * the event may be propagated; if so, this function is used.
2517  *
2518  * gtk_propagate_event() calls gtk_widget_event() on each widget it
2519  * decides to send the event to. So gtk_widget_event() is the lowest-level
2520  * function; it simply emits the #GtkWidget::event and possibly an
2521  * event-specific signal on a widget. gtk_propagate_event() is a bit
2522  * higher-level, and gtk_main_do_event() is the highest level.
2523  *
2524  * All that said, you most likely don't want to use any of these
2525  * functions; synthesizing events is rarely needed. There are almost
2526  * certainly better ways to achieve your goals. For example, use
2527  * gdk_window_invalidate_rect() or gtk_widget_queue_draw() instead
2528  * of making up expose events.
2529  */
2530 void
2531 gtk_propagate_event (GtkWidget *widget,
2532                      GdkEvent  *event)
2533 {
2534   g_return_if_fail (GTK_IS_WIDGET (widget));
2535   g_return_if_fail (event != NULL);
2536
2537   propagate_event (widget, event, FALSE, NULL);
2538 }
2539
2540 gboolean
2541 _gtk_propagate_captured_event (GtkWidget *widget,
2542                                GdkEvent  *event,
2543                                GtkWidget *topmost)
2544 {
2545   return propagate_event (widget, event, TRUE, topmost);
2546 }