gtkmain.c 73.3 KB
Newer Older
Cody Russell's avatar
Cody Russell committed
1
/* GTK - The GIMP Toolkit
Elliot Lee's avatar
Elliot Lee committed
2 3 4
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
Elliot Lee's avatar
Elliot Lee committed
6 7 8 9 10
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * 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.
Elliot Lee's avatar
Elliot Lee committed
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
Javier Jardón's avatar
Javier Jardón committed
15
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
Elliot Lee's avatar
Elliot Lee committed
16
 */
17 18

/*
19
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
20 21 22 23 24
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
 */

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/**
 * SECTION:gtkmain
 * @Short_description: Library initialization, main event loop, and events
 * @Title: Main loop and Events
 * @See_also:See the GLib manual, especially #GMainLoop and signal-related
 *    functions such as g_signal_connect()
 *
 * Before using GTK+, you need to initialize it; initialization connects to the
 * window system display, and parses some standard command line arguments. The
 * gtk_init() macro initializes GTK+. gtk_init() exits the application if errors
 * occur; to avoid this, use gtk_init_check(). gtk_init_check() allows you to
 * recover from a failed GTK+ initialization - you might start up your
 * application in text mode instead.
 *
 * Like all GUI toolkits, GTK+ uses an event-driven programming model. When the
 * user is doing nothing, GTK+ sits in the <firstterm>main loop</firstterm> and
 * waits for input. If the user performs some action - say, a mouse click - then
 * the main loop "wakes up" and delivers an event to GTK+. GTK+ forwards the
 * event to one or more widgets.
 *
 * When widgets receive an event, they frequently emit one or more
 * <firstterm>signals</firstterm>. Signals notify your program that "something
 * interesting happened" by invoking functions you've connected to the signal
 * with g_signal_connect(). Functions connected to a signal are often termed
 * <firstterm>callbacks</firstterm>.
 *
 * When your callbacks are invoked, you would typically take some action - for
 * example, when an Open button is clicked you might display a
53
 * #GtkFileChooserDialog. After a callback finishes, GTK+ will return to the
54 55 56 57
 * main loop and await more user input.
 * </para>
 * <example>
 * <title>Typical <function>main()</function> function for a GTK+ application</title>
58
 * <programlisting>
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
 * int
 * main (int argc, char **argv)
 * {
 *   /&ast; Initialize i18n support &ast;/
 *   gtk_set_locale ();
 *
 *   /&ast; Initialize the widget set &ast;/
 *   gtk_init (&argc, &argv);
 *
 *   /&ast; Create the main window &ast;/
 *   mainwin = gtk_window_new (GTK_WINDOW_TOPLEVEL);
 *
 *   /&ast; Set up our GUI elements &ast;/
 *   ...
 *
 *   /&ast; Show the application window &ast;/
 *   gtk_widget_show_all (mainwin);
 *
 *   /&ast; Enter the main event loop, and wait for user interaction &ast;/
 *   gtk_main ();
 *
 *   /&ast; The user lost interest &ast;/
 *   return 0;
 * }
83
 * </programlisting>
84 85 86 87 88 89
 * </example>
 * <para>
 * It's OK to use the GLib main loop directly instead of gtk_main(), though it
 * involves slightly more typing. See #GMainLoop in the GLib documentation.
 */

90
#include "config.h"
91

92
#include "gdk/gdk.h"
93

94
#include <locale.h>
Robert Brady's avatar
Robert Brady committed
95

Elliot Lee's avatar
Elliot Lee committed
96 97
#include <stdio.h>
#include <stdlib.h>
98
#include <string.h>
99
#ifdef HAVE_UNISTD_H
100 101
#include <unistd.h>
#endif
102
#include <sys/types.h>          /* For uid_t, gid_t */
103

Tor Lillqvist's avatar
Tor Lillqvist committed
104 105 106 107 108
#ifdef G_OS_WIN32
#define STRICT
#include <windows.h>
#undef STRICT
#endif
109

Tor Lillqvist's avatar
Tor Lillqvist committed
110 111
#include "gtkintl.h"

112
#include "gtkaccelmapprivate.h"
113
#include "gtkbox.h"
114
#include "gtkclipboard.h"
115
#include "gtkdebug.h"
116
#include "gtkdnd.h"
117 118
#include "gtkmain.h"
#include "gtkmenu.h"
119
#include "gtkmodules.h"
120
#include "gtkmodulesprivate.h"
121
#include "gtkprivate.h"
122
#include "gtkrecentmanager.h"
123
#include "gtkresources.h"
124
#include "gtkselectionprivate.h"
125
#include "gtksettingsprivate.h"
126 127
#include "gtktooltip.h"
#include "gtkversion.h"
Emmanuele Bassi's avatar
Emmanuele Bassi committed
128
#include "gtkwidgetprivate.h"
129
#include "gtkwindowprivate.h"
130

131
#include "a11y/gailutil.h"
132

Elliot Lee's avatar
Elliot Lee committed
133 134
/* Private type definitions
 */
135
typedef struct _GtkKeySnooperData        GtkKeySnooperData;
Elliot Lee's avatar
Elliot Lee committed
136

137 138 139 140
struct _GtkKeySnooperData
{
  GtkKeySnoopFunc func;
  gpointer func_data;
141
  guint id;
142 143
};

144 145
static gint  gtk_invoke_key_snoopers     (GtkWidget          *grab_widget,
                                          GdkEvent           *event);
146

147 148
static GtkWindowGroup *gtk_main_get_window_group (GtkWidget   *widget);

149
static guint gtk_main_loop_level = 0;
Matthias Clasen's avatar
Matthias Clasen committed
150
static gint pre_initialized = FALSE;
151
static gint gtk_initialized = FALSE;
152
static GList *current_events = NULL;
Elliot Lee's avatar
Elliot Lee committed
153

154 155
static GSList *main_loops = NULL;      /* stack of currently executing main loops */

156 157
static GSList *key_snoopers = NULL;

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 */
Elliot Lee's avatar
Elliot Lee committed
177

178
/**
179
 * gtk_get_major_version:
180
 *
181 182
 * Returns the major version number of the GTK+ library.
 * (e.g. in GTK+ version 3.1.5 this is 3.)
183 184 185 186 187 188
 *
 * This function is in the library, so it represents the GTK+ library
 * your code is running against. Contrast with the #GTK_MAJOR_VERSION
 * macro, which represents the major version of the GTK+ headers you
 * have included when compiling your code.
 *
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 197 198 199
{
  return GTK_MAJOR_VERSION;
}

/**
200
 * gtk_get_minor_version:
201
 *
202 203
 * Returns the minor version number of the GTK+ library.
 * (e.g. in GTK+ version 3.1.5 this is 1.)
204 205 206 207 208 209
 *
 * This function is in the library, so it represents the GTK+ library
 * your code is are running against. Contrast with the
 * #GTK_MINOR_VERSION macro, which represents the minor version of the
 * GTK+ headers you have included when compiling your code.
 *
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 218 219 220
{
  return GTK_MINOR_VERSION;
}

/**
221
 * gtk_get_micro_version:
222
 *
223 224
 * Returns the micro version number of the GTK+ library.
 * (e.g. in GTK+ version 3.1.5 this is 5.)
225 226 227 228 229 230
 *
 * This function is in the library, so it represents the GTK+ library
 * your code is are running against. Contrast with the
 * #GTK_MICRO_VERSION macro, which represents the micro version of the
 * GTK+ headers you have included when compiling your code.
 *
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 239 240 241
{
  return GTK_MICRO_VERSION;
}

/**
242
 * gtk_get_binary_age:
243
 *
244 245 246
 * Returns the binary age as passed to <application>libtool</application>
 * when building the GTK+ library the process is running against.
 * If <application>libtool</application> means nothing to you, don't
247 248
 * worry about it.
 *
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 257 258 259
{
  return GTK_BINARY_AGE;
}

/**
260
 * gtk_get_interface_age:
261
 *
262 263 264
 * Returns the interface age as passed to <application>libtool</application>
 * when building the GTK+ library the process is running against.
 * If <application>libtool</application> means nothing to you, don't
265 266
 * worry about it.
 *
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 275 276
{
  return GTK_INTERFACE_AGE;
}

277 278
/**
 * gtk_check_version:
279 280 281 282
 * @required_major: the required major version
 * @required_minor: the required minor version
 * @required_micro: the required micro version
 *
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
 * Checks that the GTK+ library in use is compatible with the
 * given version. Generally you would pass in the constants
 * #GTK_MAJOR_VERSION, #GTK_MINOR_VERSION, #GTK_MICRO_VERSION
 * as the three arguments to this function; that produces
 * a check that the library in use is compatible with
 * the version of GTK+ the application or module was compiled
 * against.
 *
 * Compatibility is defined by two things: first the version
 * of the running library is newer than the version
 * @required_major.required_minor.@required_micro. Second
 * the running library must be binary compatible with the
 * version @required_major.required_minor.@required_micro
 * (same major version.)
 *
 * This function is primarily for GTK+ modules; the module
 * can call this function to check that it wasn't loaded
 * into an incompatible version of GTK+. However, such a
301
 * check isn't completely reliable, since the module may be
302 303 304 305 306 307 308 309
 * linked against an old version of GTK+ and calling the
 * old version of gtk_check_version(), but still get loaded
 * into an application using a newer version of GTK+.
 *
 * Return value: %NULL if the GTK+ library is compatible with the
 *   given version, or a string describing the version mismatch.
 *   The returned string is owned by GTK+ and should not be modified
 *   or freed.
310
 */
311
const gchar*
312
gtk_check_version (guint required_major,
313 314
                   guint required_minor,
                   guint required_micro)
315
{
316 317 318
  gint gtk_effective_micro = 100 * GTK_MINOR_VERSION + GTK_MICRO_VERSION;
  gint required_effective_micro = 100 * required_minor + required_micro;

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 328 329
  return NULL;
}

Owen Taylor's avatar
Owen Taylor committed
330 331 332 333 334 335 336 337 338 339
/* This checks to see if the process is running suid or sgid
 * at the current time. If so, we don't allow GTK+ to be initialized.
 * This is meant to be a mild check - we only error out if we
 * can prove the programmer is doing something wrong, not if
 * they could be doing something wrong. For this reason, we
 * don't use issetugid() on BSD or prctl (PR_GET_DUMPABLE).
 */
static gboolean
check_setugid (void)
{
340
/* this isn't at all relevant on MS Windows and doesn't compile ... --hb */
341
#ifndef G_OS_WIN32
Owen Taylor's avatar
Owen Taylor committed
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
  gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
  
#ifdef HAVE_GETRESUID
  /* These aren't in the header files, so we prototype them here.
   */
  int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
  int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);

  if (getresuid (&ruid, &euid, &suid) != 0 ||
      getresgid (&rgid, &egid, &sgid) != 0)
#endif /* HAVE_GETRESUID */
    {
      suid = ruid = getuid ();
      sgid = rgid = getgid ();
      euid = geteuid ();
      egid = getegid ();
    }

  if (ruid != euid || ruid != suid ||
      rgid != egid || rgid != sgid)
    {
      g_warning ("This process is currently running setuid or setgid.\n"
365 366 367 368
                 "This is not a supported use of GTK+. You must create a helper\n"
                 "program instead. For further details, see:\n\n"
                 "    http://www.gtk.org/setuid.html\n\n"
                 "Refusing to initialize GTK+.");
Owen Taylor's avatar
Owen Taylor committed
369 370
      exit (1);
    }
371
#endif
Owen Taylor's avatar
Owen Taylor committed
372 373 374
  return TRUE;
}

375 376 377 378 379
static gboolean do_setlocale = TRUE;

/**
 * gtk_disable_setlocale:
 * 
380 381
 * Prevents gtk_init(), gtk_init_check(), gtk_init_with_args() and
 * gtk_parse_args() from automatically
382 383 384
 * calling <literal>setlocale (LC_ALL, "")</literal>. You would
 * want to use this function if you wanted to set the locale for
 * 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 388
 *
 * Most programs should not need to call this function.
 **/
389
void
390 391
gtk_disable_setlocale (void)
{
Matthias Clasen's avatar
Matthias Clasen committed
392
  if (pre_initialized)
393 394 395 396 397
    g_warning ("gtk_disable_setlocale() must be called before gtk_init()");
    
  do_setlocale = FALSE;
}

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 406 407

#ifdef G_ENABLE_DEBUG
static gboolean
gtk_arg_debug_cb (const char *key, const char *value, gpointer user_data)
Elliot Lee's avatar
Elliot Lee committed
408
{
409
  debug_flags |= g_parse_debug_string (value,
410 411
                                       gtk_debug_keys,
                                       G_N_ELEMENTS (gtk_debug_keys));
412

413 414
  return TRUE;
}
Tim Janik's avatar
Tim Janik committed
415

416 417 418
static gboolean
gtk_arg_no_debug_cb (const char *key, const char *value, gpointer user_data)
{
419
  debug_flags &= ~g_parse_debug_string (value,
420 421
                                        gtk_debug_keys,
                                        G_N_ELEMENTS (gtk_debug_keys));
422 423

  return TRUE;
424 425 426 427 428 429 430 431 432
}
#endif /* G_ENABLE_DEBUG */

static gboolean
gtk_arg_module_cb (const char *key, const char *value, gpointer user_data)
{
  if (value && *value)
    {
      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 438 439 440 441 442
      
      g_string_append (gtk_modules_string, value);
    }

  return TRUE;
}

Matthias Clasen's avatar
Matthias Clasen committed
443
static const GOptionEntry gtk_args[] = {
444 445 446
  { "gtk-module",       0, 0, G_OPTION_ARG_CALLBACK, gtk_arg_module_cb,   
    /* Description of --gtk-module=MODULES in --help output */ N_("Load additional GTK+ modules"), 
    /* 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 451 452 453 454 455 456
  { "gtk-debug",        0, 0, G_OPTION_ARG_CALLBACK, gtk_arg_debug_cb,    
    /* Description of --gtk-debug=FLAGS in --help output */    N_("GTK+ debugging flags to set"), 
    /* Placeholder in --gtk-debug=FLAGS in --help output */    N_("FLAGS") },
  { "gtk-no-debug",     0, 0, G_OPTION_ARG_CALLBACK, gtk_arg_no_debug_cb, 
    /* Description of --gtk-no-debug=FLAGS in --help output */ N_("GTK+ debugging flags to unset"), 
    /* Placeholder in --gtk-no-debug=FLAGS in --help output */ N_("FLAGS") },
#endif 
457 458 459
  { NULL }
};

Tor Lillqvist's avatar
Tor Lillqvist committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
#ifdef G_OS_WIN32

static char *iso639_to_check = NULL;
static char *iso3166_to_check = NULL;
static char *script_to_check = NULL;
static gboolean setlocale_called = FALSE;

static BOOL CALLBACK
enum_locale_proc (LPTSTR locale)
{
  LCID lcid;
  char iso639[10];
  char iso3166[10];
  char *endptr;


  lcid = strtoul (locale, &endptr, 16);
  if (*endptr == '\0' &&
      GetLocaleInfo (lcid, LOCALE_SISO639LANGNAME, iso639, sizeof (iso639)) &&
      GetLocaleInfo (lcid, LOCALE_SISO3166CTRYNAME, iso3166, sizeof (iso3166)))
    {
      if (strcmp (iso639, iso639_to_check) == 0 &&
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
          ((iso3166_to_check != NULL &&
            strcmp (iso3166, iso3166_to_check) == 0) ||
           (iso3166_to_check == NULL &&
            SUBLANGID (LANGIDFROMLCID (lcid)) == SUBLANG_DEFAULT)))
        {
          char language[100], country[100];
          char locale[300];

          if (script_to_check != NULL)
            {
              /* If lcid is the "other" script for this language,
               * return TRUE, i.e. continue looking.
               */
              if (strcmp (script_to_check, "Latn") == 0)
                {
                  switch (LANGIDFROMLCID (lcid))
                    {
                    case MAKELANGID (LANG_AZERI, SUBLANG_AZERI_CYRILLIC):
                      return TRUE;
                    case MAKELANGID (LANG_UZBEK, SUBLANG_UZBEK_CYRILLIC):
                      return TRUE;
                    case MAKELANGID (LANG_SERBIAN, SUBLANG_SERBIAN_CYRILLIC):
                      return TRUE;
                    case MAKELANGID (LANG_SERBIAN, 0x07):
                      /* Serbian in Bosnia and Herzegovina, Cyrillic */
                      return TRUE;
                    }
                }
              else if (strcmp (script_to_check, "Cyrl") == 0)
                {
                  switch (LANGIDFROMLCID (lcid))
                    {
                    case MAKELANGID (LANG_AZERI, SUBLANG_AZERI_LATIN):
                      return TRUE;
                    case MAKELANGID (LANG_UZBEK, SUBLANG_UZBEK_LATIN):
                      return TRUE;
                    case MAKELANGID (LANG_SERBIAN, SUBLANG_SERBIAN_LATIN):
                      return TRUE;
                    case MAKELANGID (LANG_SERBIAN, 0x06):
                      /* Serbian in Bosnia and Herzegovina, Latin */
                      return TRUE;
                    }
                }
            }

          SetThreadLocale (lcid);

          if (GetLocaleInfo (lcid, LOCALE_SENGLANGUAGE, language, sizeof (language)) &&
              GetLocaleInfo (lcid, LOCALE_SENGCOUNTRY, country, sizeof (country)))
            {
              strcpy (locale, language);
              strcat (locale, "_");
              strcat (locale, country);

              if (setlocale (LC_ALL, locale) != NULL)
                setlocale_called = TRUE;
            }

          return FALSE;
        }
Tor Lillqvist's avatar
Tor Lillqvist committed
542 543 544 545 546 547 548
    }

  return TRUE;
}
  
#endif

549
static void
550
setlocale_initialization (void)
551
{
552
  static gboolean initialized = FALSE;
553

554
  if (initialized)
Matthias Clasen's avatar
Matthias Clasen committed
555
    return;
556
  initialized = TRUE;
Matthias Clasen's avatar
Matthias Clasen committed
557

558
  if (do_setlocale)
559
    {
Tor Lillqvist's avatar
Tor Lillqvist committed
560 561 562 563 564 565
#ifdef G_OS_WIN32
      /* If some of the POSIXish environment variables are set, set
       * the Win32 thread locale correspondingly.
       */ 
      char *p = getenv ("LC_ALL");
      if (p == NULL)
566
        p = getenv ("LANG");
Tor Lillqvist's avatar
Tor Lillqvist committed
567 568

      if (p != NULL)
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
        {
          p = g_strdup (p);
          if (strcmp (p, "C") == 0)
            SetThreadLocale (LOCALE_SYSTEM_DEFAULT);
          else
            {
              /* Check if one of the supported locales match the
               * environment variable. If so, use that locale.
               */
              iso639_to_check = p;
              iso3166_to_check = strchr (iso639_to_check, '_');
              if (iso3166_to_check != NULL)
                {
                  *iso3166_to_check++ = '\0';

                  script_to_check = strchr (iso3166_to_check, '@');
                  if (script_to_check != NULL)
                    *script_to_check++ = '\0';

                  /* Handle special cases. */

                  /* The standard code for Serbia and Montenegro was
                   * "CS", but MSFT uses for some reason "SP". By now
                   * (October 2006), SP has split into two, "RS" and
                   * "ME", but don't bother trying to handle those
                   * yet. Do handle the even older "YU", though.
                   */
                  if (strcmp (iso3166_to_check, "CS") == 0 ||
                      strcmp (iso3166_to_check, "YU") == 0)
                    iso3166_to_check = "SP";
                }
              else
                {
                  script_to_check = strchr (iso639_to_check, '@');
                  if (script_to_check != NULL)
                    *script_to_check++ = '\0';
                  /* LANG_SERBIAN == LANG_CROATIAN, recognize just "sr" */
                  if (strcmp (iso639_to_check, "sr") == 0)
                    iso3166_to_check = "SP";
                }

              EnumSystemLocales (enum_locale_proc, LCID_SUPPORTED);
            }
          g_free (p);
        }
Tor Lillqvist's avatar
Tor Lillqvist committed
614
      if (!setlocale_called)
615
        setlocale (LC_ALL, "");
Tor Lillqvist's avatar
Tor Lillqvist committed
616
#else
617
      if (!setlocale (LC_ALL, ""))
618
        g_warning ("Locale not supported by C library.\n\tUsing the fallback 'C' locale.");
Tor Lillqvist's avatar
Tor Lillqvist committed
619
#endif
620
    }
621 622 623 624
}

static void
do_pre_parse_initialization (int    *argc,
625
                             char ***argv)
626 627 628 629 630 631 632
{
  const gchar *env_string;
  
  if (pre_initialized)
    return;

  pre_initialized = TRUE;
633

634 635
  if (_gtk_module_has_mixed_deps (NULL))
    g_error ("GTK+ 2.x symbols detected. Using GTK+ 2.x and GTK+ 3 in the same process is not supported");
636

Matthias Clasen's avatar
Matthias Clasen committed
637
  gdk_pre_parse_libgtk_only ();
Owen Taylor's avatar
Owen Taylor committed
638
  gdk_event_handler_set ((GdkEventFunc)gtk_main_do_event, NULL, NULL);
639

640
#ifdef G_ENABLE_DEBUG
Matthias Clasen's avatar
Matthias Clasen committed
641
  env_string = g_getenv ("GTK_DEBUG");
642 643
  if (env_string != NULL)
    {
644
      debug_flags = g_parse_debug_string (env_string,
645 646
                                          gtk_debug_keys,
                                          G_N_ELEMENTS (gtk_debug_keys));
647 648
      env_string = NULL;
    }
649
#endif  /* G_ENABLE_DEBUG */
650

Matthias Clasen's avatar
Matthias Clasen committed
651
  env_string = g_getenv ("GTK_MODULES");
652
  if (env_string)
653
    gtk_modules_string = g_string_new (env_string);
654
}
655

656 657 658
static void
gettext_initialization (void)
{
659 660
  setlocale_initialization ();

661
#ifdef ENABLE_NLS
662 663
  bindtextdomain (GETTEXT_PACKAGE, _gtk_get_localedir ());
  bindtextdomain (GETTEXT_PACKAGE "-properties", _gtk_get_localedir ());
664 665 666 667 668 669 670
#    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  bind_textdomain_codeset (GETTEXT_PACKAGE "-properties", "UTF-8");
#    endif
#endif  
}

671
/* XXX: Remove me after getting rid of gail */
672
extern void _gtk_accessibility_init (void);
673

674 675
static void
do_post_parse_initialization (int    *argc,
676
                              char ***argv)
677
{
678 679 680
  if (gtk_initialized)
    return;

681 682
  gettext_initialization ();

683
#ifdef SIGPIPE
684
  signal (SIGPIPE, SIG_IGN);
685
#endif
686

687 688 689 690 691 692 693 694 695
  if (g_fatal_warnings)
    {
      GLogLevelFlags fatal_mask;

      fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
      fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
      g_log_set_always_fatal (fatal_mask);
    }

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
Robert Brady's avatar
Robert Brady committed
701 702 703
   * to be RTL, otherwise translate to default:LTR.
   * Do *not* translate it to "predefinito:LTR", if it
   * it isn't default:LTR or default:RTL it will not work 
704 705
   */
    char *e = _("default:LTR");
Matthias Clasen's avatar
Matthias Clasen committed
706
    if (strcmp (e, "default:RTL")==0) 
707
      gtk_widget_set_default_direction (GTK_TEXT_DIR_RTL);
Matthias Clasen's avatar
Matthias Clasen committed
708
    else if (strcmp (e, "default:LTR"))
709 710 711
      g_warning ("Whoever translated default:LTR did so wrongly.\n");
  }

712 713
  _gtk_register_resource ();

714 715 716 717
  /* do what the call to gtk_type_init() used to do */
  g_type_init ();

  _gtk_accel_map_init ();
718

Elliot Lee's avatar
Elliot Lee committed
719 720
  /* Set the 'initialized' flag.
   */
721
  gtk_initialized = TRUE;
722

723 724
  /* load gtk modules */
  if (gtk_modules_string)
725
    {
726 727
      _gtk_modules_init (argc, argv, gtk_modules_string->str);
      g_string_free (gtk_modules_string, TRUE);
728
    }
729 730 731 732
  else
    {
      _gtk_modules_init (argc, argv, NULL);
    }
733

734
  _gtk_accessibility_init ();
735 736 737 738 739 740 741 742 743 744
}


typedef struct
{
  gboolean open_default_display;
} OptionGroupInfo;

static gboolean
pre_parse_hook (GOptionContext *context,
745 746 747
                GOptionGroup   *group,
                gpointer        data,
                GError        **error)
748 749 750 751 752 753 754 755
{
  do_pre_parse_initialization (NULL, NULL);
  
  return TRUE;
}

static gboolean
post_parse_hook (GOptionContext *context,
756 757 758
                 GOptionGroup   *group,
                 gpointer       data,
                 GError        **error)
759 760 761 762 763 764 765
{
  OptionGroupInfo *info = data;

  
  do_post_parse_initialization (NULL, NULL);
  
  if (info->open_default_display)
766 767
    {
      if (gdk_display_open_default_libgtk_only () == NULL)
768 769 770 771 772 773 774 775 776 777
        {
          const char *display_name = gdk_get_display_arg_name ();
          g_set_error (error,
                       G_OPTION_ERROR,
                       G_OPTION_ERROR_FAILED,
                       _("Cannot open display: %s"),
                       display_name ? display_name : "" );

          return FALSE;
        }
778 779 780
    }

  return TRUE;
781 782 783
}


784 785 786
/**
 * gtk_get_debug_flags:
 *
787 788 789 790 791 792
 * Returns the GTK+ debug flags.
 *
 * This function is intended for GTK+ modules that want
 * to adjust their debug output based on GTK+ debug flags.
 *
 * Returns: the GTK+ debug flags.
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
 */
guint
gtk_get_debug_flags (void)
{
  return debug_flags;
}

/**
 * gtk_set_debug_flags:
 *
 * Sets the GTK+ debug flags.
 */
void
gtk_set_debug_flags (guint flags)
{
  debug_flags = flags;
}

811
/**
812
 * gtk_get_option_group: (skip)
813 814 815
 * @open_default_display: whether to open the default display
 *     when parsing the commandline arguments
 *
816
 * Returns a #GOptionGroup for the commandline arguments recognized
817 818 819 820
 * by GTK+ and GDK.
 *
 * You should add this group to your #GOptionContext
 * with g_option_context_add_group(), if you are using
821 822
 * g_option_context_parse() to parse your commandline arguments.
 *
823
 * Returns: a #GOptionGroup for the commandline arguments recognized
824
 *     by GTK+
825 826 827
 *
 * Since: 2.6
 */
828 829 830 831 832 833
GOptionGroup *
gtk_get_option_group (gboolean open_default_display)
{
  GOptionGroup *group;
  OptionGroupInfo *info;

834 835
  gettext_initialization ();

836 837 838 839 840 841 842 843
  info = g_new0 (OptionGroupInfo, 1);
  info->open_default_display = open_default_display;
  
  group = g_option_group_new ("gtk", _("GTK+ Options"), _("Show GTK+ Options"), info, g_free);
  g_option_group_set_parse_hooks (group, pre_parse_hook, post_parse_hook);

  gdk_add_option_entries_libgtk_only (group);
  g_option_group_add_entries (group, gtk_args);
844
  g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
845 846 847 848
  
  return group;
}

849 850
/**
 * gtk_init_with_args:
851 852 853 854 855 856
 * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
 *     your main() function (or 0 if @argv is %NULL). This will be changed if 
 *     any arguments were handled.
 * @argv: (array length=argc) (inout) (allow-none): Address of the
 *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
 *     understood by GTK+ are stripped before return.
857
 * @parameter_string: a string which is displayed in
858
 *    the first line of <option>--help</option> output, after
859
 *    <literal><replaceable>programname</replaceable> [OPTION...]</literal>
860 861
 * @entries: (array zero-terminated=1): a %NULL-terminated array
 *    of #GOptionEntrys describing the options of your program
862 863
 * @translation_domain: a translation domain to use for translating
 *    the <option>--help</option> output for the options in @entries
864 865
 *    and the @parameter_string with gettext(), or %NULL
 * @error: a return location for errors
866
 *
867 868 869
 * This function does the same work as gtk_init_check().
 * Additionally, it allows you to add your own commandline options,
 * and it automatically generates nicely formatted
870 871 872
 * <option>--help</option> output. Note that your program will
 * be terminated after writing out the help output.
 *
873 874
 * Returns: %TRUE if the windowing system has been successfully
 *     initialized, %FALSE otherwise
875
 *
876 877
 * Since: 2.6
 */
878
gboolean
879 880 881 882 883 884
gtk_init_with_args (gint                 *argc,
                    gchar              ***argv,
                    const gchar          *parameter_string,
                    const GOptionEntry   *entries,
                    const gchar          *translation_domain,
                    GError              **error)
885 886 887 888
{
  GOptionContext *context;
  GOptionGroup *gtk_group;
  gboolean retval;
Matthias Clasen's avatar
Matthias Clasen committed
889

890
  if (gtk_initialized)
891
    return gdk_display_open_default_libgtk_only () != NULL;
892

893 894
  gettext_initialization ();

Matthias Clasen's avatar
Matthias Clasen committed
895 896 897
  if (!check_setugid ())
    return FALSE;

898
  gtk_group = gtk_get_option_group (TRUE);
899

900 901
  context = g_option_context_new (parameter_string);
  g_option_context_add_group (context, gtk_group);
902 903
  g_option_context_set_translation_domain (context, translation_domain);

904 905 906
  if (entries)
    g_option_context_add_main_entries (context, entries, translation_domain);
  retval = g_option_context_parse (context, argc, argv, error);
907

908 909 910 911 912 913 914 915
  g_option_context_free (context);

  return retval;
}


/**
 * gtk_parse_args:
916
 * @argc: (inout): a pointer to the number of command line arguments
917 918
 * @argv: (array length=argc) (inout): a pointer to the array of
 *     command line arguments
919
 *
920 921 922 923 924 925 926
 * Parses command line arguments, and initializes global
 * attributes of GTK+, but does not actually open a connection
 * to a display. (See gdk_display_open(), gdk_get_display_arg_name())
 *
 * Any arguments used by GTK+ or GDK are removed from the array and
 * @argc and @argv are updated accordingly.
 *
927
 * There is no need to call this function explicitely if you are using
928 929
 * gtk_init(), or gtk_init_check().
 *
930 931
 * Return value: %TRUE if initialization succeeded, otherwise %FALSE
 */
932 933
gboolean
gtk_parse_args (int    *argc,
934
                char ***argv)
935 936
{
  GOptionContext *option_context;
937
  GOptionGroup *gtk_group;
938
  GError *error = NULL;
939 940 941 942
  
  if (gtk_initialized)
    return TRUE;

943 944
  gettext_initialization ();

945 946 947 948 949 950
  if (!check_setugid ())
    return FALSE;

  option_context = g_option_context_new (NULL);
  g_option_context_set_ignore_unknown_options (option_context, TRUE);
  g_option_context_set_help_enabled (option_context, FALSE);
951 952
  gtk_group = gtk_get_option_group (FALSE);
  g_option_context_set_main_group (option_context, gtk_group);
953 954 955 956 957 958
  if (!g_option_context_parse (option_context, argc, argv, &error))
    {
      g_warning ("%s", error->message);
      g_error_free (error);
    }

959 960
  g_option_context_free (option_context);

961 962
  return TRUE;
}
963

964
#ifdef G_PLATFORM_WIN32
965
#undef gtk_init_check
966
#endif
967 968 969

/**
 * gtk_init_check:
970
 * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
971 972
 *     your main() function (or 0 if @argv is %NULL). This will be changed if 
 *     any arguments were handled.
973
 * @argv: (array length=argc) (inout) (allow-none): Address of the
974 975
 *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
 *     understood by GTK+ are stripped before return.
976
 *
977 978 979
 * This function does the same work as gtk_init() with only a single
 * change: It does not terminate the program if the windowing system
 * can't be initialized. Instead it returns %FALSE on failure.
980
 *
981 982 983 984 985 986 987
 * This way the application can fall back to some other means of
 * communication with the user - for example a curses or command line
 * interface.
 *
 * Return value: %TRUE if the windowing system has been successfully
 *     initialized, %FALSE otherwise
 */
988
gboolean
989 990
gtk_init_check (int    *argc,
                char ***argv)
991 992 993 994
{
  if (!gtk_parse_args (argc, argv))
    return FALSE;

995
  return gdk_display_open_default_libgtk_only () != NULL;
996 997
}

998
#ifdef G_PLATFORM_WIN32
999
#undef gtk_init
1000
#endif
1001

1002
/**
Matthias Clasen's avatar
Matthias Clasen committed
1003
 * gtk_init:
1004
 * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
1005 1006
 *     your main() function (or 0 if @argv is %NULL). This will be changed if 
 *     any arguments were handled.
1007
 * @argv: (array length=argc) (inout) (allow-none): Address of the
1008
 *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
1009
 *     understood by GTK+ are stripped before return.
1010
 *
1011
 * Call this function before using any other GTK+ functions in your GUI
1012
 * applications.  It will initialize everything needed to operate the
1013
 * toolkit and parses some standard command line options.
1014
 *
1015 1016 1017 1018
 * Although you are expected to pass the @argc, @argv parameters from main() to 
 * this function, it is possible to pass %NULL if @argv is not available or 
 * commandline handling is not required.
 *
1019 1020 1021 1022 1023 1024 1025 1026
 * @argc and @argv are adjusted accordingly so your own code will
 * never see those standard arguments.
 *
 * Note that there are some alternative ways to initialize GTK+:
 * if you are calling gtk_parse_args(), gtk_init_check(),
 * gtk_init_with_args() or g_option_context_parse() with
 * the option group returned by gtk_get_option_group(),
 * you <emphasis>don't</emphasis> have to call gtk_init().
1027 1028
 *
 * <note><para>
1029 1030 1031 1032
 * This function will terminate your program if it was unable to
 * initialize the windowing system for some reason. If you want
 * your program to fall back to a textual interface you want to
 * call gtk_init_check() instead.
1033
 * </para></note>
1034 1035 1036 1037 1038 1039 1040 1041 1042
 *
 * <note><para>
 * Since 2.18, GTK+ calls <literal>signal (SIGPIPE, SIG_IGN)</literal>
 * during initialization, to ignore SIGPIPE signals, since these are
 * almost never wanted in graphical applications. If you do need to
 * handle SIGPIPE for some reason, reset the handler after gtk_init(),
 * but notice that other libraries (e.g. libdbus or gvfs) might do
 * similar things.
 * </para></note>
1043
 */
1044 1045 1046 1047 1048
void
gtk_init (int *argc, char ***argv)
{
  if (!gtk_init_check (argc, argv))
    {
1049
      const char *display_name_arg = gdk_get_display_arg_name ();
1050 1051 1052
      if (display_name_arg == NULL)
        display_name_arg = getenv("DISPLAY");
      g_warning ("cannot open display: %s", display_name_arg ? display_name_arg : "");
1053
      exit (1);
1054
    }
Elliot Lee's avatar
Elliot Lee committed
1055 1056
}

Fridrich Strba's avatar
Fridrich Strba committed
1057 1058 1059 1060 1061 1062 1063 1064
#ifdef G_OS_WIN32

/* This is relevant when building with gcc for Windows (MinGW),
 * where we want to be struct packing compatible with MSVC,
 * i.e. use the -mms-bitfields switch.
 * For Cygwin there should be no need to be compatible with MSVC,
 * so no need to use G_PLATFORM_WIN32.
 */
1065 1066 1067 1068 1069 1070

static void
check_sizeof_GtkWindow (size_t sizeof_GtkWindow)
{
  if (sizeof_GtkWindow != sizeof (GtkWindow))
    g_error ("Incompatible build!\n"
1071
             "The code using GTK+ thinks GtkWindow is of different\n"
1072
             "size than it actually is in this build of GTK+.\n"
1073 1074 1075
             "On Windows, this probably means that you have compiled\n"
             "your code with gcc without the -mms-bitfields switch,\n"
             "or that you are using an unsupported compiler.");
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
}

/* In GTK+ 2.0 the GtkWindow struct actually is the same size in
 * gcc-compiled code on Win32 whether compiled with -fnative-struct or
 * not. Unfortunately this wan't noticed until after GTK+ 2.0.1. So,
 * from GTK+ 2.0.2 on, check some other struct, too, where the use of
 * -fnative-struct still matters. GtkBox is one such.
 */
static void
check_sizeof_GtkBox (size_t sizeof_GtkBox)
{
  if (sizeof_GtkBox != sizeof (GtkBox))
    g_error ("Incompatible build!\n"
1089
             "The code using GTK+ thinks GtkBox is of different\n"
1090
             "size than it actually is in this build of GTK+.\n"
1091 1092 1093
             "On Windows, this probably means that you have compiled\n"
             "your code with gcc without the -mms-bitfields switch,\n"
             "or that you are using an unsupported compiler.");
1094 1095 1096 1097 1098 1099
}

/* These two functions might get more checks added later, thus pass
 * in the number of extra args.
 */
void
1100
gtk_init_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
1101 1102
{
  check_sizeof_GtkWindow (sizeof_GtkWindow);
1103 1104
  if (num_checks >= 2)
    check_sizeof_GtkBox (sizeof_GtkBox);
1105 1106 1107 1108
  gtk_init (argc, argv);
}

gboolean
1109
gtk_init_check_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
1110 1111
{
  check_sizeof_GtkWindow (sizeof_GtkWindow);
1112 1113
  if (num_checks >= 2)
    check_sizeof_GtkBox (sizeof_GtkBox);
1114 1115 1116 1117 1118
  return gtk_init_check (argc, argv);
}

#endif

1119 1120 1121 1122 1123
/**
 * gtk_get_default_language:
 *
 * Returns the #PangoLanguage for the default language currently in
 * effect. (Note that this can change over the life of an
1124
 * application.) The default language is derived from the current
1125
 * locale. It determines, for example, whether GTK+ uses the
1126 1127
 * right-to-left or left-to-right text direction.
 *
1128 1129 1130 1131 1132 1133
 * This function is equivalent to pango_language_get_default().
 * See that function for details.
 *
 * Return value: the default language as a #PangoLanguage,
 *     must not be freed
 */
1134 1135 1136
PangoLanguage *
gtk_get_default_language (void)
{
1137
  return pango_language_get_default ();
1138 1139
}

1140 1141 1142 1143 1144 1145 1146 1147
/**
 * gtk_main:
 *
 * Runs the main loop until gtk_main_quit() is called.
 *
 * You can nest calls to gtk_main(). In that case gtk_main_quit()
 * will make the innermost invocation of the main loop return.
 */
Elliot Lee's avatar
Elliot Lee committed
1148
void
1149
gtk_main (void)
Elliot Lee's avatar
Elliot Lee committed
1150
{
1151 1152
  GMainLoop *loop;

1153
  gtk_main_loop_level++;
1154

Manish Singh's avatar
Manish Singh committed
1155
  loop = g_main_loop_new (NULL, TRUE);
1156 1157
  main_loops = g_slist_prepend (main_loops, loop);

Manish Singh's avatar
Manish Singh committed
1158
  if (g_main_loop_is_running (main_loops->data))
1159 1160
    {
      GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1161
      g_main_loop_run (loop);
1162 1163 1164
      GDK_THREADS_ENTER ();
      gdk_flush ();
    }
1165

1166 1167
  main_loops = g_slist_remove (main_loops, loop);

Manish Singh's avatar
Manish Singh committed
1168
  g_main_loop_unref (loop);
1169

1170
  gtk_main_loop_level--;
1171 1172

  if (gtk_main_loop_level == 0)
1173 1174 1175 1176 1177 1178 1179
    {
      /* Try storing all clipboard data we have */
      _gtk_clipboard_store_all ();

      /* Synchronize the recent manager singleton */
      _gtk_recent_manager_sync ();
    }
1180 1181
}

1182 1183 1184 1185 1186 1187 1188 1189
/**
 * gtk_main_level:
 *
 * Asks for the current nesting level of the main loop.
 *
 * Returns: the nesting level of the current invocation
 *     of the main loop
 */
1190 1191 1192
guint
gtk_main_level (void)
{
1193
  return gtk_main_loop_level;
Elliot Lee's avatar
Elliot Lee committed
1194 1195
}

1196 1197 1198 1199 1200 1201
/**
 * gtk_main_quit:
 *
 * Makes the innermost invocation of the main loop return
 * when it regains control.
 */
Elliot Lee's avatar
Elliot Lee committed
1202
void
1203
gtk_main_quit (void)
Elliot Lee's avatar
Elliot Lee committed
1204
{
1205 1206
  g_return_if_fail (main_loops != NULL);

Manish Singh's avatar
Manish Singh committed
1207
  g_main_loop_quit (main_loops->data);
Elliot Lee's avatar
Elliot Lee committed
1208 1209
}

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
/**
 * gtk_events_pending:
 *
 * Checks if any events are pending.
 *
 * This can be used to update the UI and invoke timeouts etc.
 * while doing some time intensive computation.
 *
 * <example>
 * <title>Updating the UI during a long computation</title>
1220 1221 1222
 * <programlisting>
 *  /&ast; computation going on... &ast;/
 *
1223 1224
 *  while (gtk_events_pending ())
 *    gtk_main_iteration ();
1225 1226 1227
 *
 *  /&ast; ...computation continued &ast;/
 * </programlisting>
1228 1229 1230 1231
 * </example>
 *
 * Returns: %TRUE if any events are pending, %FALSE otherwise
 */
1232
gboolean
1233 1234
gtk_events_pending (void)
{
1235
  gboolean result;
1236 1237

  GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1238
  result = g_main_context_pending (NULL);
1239 1240 1241
  GDK_THREADS_ENTER ();

  return result;
1242 1243
}

1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
/**
 * gtk_main_iteration:
 *
 * Runs a single iteration of the mainloop.
 *
 * If no events are waiting to be processed GTK+ will block
 * until the next event is noticed. If you don't want to block
 * look at gtk_main_iteration_do() or check if any events are
 * pending with gtk_events_pending() first.
 *
 * Returns: %TRUE if gtk_main_quit() has been called for the
 *     innermost mainloop
 */
1257
gboolean
1258
gtk_main_iteration (void)
1259
{
1260
  GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1261
  g_main_context_iteration (NULL, TRUE);
1262
  GDK_THREADS_ENTER ();
1263

1264
  if (main_loops)
Manish Singh's avatar
Manish Singh committed
1265
    return !g_main_loop_is_running (main_loops->data);
1266 1267
  else
    return TRUE;
1268 1269
}

1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
/**
 * gtk_main_iteration_do:
 * @blocking: %TRUE if you want GTK+ to block if no events are pending
 *
 * Runs a single iteration of the mainloop.
 * If no events are available either return or block depending on
 * the value of @blocking.
 *
 * Returns: %TRUE if gtk_main_quit() has been called for the
 *     innermost mainloop
 */
1281
gboolean
1282
gtk_main_iteration_do (gboolean blocking)
1283
{
1284
  GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1285
  g_main_context_iteration (NULL, blocking);
1286
  GDK_THREADS_ENTER ();
1287

1288
  if (main_loops)
Manish Singh's avatar
Manish Singh committed
1289
    return !g_main_loop_is_running (main_loops->data);
1290 1291
  else
    return TRUE;
1292 1293
}

1294
/* private libgtk to libgdk interfaces */
1295 1296 1297 1298
gboolean gdk_device_grab_info_libgtk_only (GdkDisplay  *display,
                                           GdkDevice   *device,
                                           GdkWindow  **grab_window,
                                           gboolean    *owner_events);
1299 1300 1301

static void
rewrite_events_translate (GdkWindow *old_window,
1302 1303 1304
                          GdkWindow *new_window,
                          gdouble   *x,
                          gdouble   *y)
1305 1306 1307 1308
{
  gint old_origin_x, old_origin_y;
  gint new_origin_x, new_origin_y;

1309 1310
  gdk_window_get_origin (old_window, &old_origin_x, &old_origin_y);
  gdk_window_get_origin (new_window, &new_origin_x, &new_origin_y);
1311

1312 1313
  *x += old_origin_x - new_origin_x;
  *y += old_origin_y - new_origin_y;
1314 1315
}

1316
static GdkEvent *
1317
rewrite_event_for_window (GdkEvent  *event,
1318
                          GdkWindow *new_window)
1319 1320 1321 1322 1323 1324 1325
{
  event = gdk_event_copy (event);

  switch (event->type)
    {
    case GDK_SCROLL:
      rewrite_events_translate (event->any.window,
1326 1327
                                new_window,
                                &event->scroll.x, &event->scroll.y);
1328 1329 1330 1331 1332 1333
      break;
    case GDK_BUTTON_PRESS:
    case GDK_2BUTTON_PRESS:
    case GDK_3BUTTON_PRESS:
    case GDK_BUTTON_RELEASE:
      rewrite_events_translate (event->any.window,
1334 1335
                                new_window,
                                &event->button.x, &event->button.y);
1336 1337 1338
      break;
    case GDK_MOTION_NOTIFY:
      rewrite_events_translate (event->any.window,
1339 1340
                                new_window,
                                &event->motion.x, &event->motion.y);
1341
      break;
1342 1343 1344 1345 1346 1347 1348 1349
    case GDK_TOUCH_BEGIN:
    case GDK_TOUCH_UPDATE:
    case GDK_TOUCH_END:
    case GDK_TOUCH_CANCEL:
      rewrite_events_translate (event->any.window,
                                new_window,
                                &event->touch.x, &event->touch.y);
      break;
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    case GDK_KEY_PRESS:
    case GDK_KEY_RELEASE:
    case GDK_PROXIMITY_IN:
    case GDK_PROXIMITY_OUT:
      break;

    default:
      return event;
    }

  g_object_unref (event->any.window);
  event->any.window = g_object_ref (new_window);

  return event;
}

/* If there is a pointer or keyboard grab in effect with owner_events = TRUE,
 * then what X11 does is deliver the event normally if it was going to this
 * client, otherwise, delivers it in terms of the grab window. This function
 * rewrites events to the effect that events going to the same window group
 * are delivered normally, otherwise, the event is delivered in terms of the
 * grab window.
 */
static GdkEvent *
rewrite_event_for_grabs (GdkEvent *event)
{
  GdkWindow *grab_window;
1377
  GtkWidget *event_widget, *grab_widget;
1378
  gpointer grab_widget_ptr;
1379
  gboolean owner_events;
1380
  GdkDisplay *display;
1381
  GdkDevice *device;
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394

  switch (event->type)
    {
    case GDK_SCROLL:
    case GDK_BUTTON_PRESS:
    case GDK_2BUTTON_PRESS:
    case GDK_3BUTTON_PRESS:
    case GDK_BUTTON_RELEASE:
    case GDK_MOTION_NOTIFY:
    case GDK_PROXIMITY_IN:
    case GDK_PROXIMITY_OUT:
    case GDK_KEY_PRESS:
    case GDK_KEY_RELEASE:
1395 1396 1397 1398
    case GDK_TOUCH_BEGIN:
    case GDK_TOUCH_UPDATE:
    case GDK_TOUCH_END:
    case GDK_TOUCH_CANCEL:
1399
      display = gdk_window_get_display (event->any.window);
1400 1401 1402
      device = gdk_event_get_device (event);

      if (!gdk_device_grab_info_libgtk_only (display, device, &grab_window, &owner_events) ||
1403
          !owner_events)
1404
        return NULL;
1405 1406 1407 1408 1409 1410
      break;
    default:
      return NULL;
    }

  event_widget = gtk_get_event_widget (event);
1411 1412
  gdk_window_get_user_data (grab_window, &grab_widget_ptr);
  grab_widget = grab_widget_ptr;
1413 1414 1415 1416 1417 1418 1419 1420

  if (grab_widget &&
      gtk_main_get_window_group (grab_widget) != gtk_main_get_window_group (event_widget))
    return rewrite_event_for_window (event, grab_window);
  else
    return NULL;
}

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457