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