]> Pileus Git - ~andy/gtk/blob - gdk/gdk.c
Change FSF Address
[~andy/gtk] / gdk / gdk.c
1 /* GDK - The GIMP Drawing Kit
2  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /*
19  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
20  * file for a list of people on the GTK+ Team.  See the ChangeLog
21  * files for a list of changes.  These files are distributed with
22  * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
23  */
24
25 #include "config.h"
26
27 #include "gdkmain.h"
28
29 #include "gdkinternals.h"
30 #include "gdkintl.h"
31
32 #ifndef HAVE_XCONVERTCASE
33 #include "gdkkeysyms.h"
34 #endif
35
36 #include <string.h>
37 #include <stdlib.h>
38
39
40 /**
41  * SECTION:general
42  * @Short_description: Library initialization and miscellaneous functions
43  * @Title: General
44  *
45  * This section describes the GDK initialization functions and miscellaneous
46  * utility functions, as well as deprecation facilities.
47  *
48  * The GDK and GTK+ headers annotate deprecated APIs in a way that produces
49  * compiler warnings if these deprecated APIs are used. The warnings
50  * can be turned off by defining the macro %GDK_DISABLE_DEPRECATION_WARNINGS
51  * before including the glib.h header.
52  *
53  * GDK and GTK+ also provide support for building applications against
54  * defined subsets of deprecated or new APIs. Define the macro
55  * %GDK_VERSION_MIN_REQUIRED to specify up to what version
56  * you want to receive warnings about deprecated APIs. Define the
57  * macro %GDK_VERSION_MAX_ALLOWED to specify the newest version
58  * whose API you want to use.
59  */
60
61 /**
62  * GDK_WINDOWING_X11:
63  *
64  * The #GDK_WINDOWING_X11 macro is defined if the X11 backend
65  * is supported.
66  *
67  * Use this macro to guard code that is specific to the X11 backend.
68  */
69
70 /**
71  * GDK_WINDOWING_WIN32:
72  *
73  * The #GDK_WINDOWING_WIN32 macro is defined if the Win32 backend
74  * is supported.
75  *
76  * Use this macro to guard code that is specific to the Win32 backend.
77  */
78
79 /**
80  * GDK_WINDOWING_QUARTZ:
81  *
82  * The #GDK_WINDOWING_QUARTZ macro is defined if the Quartz backend
83  * is supported.
84  *
85  * Use this macro to guard code that is specific to the Quartz backend.
86  */
87
88 /**
89  * GDK_DISABLE_DEPRECATION_WARNINGS:
90  *
91  * A macro that should be defined before including the gdk.h header.
92  * If it is defined, no compiler warnings will be produced for uses
93  * of deprecated GDK APIs.
94  */
95
96 typedef struct _GdkPredicate  GdkPredicate;
97
98 struct _GdkPredicate
99 {
100   GdkEventFunc func;
101   gpointer data;
102 };
103
104 typedef struct _GdkThreadsDispatch GdkThreadsDispatch;
105
106 struct _GdkThreadsDispatch
107 {
108   GSourceFunc func;
109   gpointer data;
110   GDestroyNotify destroy;
111 };
112
113
114 /* Private variable declarations
115  */
116 static int gdk_initialized = 0;                     /* 1 if the library is initialized,
117                                                      * 0 otherwise.
118                                                      */
119
120 static gchar  *gdk_progclass = NULL;
121
122 static GMutex gdk_threads_mutex;
123
124 static GCallback gdk_threads_lock = NULL;
125 static GCallback gdk_threads_unlock = NULL;
126
127 #ifdef G_ENABLE_DEBUG
128 static const GDebugKey gdk_debug_keys[] = {
129   {"events",        GDK_DEBUG_EVENTS},
130   {"misc",          GDK_DEBUG_MISC},
131   {"dnd",           GDK_DEBUG_DND},
132   {"xim",           GDK_DEBUG_XIM},
133   {"nograbs",       GDK_DEBUG_NOGRABS},
134   {"input",         GDK_DEBUG_INPUT},
135   {"cursor",        GDK_DEBUG_CURSOR},
136   {"multihead",     GDK_DEBUG_MULTIHEAD},
137   {"xinerama",      GDK_DEBUG_XINERAMA},
138   {"draw",          GDK_DEBUG_DRAW},
139   {"eventloop",     GDK_DEBUG_EVENTLOOP}
140 };
141
142 static gboolean
143 gdk_arg_debug_cb (const char *key, const char *value, gpointer user_data, GError **error)
144 {
145   guint debug_value = g_parse_debug_string (value,
146                                             (GDebugKey *) gdk_debug_keys,
147                                             G_N_ELEMENTS (gdk_debug_keys));
148
149   if (debug_value == 0 && value != NULL && strcmp (value, "") != 0)
150     {
151       g_set_error (error,
152                    G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
153                    _("Error parsing option --gdk-debug"));
154       return FALSE;
155     }
156
157   _gdk_debug_flags |= debug_value;
158
159   return TRUE;
160 }
161
162 static gboolean
163 gdk_arg_no_debug_cb (const char *key, const char *value, gpointer user_data, GError **error)
164 {
165   guint debug_value = g_parse_debug_string (value,
166                                             (GDebugKey *) gdk_debug_keys,
167                                             G_N_ELEMENTS (gdk_debug_keys));
168
169   if (debug_value == 0 && value != NULL && strcmp (value, "") != 0)
170     {
171       g_set_error (error,
172                    G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
173                    _("Error parsing option --gdk-no-debug"));
174       return FALSE;
175     }
176
177   _gdk_debug_flags &= ~debug_value;
178
179   return TRUE;
180 }
181 #endif /* G_ENABLE_DEBUG */
182
183 static gboolean
184 gdk_arg_class_cb (const char *key, const char *value, gpointer user_data, GError **error)
185 {
186   gdk_set_program_class (value);
187
188   return TRUE;
189 }
190
191 static gboolean
192 gdk_arg_name_cb (const char *key, const char *value, gpointer user_data, GError **error)
193 {
194   g_set_prgname (value);
195
196   return TRUE;
197 }
198
199 static const GOptionEntry gdk_args[] = {
200   { "class",        0, 0,                     G_OPTION_ARG_CALLBACK, gdk_arg_class_cb,
201     /* Description of --class=CLASS in --help output */        N_("Program class as used by the window manager"),
202     /* Placeholder in --class=CLASS in --help output */        N_("CLASS") },
203   { "name",         0, 0,                     G_OPTION_ARG_CALLBACK, gdk_arg_name_cb,
204     /* Description of --name=NAME in --help output */          N_("Program name as used by the window manager"),
205     /* Placeholder in --name=NAME in --help output */          N_("NAME") },
206   { "display",      0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_STRING,   &_gdk_display_name,
207     /* Description of --display=DISPLAY in --help output */    N_("X display to use"),
208     /* Placeholder in --display=DISPLAY in --help output */    N_("DISPLAY") },
209 #ifdef G_ENABLE_DEBUG
210   { "gdk-debug",    0, 0, G_OPTION_ARG_CALLBACK, gdk_arg_debug_cb,  
211     /* Description of --gdk-debug=FLAGS in --help output */    N_("GDK debugging flags to set"),
212     /* Placeholder in --gdk-debug=FLAGS in --help output */    N_("FLAGS") },
213   { "gdk-no-debug", 0, 0, G_OPTION_ARG_CALLBACK, gdk_arg_no_debug_cb, 
214     /* Description of --gdk-no-debug=FLAGS in --help output */ N_("GDK debugging flags to unset"),
215     /* Placeholder in --gdk-no-debug=FLAGS in --help output */ N_("FLAGS") },
216 #endif 
217   { NULL }
218 };
219
220 /**
221  * gdk_add_option_entries_libgtk_only:
222  * @group: An option group.
223  *
224  * Appends gdk option entries to the passed in option group. This is
225  * not public API and must not be used by applications.
226  */
227 void
228 gdk_add_option_entries_libgtk_only (GOptionGroup *group)
229 {
230   g_option_group_add_entries (group, gdk_args);
231 }
232
233 void
234 gdk_pre_parse_libgtk_only (void)
235 {
236   const char *rendering_mode;
237
238   gdk_initialized = TRUE;
239
240   /* We set the fallback program class here, rather than lazily in
241    * gdk_get_program_class, since we don't want -name to override it.
242    */
243   gdk_progclass = g_strdup (g_get_prgname ());
244   if (gdk_progclass && gdk_progclass[0])
245     gdk_progclass[0] = g_ascii_toupper (gdk_progclass[0]);
246   
247 #ifdef G_ENABLE_DEBUG
248   {
249     gchar *debug_string = getenv("GDK_DEBUG");
250     if (debug_string != NULL)
251       _gdk_debug_flags = g_parse_debug_string (debug_string,
252                                               (GDebugKey *) gdk_debug_keys,
253                                               G_N_ELEMENTS (gdk_debug_keys));
254   }
255 #endif  /* G_ENABLE_DEBUG */
256
257   if (getenv ("GDK_NATIVE_WINDOWS"))
258     {
259       g_warning ("The GDK_NATIVE_WINDOWS environment variable is not supported in GTK3.\n"
260                  "See the documentation for gdk_window_ensure_native() on how to get native windows.");
261       g_unsetenv ("GDK_NATIVE_WINDOWS");
262     }
263
264   rendering_mode = g_getenv ("GDK_RENDERING");
265   if (rendering_mode)
266     {
267       if (g_str_equal (rendering_mode, "similar"))
268         _gdk_rendering_mode = GDK_RENDERING_MODE_SIMILAR;
269       else if (g_str_equal (rendering_mode, "image"))
270         _gdk_rendering_mode = GDK_RENDERING_MODE_IMAGE;
271       else if (g_str_equal (rendering_mode, "recording"))
272         _gdk_rendering_mode = GDK_RENDERING_MODE_RECORDING;
273     }
274
275   g_type_init ();
276
277   /* Do any setup particular to the windowing system */
278   gdk_display_manager_get ();
279 }
280
281   
282 /**
283  * gdk_parse_args:
284  * @argc: the number of command line arguments.
285  * @argv: (inout) (array length=argc): the array of command line arguments.
286  * 
287  * Parse command line arguments, and store for future
288  * use by calls to gdk_display_open().
289  *
290  * Any arguments used by GDK are removed from the array and @argc and @argv are
291  * updated accordingly.
292  *
293  * You shouldn't call this function explicitely if you are using
294  * gtk_init(), gtk_init_check(), gdk_init(), or gdk_init_check().
295  *
296  * Since: 2.2
297  **/
298 void
299 gdk_parse_args (int    *argc,
300                 char ***argv)
301 {
302   GOptionContext *option_context;
303   GOptionGroup *option_group;
304   GError *error = NULL;
305
306   if (gdk_initialized)
307     return;
308
309   gdk_pre_parse_libgtk_only ();
310
311   option_context = g_option_context_new (NULL);
312   g_option_context_set_ignore_unknown_options (option_context, TRUE);
313   g_option_context_set_help_enabled (option_context, FALSE);
314   option_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
315   g_option_context_set_main_group (option_context, option_group);
316
317   g_option_group_add_entries (option_group, gdk_args);
318
319   if (!g_option_context_parse (option_context, argc, argv, &error))
320     {
321       g_warning ("%s", error->message);
322       g_error_free (error);
323     }
324   g_option_context_free (option_context);
325
326   GDK_NOTE (MISC, g_message ("progname: \"%s\"", g_get_prgname ()));
327 }
328
329 /**
330  * gdk_get_display_arg_name:
331  *
332  * Gets the display name specified in the command line arguments passed
333  * to gdk_init() or gdk_parse_args(), if any.
334  *
335  * Returns: the display name, if specified explicitely, otherwise %NULL
336  *   this string is owned by GTK+ and must not be modified or freed.
337  *
338  * Since: 2.2
339  */
340 const gchar *
341 gdk_get_display_arg_name (void)
342 {
343   if (!_gdk_display_arg_name)
344     _gdk_display_arg_name = g_strdup (_gdk_display_name);
345
346    return _gdk_display_arg_name;
347 }
348
349 /**
350  * gdk_display_open_default_libgtk_only:
351  *
352  * Opens the default display specified by command line arguments or
353  * environment variables, sets it as the default display, and returns
354  * it.  gdk_parse_args must have been called first. If the default
355  * display has previously been set, simply returns that. An internal
356  * function that should not be used by applications.
357  *
358  * Return value: (transfer none): the default display, if it could be
359  *   opened, otherwise %NULL.
360  **/
361 GdkDisplay *
362 gdk_display_open_default_libgtk_only (void)
363 {
364   GdkDisplay *display;
365
366   g_return_val_if_fail (gdk_initialized, NULL);
367
368   display = gdk_display_get_default ();
369   if (display)
370     return display;
371
372   display = gdk_display_open (gdk_get_display_arg_name ());
373
374   return display;
375 }
376
377 /**
378  * gdk_init_check:
379  * @argc: (inout): the number of command line arguments.
380  * @argv: (array length=argc) (inout): the array of command line arguments.
381  *
382  * Initializes the GDK library and connects to the windowing system,
383  * returning %TRUE on success.
384  *
385  * Any arguments used by GDK are removed from the array and @argc and @argv
386  * are updated accordingly.
387  *
388  * GTK+ initializes GDK in gtk_init() and so this function is not usually
389  * needed by GTK+ applications.
390  *
391  * Returns: %TRUE if initialization succeeded.
392  */
393 gboolean
394 gdk_init_check (int    *argc,
395                 char ***argv)
396 {
397   gdk_parse_args (argc, argv);
398
399   return gdk_display_open_default_libgtk_only () != NULL;
400 }
401
402
403 /**
404  * gdk_init:
405  * @argc: (inout): the number of command line arguments.
406  * @argv: (array length=argc) (inout): the array of command line arguments.
407  *
408  * Initializes the GDK library and connects to the windowing system.
409  * If initialization fails, a warning message is output and the application
410  * terminates with a call to <literal>exit(1)</literal>.
411  *
412  * Any arguments used by GDK are removed from the array and @argc and @argv
413  * are updated accordingly.
414  *
415  * GTK+ initializes GDK in gtk_init() and so this function is not usually
416  * needed by GTK+ applications.
417  */
418 void
419 gdk_init (int *argc, char ***argv)
420 {
421   if (!gdk_init_check (argc, argv))
422     {
423       const char *display_name = gdk_get_display_arg_name ();
424       g_warning ("cannot open display: %s", display_name ? display_name : "");
425       exit(1);
426     }
427 }
428
429
430
431 /**
432  * SECTION:threads
433  * @Short_description: Functions for using GDK in multi-threaded programs
434  * @Title: Threads
435  *
436  * For thread safety, GDK relies on the thread primitives in GLib,
437  * and on the thread-safe GLib main loop.
438  *
439  * GLib is completely thread safe (all global data is automatically
440  * locked), but individual data structure instances are not automatically
441  * locked for performance reasons. So e.g. you must coordinate
442  * accesses to the same #GHashTable from multiple threads.
443  *
444  * GTK+ is "thread aware" but not thread safe &mdash; it provides a
445  * global lock controlled by gdk_threads_enter()/gdk_threads_leave()
446  * which protects all use of GTK+. That is, only one thread can use GTK+
447  * at any given time.
448  *
449  * Unfortunately the above holds with the X11 backend only. With the
450  * Win32 backend, GDK calls should not be attempted from multiple threads
451  * at all.
452  *
453  * You must call gdk_threads_init() before executing any other GTK+ or
454  * GDK functions in a threaded GTK+ program.
455  *
456  * Idles, timeouts, and input functions from GLib, such as g_idle_add(),
457  * are executed outside of the main GTK+ lock. So, if you need to call
458  * GTK+ inside of such a callback, you must surround the callback with
459  * a gdk_threads_enter()/gdk_threads_leave() pair or use
460  * gdk_threads_add_idle_full() which does this for you.
461  * However, event dispatching from the mainloop is still executed within
462  * the main GTK+ lock, so callback functions connected to event signals
463  * like #GtkWidget::button-press-event, do not need thread protection.
464  *
465  * In particular, this means, if you are writing widgets that might
466  * be used in threaded programs, you <emphasis>must</emphasis> surround
467  * timeouts and idle functions in this matter.
468  *
469  * As always, you must also surround any calls to GTK+ not made within
470  * a signal handler with a gdk_threads_enter()/gdk_threads_leave() pair.
471  *
472  * Before calling gdk_threads_leave() from a thread other
473  * than your main thread, you probably want to call gdk_flush()
474  * to send all pending commands to the windowing system.
475  * (The reason you don't need to do this from the main thread
476  * is that GDK always automatically flushes pending commands
477  * when it runs out of incoming events to process and has
478  * to sleep while waiting for more events.)
479  *
480  * A minimal main program for a threaded GTK+ application
481  * looks like:
482  * <informalexample>
483  * <programlisting role="C">
484  * int
485  * main (int argc, char *argv[])
486  * {
487  *   GtkWidget *window;
488  *
489  *   gdk_threads_init (<!-- -->);
490  *   gdk_threads_enter (<!-- -->);
491  *
492  *   gtk_init (&argc, &argv);
493  *
494  *   window = create_window (<!-- -->);
495  *   gtk_widget_show (window);
496  *
497  *   gtk_main (<!-- -->);
498  *   gdk_threads_leave (<!-- -->);
499  *
500  *   return 0;
501  * }
502  * </programlisting>
503  * </informalexample>
504  *
505  * Callbacks require a bit of attention. Callbacks from GTK+ signals
506  * are made within the GTK+ lock. However callbacks from GLib (timeouts,
507  * IO callbacks, and idle functions) are made outside of the GTK+
508  * lock. So, within a signal handler you do not need to call
509  * gdk_threads_enter(), but within the other types of callbacks, you
510  * do.
511  *
512  * Erik Mouw contributed the following code example to
513  * illustrate how to use threads within GTK+ programs.
514  * <informalexample>
515  * <programlisting role="C">
516  * /<!---->*-------------------------------------------------------------------------
517  *  * Filename:      gtk-thread.c
518  *  * Version:       0.99.1
519  *  * Copyright:     Copyright (C) 1999, Erik Mouw
520  *  * Author:        Erik Mouw &lt;J.A.K.Mouw@its.tudelft.nl&gt;
521  *  * Description:   GTK threads example.
522  *  * Created at:    Sun Oct 17 21:27:09 1999
523  *  * Modified by:   Erik Mouw &lt;J.A.K.Mouw@its.tudelft.nl&gt;
524  *  * Modified at:   Sun Oct 24 17:21:41 1999
525  *  *-----------------------------------------------------------------------*<!---->/
526  * /<!---->*
527  *  * Compile with:
528  *  *
529  *  * cc -o gtk-thread gtk-thread.c `gtk-config --cflags --libs gthread`
530  *  *
531  *  * Thanks to Sebastian Wilhelmi and Owen Taylor for pointing out some
532  *  * bugs.
533  *  *
534  *  *<!---->/
535  *
536  * #include <stdio.h>
537  * #include <stdlib.h>
538  * #include <unistd.h>
539  * #include <time.h>
540  * #include <gtk/gtk.h>
541  * #include <glib.h>
542  * #include <pthread.h>
543  *
544  * #define YES_IT_IS    (1)
545  * #define NO_IT_IS_NOT (0)
546  *
547  * typedef struct
548  * {
549  *   GtkWidget *label;
550  *   int what;
551  * } yes_or_no_args;
552  *
553  * G_LOCK_DEFINE_STATIC (yes_or_no);
554  * static volatile int yes_or_no = YES_IT_IS;
555  *
556  * void destroy (GtkWidget *widget, gpointer data)
557  * {
558  *   gtk_main_quit (<!-- -->);
559  * }
560  *
561  * void *argument_thread (void *args)
562  * {
563  *   yes_or_no_args *data = (yes_or_no_args *)args;
564  *   gboolean say_something;
565  *
566  *   for (;;)
567  *     {
568  *       /<!---->* sleep a while *<!---->/
569  *       sleep(rand(<!-- -->) / (RAND_MAX / 3) + 1);
570  *
571  *       /<!---->* lock the yes_or_no_variable *<!---->/
572  *       G_LOCK(yes_or_no);
573  *
574  *       /<!---->* do we have to say something? *<!---->/
575  *       say_something = (yes_or_no != data->what);
576  *
577  *       if(say_something)
578  *      {
579  *        /<!---->* set the variable *<!---->/
580  *        yes_or_no = data->what;
581  *      }
582  *
583  *       /<!---->* Unlock the yes_or_no variable *<!---->/
584  *       G_UNLOCK (yes_or_no);
585  *
586  *       if (say_something)
587  *      {
588  *        /<!---->* get GTK thread lock *<!---->/
589  *        gdk_threads_enter (<!-- -->);
590  *
591  *        /<!---->* set label text *<!---->/
592  *        if(data->what == YES_IT_IS)
593  *          gtk_label_set_text (GTK_LABEL (data->label), "O yes, it is!");
594  *        else
595  *          gtk_label_set_text (GTK_LABEL (data->label), "O no, it isn't!");
596  *
597  *        /<!---->* release GTK thread lock *<!---->/
598  *        gdk_threads_leave (<!-- -->);
599  *      }
600  *     }
601  *
602  *   return NULL;
603  * }
604  *
605  * int main (int argc, char *argv[])
606  * {
607  *   GtkWidget *window;
608  *   GtkWidget *label;
609  *   yes_or_no_args yes_args, no_args;
610  *   pthread_t no_tid, yes_tid;
611  *
612  *   /<!---->* init threads *<!---->/
613  *   gdk_threads_init (<!-- -->);
614  *   gdk_threads_enter (<!-- -->);
615  *
616  *   /<!---->* init gtk *<!---->/
617  *   gtk_init(&argc, &argv);
618  *
619  *   /<!---->* init random number generator *<!---->/
620  *   srand ((unsigned int) time (NULL));
621  *
622  *   /<!---->* create a window *<!---->/
623  *   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
624  *
625  *   g_signal_connect (window, "destroy", G_CALLBACK (destroy), NULL);
626  *
627  *   gtk_container_set_border_width (GTK_CONTAINER (window), 10);
628  *
629  *   /<!---->* create a label *<!---->/
630  *   label = gtk_label_new ("And now for something completely different ...");
631  *   gtk_container_add (GTK_CONTAINER (window), label);
632  *
633  *   /<!---->* show everything *<!---->/
634  *   gtk_widget_show (label);
635  *   gtk_widget_show (window);
636  *
637  *   /<!---->* create the threads *<!---->/
638  *   yes_args.label = label;
639  *   yes_args.what = YES_IT_IS;
640  *   pthread_create (&yes_tid, NULL, argument_thread, &yes_args);
641  *
642  *   no_args.label = label;
643  *   no_args.what = NO_IT_IS_NOT;
644  *   pthread_create (&no_tid, NULL, argument_thread, &no_args);
645  *
646  *   /<!---->* enter the GTK main loop *<!---->/
647  *   gtk_main (<!-- -->);
648  *   gdk_threads_leave (<!-- -->);
649  *
650  *   return 0;
651  * }
652  * </programlisting>
653  * </informalexample>
654  */
655
656
657 /**
658  * gdk_threads_enter:
659  *
660  * This function marks the beginning of a critical section in which
661  * GDK and GTK+ functions can be called safely and without causing race
662  * conditions. Only one thread at a time can be in such a critial
663  * section.
664  */
665 void
666 gdk_threads_enter (void)
667 {
668   if (gdk_threads_lock)
669     (*gdk_threads_lock) ();
670 }
671
672 /**
673  * gdk_threads_leave:
674  *
675  * Leaves a critical region begun with gdk_threads_enter().
676  */
677 void
678 gdk_threads_leave (void)
679 {
680   if (gdk_threads_unlock)
681     (*gdk_threads_unlock) ();
682 }
683
684 static void
685 gdk_threads_impl_lock (void)
686 {
687   g_mutex_lock (&gdk_threads_mutex);
688 }
689
690 static void
691 gdk_threads_impl_unlock (void)
692 {
693   g_mutex_unlock (&gdk_threads_mutex);
694 }
695
696 /**
697  * gdk_threads_init:
698  *
699  * Initializes GDK so that it can be used from multiple threads
700  * in conjunction with gdk_threads_enter() and gdk_threads_leave().
701  *
702  * This call must be made before any use of the main loop from
703  * GTK+; to be safe, call it before gtk_init().
704  */
705 void
706 gdk_threads_init (void)
707 {
708   if (!gdk_threads_lock)
709     gdk_threads_lock = gdk_threads_impl_lock;
710   if (!gdk_threads_unlock)
711     gdk_threads_unlock = gdk_threads_impl_unlock;
712 }
713
714 /**
715  * gdk_threads_set_lock_functions: (skip)
716  * @enter_fn:   function called to guard GDK
717  * @leave_fn: function called to release the guard
718  *
719  * Allows the application to replace the standard method that
720  * GDK uses to protect its data structures. Normally, GDK
721  * creates a single #GMutex that is locked by gdk_threads_enter(),
722  * and released by gdk_threads_leave(); using this function an
723  * application provides, instead, a function @enter_fn that is
724  * called by gdk_threads_enter() and a function @leave_fn that is
725  * called by gdk_threads_leave().
726  *
727  * The functions must provide at least same locking functionality
728  * as the default implementation, but can also do extra application
729  * specific processing.
730  *
731  * As an example, consider an application that has its own recursive
732  * lock that when held, holds the GTK+ lock as well. When GTK+ unlocks
733  * the GTK+ lock when entering a recursive main loop, the application
734  * must temporarily release its lock as well.
735  *
736  * Most threaded GTK+ apps won't need to use this method.
737  *
738  * This method must be called before gdk_threads_init(), and cannot
739  * be called multiple times.
740  *
741  * Since: 2.4
742  **/
743 void
744 gdk_threads_set_lock_functions (GCallback enter_fn,
745                                 GCallback leave_fn)
746 {
747   g_return_if_fail (gdk_threads_lock == NULL &&
748                     gdk_threads_unlock == NULL);
749
750   gdk_threads_lock = enter_fn;
751   gdk_threads_unlock = leave_fn;
752 }
753
754 static gboolean
755 gdk_threads_dispatch (gpointer data)
756 {
757   GdkThreadsDispatch *dispatch = data;
758   gboolean ret = FALSE;
759
760   GDK_THREADS_ENTER ();
761
762   if (!g_source_is_destroyed (g_main_current_source ()))
763     ret = dispatch->func (dispatch->data);
764
765   GDK_THREADS_LEAVE ();
766
767   return ret;
768 }
769
770 static void
771 gdk_threads_dispatch_free (gpointer data)
772 {
773   GdkThreadsDispatch *dispatch = data;
774
775   if (dispatch->destroy && dispatch->data)
776     dispatch->destroy (dispatch->data);
777
778   g_slice_free (GdkThreadsDispatch, data);
779 }
780
781
782 /**
783  * gdk_threads_add_idle_full:
784  * @priority: the priority of the idle source. Typically this will be in the
785  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE
786  * @function: function to call
787  * @data:     data to pass to @function
788  * @notify: (allow-none):   function to call when the idle is removed, or %NULL
789  *
790  * Adds a function to be called whenever there are no higher priority
791  * events pending.  If the function returns %FALSE it is automatically
792  * removed from the list of event sources and will not be called again.
793  *
794  * This variant of g_idle_add_full() calls @function with the GDK lock
795  * held. It can be thought of a MT-safe version for GTK+ widgets for the
796  * following use case, where you have to worry about idle_callback()
797  * running in thread A and accessing @self after it has been finalized
798  * in thread B:
799  *
800  * |[
801  * static gboolean
802  * idle_callback (gpointer data)
803  * {
804  *    /&ast; gdk_threads_enter(); would be needed for g_idle_add() &ast;/
805  *
806  *    SomeWidget *self = data;
807  *    /&ast; do stuff with self &ast;/
808  *
809  *    self->idle_id = 0;
810  *
811  *    /&ast; gdk_threads_leave(); would be needed for g_idle_add() &ast;/
812  *    return FALSE;
813  * }
814  *
815  * static void
816  * some_widget_do_stuff_later (SomeWidget *self)
817  * {
818  *    self->idle_id = gdk_threads_add_idle (idle_callback, self)
819  *    /&ast; using g_idle_add() here would require thread protection in the callback &ast;/
820  * }
821  *
822  * static void
823  * some_widget_finalize (GObject *object)
824  * {
825  *    SomeWidget *self = SOME_WIDGET (object);
826  *    if (self->idle_id)
827  *      g_source_remove (self->idle_id);
828  *    G_OBJECT_CLASS (parent_class)->finalize (object);
829  * }
830  * ]|
831  *
832  * Return value: the ID (greater than 0) of the event source.
833  *
834  * Since: 2.12
835  * Rename to: gdk_threads_add_idle
836  */
837 guint
838 gdk_threads_add_idle_full (gint           priority,
839                            GSourceFunc    function,
840                            gpointer       data,
841                            GDestroyNotify notify)
842 {
843   GdkThreadsDispatch *dispatch;
844
845   g_return_val_if_fail (function != NULL, 0);
846
847   dispatch = g_slice_new (GdkThreadsDispatch);
848   dispatch->func = function;
849   dispatch->data = data;
850   dispatch->destroy = notify;
851
852   return g_idle_add_full (priority,
853                           gdk_threads_dispatch,
854                           dispatch,
855                           gdk_threads_dispatch_free);
856 }
857
858 /**
859  * gdk_threads_add_idle: (skip)
860  * @function: function to call
861  * @data:     data to pass to @function
862  *
863  * A wrapper for the common usage of gdk_threads_add_idle_full() 
864  * assigning the default priority, #G_PRIORITY_DEFAULT_IDLE.
865  *
866  * See gdk_threads_add_idle_full().
867  *
868  * Return value: the ID (greater than 0) of the event source.
869  * 
870  * Since: 2.12
871  */
872 guint
873 gdk_threads_add_idle (GSourceFunc    function,
874                       gpointer       data)
875 {
876   return gdk_threads_add_idle_full (G_PRIORITY_DEFAULT_IDLE,
877                                     function, data, NULL);
878 }
879
880
881 /**
882  * gdk_threads_add_timeout_full:
883  * @priority: the priority of the timeout source. Typically this will be in the
884  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
885  * @interval: the time between calls to the function, in milliseconds
886  *             (1/1000ths of a second)
887  * @function: function to call
888  * @data:     data to pass to @function
889  * @notify: (allow-none):   function to call when the timeout is removed, or %NULL
890  *
891  * Sets a function to be called at regular intervals holding the GDK lock,
892  * with the given priority.  The function is called repeatedly until it 
893  * returns %FALSE, at which point the timeout is automatically destroyed 
894  * and the function will not be called again.  The @notify function is
895  * called when the timeout is destroyed.  The first call to the
896  * function will be at the end of the first @interval.
897  *
898  * Note that timeout functions may be delayed, due to the processing of other
899  * event sources. Thus they should not be relied on for precise timing.
900  * After each call to the timeout function, the time of the next
901  * timeout is recalculated based on the current time and the given interval
902  * (it does not try to 'catch up' time lost in delays).
903  *
904  * This variant of g_timeout_add_full() can be thought of a MT-safe version 
905  * for GTK+ widgets for the following use case:
906  *
907  * |[
908  * static gboolean timeout_callback (gpointer data)
909  * {
910  *    SomeWidget *self = data;
911  *    
912  *    /&ast; do stuff with self &ast;/
913  *    
914  *    self->timeout_id = 0;
915  *    
916  *    return G_SOURCE_REMOVE;
917  * }
918  *  
919  * static void some_widget_do_stuff_later (SomeWidget *self)
920  * {
921  *    self->timeout_id = g_timeout_add (timeout_callback, self)
922  * }
923  *  
924  * static void some_widget_finalize (GObject *object)
925  * {
926  *    SomeWidget *self = SOME_WIDGET (object);
927  *    
928  *    if (self->timeout_id)
929  *      g_source_remove (self->timeout_id);
930  *    
931  *    G_OBJECT_CLASS (parent_class)->finalize (object);
932  * }
933  * ]|
934  *
935  * Return value: the ID (greater than 0) of the event source.
936  * 
937  * Since: 2.12
938  * Rename to: gdk_threads_add_timeout
939  */
940 guint
941 gdk_threads_add_timeout_full (gint           priority,
942                               guint          interval,
943                               GSourceFunc    function,
944                               gpointer       data,
945                               GDestroyNotify notify)
946 {
947   GdkThreadsDispatch *dispatch;
948
949   g_return_val_if_fail (function != NULL, 0);
950
951   dispatch = g_slice_new (GdkThreadsDispatch);
952   dispatch->func = function;
953   dispatch->data = data;
954   dispatch->destroy = notify;
955
956   return g_timeout_add_full (priority, 
957                              interval,
958                              gdk_threads_dispatch, 
959                              dispatch, 
960                              gdk_threads_dispatch_free);
961 }
962
963 /**
964  * gdk_threads_add_timeout: (skip)
965  * @interval: the time between calls to the function, in milliseconds
966  *             (1/1000ths of a second)
967  * @function: function to call
968  * @data:     data to pass to @function
969  *
970  * A wrapper for the common usage of gdk_threads_add_timeout_full() 
971  * assigning the default priority, #G_PRIORITY_DEFAULT.
972  *
973  * See gdk_threads_add_timeout_full().
974  * 
975  * Return value: the ID (greater than 0) of the event source.
976  *
977  * Since: 2.12
978  */
979 guint
980 gdk_threads_add_timeout (guint       interval,
981                          GSourceFunc function,
982                          gpointer    data)
983 {
984   return gdk_threads_add_timeout_full (G_PRIORITY_DEFAULT,
985                                        interval, function, data, NULL);
986 }
987
988
989 /**
990  * gdk_threads_add_timeout_seconds_full:
991  * @priority: the priority of the timeout source. Typically this will be in the
992  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
993  * @interval: the time between calls to the function, in seconds
994  * @function: function to call
995  * @data:     data to pass to @function
996  * @notify: (allow-none): function to call when the timeout is removed, or %NULL
997  *
998  * A variant of gdk_threads_add_timeout_full() with second-granularity.
999  * See g_timeout_add_seconds_full() for a discussion of why it is
1000  * a good idea to use this function if you don't need finer granularity.
1001  *
1002  *  Return value: the ID (greater than 0) of the event source.
1003  * 
1004  * Since: 2.14
1005  * Rename to: gdk_threads_add_timeout_seconds
1006  */
1007 guint
1008 gdk_threads_add_timeout_seconds_full (gint           priority,
1009                                       guint          interval,
1010                                       GSourceFunc    function,
1011                                       gpointer       data,
1012                                       GDestroyNotify notify)
1013 {
1014   GdkThreadsDispatch *dispatch;
1015
1016   g_return_val_if_fail (function != NULL, 0);
1017
1018   dispatch = g_slice_new (GdkThreadsDispatch);
1019   dispatch->func = function;
1020   dispatch->data = data;
1021   dispatch->destroy = notify;
1022
1023   return g_timeout_add_seconds_full (priority, 
1024                                      interval,
1025                                      gdk_threads_dispatch, 
1026                                      dispatch, 
1027                                      gdk_threads_dispatch_free);
1028 }
1029
1030 /**
1031  * gdk_threads_add_timeout_seconds: (skip)
1032  * @interval: the time between calls to the function, in seconds
1033  * @function: function to call
1034  * @data:     data to pass to @function
1035  *
1036  * A wrapper for the common usage of gdk_threads_add_timeout_seconds_full() 
1037  * assigning the default priority, #G_PRIORITY_DEFAULT.
1038  *
1039  * For details, see gdk_threads_add_timeout_full().
1040  * 
1041  * Return value: the ID (greater than 0) of the event source.
1042  *
1043  * Since: 2.14
1044  */
1045 guint
1046 gdk_threads_add_timeout_seconds (guint       interval,
1047                                  GSourceFunc function,
1048                                  gpointer    data)
1049 {
1050   return gdk_threads_add_timeout_seconds_full (G_PRIORITY_DEFAULT,
1051                                                interval, function, data, NULL);
1052 }
1053
1054 /**
1055  * gdk_get_program_class:
1056  *
1057  * Gets the program class. Unless the program class has explicitly
1058  * been set with gdk_set_program_class() or with the <option>--class</option>
1059  * commandline option, the default value is the program name (determined
1060  * with g_get_prgname()) with the first character converted to uppercase.
1061  *
1062  * Returns: the program class.
1063  */
1064 const char *
1065 gdk_get_program_class (void)
1066 {
1067   return gdk_progclass;
1068 }
1069
1070 /**
1071  * gdk_set_program_class:
1072  * @program_class: a string.
1073  *
1074  * Sets the program class. The X11 backend uses the program class to set
1075  * the class name part of the <literal>WM_CLASS</literal> property on
1076  * toplevel windows; see the ICCCM.
1077  */
1078 void
1079 gdk_set_program_class (const char *program_class)
1080 {
1081   g_free (gdk_progclass);
1082
1083   gdk_progclass = g_strdup (program_class);
1084 }
1085
1086 /**
1087  * gdk_disable_multidevice:
1088  *
1089  * Disables multidevice support in GDK. This call must happen prior
1090  * to gdk_display_open(), gtk_init(), gtk_init_with_args() or
1091  * gtk_init_check() in order to take effect.
1092  *
1093  * Most common GTK+ applications won't ever need to call this. Only
1094  * applications that do mixed GDK/Xlib calls could want to disable
1095  * multidevice support if such Xlib code deals with input devices in
1096  * any way and doesn't observe the presence of XInput 2.
1097  *
1098  * Since: 3.0
1099  */
1100 void
1101 gdk_disable_multidevice (void)
1102 {
1103   if (gdk_initialized)
1104     return;
1105
1106   _gdk_disable_multidevice = TRUE;
1107 }