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