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