gtkmain.c 64.5 KB
Newer Older
Elliot Lee's avatar
Elliot Lee committed
1 2 3 4
/* GTK - The GIMP Toolkit
 * 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 28
#include <config.h>

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 34 35 36 37

#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
#include <libintl.h>
#endif

Elliot Lee's avatar
Elliot Lee committed
38 39
#include <stdio.h>
#include <stdlib.h>
40
#include <string.h>
41
#ifdef HAVE_UNISTD_H
42 43
#include <unistd.h>
#endif
44 45
#include <sys/types.h>		/* For uid_t, gid_t */

Tor Lillqvist's avatar
Tor Lillqvist committed
46 47 48 49 50
#ifdef G_OS_WIN32
#define STRICT
#include <windows.h>
#undef STRICT
#endif
51

52
#include <pango/pango-types.h>	/* For pango_language_from_string */
53

Tor Lillqvist's avatar
Tor Lillqvist committed
54 55
#include "gtkintl.h"

56
#include "gtkaccelmap.h"
57
#include "gtkbox.h"
58
#include "gtkclipboard.h"
59
#include "gtkdnd.h"
60
#include "gtkversion.h"
Elliot Lee's avatar
Elliot Lee committed
61
#include "gtkmain.h"
62
#include "gtkmodules.h"
Elliot Lee's avatar
Elliot Lee committed
63 64
#include "gtkrc.h"
#include "gtkselection.h"
65
#include "gtksettings.h"
Elliot Lee's avatar
Elliot Lee committed
66 67
#include "gtkwidget.h"
#include "gtkwindow.h"
Kristian Rietveld's avatar
Kristian Rietveld committed
68
#include "gtktooltip.h"
69
#include "gtkprivate.h"
70
#include "gtkdebug.h"
71
#include "gtkalias.h"
Elliot Lee's avatar
Elliot Lee committed
72

73 74
#include "gdk/gdkprivate.h" /* for GDK_WINDOW_DESTROYED */

Elliot Lee's avatar
Elliot Lee committed
75 76
/* Private type definitions
 */
77 78
typedef struct _GtkInitFunction		 GtkInitFunction;
typedef struct _GtkQuitFunction		 GtkQuitFunction;
79
typedef struct _GtkClosure	         GtkClosure;
80
typedef struct _GtkKeySnooperData	 GtkKeySnooperData;
Elliot Lee's avatar
Elliot Lee committed
81 82 83 84 85 86 87

struct _GtkInitFunction
{
  GtkFunction function;
  gpointer data;
};

88 89
struct _GtkQuitFunction
{
90
  guint id;
91 92 93 94 95 96 97
  guint main_level;
  GtkCallbackMarshal marshal;
  GtkFunction function;
  gpointer data;
  GtkDestroyNotify destroy;
};

98
struct _GtkClosure
Elliot Lee's avatar
Elliot Lee committed
99
{
100
  GtkCallbackMarshal marshal;
Elliot Lee's avatar
Elliot Lee committed
101 102 103 104
  gpointer data;
  GtkDestroyNotify destroy;
};

105 106 107 108
struct _GtkKeySnooperData
{
  GtkKeySnoopFunc func;
  gpointer func_data;
109
  guint id;
110 111
};

112 113 114 115
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);
116 117 118 119 120 121 122

static void     gtk_destroy_closure      (gpointer            data);
static gboolean gtk_invoke_idle_timeout  (gpointer            data);
static void     gtk_invoke_input         (gpointer            data,
					  gint                source,
					  GdkInputCondition   condition);

123
#if 0
124 125 126 127
static void  gtk_error			 (gchar		     *str);
static void  gtk_warning		 (gchar		     *str);
static void  gtk_message		 (gchar		     *str);
static void  gtk_print			 (gchar		     *str);
128
#endif
129

130 131
static GtkWindowGroup *gtk_main_get_window_group (GtkWidget   *widget);

132 133 134
const guint gtk_major_version = GTK_MAJOR_VERSION;
const guint gtk_minor_version = GTK_MINOR_VERSION;
const guint gtk_micro_version = GTK_MICRO_VERSION;
135 136
const guint gtk_binary_age = GTK_BINARY_AGE;
const guint gtk_interface_age = GTK_INTERFACE_AGE;
137

138
static guint gtk_main_loop_level = 0;
Matthias Clasen's avatar
Matthias Clasen committed
139
static gint pre_initialized = FALSE;
140
static gint gtk_initialized = FALSE;
141
static GList *current_events = NULL;
Elliot Lee's avatar
Elliot Lee committed
142

143 144
static GSList *main_loops = NULL;      /* stack of currently executing main loops */

145
static GList *init_functions = NULL;	   /* A list of init functions.
Elliot Lee's avatar
Elliot Lee committed
146
					    */
147 148
static GList *quit_functions = NULL;	   /* A list of quit functions.
					    */
149 150
static GSList *key_snoopers = NULL;

151
guint gtk_debug_flags = 0;		   /* Global GTK debug flag */
152 153

#ifdef G_ENABLE_DEBUG
154
static const GDebugKey gtk_debug_keys[] = {
155
  {"misc", GTK_DEBUG_MISC},
156
  {"plugsocket", GTK_DEBUG_PLUGSOCKET},
157
  {"text", GTK_DEBUG_TEXT},
158
  {"tree", GTK_DEBUG_TREE},
159
  {"updates", GTK_DEBUG_UPDATES},
160
  {"keybindings", GTK_DEBUG_KEYBINDINGS},
161
  {"multihead", GTK_DEBUG_MULTIHEAD},
162
  {"modules", GTK_DEBUG_MODULES},
163
  {"geometry", GTK_DEBUG_GEOMETRY},
164 165
  {"icontheme", GTK_DEBUG_ICONTHEME},
  {"printing", GTK_DEBUG_PRINTING}
166 167
};
#endif /* G_ENABLE_DEBUG */
Elliot Lee's avatar
Elliot Lee committed
168

169 170 171
/**
 * gtk_check_version:
 * @required_major: the required major version.
172 173
 * @required_minor: the required minor version.
 * @required_micro: the required micro version.
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
 * 
 * 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.
 **/
203 204 205 206 207
gchar*
gtk_check_version (guint required_major,
		   guint required_minor,
		   guint required_micro)
{
208 209 210
  gint gtk_effective_micro = 100 * GTK_MINOR_VERSION + GTK_MICRO_VERSION;
  gint required_effective_micro = 100 * required_minor + required_micro;

211
  if (required_major > GTK_MAJOR_VERSION)
212
    return "Gtk+ version too old (major mismatch)";
213
  if (required_major < GTK_MAJOR_VERSION)
214
    return "Gtk+ version too new (major mismatch)";
215
  if (required_effective_micro < gtk_effective_micro - GTK_BINARY_AGE)
216
    return "Gtk+ version too new (micro mismatch)";
217
  if (required_effective_micro > gtk_effective_micro)
218
    return "Gtk+ version too old (micro mismatch)";
219 220 221
  return NULL;
}

Owen Taylor's avatar
Owen Taylor committed
222 223 224 225 226 227 228 229 230 231
/* 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)
{
232
/* this isn't at all relevant on MS Windows and doesn't compile ... --hb */
233
#ifndef G_OS_WIN32
Owen Taylor's avatar
Owen Taylor committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
  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);
    }
263
#endif
Owen Taylor's avatar
Owen Taylor committed
264 265 266
  return TRUE;
}

Tor Lillqvist's avatar
Tor Lillqvist committed
267 268 269 270
#ifdef G_OS_WIN32

G_WIN32_DLLMAIN_FOR_DLL_NAME(static, dll_name)

271 272 273 274 275 276 277 278 279 280 281
const gchar *
_gtk_get_datadir (void)
{
  static char *gtk_datadir = NULL;
  if (gtk_datadir == NULL)
    gtk_datadir = g_win32_get_package_installation_subdirectory
      (GETTEXT_PACKAGE, dll_name, "share");

  return gtk_datadir;
}

Tor Lillqvist's avatar
Tor Lillqvist committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
const gchar *
_gtk_get_libdir (void)
{
  static char *gtk_libdir = NULL;
  if (gtk_libdir == NULL)
    gtk_libdir = g_win32_get_package_installation_subdirectory
      (GETTEXT_PACKAGE, dll_name, "lib");

  return gtk_libdir;
}

const gchar *
_gtk_get_localedir (void)
{
  static char *gtk_localedir = NULL;
  if (gtk_localedir == NULL)
298 299 300 301 302 303 304 305 306 307 308 309
    {
      gchar *temp;
      
      temp = g_win32_get_package_installation_subdirectory
        (GETTEXT_PACKAGE, dll_name, "lib\\locale");

      /* gtk_localedir is passed to bindtextdomain() which isn't
       * UTF-8-aware.
       */
      gtk_localedir = g_win32_locale_filename_from_utf8 (temp);
      g_free (temp);
    }
Tor Lillqvist's avatar
Tor Lillqvist committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
  return gtk_localedir;
}

const gchar *
_gtk_get_sysconfdir (void)
{
  static char *gtk_sysconfdir = NULL;
  if (gtk_sysconfdir == NULL)
    gtk_sysconfdir = g_win32_get_package_installation_subdirectory
      (GETTEXT_PACKAGE, dll_name, "etc");

  return gtk_sysconfdir;
}

const gchar *
_gtk_get_data_prefix (void)
{
  static char *gtk_data_prefix = NULL;
  if (gtk_data_prefix == NULL)
    gtk_data_prefix = g_win32_get_package_installation_directory
      (GETTEXT_PACKAGE, dll_name);

  return gtk_data_prefix;
}

#endif /* G_OS_WIN32 */

337 338 339 340 341
static gboolean do_setlocale = TRUE;

/**
 * gtk_disable_setlocale:
 * 
342 343
 * Prevents gtk_init(), gtk_init_check(), gtk_init_with_args() and
 * gtk_parse_args() from automatically
344 345 346 347
 * 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.
348 349 350
 *
 * Most programs should not need to call this function.
 **/
351
void
352 353
gtk_disable_setlocale (void)
{
Matthias Clasen's avatar
Matthias Clasen committed
354
  if (pre_initialized)
355 356 357 358 359
    g_warning ("gtk_disable_setlocale() must be called before gtk_init()");
    
  do_setlocale = FALSE;
}

360
#ifdef G_PLATFORM_WIN32
361
#undef gtk_init_check
362
#endif
363

364
static GString *gtk_modules_string = NULL;
365
static gboolean g_fatal_warnings = FALSE;
366 367 368 369

#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
370
{
371 372
  gtk_debug_flags |= g_parse_debug_string (value,
					   gtk_debug_keys,
373
					   G_N_ELEMENTS (gtk_debug_keys));
374

375 376
  return TRUE;
}
Tim Janik's avatar
Tim Janik committed
377

378 379 380 381 382
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,
383
					    G_N_ELEMENTS (gtk_debug_keys));
384 385

  return TRUE;
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
}
#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
405
static const GOptionEntry gtk_args[] = {
406 407 408
  { "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") },
409
  { "g-fatal-warnings", 0, 0, G_OPTION_ARG_NONE, &g_fatal_warnings, 
410
    /* Description of --g-fatal-warnings in --help output */   N_("Make all warnings fatal"), NULL },
411
#ifdef G_ENABLE_DEBUG
412 413 414 415 416 417 418
  { "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 
419 420 421
  { NULL }
};

Tor Lillqvist's avatar
Tor Lillqvist committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 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
#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

511 512 513 514 515
static void
do_pre_parse_initialization (int    *argc,
			     char ***argv)
{
  const gchar *env_string;
Owen Taylor's avatar
Owen Taylor committed
516
  
517 518 519 520 521 522
#if	0
  g_set_error_handler (gtk_error);
  g_set_warning_handler (gtk_warning);
  g_set_message_handler (gtk_message);
  g_set_print_handler (gtk_print);
#endif
523

Matthias Clasen's avatar
Matthias Clasen committed
524 525 526 527 528
  if (pre_initialized)
    return;

  pre_initialized = TRUE;

529
  if (do_setlocale)
530
    {
Tor Lillqvist's avatar
Tor Lillqvist committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 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
#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
588 589
      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
590
#endif
591
    }
592

Matthias Clasen's avatar
Matthias Clasen committed
593
  gdk_pre_parse_libgtk_only ();
Owen Taylor's avatar
Owen Taylor committed
594
  gdk_event_handler_set ((GdkEventFunc)gtk_main_do_event, NULL, NULL);
595
  
596
#ifdef G_ENABLE_DEBUG
Matthias Clasen's avatar
Matthias Clasen committed
597
  env_string = g_getenv ("GTK_DEBUG");
598 599 600
  if (env_string != NULL)
    {
      gtk_debug_flags = g_parse_debug_string (env_string,
601
					      gtk_debug_keys,
602
					      G_N_ELEMENTS (gtk_debug_keys));
603 604
      env_string = NULL;
    }
605
#endif	/* G_ENABLE_DEBUG */
606

Matthias Clasen's avatar
Matthias Clasen committed
607
  env_string = g_getenv ("GTK_MODULES");
608
  if (env_string)
609
    gtk_modules_string = g_string_new (env_string);
610
}
611

612 613 614 615 616 617 618 619 620 621 622 623 624
static void
gettext_initialization (void)
{
#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  
}

625 626 627 628
static void
do_post_parse_initialization (int    *argc,
			      char ***argv)
{
629 630 631
  if (gtk_initialized)
    return;

632 633
  gettext_initialization ();

634 635 636 637 638 639 640 641 642
  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);
    }

643 644
  if (gtk_debug_flags & GTK_DEBUG_UPDATES)
    gdk_window_set_debug_updates (TRUE);
645

646 647
  {
  /* Translate to default:RTL if you want your widgets
Robert Brady's avatar
Robert Brady committed
648 649 650
   * 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 
651 652 653 654 655 656 657 658 659
   */
    char *e = _("default:LTR");
    if (strcmp (e, "default:RTL")==0) {
      gtk_widget_set_default_direction (GTK_TEXT_DIR_RTL);
    } else if (strcmp (e, "default:LTR")) {
      g_warning ("Whoever translated default:LTR did so wrongly.\n");
    }
  }

660
  gtk_type_init (0);
661
  _gtk_accel_map_init ();  
662
  _gtk_rc_init ();
663

Elliot Lee's avatar
Elliot Lee committed
664 665
  /* Set the 'initialized' flag.
   */
666
  gtk_initialized = TRUE;
667

668 669
  /* load gtk modules */
  if (gtk_modules_string)
670
    {
671 672
      _gtk_modules_init (argc, argv, gtk_modules_string->str);
      g_string_free (gtk_modules_string, TRUE);
673
    }
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
}


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)
705 706 707
    {
      if (gdk_display_open_default_libgtk_only () == NULL)
	{
708
	  const char *display_name = gdk_get_display_arg_name ();
709 710 711 712
	  g_set_error (error, 
		       G_OPTION_ERROR, 
		       G_OPTION_ERROR_FAILED,
		       "cannot open display: %s",
713
		       display_name ? display_name : "" );
714 715 716 717 718 719
	  
	  return FALSE;
	}
    }

  return TRUE;
720 721 722
}


723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
/**
 * 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.
 *
 * Returns a #GOptionGroup for the commandline arguments recognized
 *   by GTK+
 *
 * Since: 2.6
 */
738 739 740 741 742 743
GOptionGroup *
gtk_get_option_group (gboolean open_default_display)
{
  GOptionGroup *group;
  OptionGroupInfo *info;

744 745
  gettext_initialization ();

746 747 748 749 750 751 752 753
  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);
754
  g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
755 756 757 758
  
  return group;
}

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
/**
 * 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
 *    the first line of <option>--help</option> output, after 
 *    <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
 *    with gettext(), or %NULL
 * @error: a return location for errors 
 *
 * This function does the same work as gtk_init_check(). 
 * Additionally, it allows you to add your own commandline options, 
775
 * and it automatically generates nicely formatted 
776 777 778 779 780 781 782 783
 * <option>--help</option> output. Note that your program will
 * be terminated after writing out the help output.
 *
 * Returns: %TRUE if the GUI has been successfully initialized, 
 *               %FALSE otherwise.
 * 
 * Since: 2.6
 */
784 785 786 787 788 789 790 791 792 793 794
gboolean
gtk_init_with_args (int            *argc,
		    char         ***argv,
		    char           *parameter_string,  
		    GOptionEntry   *entries,
		    char           *translation_domain,
		    GError        **error)
{
  GOptionContext *context;
  GOptionGroup *gtk_group;
  gboolean retval;
Matthias Clasen's avatar
Matthias Clasen committed
795

796 797 798
  if (gtk_initialized)
    return TRUE;

799 800
  gettext_initialization ();

Matthias Clasen's avatar
Matthias Clasen committed
801 802 803
  if (!check_setugid ())
    return FALSE;

804 805 806 807 808 809 810 811
  gtk_group = gtk_get_option_group (TRUE);
  
  context = g_option_context_new (parameter_string);
  g_option_context_add_group (context, gtk_group);
  
  if (entries)
    g_option_context_add_main_entries (context, entries, translation_domain);
  retval = g_option_context_parse (context, argc, argv, error);
812
  
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
  g_option_context_free (context);

  return retval;
}


/**
 * gtk_parse_args:
 * @argc: a pointer to the number of command line arguments.
 * @argv: a pointer to the array of command line arguments.
 * 
 * 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;
841
  GOptionGroup *gtk_group;
842
  GError *error = NULL;
843 844 845 846
  
  if (gtk_initialized)
    return TRUE;

847 848
  gettext_initialization ();

849 850 851 852 853 854
  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);
855 856
  gtk_group = gtk_get_option_group (FALSE);
  g_option_context_set_main_group (option_context, gtk_group);
857 858 859 860 861 862
  if (!g_option_context_parse (option_context, argc, argv, &error))
    {
      g_warning ("%s", error->message);
      g_error_free (error);
    }

863 864
  g_option_context_free (option_context);

865 866
  return TRUE;
}
867

868
#ifdef G_PLATFORM_WIN32
869
#undef gtk_init_check
870
#endif
871 872 873 874

/**
 * gtk_init_check:
 * @argc: Address of the <parameter>argc</parameter> parameter of your 
Matthias Clasen's avatar
Matthias Clasen committed
875 876 877
 *   main() function. Changed if any arguments were handled.
 * @argv: Address of the <parameter>argv</parameter> parameter of main(). 
 *   Any parameters understood by gtk_init() are stripped before return.
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
 * 
 * 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 
 * 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;

896
  return gdk_display_open_default_libgtk_only () != NULL;
897 898
}

899
#ifdef G_PLATFORM_WIN32
900
#undef gtk_init
901
#endif
902

903
/**
Matthias Clasen's avatar
Matthias Clasen committed
904
 * gtk_init:
905
 * @argc: Address of the <parameter>argc</parameter> parameter of your 
Matthias Clasen's avatar
Matthias Clasen committed
906 907 908
 *   main() function. Changed if any arguments were handled.
 * @argv: Address of the <parameter>argv</parameter> parameter of main(). 
 *   Any parameters understood by gtk_init() are stripped before return.
909 910
 * 
 * Call this function before using any other GTK+ functions in your GUI
Matthias Clasen's avatar
Matthias Clasen committed
911 912
 * applications.  It will initialize everything needed to operate the 
 * toolkit and parses some standard command line options. @argc and 
Matthias Clasen's avatar
Matthias Clasen committed
913
 * @argv are adjusted accordingly so your own code will 
914 915 916 917 918 919 920
 * 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().
921 922 923 924 925 926 927
 *
 * <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>
 **/
928 929 930 931 932
void
gtk_init (int *argc, char ***argv)
{
  if (!gtk_init_check (argc, argv))
    {
933
      const char *display_name_arg = gdk_get_display_arg_name ();
934
      g_warning ("cannot open display: %s", display_name_arg ? display_name_arg : " ");
935
      exit (1);
936
    }
Elliot Lee's avatar
Elliot Lee committed
937 938
}

939
#ifdef G_PLATFORM_WIN32
940 941 942 943 944 945 946 947 948

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"
949 950
	     "your code with gcc without the -mms-bitfields switch,\n"
	     "or that you are using an unsupported compiler.");
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
}

/* 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"
967 968
	     "your code with gcc without the -mms-bitfields switch,\n"
	     "or that you are using an unsupported compiler.");
969 970 971 972 973 974
}

/* These two functions might get more checks added later, thus pass
 * in the number of extra args.
 */
void
975
gtk_init_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
976 977
{
  check_sizeof_GtkWindow (sizeof_GtkWindow);
978 979
  if (num_checks >= 2)
    check_sizeof_GtkBox (sizeof_GtkBox);
980 981 982 983
  gtk_init (argc, argv);
}

gboolean
984
gtk_init_check_abi_check (int *argc, char ***argv, int num_checks, size_t sizeof_GtkWindow, size_t sizeof_GtkBox)
985 986
{
  check_sizeof_GtkWindow (sizeof_GtkWindow);
987 988
  if (num_checks >= 2)
    check_sizeof_GtkBox (sizeof_GtkBox);
989 990 991 992 993
  return gtk_init_check (argc, argv);
}

#endif

Elliot Lee's avatar
Elliot Lee committed
994
void
Tor Lillqvist's avatar
Tor Lillqvist committed
995
gtk_exit (gint errorcode)
Elliot Lee's avatar
Elliot Lee committed
996
{
997
  exit (errorcode);
Elliot Lee's avatar
Elliot Lee committed
998 999
}

1000 1001 1002 1003

/**
 * gtk_set_locale:
 *
1004 1005 1006
 * Initializes internationalization support for GTK+. gtk_init()
 * automatically does this, so there is typically no point
 * in calling this function.
1007
 *
1008 1009 1010 1011 1012
 * 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.)
1013
 * 
1014
 * In detail - sets the current locale according to the
1015 1016 1017
 * 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.
1018
 * 
Matthias Clasen's avatar
Matthias Clasen committed
1019
 * Returns: a string corresponding to the locale set, typically in the
1020 1021
 * 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
1022 1023 1024
 * 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.
1025
 **/
Sven Neumann's avatar
Sven Neumann committed
1026
gchar *
1027
gtk_set_locale (void)
Elliot Lee's avatar
Elliot Lee committed
1028 1029 1030 1031
{
  return gdk_set_locale ();
}

1032
/**
1033
 * _gtk_get_lc_ctype:
1034
 *
1035 1036 1037 1038 1039 1040 1041 1042 1043
 * 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.
1044
 * 
1045 1046
 * 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
1047 1048 1049 1050 1051
 * 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
1052 1053 1054 1055 1056 1057 1058 1059
 * 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)
1060
{
1061 1062 1063 1064 1065
#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
1066 1067
   * locale-dependent C library functions like ctime(). But just for
   * kicks, do obey LC_ALL, LC_CTYPE and LANG in GTK. (This also makes
1068 1069 1070 1071
   * 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
1072 1073
  gchar *p;

1074 1075
  p = getenv ("LC_ALL");
  if (p != NULL)
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    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 ();
1087
#else
1088
  return g_strdup (setlocale (LC_CTYPE, NULL));
1089
#endif
1090 1091 1092 1093 1094 1095 1096 1097 1098
}

/**
 * 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
1099 1100 1101 1102
 * right-to-left or left-to-right text direction.
 *
 * This function is equivalent to pango_language_get_default().  See
 * that function for details.
1103 1104 1105 1106 1107 1108 1109
 * 
 * Return value: the default language as a #PangoLanguage, must not be
 * freed
 **/
PangoLanguage *
gtk_get_default_language (void)
{
1110
  return pango_language_get_default ();
1111 1112
}

Elliot Lee's avatar
Elliot Lee committed
1113
void
1114
gtk_main (void)
Elliot Lee's avatar
Elliot Lee committed
1115 1116 1117 1118
{
  GList *tmp_list;
  GList *functions;
  GtkInitFunction *init;
1119 1120
  GMainLoop *loop;

1121
  gtk_main_loop_level++;
1122
  
Manish Singh's avatar
Manish Singh committed
1123
  loop = g_main_loop_new (NULL, TRUE);
1124 1125
  main_loops = g_slist_prepend (main_loops, loop);

Elliot Lee's avatar
Elliot Lee committed
1126 1127
  tmp_list = functions = init_functions;
  init_functions = NULL;
1128
  
Elliot Lee's avatar
Elliot Lee committed
1129 1130 1131 1132
  while (tmp_list)
    {
      init = tmp_list->data;
      tmp_list = tmp_list->next;
1133
      
Elliot Lee's avatar
Elliot Lee committed
1134 1135 1136 1137
      (* init->function) (init->data);
      g_free (init);
    }
  g_list_free (functions);
1138

Manish Singh's avatar
Manish Singh committed
1139
  if (g_main_loop_is_running (main_loops->data))
1140 1141
    {
      GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1142
      g_main_loop_run (loop);
1143 1144 1145
      GDK_THREADS_ENTER ();
      gdk_flush ();
    }
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155

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

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

1156
	  tmp_list = quit_functions;
1157
	  quit_functions = g_list_remove_link (quit_functions, quit_functions);
1158
	  g_list_free_1 (tmp_list);
1159

1160
	  if ((quitf->main_level && quitf->main_level != gtk_main_loop_level) ||
1161
	      gtk_quit_invoke_function (quitf))
1162
	    {
1163
	      reinvoke_list = g_list_prepend (reinvoke_list, quitf);
1164 1165 1166
	    }
	  else
	    {
1167
	      gtk_quit_destroy (quitf);
1168 1169 1170 1171
	    }
	}
      if (reinvoke_list)
	{
1172
	  GList *work;
1173
	  
1174
	  work = g_list_last (reinvoke_list);
1175
	  if (quit_functions)
1176 1177 1178
	    quit_functions->prev = work;
	  work->next = quit_functions;
	  quit_functions = work;
1179
	}
1180 1181

      gdk_flush ();
1182
    }
1183
    
1184 1185
  main_loops = g_slist_remove (main_loops, loop);

Manish Singh's avatar
Manish Singh committed
1186
  g_main_loop_unref (loop);
1187

1188
  gtk_main_loop_level--;
1189 1190 1191 1192

  /* Try storing all clipboard data we have */
  if (gtk_main_loop_level == 0)
    _gtk_clipboard_store_all ();
1193 1194 1195 1196 1197
}

guint
gtk_main_level (void)
{
1198
  return gtk_main_loop_level;
Elliot Lee's avatar
Elliot Lee committed
1199 1200 1201
}

void
1202
gtk_main_quit (void)
Elliot Lee's avatar
Elliot Lee committed
1203
{
1204 1205
  g_return_if_fail (main_loops != NULL);

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

1209
gboolean
1210 1211
gtk_events_pending (void)
{
1212 1213 1214
  gboolean result;
  
  GDK_THREADS_LEAVE ();  
Manish Singh's avatar
Manish Singh committed
1215
  result = g_main_context_pending (NULL);
1216 1217 1218
  GDK_THREADS_ENTER ();

  return result;
1219 1220
}

1221
gboolean
1222
gtk_main_iteration (void)
1223
{
1224
  GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1225
  g_main_context_iteration (NULL, TRUE);
1226
  GDK_THREADS_ENTER ();
1227

1228
  if (main_loops)
Manish Singh's avatar
Manish Singh committed
1229
    return !g_main_loop_is_running (main_loops->data);
1230 1231
  else
    return TRUE;
1232 1233
}

1234
gboolean
1235
gtk_main_iteration_do (gboolean blocking)
1236
{
1237
  GDK_THREADS_LEAVE ();
Manish Singh's avatar
Manish Singh committed
1238
  g_main_context_iteration (NULL, blocking);
1239
  GDK_THREADS_ENTER ();
1240

1241
  if (main_loops)
Manish Singh's avatar
Manish Singh committed
1242
    return !g_main_loop_is_running (main_loops->data);
1243 1244
  else
    return TRUE;
1245 1246
}

1247 1248
/* private libgtk to libgdk interfaces
 */
1249 1250
gboolean gdk_pointer_grab_info_libgtk_only  (GdkDisplay *display,
					     GdkWindow **grab_window,
1251
					     gboolean   *owner_events);
1252 1253
gboolean gdk_keyboard_grab_info_libgtk_only (GdkDisplay *display,
					     GdkWindow **grab_window,
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
					     gboolean   *owner_events);

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

1268 1269
  *x += old_origin_x - new_origin_x;
  *y += old_origin_y - new_origin_y;
1270 1271
}

1272
static GdkEvent *
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
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;
1325
  GtkWidget *event_widget, *grab_widget;
1326
  gboolean owner_events;
1327
  GdkDisplay *display;
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338

  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:
1339 1340
      display = gdk_drawable_get_display (event->proximity.window);
      if (!gdk_pointer_grab_info_libgtk_only (display, &grab_window, &owner_events) ||
1341 1342 1343 1344 1345 1346
	  !owner_events)
	return NULL;
      break;

    case GDK_KEY_PRESS:
    case GDK_KEY_RELEASE:
1347 1348
      display = gdk_drawable_get_display (event->key.window);
      if (!gdk_keyboard_grab_info_libgtk_only (display, &grab_window, &owner_events) ||
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
	  !owner_events)
	return NULL;
      break;

    default:
      return NULL;
    }

  event_widget = gtk_get_event_widget (event);
  gdk_window_get_user_data (grab_window, (void**) &grab_widget);

  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
1367
void 
1368
gtk_main_do_event (GdkEvent *event)
Elliot Lee's avatar
Elliot Lee committed
1369 1370 1371
{
  GtkWidget *event_widget;
  GtkWidget *grab_widget;
1372
  GtkWindowGroup *window_group;
1373
  GdkEvent *next_event;
1374
  GdkEvent *rewritten_event = NULL;
1375
  GList *tmp_list;
1376 1377 1378

  /* If there are any events pending then get the next one.
   */
1379
  next_event = gdk_event_peek ();
1380
  
1381 1382 1383 1384 1385 1386 1387
  /* Try to compress enter/leave notify events. These event
   *  pairs occur when the mouse is dragged quickly across
   *  a window with many buttons (or through a menu). Instead
   *  of highlighting and de-highlighting each widget that
   *  is crossed it is better to simply de-highlight the widget
   *  which contained the mouse initially and highlight the
   *  widget which ends up containing the mouse.
1388
   */
1389 1390 1391 1392 1393 1394 1395 1396
  if (next_event)
    if (((event->type == GDK_ENTER_NOTIFY) ||
	 (event->type == GDK_LEAVE_NOTIFY)) &&
	((next_event->type == GDK_ENTER_NOTIFY) ||
	 (next_event->type == GDK_LEAVE_NOTIFY)) &&
	(next_event->type != event->type) &&
	(next_event->any.window == event->any.window))
      {
1397 1398 1399 1400
	/* Throw both the peeked copy and the queued copy away 
	 */
	gdk_event_free (next_event);
	next_event = gdk_event_get ();
1401 1402 1403 1404
	gdk_event_free (next_event);
	
	return;
      }
1405

1406
  if (next_event)
1407
    gdk_event_free (next_event);
1408

1409 1410 1411 1412 1413 1414
  if (event->type == GDK_SETTING)
    {
      _gtk_settings_handle_event (&event->setting);
      return;
    }

1415 1416 1417 1418 1419 1420
  if (event->type == GDK_OWNER_CHANGE)
    {
      _gtk_clipboard_handle_event (&event->owner_change);
      return;
    }

1421 1422 1423 1424 1425 1426 1427 1428 1429
  /* 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
1430
    {
1431 1432 1433 1434 1435 1436 1437
      /* 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)
1438 1439
	_gtk_selection_incr_event (event->any.window,
				   &event->property);
1440

1441
      return;
Elliot Lee's avatar
Elliot Lee committed
1442
    }
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452

  /* 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);
    }
1453
  
1454 1455
  window_group = gtk_main_get_window_group (event_widget);

1456 1457
  /* Push the event onto a stack of current events for
   * gtk_current_event_get().
Elliot Lee's avatar
Elliot Lee committed
1458
   */
1459
  current_events = g_list_prepend (current_events, event);
1460

1461
  /* If there is a grab in effect...
Elliot Lee's avatar
Elliot Lee committed
1462
   */
1463
  if (window_group->grabs)
Elliot Lee's avatar
Elliot Lee committed
1464
    {
1465
      grab_widget = window_group->grabs->data;
1466
      
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
      /* 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 (GTK_WIDGET_IS_SENSITIVE (event_widget) &&
	  gtk_widget_is_ancestor (event_widget, grab_widget))
	grab_widget = event_widget;
    }
  else
    {
      grab_widget = event_widget;
Elliot Lee's avatar
Elliot Lee committed
1478
    }
1479

1480 1481 1482 1483 1484 1485 1486 1487 1488
  /* Not all events get sent to the grabbing widget.
   * The delete, destroy, expose, focus change and resize
   *  events still get sent to the event widget because
   *  1) these events have no meaning for the grabbing widget
   *  and 2) redirecting these events to the grabbing widget
   *  could cause the display to be messed up.
   * 
   * Drag events are also not redirected, since it isn't
   *  clear what the semantics of that would be.
Elliot Lee's avatar
Elliot Lee committed
1489
   */
1490
  switch (event->type)
Elliot Lee's avatar
Elliot Lee committed
1491
    {
1492 1493
    case GDK_NOTHING:
      break;
1494
      
1495
    case GDK_DELETE:
Manish Singh's avatar
Manish Singh committed
1496
      g_object_ref (event_widget);
1497
      if ((!window_group->grabs || gtk_widget_get_toplevel (window_group->grabs->data) == event_widget) &&
Owen Taylor's avatar
Owen Taylor committed
1498
	  !gtk_widget_event (event_widget, event))
1499
	gtk_widget_destroy (event_widget);
Manish Singh's avatar
Manish Singh committed
1500
      g_object_unref (event_widget);
1501
      break;
1502
      
1503
    case GDK_DESTROY:
1504 1505 1506 1507 1508
      /* Unexpected GDK_DESTROY from the outside, ignore for
       * child windows, handle like a GDK_DELETE for toplevels
       */
      if (!event_widget->parent)
	{
Manish Singh's avatar
Manish Singh committed
1509
	  g_object_ref (event_widget);
1510
	  if (!gtk_widget_event (event_widget, event) &&
1511
	      GTK_WIDGET_REALIZED (event_widget))
1512
	    gtk_widget_destroy (event_widget);
Manish Singh's avatar
Manish Singh committed
1513
	  g_object_unref (event_widget);
1514
	}
1515
      break;
1516
      
1517
    case GDK_EXPOSE:
1518
      if (event->any.window && GTK_WIDGET_DOUBLE_BUFFERED (event_widget))
1519 1520 1521 1522 1523 1524 1525
	{
	  gdk_window_begin_paint_region (event->any.window, event->expose.region);
	  gtk_widget_send_expose (event_widget, event);
	  gdk_window_end_paint (event->any.window);
	}
      else
	gtk_widget_send_expose (event_widget, event);
1526 1527 1528
      break;

    case GDK_PROPERTY_NOTIFY:
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
    case GDK_NO_EXPOSE:
    case GDK_FOCUS_CHANGE:
    case GDK_CONFIGURE:
    case GDK_MAP:
    case GDK_UNMAP:
    case GDK_SELECTION_CLEAR:
    case GDK_SELECTION_REQUEST:
    case GDK_SELECTION_NOTIFY:
    case GDK_CLIENT_EVENT:
    case GDK_VISIBILITY_NOTIFY:
1539
    case GDK_WINDOW_STATE:
1540
    case GDK_GRAB_BROKEN:
1541 1542
      gtk_widget_event (event_widget, event);
      break;
1543

1544
    case GDK_SCROLL:
1545 1546 1547 1548 1549 1550
    case GDK_BUTTON_PRESS:
    case GDK_2BUTTON_PRESS:
    case GDK_3BUTTON_PRESS:
      gtk_propagate_event (grab_widget, event);
      break;

1551 1552 1553
    case GDK_KEY_PRESS:
    case GDK_KEY_RELEASE:
      if (key_snoopers)
Elliot Lee's avatar
Elliot Lee committed
1554
	{
1555 1556
	  if (gtk_invoke_key_snoopers (grab_widget, event))
	    break;
Elliot Lee's avatar
Elliot Lee committed
1557
	}
Owen Taylor's avatar