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