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