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