gtkmain.c 73.6 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
  {"no-css-cache", GTK_DEBUG_NO_CSS_CACHE}
176 177
};
#endif /* G_ENABLE_DEBUG */
Elliot Lee's avatar
Elliot Lee committed
178

179
/**
180
 * gtk_get_major_version:
181
 *
182 183
 * Returns the major version number of the GTK+ library.
 * (e.g. in GTK+ version 3.1.5 this is 3.)
184 185 186 187 188 189
 *
 * 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.
 *
190
 * Returns: the major version number of the GTK+ library
191 192
 *
 * Since: 3.0
193 194
 */
guint
195
gtk_get_major_version (void)
196 197 198 199 200
{
  return GTK_MAJOR_VERSION;
}

/**
201
 * gtk_get_minor_version:
202
 *
203 204
 * Returns the minor version number of the GTK+ library.
 * (e.g. in GTK+ version 3.1.5 this is 1.)
205 206 207 208 209 210
 *
 * 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.
 *
211
 * Returns: the minor version number of the GTK+ library
212 213
 *
 * Since: 3.0
214 215
 */
guint
216
gtk_get_minor_version (void)
217 218 219 220 221
{
  return GTK_MINOR_VERSION;
}

/**
222
 * gtk_get_micro_version:
223
 *
224 225
 * Returns the micro version number of the GTK+ library.
 * (e.g. in GTK+ version 3.1.5 this is 5.)
226 227 228 229 230 231
 *
 * 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.
 *
232
 * Returns: the micro version number of the GTK+ library
233 234
 *
 * Since: 3.0
235 236
 */
guint
237
gtk_get_micro_version (void)
238 239 240 241 242
{
  return GTK_MICRO_VERSION;
}

/**
243
 * gtk_get_binary_age:
244
 *
245 246 247
 * 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
248 249
 * worry about it.
 *
250
 * Returns: the binary age of the GTK+ library
251 252
 *
 * Since: 3.0
253 254
 */
guint
255
gtk_get_binary_age (void)
256 257 258 259 260
{
  return GTK_BINARY_AGE;
}

/**
261
 * gtk_get_interface_age:
262
 *
263 264 265
 * 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
266 267
 * worry about it.
 *
268
 * Returns: the interface age of the GTK+ library
269 270
 *
 * Since: 3.0
271 272
 */
guint
273
gtk_get_interface_age (void)
274 275 276 277
{
  return GTK_INTERFACE_AGE;
}

278 279
/**
 * gtk_check_version:
280 281 282 283
 * @required_major: the required major version
 * @required_minor: the required minor version
 * @required_micro: the required micro version
 *
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
 * 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
302
 * check isn't completely reliable, since the module may be
303 304 305 306 307 308 309 310
 * 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.
311
 */
312
const gchar*
313
gtk_check_version (guint required_major,
314 315
                   guint required_minor,
                   guint required_micro)
316
{
317 318 319
  gint gtk_effective_micro = 100 * GTK_MINOR_VERSION + GTK_MICRO_VERSION;
  gint required_effective_micro = 100 * required_minor + required_micro;

320
  if (required_major > GTK_MAJOR_VERSION)
321
    return "GTK+ version too old (major mismatch)";
322
  if (required_major < GTK_MAJOR_VERSION)
323
    return "GTK+ version too new (major mismatch)";
324
  if (required_effective_micro < gtk_effective_micro - GTK_BINARY_AGE)
325
    return "GTK+ version too new (micro mismatch)";
326
  if (required_effective_micro > gtk_effective_micro)
327
    return "GTK+ version too old (micro mismatch)";
328 329 330
  return NULL;
}

Owen Taylor's avatar
Owen Taylor committed
331 332 333 334 335 336 337 338 339 340
/* 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)
{
341
/* this isn't at all relevant on MS Windows and doesn't compile ... --hb */
342
#ifndef G_OS_WIN32
Owen Taylor's avatar
Owen Taylor committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  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"
366 367 368 369
                 "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
370 371
      exit (1);
    }
372
#endif
Owen Taylor's avatar
Owen Taylor committed
373 374 375
  return TRUE;
}

376 377 378 379 380
static gboolean do_setlocale = TRUE;

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

399
#ifdef G_PLATFORM_WIN32
400
#undef gtk_init_check
401
#endif
402

403
static GString *gtk_modules_string = NULL;
404
static gboolean g_fatal_warnings = FALSE;
405 406 407 408

#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
409
{
410
  debug_flags |= g_parse_debug_string (value,
411 412
                                       gtk_debug_keys,
                                       G_N_ELEMENTS (gtk_debug_keys));
413

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

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

  return TRUE;
425 426 427 428 429 430 431 432 433
}
#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)
434
        g_string_append_c (gtk_modules_string, G_SEARCHPATH_SEPARATOR);
435
      else
436
        gtk_modules_string = g_string_new (NULL);
437 438 439 440 441 442 443
      
      g_string_append (gtk_modules_string, value);
    }

  return TRUE;
}

Matthias Clasen's avatar
Matthias Clasen committed
444
static const GOptionEntry gtk_args[] = {
445 446 447
  { "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") },
448
  { "g-fatal-warnings", 0, 0, G_OPTION_ARG_NONE, &g_fatal_warnings, 
449
    /* Description of --g-fatal-warnings in --help output */   N_("Make all warnings fatal"), NULL },
450
#ifdef G_ENABLE_DEBUG
451 452 453 454 455 456 457
  { "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 
458 459 460
  { NULL }
};

Tor Lillqvist's avatar
Tor Lillqvist committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
#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 &&
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 542
          ((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
543 544 545 546 547 548 549
    }

  return TRUE;
}
  
#endif

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

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

559
  if (do_setlocale)
560
    {
Tor Lillqvist's avatar
Tor Lillqvist committed
561 562 563 564 565 566
#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)
567
        p = getenv ("LANG");
Tor Lillqvist's avatar
Tor Lillqvist committed
568 569

      if (p != NULL)
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 614
        {
          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
615
      if (!setlocale_called)
616
        setlocale (LC_ALL, "");
Tor Lillqvist's avatar
Tor Lillqvist committed
617
#else
618
      if (!setlocale (LC_ALL, ""))
619
        g_warning ("Locale not supported by C library.\n\tUsing the fallback 'C' locale.");
Tor Lillqvist's avatar
Tor Lillqvist committed
620
#endif
621
    }
622 623 624 625
}

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

  pre_initialized = TRUE;
634

635 636
  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");
637

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

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

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

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

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

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

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

683 684
  gettext_initialization ();

685
#ifdef SIGPIPE
686
  signal (SIGPIPE, SIG_IGN);
687
#endif
688

689 690 691 692 693 694 695 696 697
  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);
    }

698
  if (debug_flags & GTK_DEBUG_UPDATES)
699
    gdk_window_set_debug_updates (TRUE);
700

701 702
  {
  /* Translate to default:RTL if you want your widgets
Robert Brady's avatar
Robert Brady committed
703 704 705
   * 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 
706 707
   */
    char *e = _("default:LTR");
Matthias Clasen's avatar
Matthias Clasen committed
708
    if (strcmp (e, "default:RTL")==0) 
709
      gtk_widget_set_default_direction (GTK_TEXT_DIR_RTL);
Matthias Clasen's avatar
Matthias Clasen committed
710
    else if (strcmp (e, "default:LTR"))
711 712 713
      g_warning ("Whoever translated default:LTR did so wrongly.\n");
  }

714 715
  _gtk_register_resource ();

716 717 718 719
  /* do what the call to gtk_type_init() used to do */
  g_type_init ();

  _gtk_accel_map_init ();
720

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

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

736
  _gtk_accessibility_init ();
737 738 739 740 741 742 743 744 745 746
}


typedef struct
{
  gboolean open_default_display;
} OptionGroupInfo;

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

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

  
  do_post_parse_initialization (NULL, NULL);
  
  if (info->open_default_display)
768 769
    {
      if (gdk_display_open_default_libgtk_only () == NULL)
770 771 772 773 774 775 776 777 778 779
        {
          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;
        }
780 781 782
    }

  return TRUE;
783 784 785
}


786 787 788
/**
 * gtk_get_debug_flags:
 *
789 790 791 792 793 794
 * 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.
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
 */
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;
}

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

836 837
  gettext_initialization ();

838 839 840 841 842 843 844 845
  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);
846
  g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
847 848 849 850
  
  return group;
}

851 852
/**
 * gtk_init_with_args:
853 854 855 856 857 858
 * @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.
859
 * @parameter_string: a string which is displayed in
860
 *    the first line of <option>--help</option> output, after
861
 *    <literal><replaceable>programname</replaceable> [OPTION...]</literal>
862 863
 * @entries: (array zero-terminated=1): a %NULL-terminated array
 *    of #GOptionEntrys describing the options of your program
864 865
 * @translation_domain: a translation domain to use for translating
 *    the <option>--help</option> output for the options in @entries
866 867
 *    and the @parameter_string with gettext(), or %NULL
 * @error: a return location for errors
868
 *
869 870 871
 * 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
872 873 874
 * <option>--help</option> output. Note that your program will
 * be terminated after writing out the help output.
 *
875 876
 * Returns: %TRUE if the windowing system has been successfully
 *     initialized, %FALSE otherwise
877
 *
878 879
 * Since: 2.6
 */
880
gboolean
881 882 883 884 885 886
gtk_init_with_args (gint                 *argc,
                    gchar              ***argv,
                    const gchar          *parameter_string,
                    const GOptionEntry   *entries,
                    const gchar          *translation_domain,
                    GError              **error)
887 888 889 890
{
  GOptionContext *context;
  GOptionGroup *gtk_group;
  gboolean retval;
Matthias Clasen's avatar
Matthias Clasen committed
891

892
  if (gtk_initialized)
893
    return gdk_display_open_default_libgtk_only () != NULL;
894

895 896
  gettext_initialization ();

Matthias Clasen's avatar
Matthias Clasen committed
897 898 899
  if (!check_setugid ())
    return FALSE;

900
  gtk_group = gtk_get_option_group (TRUE);
901

902 903
  context = g_option_context_new (parameter_string);
  g_option_context_add_group (context, gtk_group);
904 905
  g_option_context_set_translation_domain (context, translation_domain);

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

910 911 912 913 914 915 916 917
  g_option_context_free (context);

  return retval;
}


/**
 * gtk_parse_args:
918
 * @argc: (inout): a pointer to the number of command line arguments
919 920
 * @argv: (array length=argc) (inout): a pointer to the array of
 *     command line arguments
921
 *
922 923 924 925 926 927 928
 * 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.
 *
929
 * There is no need to call this function explicitely if you are using
930 931
 * gtk_init(), or gtk_init_check().
 *
932 933
 * Return value: %TRUE if initialization succeeded, otherwise %FALSE
 */
934 935
gboolean
gtk_parse_args (int    *argc,
936
                char ***argv)
937 938
{
  GOptionContext *option_context;
939
  GOptionGroup *gtk_group;
940
  GError *error = NULL;
941 942 943 944
  
  if (gtk_initialized)
    return TRUE;

945 946
  gettext_initialization ();

947 948 949 950 951 952
  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);
953 954
  gtk_group = gtk_get_option_group (FALSE);
  g_option_context_set_main_group (option_context, gtk_group);
955 956 957 958 959 960
  if (!g_option_context_parse (option_context, argc, argv, &error))
    {
      g_warning ("%s", error->message);
      g_error_free (error);
    }

961 962
  g_option_context_free (option_context);

963 964
  return TRUE;
}
965

966
#ifdef G_PLATFORM_WIN32
967
#undef gtk_init_check
968
#endif
969 970 971

/**
 * gtk_init_check:
972
 * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
973 974
 *     your main() function (or 0 if @argv is %NULL). This will be changed if 
 *     any arguments were handled.
975
 * @argv: (array length=argc) (inout) (allow-none): Address of the
976 977
 *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
 *     understood by GTK+ are stripped before return.
978
 *
979 980 981
 * 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.
982
 *
983 984 985 986 987 988 989
 * 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
 */
990
gboolean
991 992
gtk_init_check (int    *argc,
                char ***argv)
993 994 995 996
{
  if (!gtk_parse_args (argc, argv))
    return FALSE;

997
  return gdk_display_open_default_libgtk_only () != NULL;
998 999
}

1000
#ifdef G_PLATFORM_WIN32
1001
#undef gtk_init
1002
#endif
1003

1004
/**
Matthias Clasen's avatar
Matthias Clasen committed
1005
 * gtk_init:
1006
 * @argc: (inout): Address of the <parameter>argc</parameter> parameter of
1007 1008
 *     your main() function (or 0 if @argv is %NULL). This will be changed if 
 *     any arguments were handled.
1009
 * @argv: (array length=argc) (inout) (allow-none): Address of the
1010
 *     <parameter>argv</parameter> parameter of main(), or %NULL. Any options
1011
 *     understood by GTK+ are stripped before return.
1012
 *
1013
 * Call this function before using any other GTK+ functions in your GUI
1014
 * applications.  It will initialize everything needed to operate the
1015
 * toolkit and parses some standard command line options.
1016
 *
1017 1018 1019 1020
 * 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.
 *
1021 1022 1023 1024 1025 1026 1027 1028
 * @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().
1029 1030
 *
 * <note><para>
1031 1032 1033 1034
 * 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.
1035
 * </para></note>
1036 1037 1038 1039 1040 1041 1042 1043 1044
 *
 * <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>
1045
 */
1046 1047 1048 1049 1050
void
gtk_init (int *argc, char ***argv)
{
  if (!gtk_init_check (argc, argv))
    {
1051
      const char *display_name_arg = gdk_get_display_arg_name ();
1052 1053 1054
      if (display_name_arg == NULL)
        display_name_arg = getenv("DISPLAY");
      g_warning ("cannot open display: %s", display_name_arg ? display_name_arg : "");
1055
      exit (1);
1056
    }
Elliot Lee's avatar
Elliot Lee committed
1057 1058
}

Fridrich Strba's avatar
Fridrich Strba committed
1059 1060 1061 1062 1063 1064 1065 1066
#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.
 */
1067 1068 1069 1070 1071 1072

static void
check_sizeof_GtkWindow (size_t sizeof_GtkWindow)
{
  if (sizeof_GtkWindow != sizeof (GtkWindow))
    g_error ("Incompatible build!\n"
1073
             "The code using GTK+ thinks GtkWindow is of different\n"
1074
             "size than it actually is in this build of GTK+.\n"
1075 1076 1077
             "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.");
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
}

/* 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"
1091
             "The code using GTK+ thinks GtkBox is of different\n"
1092
             "size than it actually is in this build of GTK+.\n"
1093 1094 1095
             "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.");
1096 1097 1098 1099 1100 1101
}

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

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

#endif

1121 1122 1123 1124 1125
/**
 * gtk_get_default_language:
 *
 * Returns the #PangoLanguage for the default language currently in
 * effect. (Note that this can change over the life of an
1126
 * application.) The default language is derived from the current
1127
 * locale. It determines, for example, whether GTK+ uses the
1128 1129
 * right-to-left or left-to-right text direction.
 *
1130 1131 1132 1133 1134 1135
 * 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
 */
1136 1137 1138
PangoLanguage *
gtk_get_default_language (void)
{
1139
  return pango_language_get_default ();
1140 1141
}

1142 1143 1144 1145 1146 1147 1148 1149
/**
 * 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
1150
void
1151
gtk_main (void)
Elliot Lee's avatar
Elliot Lee committed
1152
{
1153 1154
  GMainLoop *loop;

1155
  gtk_main_loop_level++;
1156

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

Manish Singh's avatar
Manish Singh committed
1160
  if (g_main_loop_is_running (main_loops->data))
1161
    {
1162
      gdk_threads_leave ();
Manish Singh's avatar
Manish Singh committed
1163
      g_main_loop_run (loop);
1164
      gdk_threads_enter ();
1165 1166
      gdk_flush ();
    }
1167

1168 1169
  main_loops = g_slist_remove (main_loops, loop);

Manish Singh's avatar
Manish Singh committed
1170
  g_main_loop_unref (loop);
1171

1172
  gtk_main_loop_level--;
1173 1174

  if (gtk_main_loop_level == 0)
1175
    {
1176 1177
      /* Keep this section in sync with gtk_application_shutdown() */

1178 1179 1180 1181 1182
      /* Try storing all clipboard data we have */
      _gtk_clipboard_store_all ();

      /* Synchronize the recent manager singleton */
      _gtk_recent_manager_sync ();
1183 1184

      _gtk_accessibility_shutdown ();
1185
    }
1186 1187
}

1188 1189 1190 1191 1192 1193 1194 1195
/**
 * 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
 */
1196 1197 1198
guint
gtk_main_level (void)
{
1199
  return gtk_main_loop_level;
Elliot Lee's avatar
Elliot Lee committed
1200 1201
}

1202 1203 1204 1205 1206 1207
/**
 * gtk_main_quit:
 *
 * Makes the innermost invocation of the main loop return
 * when it regains control.
 */
Elliot Lee's avatar
Elliot Lee committed
1208
void
1209
gtk_main_quit (void)
Elliot Lee's avatar
Elliot Lee committed
1210
{
1211 1212
  g_return_if_fail (main_loops != NULL);

Manish Singh's avatar
Manish Singh committed
1213
  g_main_loop_quit (main_loops->data);
Elliot Lee's avatar
Elliot Lee committed
1214 1215
}

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
/**
 * 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>
1226 1227 1228
 * <programlisting>
 *  /&ast; computation going on... &ast;/
 *
1229 1230
 *  while (gtk_events_pending ())
 *    gtk_main_iteration ();
1231 1232 1233
 *
 *  /&ast; ...computation continued &ast;/
 * </programlisting>
1234 1235 1236 1237
 * </example>
 *
 * Returns: %TRUE if any events are pending, %FALSE otherwise
 */
1238
gboolean
1239 1240
gtk_events_pending (void)
{
1241
  gboolean result;
1242

1243
  gdk_threads_leave ();
Manish Singh's avatar
Manish Singh committed
1244
  result = g_main_context_pending (NULL);
1245
  gdk_threads_enter ();
1246 1247

  return result;
1248 1249
}

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
/**
 * 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
 */
1263
gboolean
1264
gtk_main_iteration (void)
1265
{
1266
  gdk_threads_leave ();
Manish Singh's avatar
Manish Singh committed
1267
  g_main_context_iteration (NULL, TRUE);
1268
  gdk_threads_enter ();
1269

1270
  if (main_loops)
Manish Singh's avatar
Manish Singh committed
1271
    return !g_main_loop_is_running (main_loops->data);
1272 1273
  else
    return TRUE;
1274 1275
}

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
/**
 * 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
 */
1287
gboolean
1288
gtk_main_iteration_do (gboolean blocking)
1289
{
1290
  gdk_threads_leave ();
Manish Singh's avatar
Manish Singh committed
1291
  g_main_context_iteration (NULL, blocking);
1292
  gdk_threads_enter ();
1293

1294
  if (main_loops)
Manish Singh's avatar
Manish Singh committed
1295
    return !g_main_loop_is_running (main_loops->data);
1296 1297
  else
    return TRUE;
1298 1299
}

1300
/* private libgtk to libgdk interfaces */
1301 1302 1303 1304
gboolean gdk_device_grab_info_libgtk_only (GdkDisplay  *display,
                                           GdkDevice   *device,
                                           GdkWindow  **grab_window,
                                           gboolean    *owner_events);
1305 1306 1307

static void
rewrite_events_translate (GdkWindow *old_window,
1308 1309 1310
                          GdkWindow *new_window,
                          gdouble   *x,
                          gdouble   *y)
1311 1312 1313 1314
{
  gint old_origin_x, old_origin_y;
  gint new_origin_x, new_origin_y;

1315 1316
  gdk_window_get_origin (old_window, &old_origin_x, &old_origin_y);
  gdk_window_get_origin (new_window, &new_origin_x, &new_origin_y);
1317

1318 1319
  *x += old_origin_x - new_origin_x;
  *y += old_origin_y - new_origin_y;
1320 1321
}

1322
static GdkEvent *
1323
rewrite_event_for_window (GdkEvent  *event,
1324
                          GdkWindow *new_window)
1325 1326 1327 1328 1329 1330 1331
{
  event = gdk_event_copy (event);

  switch (event->type)
    {
    case GDK_SCROLL:
      rewrite_events_translate (event->any.window,
1332 1333
                                new_window,
                                &event->scroll.x, &event->scroll.y);
1334 1335 1336 1337 1338 1339
      break;
    case GDK_BUTTON_PRESS:
    case GDK_2BUTTON_PRESS:
    case GDK_3BUTTON_PRESS:
    case GDK_BUTTON_RELEASE:
      rewrite_events_translate (event->any.window,
1340 1341
                                new_window,
                                &event->button.x, &event->button.y);
1342 1343 1344
      break;
    case GDK_MOTION_NOTIFY:
      rewrite_events_translate (event->any.window,
1345 1346
                                new_window,
                                &event->motion.x, &event->motion.y);
1347
      break;
1348 1349 1350 1351 1352 1353 1354 1355
    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;
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    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;
1383
  GtkWidget *event_widget, *grab_widget;
1384
  gpointer grab_widget_ptr;
1385
  gboolean owner_events;
1386
  GdkDisplay *display;
1387
  GdkDevice *device;
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400

  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:
1401 1402 1403 1404
    case GDK_TOUCH_BEGIN:
    case GDK_TOUCH_UPDATE:
    case GDK_TOUCH_END:
    case GDK_TOUCH_CANCEL:
1405
      display = gdk_window_get_display (event->any.window);
1406 1407 1408
      device = gdk_event_get_device (event);

      if (!gdk_device_grab_info_libgtk_only (display, device, &grab_window, &owner_events) ||
1409
          !owner_events)
1410
        return NULL;