gtkmain.c 65.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
15 16 17
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
Elliot Lee's avatar
Elliot Lee committed
18
 */
19 20

/*
21
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
22 23 24 25 26
 * 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/. 
 */

27
#include "config.h"
28

Matthias Clasen's avatar
Matthias Clasen committed
29
#include <glib.h>
30 31
#include "gdkconfig.h"

32
#include <locale.h>
Robert Brady's avatar
Robert Brady committed
33

Elliot Lee's avatar
Elliot Lee committed
34 35
#include <stdio.h>
#include <stdlib.h>
36
#include <string.h>
37
#ifdef HAVE_UNISTD_H
38 39
#include <unistd.h>
#endif
40 41
#include <sys/types.h>		/* For uid_t, gid_t */

Tor Lillqvist's avatar
Tor Lillqvist committed
42 43 44 45 46
#ifdef G_OS_WIN32
#define STRICT
#include <windows.h>
#undef STRICT
#endif
47

Tor Lillqvist's avatar
Tor Lillqvist committed
48 49
#include "gtkintl.h"

50
#include "gtkaccelmap.h"
51
#include "gtkbox.h"
52
#include "gtkclipboard.h"
53
#include "gtkdnd.h"
54
#include "gtkversion.h"
Elliot Lee's avatar
Elliot Lee committed
55
#include "gtkmain.h"
56
#include "gtkmodules.h"
Elliot Lee's avatar
Elliot Lee committed
57
#include "gtkrc.h"
58
#include "gtkrecentmanager.h"
Elliot Lee's avatar
Elliot Lee committed
59
#include "gtkselection.h"
60
#include "gtksettings.h"
Elliot Lee's avatar
Elliot Lee committed
61 62
#include "gtkwidget.h"
#include "gtkwindow.h"
Kristian Rietveld's avatar
Kristian Rietveld committed
63
#include "gtktooltip.h"
64
#include "gtkdebug.h"
65 66
#include "gtkmenu.h"
#include "gdk/gdkkeysyms.h"
Elliot Lee's avatar
Elliot Lee committed
67

68 69
#include "gdk/gdkprivate.h" /* for GDK_WINDOW_DESTROYED */

70 71
#ifdef G_OS_WIN32

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
static HMODULE gtk_dll;

BOOL WINAPI
DllMain (HINSTANCE hinstDLL,
	 DWORD     fdwReason,
	 LPVOID    lpvReserved)
{
  switch (fdwReason)
    {
    case DLL_PROCESS_ATTACH:
      gtk_dll = (HMODULE) hinstDLL;
      break;
    }

  return TRUE;
}
88

89 90 91
/* These here before inclusion of gtkprivate.h so that the original
 * GTK_LIBDIR and GTK_LOCALEDIR definitions are seen. Yeah, this is a
 * bit sucky.
92
 */
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
const gchar *
_gtk_get_libdir (void)
{
  static char *gtk_libdir = NULL;
  if (gtk_libdir == NULL)
    {
      gchar *root = g_win32_get_package_installation_directory_of_module (gtk_dll);
      gchar *slash = strrchr (root, '\\');
      if (g_ascii_strcasecmp (slash + 1, ".libs") == 0)
	gtk_libdir = GTK_LIBDIR;
      else
	gtk_libdir = g_build_filename (root, "lib", NULL);
      g_free (root);
    }

  return gtk_libdir;
}

111 112 113 114 115 116 117
const gchar *
_gtk_get_localedir (void)
{
  static char *gtk_localedir = NULL;
  if (gtk_localedir == NULL)
    {
      const gchar *p;
118
      gchar *root, *temp;
119 120 121 122 123 124 125 126 127 128
      
      /* GTK_LOCALEDIR ends in either /lib/locale or
       * /share/locale. Scan for that slash.
       */
      p = GTK_LOCALEDIR + strlen (GTK_LOCALEDIR);
      while (*--p != '/')
	;
      while (*--p != '/')
	;

129 130 131
      root = g_win32_get_package_installation_directory_of_module (gtk_dll);
      temp = g_build_filename (root, p, NULL);
      g_free (root);
132 133 134 135 136 137 138 139 140 141 142 143 144 145

      /* gtk_localedir is passed to bindtextdomain() which isn't
       * UTF-8-aware.
       */
      gtk_localedir = g_win32_locale_filename_from_utf8 (temp);
      g_free (temp);
    }
  return gtk_localedir;
}

#endif

#include "gtkprivate.h"

Elliot Lee's avatar
Elliot Lee committed
146 147
/* Private type definitions
 */
148 149 150
typedef struct _GtkInitFunction		 GtkInitFunction;
typedef struct _GtkQuitFunction		 GtkQuitFunction;
typedef struct _GtkKeySnooperData	 GtkKeySnooperData;
Elliot Lee's avatar
Elliot Lee committed
151 152 153 154 155 156 157

struct _GtkInitFunction
{
  GtkFunction function;
  gpointer data;
};

158 159
struct _GtkQuitFunction
{
160
  guint id;
161 162 163 164
  guint main_level;
  GtkCallbackMarshal marshal;
  GtkFunction function;
  gpointer data;
165
  GDestroyNotify destroy;
166 167
};

168 169 170 171
struct _GtkKeySnooperData
{
  GtkKeySnoopFunc func;
  gpointer func_data;
172
  guint id;
173 174
};

175 176 177 178
static gint  gtk_quit_invoke_function	 (GtkQuitFunction    *quitf);
static void  gtk_quit_destroy		 (GtkQuitFunction    *quitf);
static gint  gtk_invoke_key_snoopers	 (GtkWidget	     *grab_widget,
					  GdkEvent	     *event);
179

180 181
static GtkWindowGroup *gtk_main_get_window_group (GtkWidget   *widget);

182 183 184
const guint gtk_major_version = GTK_MAJOR_VERSION;
const guint gtk_minor_version = GTK_MINOR_VERSION;
const guint gtk_micro_version = GTK_MICRO_VERSION;
185 186
const guint gtk_binary_age = GTK_BINARY_AGE;
const guint gtk_interface_age = GTK_INTERFACE_AGE;
187

188
static guint gtk_main_loop_level = 0;
Matthias Clasen's avatar
Matthias Clasen committed
189
static gint pre_initialized = FALSE;
190
static gint gtk_initialized = FALSE;
191
static GList *current_events = NULL;
Elliot Lee's avatar
Elliot Lee committed
192

193 194
static GSList *main_loops = NULL;      /* stack of currently executing main loops */

195
static GList *init_functions = NULL;	   /* A list of init functions.
Elliot Lee's avatar
Elliot Lee committed
196
					    */
197 198
static GList *quit_functions = NULL;	   /* A list of quit functions.
					    */
199 200
static GSList *key_snoopers = NULL;

201
guint gtk_debug_flags = 0;		   /* Global GTK debug flag */
202 203

#ifdef G_ENABLE_DEBUG
204
static const GDebugKey gtk_debug_keys[] = {
205
  {"misc", GTK_DEBUG_MISC},
206
  {"plugsocket", GTK_DEBUG_PLUGSOCKET},
207
  {"text", GTK_DEBUG_TEXT},
208
  {"tree", GTK_DEBUG_TREE},
209
  {"updates", GTK_DEBUG_UPDATES},
210
  {"keybindings", GTK_DEBUG_KEYBINDINGS},
211
  {"multihead", GTK_DEBUG_MULTIHEAD},
212
  {"modules", GTK_DEBUG_MODULES},
213
  {"geometry", GTK_DEBUG_GEOMETRY},
214
  {"icontheme", GTK_DEBUG_ICONTHEME},
215
  {"printing", GTK_DEBUG_PRINTING},
216
  {"builder", GTK_DEBUG_BUILDER},
217
  {"size-request", GTK_DEBUG_SIZE_REQUEST},
218 219
};
#endif /* G_ENABLE_DEBUG */
Elliot Lee's avatar
Elliot Lee committed
220

221 222 223
/**
 * gtk_check_version:
 * @required_major: the required major version.
224 225
 * @required_minor: the required minor version.
 * @required_micro: the required micro version.
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
 * 
 * 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
 * a check isn't completely reliable, since the module may be
 * 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.
 **/
255
const gchar*
256 257 258 259
gtk_check_version (guint required_major,
		   guint required_minor,
		   guint required_micro)
{
260 261 262
  gint gtk_effective_micro = 100 * GTK_MINOR_VERSION + GTK_MICRO_VERSION;
  gint required_effective_micro = 100 * required_minor + required_micro;

263
  if (required_major > GTK_MAJOR_VERSION)
264
    return "Gtk+ version too old (major mismatch)";
265
  if (required_major < GTK_MAJOR_VERSION)
266
    return "Gtk+ version too new (major mismatch)";
267
  if (required_effective_micro < gtk_effective_micro - GTK_BINARY_AGE)
268
    return "Gtk+ version too new (micro mismatch)";
269
  if (required_effective_micro > gtk_effective_micro)
270
    return "Gtk+ version too old (micro mismatch)";
271 272 273
  return NULL;
}

Owen Taylor's avatar
Owen Taylor committed
274 275 276 277 278 279 280 281 282 283
/* 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)
{
284
/* this isn't at all relevant on MS Windows and doesn't compile ... --hb */
285
#ifndef G_OS_WIN32
Owen Taylor's avatar
Owen Taylor committed
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  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"
		 "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+.");
      exit (1);
    }
315
#endif
Owen Taylor's avatar
Owen Taylor committed
316 317 318
  return TRUE;
}

Tor Lillqvist's avatar
Tor Lillqvist committed
319 320
#ifdef G_OS_WIN32

321 322 323 324 325
const gchar *
_gtk_get_datadir (void)
{
  static char *gtk_datadir = NULL;
  if (gtk_datadir == NULL)
326 327 328 329 330
    {
      gchar *root = g_win32_get_package_installation_directory_of_module (gtk_dll);
      gtk_datadir = g_build_filename (root, "share", NULL);
      g_free (root);
    }
331 332 333 334

  return gtk_datadir;
}

Tor Lillqvist's avatar
Tor Lillqvist committed
335 336 337 338 339
const gchar *
_gtk_get_sysconfdir (void)
{
  static char *gtk_sysconfdir = NULL;
  if (gtk_sysconfdir == NULL)
340 341 342 343 344
    {
      gchar *root = g_win32_get_package_installation_directory_of_module (gtk_dll);
      gtk_sysconfdir = g_build_filename (root, "etc", NULL);
      g_free (root);
    }
Tor Lillqvist's avatar
Tor Lillqvist committed
345 346 347 348 349 350 351 352 353

  return gtk_sysconfdir;
}

const gchar *
_gtk_get_data_prefix (void)
{
  static char *gtk_data_prefix = NULL;
  if (gtk_data_prefix == NULL)
354
    gtk_data_prefix = g_win32_get_package_installation_directory_of_module (gtk_dll);
Tor Lillqvist's avatar
Tor Lillqvist committed
355 356 357 358 359 360

  return gtk_data_prefix;
}

#endif /* G_OS_WIN32 */

361 362 363 364 365
static gboolean do_setlocale = TRUE;

/**
 * gtk_disable_setlocale:
 * 
366 367
 * Prevents gtk_init(), gtk_init_check(), gtk_init_with_args() and
 * gtk_parse_args() from automatically
368 369 370 371
 * 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 
 * you wanted to set different values for different locale categories.
372 373 374
 *
 * Most programs should not need to call this function.
 **/
375
void
376 377
gtk_disable_setlocale (void)
{
Matthias Clasen's avatar
Matthias Clasen committed
378
  if (pre_initialized)
379 380 381 382 383
    g_warning ("gtk_disable_setlocale() must be called before gtk_init()");
    
  do_setlocale = FALSE;
}

384
#ifdef G_PLATFORM_WIN32
385
#undef gtk_init_check
386
#endif
387

388
static GString *gtk_modules_string = NULL;
389
static gboolean g_fatal_warnings = FALSE;
390 391 392 393

#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
394
{
395 396
  gtk_debug_flags |= g_parse_debug_string (value,
					   gtk_debug_keys,
397
					   G_N_ELEMENTS (gtk_debug_keys));
398

399 400
  return TRUE;
}
Tim Janik's avatar
Tim Janik committed
401

402 403 404 405 406
static gboolean
gtk_arg_no_debug_cb (const char *key, const char *value, gpointer user_data)
{
  gtk_debug_flags &= ~g_parse_debug_string (value,
					    gtk_debug_keys,
407
					    G_N_ELEMENTS (gtk_debug_keys));
408 409

  return TRUE;
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
}
#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)
	g_string_append_c (gtk_modules_string, G_SEARCHPATH_SEPARATOR);
      else
	gtk_modules_string = g_string_new (NULL);
      
      g_string_append (gtk_modules_string, value);
    }

  return TRUE;
}

Matthias Clasen's avatar
Matthias Clasen committed
429
static const GOptionEntry gtk_args[] = {
430 431 432
  { "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") },
433
  { "g-fatal-warnings", 0, 0, G_OPTION_ARG_NONE, &g_fatal_warnings, 
434
    /* Description of --g-fatal-warnings in --help output */   N_("Make all warnings fatal"), NULL },
435
#ifdef G_ENABLE_DEBUG
436 437 438 439 440 441 442
  { "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 
443 444 445
  { NULL }
};

Tor Lillqvist's avatar
Tor Lillqvist committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 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
#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 &&
	  ((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;
	}
    }

  return TRUE;
}
  
#endif

535
static void
536
setlocale_initialization (void)
537
{
538
  static gboolean initialized = FALSE;
539

540
  if (initialized)
Matthias Clasen's avatar
Matthias Clasen committed
541
    return;
542
  initialized = TRUE;
Matthias Clasen's avatar
Matthias Clasen committed
543

544
  if (do_setlocale)
545
    {
Tor Lillqvist's avatar
Tor Lillqvist committed
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 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
#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)
	p = getenv ("LANG");

      if (p != NULL)
	{
	  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);
	}
      if (!setlocale_called)
	setlocale (LC_ALL, "");
#else
603 604
      if (!setlocale (LC_ALL, ""))
	g_warning ("Locale not supported by C library.\n\tUsing the fallback 'C' locale.");
Tor Lillqvist's avatar
Tor Lillqvist committed
605
#endif
606
    }
607 608
}

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
static void
check_mixed_deps (void)
{
  GModule *module;
  gpointer func;

  module = g_module_open (NULL, 0);

  if (g_module_symbol (module, "gtk_progress_get_type", &func))
    {
      g_error ("GTK+ 2.x symbols detected. Using GTK+ 2.x and GTK+ 3 in the same process is not supported");
    }

  g_module_close (module);
}

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

  pre_initialized = TRUE;
635

636 637
  check_mixed_deps ();

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 645
  if (env_string != NULL)
    {
      gtk_debug_flags = g_parse_debug_string (env_string,
646
					      gtk_debug_keys,
647
					      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 663 664 665 666 667 668 669 670 671
#ifdef ENABLE_NLS
  bindtextdomain (GETTEXT_PACKAGE, GTK_LOCALEDIR);
  bindtextdomain (GETTEXT_PACKAGE "-properties", GTK_LOCALEDIR);
#    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  bind_textdomain_codeset (GETTEXT_PACKAGE "-properties", "UTF-8");
#    endif
#endif  
}

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

679 680
  gettext_initialization ();

681
#ifdef SIGPIPE
682
  signal (SIGPIPE, SIG_IGN);
683
#endif
684

685 686 687 688 689 690 691 692 693
  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);
    }

694 695
  if (gtk_debug_flags & GTK_DEBUG_UPDATES)
    gdk_window_set_debug_updates (TRUE);
696

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

710 711 712 713
  /* do what the call to gtk_type_init() used to do */
  g_type_init ();

  _gtk_accel_map_init ();
714
  _gtk_rc_init ();
715

Elliot Lee's avatar
Elliot Lee committed
716 717
  /* Set the 'initialized' flag.
   */
718
  gtk_initialized = TRUE;
719

720 721
  /* load gtk modules */
  if (gtk_modules_string)
722
    {
723 724
      _gtk_modules_init (argc, argv, gtk_modules_string->str);
      g_string_free (gtk_modules_string, TRUE);
725
    }
726 727 728 729
  else
    {
      _gtk_modules_init (argc, argv, NULL);
    }
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
}


typedef struct
{
  gboolean open_default_display;
} OptionGroupInfo;

static gboolean
pre_parse_hook (GOptionContext *context,
		GOptionGroup   *group,
		gpointer	data,
		GError        **error)
{
  do_pre_parse_initialization (NULL, NULL);
  
  return TRUE;
}

static gboolean
post_parse_hook (GOptionContext *context,
		 GOptionGroup   *group,
		 gpointer	data,
		 GError        **error)
{
  OptionGroupInfo *info = data;

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

  return TRUE;
776 777 778
}


779 780 781 782 783 784 785 786 787 788
/**
 * gtk_get_option_group:
 * @open_default_display: whether to open the default display 
 *    when parsing the commandline arguments
 * 
 * Returns a #GOptionGroup for the commandline arguments recognized
 * by GTK+ and GDK. You should add this group to your #GOptionContext 
 * with g_option_context_add_group(), if you are using 
 * g_option_context_parse() to parse your commandline arguments.
 *
789
 * Returns: a #GOptionGroup for the commandline arguments recognized
790 791 792 793
 *   by GTK+
 *
 * Since: 2.6
 */
794 795 796 797 798 799
GOptionGroup *
gtk_get_option_group (gboolean open_default_display)
{
  GOptionGroup *group;
  OptionGroupInfo *info;

800 801
  gettext_initialization ();

802 803 804 805 806 807 808 809
  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);
810
  g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
811 812 813 814
  
  return group;
}

815 816 817 818 819
/**
 * gtk_init_with_args:
 * @argc: a pointer to the number of command line arguments.
 * @argv: a pointer to the array of command line arguments.
 * @parameter_string: a string which is displayed in
820
 *    the first line of <option>--help</option> output, after
821 822 823 824 825
 *    <literal><replaceable>programname</replaceable> [OPTION...]</literal>
 * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
 *    describing the options of your program
 * @translation_domain: a translation domain to use for translating
 *    the <option>--help</option> output for the options in @entries
826 827
 *    and the @parameter_string with gettext(), or %NULL
 * @error: a return location for errors
828
 *
829 830 831
 * 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
832 833 834
 * <option>--help</option> output. Note that your program will
 * be terminated after writing out the help output.
 *
835
 * Returns: %TRUE if the GUI has been successfully initialized,
836
 *               %FALSE otherwise.
837
 *
838 839
 * Since: 2.6
 */
840
gboolean
841 842 843 844 845 846
gtk_init_with_args (gint                 *argc,
                    gchar              ***argv,
                    const gchar          *parameter_string,
                    const GOptionEntry   *entries,
                    const gchar          *translation_domain,
                    GError              **error)
847 848 849 850
{
  GOptionContext *context;
  GOptionGroup *gtk_group;
  gboolean retval;
Matthias Clasen's avatar
Matthias Clasen committed
851

852
  if (gtk_initialized)
853
    return gdk_display_open_default_libgtk_only () != NULL;
854

855 856
  gettext_initialization ();

Matthias Clasen's avatar
Matthias Clasen committed
857 858 859
  if (!check_setugid ())
    return FALSE;

860
  gtk_group = gtk_get_option_group (TRUE);
861

862 863
  context = g_option_context_new (parameter_string);
  g_option_context_add_group (context, gtk_group);
864 865
  g_option_context_set_translation_domain (context, translation_domain);

866 867 868
  if (entries)
    g_option_context_add_main_entries (context, entries, translation_domain);
  retval = g_option_context_parse (context, argc, argv, error);
869

870 871 872 873 874 875 876 877
  g_option_context_free (context);

  return retval;
}


/**
 * gtk_parse_args:
878 879 880
 * @argc: (inout): a pointer to the number of command line arguments.
 * @argv: (array) (inout): a pointer to the array of command line arguments.
 *
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
 * 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.
 *
 * You shouldn't call this function explicitely if you are using
 * gtk_init(), or gtk_init_check().
 *
 * Return value: %TRUE if initialization succeeded, otherwise %FALSE.
 **/
gboolean
gtk_parse_args (int    *argc,
		char ***argv)
{
  GOptionContext *option_context;
898
  GOptionGroup *gtk_group;
899
  GError *error = NULL;
900 901 902 903
  
  if (gtk_initialized)
    return TRUE;

904 905
  gettext_initialization ();

906 907 908 909 910 911
  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);
912 913
  gtk_group = gtk_get_option_group (FALSE);
  g_option_context_set_main_group (option_context, gtk_group);
914 915 916 917 918 919
  if (!g_option_context_parse (option_context, argc, argv, &error))
    {
      g_warning ("%s", error->message);
      g_error_free (error);
    }

920 921
  g_option_context_free (option_context);

922 923
  return TRUE;
}
924

925
#ifdef G_PLATFORM_WIN32
926
#undef gtk_init_check
927
#endif
928 929 930

/**
 * gtk_init_check:
931
 * @argc: (inout): Address of the <parameter>argc</parameter> parameter of your
Matthias Clasen's avatar
Matthias Clasen committed
932
 *   main() function. Changed if any arguments were handled.
933
 * @argv: (array length=argc) (inout) (allow-none): Address of the <parameter>argv</parameter> parameter of main().
Matthias Clasen's avatar
Matthias Clasen committed
934
 *   Any parameters understood by gtk_init() are stripped before return.
935 936 937
 *
 * This function does the same work as gtk_init() with only
 * a single change: It does not terminate the program if the GUI can't be
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
 * initialized. Instead it returns %FALSE on failure.
 *
 * 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 GUI has been successfully initialized, 
 *               %FALSE otherwise.
 **/
gboolean
gtk_init_check (int	 *argc,
		char   ***argv)
{
  if (!gtk_parse_args (argc, argv))
    return FALSE;

953
  return gdk_display_open_default_libgtk_only () != NULL;
954 955
}

956
#ifdef G_PLATFORM_WIN32
957
#undef gtk_init
958
#endif
959

960
/**
Matthias Clasen's avatar
Matthias Clasen committed
961
 * gtk_init:
962
 * @argc: (inout): Address of the <parameter>argc</parameter> parameter of your
Matthias Clasen's avatar
Matthias Clasen committed
963
 *   main() function. Changed if any arguments were handled.
964
 * @argv: (array length=argc) (inout) (allow-none): Address of the <parameter>argv</parameter> parameter of main().
Matthias Clasen's avatar
Matthias Clasen committed
965
 *   Any parameters understood by gtk_init() are stripped before return.
966
 *
967
 * Call this function before using any other GTK+ functions in your GUI
968
 * applications.  It will initialize everything needed to operate the
Matthias Clasen's avatar
Matthias Clasen committed
969
 * toolkit and parses some standard command line options. @argc and 
Matthias Clasen's avatar
Matthias Clasen committed
970
 * @argv are adjusted accordingly so your own code will 
971 972 973 974 975 976 977
 * 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().
978 979 980 981 982 983
 *
 * <note><para>
 * This function will terminate your program if it was unable to initialize 
 * the GUI for some reason. If you want your program to fall back to a 
 * textual interface you want to call gtk_init_check() instead.
 * </para></note>
984 985 986 987 988 989 990 991 992
 *
 * <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>
993
 **/
994 995 996 997 998
void
gtk_init (int *argc, char ***argv)
{
  if (!gtk_init_check (argc, argv))
    {
999
      const char *display_name_arg = gdk_get_display_arg_name ();
1000 1001 1002
      if (display_name_arg == NULL)
        display_name_arg = getenv("DISPLAY");
      g_warning ("cannot open display: %s", display_name_arg ? display_name_arg : "");
1003
      exit (1);
1004
    }
Elliot Lee's avatar
Elliot Lee committed
1005 1006
}

1007
#ifdef G_PLATFORM_WIN32
1008 1009 1010 1011 1012 1013 1014 1015 1016

static void
check_sizeof_GtkWindow (size_t sizeof_GtkWindow)
{
  if (sizeof_GtkWindow != sizeof (GtkWindow))
    g_error ("Incompatible build!\n"
	     "The code using GTK+ thinks GtkWindow is of different\n"
             "size than it actually is in this build of GTK+.\n"
	     "On Windows, this probably means that you have compiled\n"
1017 1018
	     "your code with gcc without the -mms-bitfields switch,\n"
	     "or that you are using an unsupported compiler.");
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
}

/* 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"
	     "The code using GTK+ thinks GtkBox is of different\n"
             "size than it actually is in this build of GTK+.\n"
	     "On Windows, this probably means that you have compiled\n"
1035 1036
	     "your code with gcc without the -mms-bitfields switch,\n"
	     "or that you are using an unsupported compiler.");
1037 1038 1039 1040 1041 1042
}

/* These two functions might get more checks added later, thus pass
 * in the number of extra args.
 */
void
1043
gtk_init_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
1044 1045
{
  check_sizeof_GtkWindow (sizeof_GtkWindow);
1046 1047
  if (num_checks >= 2)
    check_sizeof_GtkBox (sizeof_GtkBox);
1048 1049 1050 1051
  gtk_init (argc, argv);
}

gboolean
1052
gtk_init_check_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
1053 1054
{
  check_sizeof_GtkWindow (sizeof_GtkWindow);
1055 1056
  if (num_checks >= 2)
    check_sizeof_GtkBox (sizeof_GtkBox);
1057 1058 1059 1060 1061
  return gtk_init_check (argc, argv);
}

#endif

1062 1063 1064
/**
 * gtk_set_locale:
 *
1065 1066 1067
 * Initializes internationalization support for GTK+. gtk_init()
 * automatically does this, so there is typically no point
 * in calling this function.
1068
 *
1069 1070 1071 1072 1073
 * If you are calling this function because you changed the locale
 * after GTK+ is was initialized, then calling this function
 * may help a bit. (Note, however, that changing the locale
 * after GTK+ is initialized may produce inconsistent results and
 * is not really supported.)
1074
 * 
1075
 * In detail - sets the current locale according to the
1076 1077 1078
 * program environment. This is the same as calling the C library function
 * <literal>setlocale (LC_ALL, "")</literal> but also takes care of the 
 * locale specific setup of the windowing system used by GDK.
1079
 * 
Matthias Clasen's avatar
Matthias Clasen committed
1080
 * Returns: a string corresponding to the locale set, typically in the
1081 1082
 * form lang_COUNTRY, where lang is an ISO-639 language code, and
 * COUNTRY is an ISO-3166 country code. On Unix, this form matches the
Matthias Clasen's avatar
Matthias Clasen committed
1083 1084 1085
 * result of the setlocale(); it is also used on other machines, such as 
 * Windows, where the C library returns a different result. The string is 
 * owned by GTK+ and should not be modified or freed.
1086
 **/
Sven Neumann's avatar
Sven Neumann committed
1087
gchar *
1088
gtk_set_locale (void)
Elliot Lee's avatar
Elliot Lee committed
1089 1090 1091 1092
{
  return gdk_set_locale ();
}

1093
/**
1094
 * _gtk_get_lc_ctype:
1095
 *
1096 1097 1098 1099 1100 1101 1102 1103 1104
 * Return the Unix-style locale string for the language currently in
 * effect. On Unix systems, this is the return value from
 * <literal>setlocale(LC_CTYPE, NULL)</literal>, and the user can
 * affect this through the environment variables LC_ALL, LC_CTYPE or
 * LANG (checked in that order). The locale strings typically is in
 * the form lang_COUNTRY, where lang is an ISO-639 language code, and
 * COUNTRY is an ISO-3166 country code. For instance, sv_FI for
 * Swedish as written in Finland or pt_BR for Portuguese as written in
 * Brazil.
1105
 * 
1106 1107
 * On Windows, the C library doesn't use any such environment
 * variables, and setting them won't affect the behaviour of functions
Matthias Clasen's avatar
Matthias Clasen committed
1108 1109 1110 1111 1112
 * like ctime(). The user sets the locale through the Regional Options 
 * in the Control Panel. The C library (in the setlocale() function) 
 * does not use country and language codes, but country and language 
 * names spelled out in English. 
 * However, this function does check the above environment
1113 1114 1115 1116 1117 1118 1119 1120
 * variables, and does return a Unix-style locale string based on
 * either said environment variables or the thread's current locale.
 *
 * Return value: a dynamically allocated string, free with g_free().
 */

gchar *
_gtk_get_lc_ctype (void)
1121
{
1122 1123 1124 1125 1126
#ifdef G_OS_WIN32
  /* Somebody might try to set the locale for this process using the
   * LANG or LC_ environment variables. The Microsoft C library
   * doesn't know anything about them. You set the locale in the
   * Control Panel. Setting these env vars won't have any affect on
1127 1128
   * locale-dependent C library functions like ctime(). But just for
   * kicks, do obey LC_ALL, LC_CTYPE and LANG in GTK. (This also makes
1129 1130 1131 1132
   * it easier to test GTK and Pango in various default languages, you
   * don't have to clickety-click in the Control Panel, you can simply
   * start the program with LC_ALL=something on the command line.)
   */
Owen Taylor's avatar
Owen Taylor committed
1133 1134
  gchar *p;

1135 1136
  p = getenv ("LC_ALL");
  if (p != NULL)
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    return g_strdup (p);

  p = getenv ("LC_CTYPE");
  if (p != NULL)
    return g_strdup (p);

  p = getenv ("LANG");
  if (p != NULL)
    return g_strdup (p);

  return g_win32_getlocale ();
1148
#else
1149
  return g_strdup (setlocale (LC_CTYPE, NULL));
1150
#endif
1151 1152 1153 1154 1155 1156 1157 1158 1159
}

/**
 * gtk_get_default_language:
 *
 * Returns the #PangoLanguage for the default language currently in
 * effect. (Note that this can change over the life of an
 * application.)  The default language is derived from the current
 * locale. It determines, for example, whether GTK+ uses the
1160 1161 1162 1163
 * right-to-left or left-to-right text direction.
 *
 * This function is equivalent to pango_language_get_default().  See
 * that function for details.
1164 1165 1166 1167 1168 1169 1170
 * 
 * Return value: the default language as a #PangoLanguage, must not be
 * freed
 **/
PangoLanguage *
gtk_get_default_language (void)
{
1171
  return pango_language_get_default ();
1172 1173
}

Elliot Lee's avatar
Elliot Lee committed
1174
void
1175
gtk_main (void)
Elliot Lee's avatar
Elliot Lee committed
1176 1177 1178 1179
{
  GList *tmp_list;
  GList *functions;
  GtkInitFunction *init;
1180 1181
  GMainLoop *loop;

1182
  gtk_main_loop_level++;
1183
  
Manish Singh's avatar
Manish Singh committed
1184
  loop = g_main_loop_new (NULL, TRUE);
1185 1186
  main_loops = g_slist_prepend (main_loops, loop);

Elliot Lee's avatar
Elliot Lee committed
1187 1188
  tmp_list = functions = init_functions;
  init_functions = NULL;
1189
  
Elliot Lee's avatar
Elliot Lee committed
1190 1191 1192 1193
  while (tmp_list)
    {
      init = tmp_list->data;
      tmp_list = tmp_list->next;
1194
      
Elliot Lee's avatar
Elliot Lee committed
1195 1196 1197 1198
      (* init->function) (init->data);
      g_free (init);
    }
  g_list_free (functions);
1199

Manish Singh's avatar
Manish Singh committed
1200
  if (g_main_loop_is_running (main_loops->data))
1201 1202
    {
      GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1203
      g_main_loop_run (loop);
1204 1205 1206
      GDK_THREADS_ENTER ();
      gdk_flush ();
    }
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216

  if (quit_functions)
    {
      GList *reinvoke_list = NULL;
      GtkQuitFunction *quitf;

      while (quit_functions)
	{
	  quitf = quit_functions->data;

1217
	  tmp_list = quit_functions;
1218
	  quit_functions = g_list_remove_link (quit_functions, quit_functions);
1219
	  g_list_free_1 (tmp_list);
1220

1221
	  if ((quitf->main_level && quitf->main_level != gtk_main_loop_level) ||
1222
	      gtk_quit_invoke_function (quitf))
1223
	    {
1224
	      reinvoke_list = g_list_prepend (reinvoke_list, quitf);
1225 1226 1227
	    }
	  else
	    {
1228
	      gtk_quit_destroy (quitf);
1229 1230 1231 1232
	    }
	}
      if (reinvoke_list)
	{
1233
	  GList *work;
1234
	  
1235
	  work = g_list_last (reinvoke_list);
1236
	  if (quit_functions)
1237 1238 1239
	    quit_functions->prev = work;
	  work->next = quit_functions;
	  quit_functions = work;
1240
	}
1241 1242

      gdk_flush ();
1243
    }
1244
    
1245 1246
  main_loops = g_slist_remove (main_loops, loop);

Manish Singh's avatar
Manish Singh committed
1247
  g_main_loop_unref (loop);
1248

1249
  gtk_main_loop_level--;
1250 1251

  if (gtk_main_loop_level == 0)
1252 1253 1254 1255 1256 1257 1258
    {
      /* Try storing all clipboard data we have */
      _gtk_clipboard_store_all ();

      /* Synchronize the recent manager singleton */
      _gtk_recent_manager_sync ();
    }
1259 1260 1261 1262 1263
}

guint
gtk_main_level (void)
{
1264
  return gtk_main_loop_level;
Elliot Lee's avatar
Elliot Lee committed
1265 1266 1267
}

void
1268
gtk_main_quit (void)
Elliot Lee's avatar
Elliot Lee committed
1269
{
1270 1271
  g_return_if_fail (main_loops != NULL);

Manish Singh's avatar
Manish Singh committed
1272
  g_main_loop_quit (main_loops->data);
Elliot Lee's avatar
Elliot Lee committed
1273 1274
}

1275
gboolean
1276 1277
gtk_events_pending (void)
{
1278 1279 1280
  gboolean result;
  
  GDK_THREADS_LEAVE ();  
Manish Singh's avatar
Manish Singh committed
1281
  result = g_main_context_pending (NULL);
1282 1283 1284
  GDK_THREADS_ENTER ();

  return result;
1285 1286
}

1287
gboolean
1288
gtk_main_iteration (void)
1289
{
1290
  GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1291
  g_main_context_iteration (NULL, TRUE);
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
gboolean
1301
gtk_main_iteration_do (gboolean blocking)
1302
{
1303
  GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1304
  g_main_context_iteration (NULL, blocking);
1305
  GDK_THREADS_ENTER ();
1306

1307
  if (main_loops)
Manish Singh's avatar
Manish Singh committed
1308
    return !g_main_loop_is_running (main_loops->data);
1309 1310
  else
    return TRUE;
1311 1312
}

1313 1314
/* private libgtk to libgdk interfaces
 */
1315 1316 1317 1318
gboolean gdk_device_grab_info_libgtk_only (GdkDisplay  *display,
                                           GdkDevice   *device,
                                           GdkWindow  **grab_window,
                                           gboolean    *owner_events);
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331

static void
rewrite_events_translate (GdkWindow *old_window,
			  GdkWindow *new_window,
			  gdouble   *x,
			  gdouble   *y)
{
  gint old_origin_x, old_origin_y;
  gint new_origin_x, new_origin_y;

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

1332 1333
  *x += old_origin_x - new_origin_x;
  *y += old_origin_y - new_origin_y;
1334 1335
}

1336
static GdkEvent *
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 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 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
rewrite_event_for_window (GdkEvent  *event,
			  GdkWindow *new_window)
{
  event = gdk_event_copy (event);

  switch (event->type)
    {
    case GDK_SCROLL:
      rewrite_events_translate (event->any.window,
				new_window,
				&event->scroll.x, &event->scroll.y);
      break;
    case GDK_BUTTON_PRESS:
    case GDK_2BUTTON_PRESS:
    case GDK_3BUTTON_PRESS:
    case GDK_BUTTON_RELEASE:
      rewrite_events_translate (event->any.window,
				new_window,
				&event->button.x, &event->button.y);
      break;
    case GDK_MOTION_NOTIFY:
      rewrite_events_translate (event->any.window,
				new_window,
				&event->motion.x, &event->motion.y);
      break;
    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;
1389
  GtkWidget *event_widget, *grab_widget;
1390
  gpointer grab_widget_ptr;
1391
  gboolean owner_events;
1392
  GdkDisplay *display;
1393
  GdkDevice *device;
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406

  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:
1407 1408 1409 1410
      display = gdk_drawable_get_display (event->any.window);
      device = gdk_event_get_device (event);

      if (!gdk_device_grab_info_libgtk_only (display, device, &grab_window, &owner_events) ||
1411
	  !owner_events)
1412
        return NULL;
1413 1414 1415 1416 1417 1418
      break;
    default:
      return NULL;
    }

  event_widget = gtk_get_event_widget (event);
1419 1420
  gdk_window_get_user_data (grab_window, &grab_widget_ptr);
  grab_widget = grab_widget_ptr;
1421 1422 1423 1424 1425 1426 1427 1428

  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;
}

Owen Taylor's avatar
Owen Taylor committed
1429
void 
1430
gtk_main_do_event (GdkEvent *event)
Elliot Lee's avatar
Elliot Lee committed
1431 1432
{
  GtkWidget *event_widget;
1433
  GtkWidget *grab_widget = NULL;
1434
  GtkWindowGroup *window_group;
1435
  GdkEvent *rewritten_event = NULL;
1436
  GdkDevice *device;
1437
  GList *tmp_list;
1438

1439 1440 1441 1442 1443 1444
  if (event->type == GDK_SETTING)
    {
      _gtk_settings_handle_event (&event->setting);
      return;
    }

1445 1446 1447 1448 1449 1450
  if (event->type == GDK_OWNER_CHANGE)
    {
      _gtk_clipboard_handle_event (&event->owner_change);
      return;
    }

1451 1452 1453 1454 1455 1456 1457 1458 1459
  /* Find the widget which got the event. We store the widget
   *  in the user_data field of GdkWindow's.
   *  Ignore the event if we don't have a widget for it, except
   *  for GDK_PROPERTY_NOTIFY events which are handled specialy.
   *  Though this happens rarely, bogus events can occour
   *  for e.g. destroyed GdkWindows. 
   */
  event_widget = gtk_get_event_widget (event);
  if (!event_widget)
Elliot Lee's avatar
Elliot Lee committed
1460
    {
1461 1462 1463 1464 1465 1466 1467
      /* To handle selection INCR transactions, we select
       * PropertyNotify events on the requestor window and create
       * a corresponding (fake) GdkWindow so that events get
       * here. There won't be a widget though, so we have to handle
	   * them specially
	   */
      if (event->type == GDK_PROPERTY_NOTIFY)
1468 1469
	_gtk_selection_incr_event (event->any.window,
				   &event->property);
1470

1471
      return;
Elliot Lee's avatar
Elliot Lee committed
1472
    }
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483

  /* If pointer or keyboard grabs are in effect, munge the events
   * so that each window group looks like a separate app.
   */
  rewritten_event = rewrite_event_for_grabs (event);
  if (rewritten_event)
    {
      event = rewritten_event;
      event_widget = gtk_get_event_widget (event);
    }

1484 1485
  window_group = gtk_main_get_window_group (event_widget);
  device = gdk_event_get_device (event);
1486

1487
  /* check whether there is a (device) grab in effect...
Elliot Lee's avatar
Elliot Lee committed
1488
   */
1489 1490
  if (device)
    grab_widget = gtk_window_group_get_current_device_grab (window_group, device);
1491

1492 1493
  if (!grab_widget && window_group->grabs)
    grab_widget = window_group->grabs->data;
1494

1495 1496 1497 1498 1499 1500 1501
  /* If the grab widget is an ancestor of the event widget
   *  then we send the event to the original event widget.
   *  This is the key to implementing modality.
   */
  if (!grab_widget ||
      (gtk_widget_is_sensitive (event_widget) &&
       gtk_widget_is_ancestor (event_widget, grab_widget)))
1502 1503 1504 1505 1506
    grab_widget = event_widget;

  /* If the widget receiving events is actually blocked by another device GTK+ grab */
  if (device &&
      _gtk_window_group_widget_is_blocked_for_device (window_group, grab_widget, device))
1507
    {
1508 1509 1510 1511
      if (rewritten_event)
        gdk_event_free (rewritten_event);

      return;
Elliot Lee's avatar
Elliot Lee committed
1512
    }
1513

1514 1515 1516 1517 1518
  /* Push the event onto a stack of current events for
   * gtk_current_event_get().
   */
  current_events = g_list_prepend (current_events, event);

1519