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