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